penambahan web socket

This commit is contained in:
2025-09-18 19:01:22 +07:00
parent 1d053646a9
commit d7bb2eb5bb
15070 changed files with 2402916 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
<template>
<NuxtLayout>
<NuxtRouteAnnouncer />
<NuxtPage />
</NuxtLayout>
</template>

View File

@@ -0,0 +1,2 @@
declare const _default: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
export default _default;

View File

@@ -0,0 +1,2 @@
declare const _default: {};
export default _default;

View File

@@ -0,0 +1 @@
export default {};

View File

@@ -0,0 +1,58 @@
import type { KeepAliveProps, TransitionProps, UnwrapRef } from 'vue';
import type { RouteLocationNormalized, RouteLocationNormalizedLoaded, RouteRecordRaw, RouteRecordRedirectOption } from 'vue-router';
import type { NitroRouteConfig } from 'nitropack';
import type { NuxtError } from 'nuxt/app';
export interface PageMeta {
[key: string]: unknown;
/**
* Validate whether a given route can validly be rendered with this page.
*
* Return true if it is valid, or false if not. If another match can't be found,
* this will mean a 404. You can also directly return an object with
* statusCode/statusMessage to respond immediately with an error (other matches
* will not be checked).
*/
validate?: (route: RouteLocationNormalized) => boolean | Partial<NuxtError> | Promise<boolean | Partial<NuxtError>>;
/**
* Where to redirect if the route is directly matched. The redirection happens
* before any navigation guard and triggers a new navigation with the new
* target location.
*/
redirect?: RouteRecordRedirectOption;
/**
* Aliases for the record. Allows defining extra paths that will behave like a
* copy of the record. Allows having paths shorthands like `/users/:id` and
* `/u/:id`. All `alias` and `path` values must share the same params.
*/
alias?: string | string[];
pageTransition?: boolean | TransitionProps;
layoutTransition?: boolean | TransitionProps;
key?: false | string | ((route: RouteLocationNormalizedLoaded) => string);
keepalive?: boolean | KeepAliveProps;
/** You may define a name for this page's route. */
name?: string;
/** You may define a path matcher, if you have a more complex pattern than can be expressed with the file name. */
path?: string;
/**
* Allows accessing the route `params` as props passed to the page component.
* @see https://router.vuejs.org/guide/essentials/passing-props
*/
props?: RouteRecordRaw['props'];
/** Set to `false` to avoid scrolling to top on page navigations */
scrollToTop?: boolean | ((to: RouteLocationNormalizedLoaded, from: RouteLocationNormalizedLoaded) => boolean);
}
declare module 'vue-router' {
interface RouteMeta extends UnwrapRef<PageMeta> {
}
}
export declare const definePageMeta: (meta: PageMeta) => void;
/**
* You can define route rules for the current page. Matching route rules will be created, based on the page's _path_.
*
* For example, a rule defined in `~/pages/foo/bar.vue` will be applied to `/foo/bar` requests. A rule in
* `~/pages/foo/[id].vue` will be applied to `/foo/**` requests.
*
* For more control, such as if you are using a custom `path` or `alias` set in the page's `definePageMeta`, you
* should set `routeRules` directly within your `nuxt.config`.
*/
export declare const defineRouteRules: (rules: NitroRouteConfig) => void;

View File

@@ -0,0 +1,24 @@
import { getCurrentInstance } from "vue";
import { useRoute } from "vue-router";
import { useNuxtApp } from "#app/nuxt";
const warnRuntimeUsage = (method) => {
console.warn(
`${method}() is a compiler-hint helper that is only usable inside the script block of a single file component which is also a page. Its arguments should be compiled away and passing it at runtime has no effect.`
);
};
export const definePageMeta = (meta) => {
if (import.meta.dev) {
const component = getCurrentInstance()?.type;
try {
const isRouteComponent = component && useRoute().matched.some((p) => Object.values(p.components || {}).includes(component));
const isRenderingServerPage = import.meta.server && useNuxtApp().ssrContext?.islandContext;
if (isRouteComponent || isRenderingServerPage || component?.__clientOnlyPage) {
return;
}
} catch {
}
warnRuntimeUsage("definePageMeta");
}
};
export const defineRouteRules = /* @__NO_SIDE_EFFECTS__ */ (rules) => {
};

View File

@@ -0,0 +1,3 @@
export { definePageMeta, defineRouteRules } from './composables.js';
export type { PageMeta } from './composables.js';
export type { NuxtPageProps } from './page.js';

View File

@@ -0,0 +1 @@
export { definePageMeta, defineRouteRules } from "./composables.js";

View File

@@ -0,0 +1,4 @@
declare const _default: import("vue").DefineComponent<{}, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>[] | undefined, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
export default _default;

View File

@@ -0,0 +1,11 @@
import { defineComponent } from "vue";
import { devPagesDir } from "#build/nuxt.config.mjs";
export default defineComponent({
name: "NuxtPage",
setup(_, props) {
if (import.meta.dev) {
console.warn(`Create a Vue component in the \`${devPagesDir}/\` directory to enable \`<NuxtPage>\``);
}
return () => props.slots.default?.();
}
});

View File

@@ -0,0 +1,30 @@
import type { AllowedComponentProps, ComponentCustomProps, ComponentPublicInstance, KeepAliveProps, TransitionProps, VNode, VNodeProps } from 'vue';
import type { RouteLocationNormalizedLoaded, RouterViewProps } from 'vue-router';
import type { RouterViewSlotProps } from './utils.js';
export interface NuxtPageProps extends RouterViewProps {
/**
* Define global transitions for all pages rendered with the `NuxtPage` component.
*/
transition?: boolean | TransitionProps;
/**
* Control state preservation of pages rendered with the `NuxtPage` component.
*/
keepalive?: boolean | KeepAliveProps;
/**
* Control when the `NuxtPage` component is re-rendered.
*/
pageKey?: string | ((route: RouteLocationNormalizedLoaded) => string);
}
declare const _default: {
new (): {
$props: AllowedComponentProps & ComponentCustomProps & VNodeProps & NuxtPageProps;
$slots: {
default?: (routeProps: RouterViewSlotProps) => VNode[];
};
/**
* Reference to the page component instance
*/
pageRef: Element | ComponentPublicInstance | null;
};
};
export default _default;

View File

@@ -0,0 +1,207 @@
import { Fragment, Suspense, defineComponent, h, inject, nextTick, onBeforeUnmount, ref, watch } from "vue";
import { RouterView } from "vue-router";
import { defu } from "defu";
import { generateRouteKey, toArray, wrapInKeepAlive } from "./utils.js";
import { RouteProvider, defineRouteProvider } from "#app/components/route-provider";
import { useNuxtApp } from "#app/nuxt";
import { useRouter } from "#app/composables/router";
import { _wrapInTransition } from "#app/components/utils";
import { LayoutMetaSymbol, PageRouteSymbol } from "#app/components/injections";
import { appKeepalive as defaultKeepaliveConfig, appPageTransition as defaultPageTransition } from "#build/nuxt.config.mjs";
const _routeProviders = import.meta.dev ? /* @__PURE__ */ new Map() : /* @__PURE__ */ new WeakMap();
export default defineComponent({
name: "NuxtPage",
inheritAttrs: false,
props: {
name: {
type: String
},
transition: {
type: [Boolean, Object],
default: void 0
},
keepalive: {
type: [Boolean, Object],
default: void 0
},
route: {
type: Object
},
pageKey: {
type: [Function, String],
default: null
}
},
setup(props, { attrs, slots, expose }) {
const nuxtApp = useNuxtApp();
const pageRef = ref();
const forkRoute = inject(PageRouteSymbol, null);
let previousPageKey;
expose({ pageRef });
const _layoutMeta = inject(LayoutMetaSymbol, null);
let vnode;
const done = nuxtApp.deferHydration();
if (import.meta.client && nuxtApp.isHydrating) {
const removeErrorHook = nuxtApp.hooks.hookOnce("app:error", done);
useRouter().beforeEach(removeErrorHook);
}
if (import.meta.client && props.pageKey) {
watch(() => props.pageKey, (next, prev) => {
if (next !== prev) {
nuxtApp.callHook("page:loading:start");
}
});
}
if (import.meta.dev) {
nuxtApp._isNuxtPageUsed = true;
}
let pageLoadingEndHookAlreadyCalled = false;
if (import.meta.client) {
const unsub = useRouter().beforeResolve(() => {
pageLoadingEndHookAlreadyCalled = false;
});
onBeforeUnmount(() => {
unsub();
});
}
return () => {
return h(RouterView, { name: props.name, route: props.route, ...attrs }, {
default: import.meta.server ? (routeProps) => {
return h(Suspense, { suspensible: true }, {
default() {
return h(RouteProvider, {
vnode: slots.default ? normalizeSlot(slots.default, routeProps) : routeProps.Component,
route: routeProps.route,
vnodeRef: pageRef
});
}
});
} : (routeProps) => {
const isRenderingNewRouteInOldFork = haveParentRoutesRendered(forkRoute, routeProps.route, routeProps.Component);
const hasSameChildren = forkRoute && forkRoute.matched.length === routeProps.route.matched.length;
if (!routeProps.Component) {
if (vnode && !hasSameChildren) {
return vnode;
}
done();
return;
}
if (vnode && _layoutMeta && !_layoutMeta.isCurrent(routeProps.route)) {
return vnode;
}
if (isRenderingNewRouteInOldFork && forkRoute && (!_layoutMeta || _layoutMeta?.isCurrent(forkRoute))) {
if (hasSameChildren) {
return vnode;
}
return null;
}
const key = generateRouteKey(routeProps, props.pageKey);
const willRenderAnotherChild = hasChildrenRoutes(forkRoute, routeProps.route, routeProps.Component);
if (!nuxtApp.isHydrating && previousPageKey === key && !willRenderAnotherChild) {
nextTick(() => {
pageLoadingEndHookAlreadyCalled = true;
nuxtApp.callHook("page:loading:end");
});
}
previousPageKey = key;
const hasTransition = !!(props.transition ?? routeProps.route.meta.pageTransition ?? defaultPageTransition);
const transitionProps = hasTransition && _mergeTransitionProps([
props.transition,
routeProps.route.meta.pageTransition,
defaultPageTransition,
{
onAfterLeave() {
delete nuxtApp._runningTransition;
nuxtApp.callHook("page:transition:finish", routeProps.Component);
}
}
]);
const keepaliveConfig = props.keepalive ?? routeProps.route.meta.keepalive ?? defaultKeepaliveConfig;
vnode = _wrapInTransition(
hasTransition && transitionProps,
wrapInKeepAlive(
keepaliveConfig,
h(Suspense, {
suspensible: true,
onPending: () => {
if (hasTransition) {
nuxtApp._runningTransition = true;
}
nuxtApp.callHook("page:start", routeProps.Component);
},
onResolve: () => {
nextTick(() => nuxtApp.callHook("page:finish", routeProps.Component).then(() => {
delete nuxtApp._runningTransition;
if (!pageLoadingEndHookAlreadyCalled && !willRenderAnotherChild) {
pageLoadingEndHookAlreadyCalled = true;
return nuxtApp.callHook("page:loading:end");
}
}).finally(done));
}
}, {
default: () => {
const routeProviderProps = {
key: key || void 0,
vnode: slots.default ? normalizeSlot(slots.default, routeProps) : routeProps.Component,
route: routeProps.route,
renderKey: key || void 0,
trackRootNodes: hasTransition,
vnodeRef: pageRef
};
if (!keepaliveConfig) {
return h(RouteProvider, routeProviderProps);
}
const routerComponentType = routeProps.Component.type;
const routeProviderKey = import.meta.dev ? routerComponentType.name || routerComponentType.__name : routerComponentType;
let PageRouteProvider = _routeProviders.get(routeProviderKey);
if (!PageRouteProvider) {
PageRouteProvider = defineRouteProvider(routerComponentType.name || routerComponentType.__name);
_routeProviders.set(routeProviderKey, PageRouteProvider);
}
return h(PageRouteProvider, routeProviderProps);
}
})
)
).default();
return vnode;
}
});
};
}
});
function _mergeTransitionProps(routeProps) {
const _props = [];
for (const prop of routeProps) {
if (!prop) {
continue;
}
_props.push({
...prop,
onAfterLeave: prop.onAfterLeave ? toArray(prop.onAfterLeave) : void 0
});
}
return defu(..._props);
}
function haveParentRoutesRendered(fork, newRoute, Component) {
if (!fork) {
return false;
}
const index = newRoute.matched.findIndex((m) => m.components?.default === Component?.type);
if (!index || index === -1) {
return false;
}
return newRoute.matched.slice(0, index).some(
(c, i) => c.components?.default !== fork.matched[i]?.components?.default
) || Component && generateRouteKey({ route: newRoute, Component }) !== generateRouteKey({ route: fork, Component });
}
function hasChildrenRoutes(fork, newRoute, Component) {
if (!fork) {
return false;
}
const index = newRoute.matched.findIndex((m) => m.components?.default === Component?.type);
return index < newRoute.matched.length - 1;
}
function normalizeSlot(slot, data) {
const slotContent = slot(data);
return slotContent.length === 1 ? h(slotContent[0]) : h(Fragment, void 0, slotContent);
}

View File

@@ -0,0 +1,2 @@
declare const _default: any;
export default _default;

View File

@@ -0,0 +1,29 @@
import { nextTick } from "vue";
import { defineNuxtPlugin } from "#app/nuxt";
import { onNuxtReady } from "#app/composables/ready";
import { useError } from "#app/composables/error";
export default defineNuxtPlugin({
name: "nuxt:checkIfPageUnused",
setup(nuxtApp) {
const error = useError();
function checkIfPageUnused() {
if (!error.value && !nuxtApp._isNuxtPageUsed) {
console.warn(
"[nuxt] Your project has pages but the `<NuxtPage />` component has not been used. You might be using the `<RouterView />` component instead, which will not work correctly in Nuxt. You can set `pages: false` in `nuxt.config` if you do not wish to use the Nuxt `vue-router` integration."
);
}
}
if (import.meta.server) {
nuxtApp.hook("app:rendered", ({ renderResult }) => {
if (renderResult?.html) {
nextTick(checkIfPageUnused);
}
});
} else {
onNuxtReady(checkIfPageUnused);
}
},
env: {
islands: false
}
});

View File

@@ -0,0 +1,2 @@
declare const _default: any;
export default _default;

View File

@@ -0,0 +1,41 @@
import { hasProtocol } from "ufo";
import { toArray } from "../utils.js";
import { defineNuxtPlugin } from "#app/nuxt";
import { useRouter } from "#app/composables/router";
import layouts from "#build/layouts";
import { namedMiddleware } from "#build/middleware";
import { _loadAsyncComponent } from "#app/composables/preload";
export default defineNuxtPlugin({
name: "nuxt:prefetch",
setup(nuxtApp) {
const router = useRouter();
nuxtApp.hooks.hook("app:mounted", () => {
router.beforeEach(async (to) => {
const layout = to?.meta?.layout;
if (layout && typeof layouts[layout] === "function") {
await layouts[layout]();
}
});
});
nuxtApp.hooks.hook("link:prefetch", (url) => {
if (hasProtocol(url)) {
return;
}
const route = router.resolve(url);
if (!route) {
return;
}
const layout = route.meta.layout;
let middleware = toArray(route.meta.middleware);
middleware = middleware.filter((m) => typeof m === "string");
for (const name of middleware) {
if (typeof namedMiddleware[name] === "function") {
namedMiddleware[name]();
}
}
if (typeof layout === "string" && layout in layouts) {
_loadAsyncComponent(layouts[layout]);
}
});
}
});

View File

@@ -0,0 +1,2 @@
declare const _default: any;
export default _default;

View File

@@ -0,0 +1,47 @@
import { joinURL } from "ufo";
import { createRouter as createRadixRouter, toRouteMatcher } from "radix3";
import defu from "defu";
import { defineNuxtPlugin, useRuntimeConfig } from "#app/nuxt";
import { prerenderRoutes } from "#app/composables/ssr";
import _routes from "#build/routes";
import routerOptions, { hashMode } from "#build/router.options";
import { crawlLinks } from "#build/nuxt.config.mjs";
let routes;
let _routeRulesMatcher = void 0;
export default defineNuxtPlugin(async () => {
if (!import.meta.server || !import.meta.prerender || hashMode) {
return;
}
if (routes && !routes.length) {
return;
}
const routeRules = useRuntimeConfig().nitro.routeRules;
if (!crawlLinks && routeRules && Object.values(routeRules).some((r) => r.prerender)) {
_routeRulesMatcher = toRouteMatcher(createRadixRouter({ routes: routeRules }));
}
routes ||= Array.from(processRoutes(await routerOptions.routes?.(_routes) ?? _routes));
const batch = routes.splice(0, 10);
prerenderRoutes(batch);
});
const OPTIONAL_PARAM_RE = /^\/?:.*(?:\?|\(\.\*\)\*)$/;
function shouldPrerender(path) {
return !_routeRulesMatcher || defu({}, ..._routeRulesMatcher.matchAll(path).reverse()).prerender;
}
function processRoutes(routes2, currentPath = "/", routesToPrerender = /* @__PURE__ */ new Set()) {
for (const route of routes2) {
if (OPTIONAL_PARAM_RE.test(route.path) && !route.children?.length && shouldPrerender(currentPath)) {
routesToPrerender.add(currentPath);
}
if (route.path.includes(":")) {
continue;
}
const fullPath = joinURL(currentPath, route.path);
if (shouldPrerender(fullPath)) {
routesToPrerender.add(fullPath);
}
if (route.children) {
processRoutes(route.children, fullPath, routesToPrerender);
}
}
return routesToPrerender;
}

View File

@@ -0,0 +1,6 @@
import type { Router } from 'vue-router';
import type { Plugin } from 'nuxt/app';
declare const plugin: Plugin<{
router: Router;
}>;
export default plugin;

View File

@@ -0,0 +1,237 @@
import { isReadonly, reactive, shallowReactive, shallowRef } from "vue";
import { START_LOCATION, createMemoryHistory, createRouter, createWebHashHistory, createWebHistory } from "vue-router";
import { isSamePath, withoutBase } from "ufo";
import { toArray } from "../utils.js";
import { getRouteRules } from "#app/composables/manifest";
import { defineNuxtPlugin, useRuntimeConfig } from "#app/nuxt";
import { clearError, createError, isNuxtError, showError, useError } from "#app/composables/error";
import { navigateTo } from "#app/composables/router";
import { appManifest as isAppManifestEnabled } from "#build/nuxt.config.mjs";
import _routes, { handleHotUpdate } from "#build/routes";
import routerOptions, { hashMode } from "#build/router.options";
import { globalMiddleware, namedMiddleware } from "#build/middleware";
function createCurrentLocation(base, location, renderedPath) {
const { pathname, search, hash } = location;
const hashPos = base.indexOf("#");
if (hashPos > -1) {
const slicePos = hash.includes(base.slice(hashPos)) ? base.slice(hashPos).length : 1;
let pathFromHash = hash.slice(slicePos);
if (pathFromHash[0] !== "/") {
pathFromHash = "/" + pathFromHash;
}
return withoutBase(pathFromHash, "");
}
const displayedPath = withoutBase(pathname, base);
const path = !renderedPath || isSamePath(displayedPath, renderedPath) ? displayedPath : renderedPath;
return path + (path.includes("?") ? "" : search) + hash;
}
const plugin = defineNuxtPlugin({
name: "nuxt:router",
enforce: "pre",
async setup(nuxtApp) {
let routerBase = useRuntimeConfig().app.baseURL;
if (hashMode && !routerBase.includes("#")) {
routerBase += "#";
}
const history = routerOptions.history?.(routerBase) ?? (import.meta.client ? hashMode ? createWebHashHistory(routerBase) : createWebHistory(routerBase) : createMemoryHistory(routerBase));
const routes = routerOptions.routes ? await routerOptions.routes(_routes) ?? _routes : _routes;
let startPosition;
const router = createRouter({
...routerOptions,
scrollBehavior: (to, from, savedPosition) => {
if (from === START_LOCATION) {
startPosition = savedPosition;
return;
}
if (routerOptions.scrollBehavior) {
router.options.scrollBehavior = routerOptions.scrollBehavior;
if ("scrollRestoration" in window.history) {
const unsub = router.beforeEach(() => {
unsub();
window.history.scrollRestoration = "manual";
});
}
return routerOptions.scrollBehavior(to, START_LOCATION, startPosition || savedPosition);
}
},
history,
routes
});
if (import.meta.hot) {
handleHotUpdate(router, routerOptions.routes ? routerOptions.routes : (routes2) => routes2);
}
if (import.meta.client && "scrollRestoration" in window.history) {
window.history.scrollRestoration = "auto";
}
nuxtApp.vueApp.use(router);
const previousRoute = shallowRef(router.currentRoute.value);
router.afterEach((_to, from) => {
previousRoute.value = from;
});
Object.defineProperty(nuxtApp.vueApp.config.globalProperties, "previousRoute", {
get: () => previousRoute.value
});
const initialURL = import.meta.server ? nuxtApp.ssrContext.url : createCurrentLocation(routerBase, window.location, nuxtApp.payload.path);
const _route = shallowRef(router.currentRoute.value);
const syncCurrentRoute = () => {
_route.value = router.currentRoute.value;
};
nuxtApp.hook("page:finish", syncCurrentRoute);
router.afterEach((to, from) => {
if (to.matched[to.matched.length - 1]?.components?.default === from.matched[from.matched.length - 1]?.components?.default) {
syncCurrentRoute();
}
});
const route = {};
for (const key in _route.value) {
Object.defineProperty(route, key, {
get: () => _route.value[key],
enumerable: true
});
}
nuxtApp._route = shallowReactive(route);
nuxtApp._middleware ||= {
global: [],
named: {}
};
const error = useError();
if (import.meta.client || !nuxtApp.ssrContext?.islandContext) {
router.afterEach(async (to, _from, failure) => {
delete nuxtApp._processingMiddleware;
if (import.meta.client && !nuxtApp.isHydrating && error.value) {
await nuxtApp.runWithContext(clearError);
}
if (failure) {
await nuxtApp.callHook("page:loading:end");
}
if (import.meta.server && failure?.type === 4) {
return;
}
if (import.meta.server && to.redirectedFrom && to.fullPath !== initialURL) {
await nuxtApp.runWithContext(() => navigateTo(to.fullPath || "/"));
}
});
}
try {
if (import.meta.server) {
await router.push(initialURL);
}
await router.isReady();
} catch (error2) {
await nuxtApp.runWithContext(() => showError(error2));
}
const resolvedInitialRoute = import.meta.client && initialURL !== router.currentRoute.value.fullPath ? router.resolve(initialURL) : router.currentRoute.value;
syncCurrentRoute();
if (import.meta.server && nuxtApp.ssrContext?.islandContext) {
return { provide: { router } };
}
const initialLayout = nuxtApp.payload.state._layout;
router.beforeEach(async (to, from) => {
await nuxtApp.callHook("page:loading:start");
to.meta = reactive(to.meta);
if (nuxtApp.isHydrating && initialLayout && !isReadonly(to.meta.layout)) {
to.meta.layout = initialLayout;
}
nuxtApp._processingMiddleware = true;
if (import.meta.client || !nuxtApp.ssrContext?.islandContext) {
const middlewareEntries = /* @__PURE__ */ new Set([...globalMiddleware, ...nuxtApp._middleware.global]);
for (const component of to.matched) {
const componentMiddleware = component.meta.middleware;
if (!componentMiddleware) {
continue;
}
for (const entry of toArray(componentMiddleware)) {
middlewareEntries.add(entry);
}
}
if (isAppManifestEnabled) {
const routeRules = await nuxtApp.runWithContext(() => getRouteRules({ path: to.path }));
if (routeRules.appMiddleware) {
for (const key in routeRules.appMiddleware) {
if (routeRules.appMiddleware[key]) {
middlewareEntries.add(key);
} else {
middlewareEntries.delete(key);
}
}
}
}
for (const entry of middlewareEntries) {
const middleware = typeof entry === "string" ? nuxtApp._middleware.named[entry] || await namedMiddleware[entry]?.().then((r) => r.default || r) : entry;
if (!middleware) {
if (import.meta.dev) {
throw new Error(`Unknown route middleware: '${entry}'. Valid middleware: ${Object.keys(namedMiddleware).map((mw) => `'${mw}'`).join(", ")}.`);
}
throw new Error(`Unknown route middleware: '${entry}'.`);
}
try {
if (import.meta.dev) {
nuxtApp._processingMiddleware = middleware._path || (typeof entry === "string" ? entry : true);
}
const result = await nuxtApp.runWithContext(() => middleware(to, from));
if (import.meta.server || !nuxtApp.payload.serverRendered && nuxtApp.isHydrating) {
if (result === false || result instanceof Error) {
const error2 = result || createError({
statusCode: 404,
statusMessage: `Page Not Found: ${initialURL}`
});
await nuxtApp.runWithContext(() => showError(error2));
return false;
}
}
if (result === true) {
continue;
}
if (result === false) {
return result;
}
if (result) {
if (isNuxtError(result) && result.fatal) {
await nuxtApp.runWithContext(() => showError(result));
}
return result;
}
} catch (err) {
const error2 = createError(err);
if (error2.fatal) {
await nuxtApp.runWithContext(() => showError(error2));
}
return error2;
}
}
}
});
router.onError(async () => {
delete nuxtApp._processingMiddleware;
await nuxtApp.callHook("page:loading:end");
});
router.afterEach((to) => {
if (to.matched.length === 0) {
return nuxtApp.runWithContext(() => showError(createError({
statusCode: 404,
fatal: false,
statusMessage: `Page not found: ${to.fullPath}`,
data: {
path: to.fullPath
}
})));
}
});
nuxtApp.hooks.hookOnce("app:created", async () => {
try {
if ("name" in resolvedInitialRoute) {
resolvedInitialRoute.name = void 0;
}
await router.replace({
...resolvedInitialRoute,
force: true
});
router.options.scrollBehavior = routerOptions.scrollBehavior;
} catch (error2) {
await nuxtApp.runWithContext(() => showError(error2));
}
});
return { provide: { router } };
}
});
export default plugin;

View File

@@ -0,0 +1,3 @@
import type { RouterConfig } from 'nuxt/schema';
declare const _default: RouterConfig;
export default _default;

View File

@@ -0,0 +1,60 @@
import { START_LOCATION } from "vue-router";
import { useNuxtApp } from "#app/nuxt";
import { isChangingPage } from "#app/components/utils";
import { useRouter } from "#app/composables/router";
export default {
scrollBehavior(to, from, savedPosition) {
const nuxtApp = useNuxtApp();
const hashScrollBehaviour = useRouter().options?.scrollBehaviorType ?? "auto";
if (to.path === from.path) {
if (from.hash && !to.hash) {
return { left: 0, top: 0 };
}
if (to.hash) {
return { el: to.hash, top: _getHashElementScrollMarginTop(to.hash), behavior: hashScrollBehaviour };
}
return false;
}
const routeAllowsScrollToTop = typeof to.meta.scrollToTop === "function" ? to.meta.scrollToTop(to, from) : to.meta.scrollToTop;
if (routeAllowsScrollToTop === false) {
return false;
}
const hookToWait = nuxtApp._runningTransition ? "page:transition:finish" : "page:loading:end";
return new Promise((resolve) => {
if (from === START_LOCATION) {
resolve(_calculatePosition(to, from, savedPosition, hashScrollBehaviour));
return;
}
nuxtApp.hooks.hookOnce(hookToWait, () => {
requestAnimationFrame(() => resolve(_calculatePosition(to, from, savedPosition, hashScrollBehaviour)));
});
});
}
};
function _getHashElementScrollMarginTop(selector) {
try {
const elem = document.querySelector(selector);
if (elem) {
return (Number.parseFloat(getComputedStyle(elem).scrollMarginTop) || 0) + (Number.parseFloat(getComputedStyle(document.documentElement).scrollPaddingTop) || 0);
}
} catch {
}
return 0;
}
function _calculatePosition(to, from, savedPosition, defaultHashScrollBehaviour) {
if (savedPosition) {
return savedPosition;
}
const isPageNavigation = isChangingPage(to, from);
if (to.hash) {
return {
el: to.hash,
top: _getHashElementScrollMarginTop(to.hash),
behavior: isPageNavigation ? defaultHashScrollBehaviour : "instant"
};
}
return {
left: 0,
top: 0
};
}

View File

@@ -0,0 +1,11 @@
import type { RouteLocationNormalizedLoaded, RouterView } from 'vue-router';
type InstanceOf<T> = T extends new (...args: any[]) => infer R ? R : never;
type RouterViewSlot = Exclude<InstanceOf<typeof RouterView>['$slots']['default'], undefined>;
export type RouterViewSlotProps = Parameters<RouterViewSlot>[0];
export declare const generateRouteKey: (routeProps: RouterViewSlotProps, override?: string | ((route: RouteLocationNormalizedLoaded) => string)) => string | false | undefined;
export declare const wrapInKeepAlive: (props: any, children: any) => {
default: () => any;
};
/** @since 3.9.0 */
export declare function toArray<T>(value: T | T[]): T[];
export {};

View File

@@ -0,0 +1,18 @@
import { KeepAlive, h } from "vue";
const ROUTE_KEY_PARENTHESES_RE = /(:\w+)\([^)]+\)/g;
const ROUTE_KEY_SYMBOLS_RE = /(:\w+)[?+*]/g;
const ROUTE_KEY_NORMAL_RE = /:\w+/g;
const interpolatePath = (route, match) => {
return match.path.replace(ROUTE_KEY_PARENTHESES_RE, "$1").replace(ROUTE_KEY_SYMBOLS_RE, "$1").replace(ROUTE_KEY_NORMAL_RE, (r) => route.params[r.slice(1)]?.toString() || "");
};
export const generateRouteKey = (routeProps, override) => {
const matchedRoute = routeProps.route.matched.find((m) => m.components?.default === routeProps.Component.type);
const source = override ?? matchedRoute?.meta.key ?? (matchedRoute && interpolatePath(routeProps.route, matchedRoute));
return typeof source === "function" ? source(routeProps.route) : source;
};
export const wrapInKeepAlive = (props, children) => {
return { default: () => import.meta.client && props ? h(KeepAlive, props === true ? {} : props, children) : children };
};
export function toArray(value) {
return Array.isArray(value) ? value : [value];
}

View File

@@ -0,0 +1,2 @@
declare const _default: any;
export default _default;

View File

@@ -0,0 +1,23 @@
import { createError } from "#app/composables/error";
import { defineNuxtRouteMiddleware } from "#app/composables/router";
export default defineNuxtRouteMiddleware(async (to, from) => {
if (!to.meta?.validate) {
return;
}
const result = await Promise.resolve(to.meta.validate(to));
if (result === true) {
return;
}
const error = createError({
fatal: import.meta.client,
statusCode: result && result.statusCode || 404,
statusMessage: result && result.statusMessage || `Page Not Found: ${to.fullPath}`,
data: {
path: to.fullPath
}
});
if (typeof window !== "undefined") {
window.history.pushState({}, "", from.fullPath);
}
return error;
});