initial commit

This commit is contained in:
Zoe
2023-01-03 09:29:04 -06:00
commit 7851137d88
12889 changed files with 2557443 additions and 0 deletions
Generated Vendored
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 - Nuxt Project
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+5
View File
@@ -0,0 +1,5 @@
# Nuxt 3
> The core of Nuxt 3
Learn more about this package: <https://v3.nuxtjs.org>
Generated Vendored
+1
View File
@@ -0,0 +1 @@
export * from './dist/app'
Generated Vendored Executable
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env node
import 'nuxi/cli'
+7
View File
@@ -0,0 +1,7 @@
function defineNuxtConfig (config) {
return config
}
module.exports = {
defineNuxtConfig
}
+4
View File
@@ -0,0 +1,4 @@
import { NuxtConfig } from '@nuxt/schema'
export { NuxtConfig } from '@nuxt/schema'
export declare function defineNuxtConfig(config: NuxtConfig): NuxtConfig
+5
View File
@@ -0,0 +1,5 @@
function defineNuxtConfig (config) {
return config
}
export { defineNuxtConfig }
+4
View File
@@ -0,0 +1,4 @@
export * from 'vue';
export declare const install: () => void;
export declare function set(target: any, key: string | number | symbol, val: any): any;
export declare function del(target: any, key: string | number | symbol): void;
+19
View File
@@ -0,0 +1,19 @@
export * from "vue";
export const install = () => {
};
export function set(target, key, val) {
if (Array.isArray(target)) {
target.length = Math.max(target.length, key);
target.splice(key, 1, val);
return val;
}
target[key] = val;
return val;
}
export function del(target, key) {
if (Array.isArray(target)) {
target.splice(key, 1);
return;
}
delete target[key];
}
+4
View File
@@ -0,0 +1,4 @@
export * from './capi';
export declare const Vue2: undefined;
export declare const isVue2 = false;
export declare const isVue3 = true;
+4
View File
@@ -0,0 +1,4 @@
export * from "./capi.mjs";
export const Vue2 = void 0;
export const isVue2 = false;
export const isVue3 = true;
+22
View File
@@ -0,0 +1,22 @@
export function createClientOnly(component: any): any;
declare const _default: import("vue").DefineComponent<Readonly<{
fallback?: any;
placeholder?: any;
placeholderTag?: any;
fallbackTag?: any;
}>, (props: any) => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>[] | import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}> | undefined, any, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<Readonly<{
fallback?: any;
placeholder?: any;
placeholderTag?: any;
fallbackTag?: any;
}>>>, {
readonly fallback?: any;
readonly placeholder?: any;
readonly placeholderTag?: any;
readonly fallbackTag?: any;
}>;
export default _default;
+75
View File
@@ -0,0 +1,75 @@
import { ref, onMounted, defineComponent, createElementBlock, h, createElementVNode } from 'vue'
export default defineComponent({
name: 'ClientOnly',
inheritAttrs: false,
// eslint-disable-next-line vue/require-prop-types
props: ['fallback', 'placeholder', 'placeholderTag', 'fallbackTag'],
setup (_, { slots, attrs }) {
const mounted = ref(false)
onMounted(() => { mounted.value = true })
return (props) => {
if (mounted.value) { return slots.default?.() }
const slot = slots.fallback || slots.placeholder
if (slot) { return slot() }
const fallbackStr = props.fallback || props.placeholder || ''
const fallbackTag = props.fallbackTag || props.placeholderTag || 'span'
return createElementBlock(fallbackTag, attrs, fallbackStr)
}
}
})
const cache = new WeakMap()
export function createClientOnly (component) {
if (cache.has(component)) {
return cache.get(component)
}
const clone = { ...component }
if (clone.render) {
// override the component render (non script setup component)
clone.render = (ctx, ...args) => {
if (ctx.mounted$) {
const res = component.render(ctx, ...args)
return (res.children === null || typeof res.children === 'string')
? createElementVNode(res.type, res.props, res.children, res.patchFlag, res.dynamicProps, res.shapeFlag)
: h(res)
} else {
return h('div', ctx.$attrs ?? ctx._.attrs)
}
}
} else if (clone.template) {
// handle runtime-compiler template
clone.template = `
<template v-if="mounted$">${component.template}</template>
<template v-else><div></div></template>
`
}
clone.setup = (props, ctx) => {
const mounted$ = ref(false)
onMounted(() => { mounted$.value = true })
return Promise.resolve(component.setup?.(props, ctx) || {})
.then((setupState) => {
return typeof setupState !== 'function'
? { ...setupState, mounted$ }
: (...args) => {
if (mounted$.value) {
const res = setupState(...args)
return (res.children === null || typeof res.children === 'string')
? createElementVNode(res.type, res.props, res.children, res.patchFlag, res.dynamicProps, res.shapeFlag)
: h(res)
} else {
return h('div', ctx.attrs)
}
}
})
}
cache.set(component, clone)
return clone
}
+4
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) | (() => null), {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{}>>, {}>;
export default _default;
+11
View File
@@ -0,0 +1,11 @@
import { defineComponent } from 'vue'
export default defineComponent({
name: 'DevOnly',
setup (_, props) {
if (process.dev) {
return () => props.slots.default?.()
}
return () => null
}
})
+2
View File
@@ -0,0 +1,2 @@
export { defineNuxtLink } from './nuxt-link';
export type { NuxtLinkOptions, NuxtLinkProps } from './nuxt-link';
+1
View File
@@ -0,0 +1 @@
export { defineNuxtLink } from "./nuxt-link.mjs";
+17
View File
@@ -0,0 +1,17 @@
import { Ref, VNode } from 'vue';
declare const _default: import("vue").DefineComponent<{
name: {
type: () => string | false | Ref<string | false>;
default: null;
};
}, () => VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>, unknown, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{
name: {
type: () => string | false | Ref<string | false>;
default: null;
};
}>>, {
name: string | false | Ref<string | false>;
}>;
export default _default;
+66
View File
@@ -0,0 +1,66 @@
import { computed, defineComponent, h, inject, nextTick, onMounted, Transition, unref } from "vue";
import { _wrapIf } from "./utils.mjs";
import { useRoute } from "#app";
import { useRoute as useVueRouterRoute } from "#build/pages";
import layouts from "#build/layouts";
import { appLayoutTransition as defaultLayoutTransition } from "#build/nuxt.config.mjs";
const LayoutLoader = defineComponent({
props: {
name: String,
...process.dev ? { hasTransition: Boolean } : {}
},
async setup(props, context) {
let vnode;
if (process.dev && process.client) {
onMounted(() => {
nextTick(() => {
if (props.name && ["#comment", "#text"].includes(vnode?.el?.nodeName)) {
console.warn(`[nuxt] \`${props.name}\` layout does not have a single root node and will cause errors when navigating between routes.`);
}
});
});
}
const LayoutComponent = await layouts[props.name]().then((r) => r.default || r);
return () => {
if (process.dev && process.client && props.hasTransition) {
vnode = h(LayoutComponent, {}, context.slots);
return vnode;
}
return h(LayoutComponent, {}, context.slots);
};
}
});
export default defineComponent({
props: {
name: {
type: [String, Boolean, Object],
default: null
}
},
setup(props, context) {
const injectedRoute = inject("_route");
const route = injectedRoute === useRoute() ? useVueRouterRoute() : injectedRoute;
const layout = computed(() => unref(props.name) ?? route.meta.layout ?? "default");
let vnode;
let _layout;
if (process.dev && process.client) {
onMounted(() => {
nextTick(() => {
if (_layout && _layout in layouts && ["#comment", "#text"].includes(vnode?.el?.nodeName)) {
console.warn(`[nuxt] \`${_layout}\` layout does not have a single root node and will cause errors when navigating between routes.`);
}
});
});
}
return () => {
const hasLayout = layout.value && layout.value in layouts;
if (process.dev && layout.value && !hasLayout && layout.value !== "default") {
console.warn(`Invalid layout \`${layout.value}\` selected.`);
}
const transitionProps = route.meta.layoutTransition ?? defaultLayoutTransition;
return _wrapIf(Transition, hasLayout && transitionProps, {
default: () => _wrapIf(LayoutLoader, hasLayout && { key: layout.value, name: layout.value, hasTransition: process.dev ? !!transitionProps : void 0 }, context.slots).default()
}).default();
};
}
});
+8
View File
@@ -0,0 +1,8 @@
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, {
error(_error: unknown): boolean;
}, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{}>> & {
onError?: ((_error: unknown) => any) | undefined;
}, {}>;
export default _default;
+21
View File
@@ -0,0 +1,21 @@
import { defineComponent, ref, onErrorCaptured } from "vue";
import { useNuxtApp } from "#app";
export default defineComponent({
emits: {
error(_error) {
return true;
}
},
setup(_props, { slots, emit }) {
const error = ref(null);
const nuxtApp = useNuxtApp();
onErrorCaptured((err) => {
if (process.client && !nuxtApp.isHydrating) {
emit("error", err);
error.value = err;
return false;
}
});
return () => error.value ? slots.error?.({ error }) : slots.default?.();
}
});
+46
View File
@@ -0,0 +1,46 @@
<template>
<ErrorTemplate v-bind="{ statusCode, statusMessage, description, stack }" />
</template>
<script setup>
import { defineAsyncComponent } from 'vue'
// Deliberately prevent reactive update when error is cleared
// eslint-disable-next-line vue/no-setup-props-destructure
const { error } = defineProps({
error: Object
})
// TODO: extract to a separate utility
const stacktrace = (error.stack || '')
.split('\n')
.splice(1)
.map((line) => {
const text = line
.replace('webpack:/', '')
.replace('.vue', '.js') // TODO: Support sourcemap
.trim()
return {
text,
internal: (line.includes('node_modules') && !line.includes('.cache')) ||
line.includes('internal') ||
line.includes('new Promise')
}
}).map(i => `<span class="stack${i.internal ? ' internal' : ''}">${i.text}</span>`).join('\n')
// Error page props
const statusCode = Number(error.statusCode || 500)
const is404 = statusCode === 404
const statusMessage = error.statusMessage ?? (is404 ? 'Page Not Found' : 'Internal Server Error')
const description = error.message || error.toString()
const stack = process.dev && !is404 ? error.description || `<pre>${stacktrace}</pre>` : undefined
// TODO: Investigate side-effect issue with imports
const _Error404 = defineAsyncComponent(() => import('@nuxt/ui-templates/templates/error-404.vue').then(r => r.default || r))
const _Error = process.dev
? defineAsyncComponent(() => import('@nuxt/ui-templates/templates/error-dev.vue').then(r => r.default || r))
: defineAsyncComponent(() => import('@nuxt/ui-templates/templates/error-500.vue').then(r => r.default || r))
const ErrorTemplate = is404 ? _Error404 : _Error
</script>
+27
View File
@@ -0,0 +1,27 @@
import { DefineComponent } from 'vue';
import type { RouteLocationRaw } from 'vue-router';
export type NuxtLinkOptions = {
componentName?: string;
externalRelAttribute?: string | null;
activeClass?: string;
exactActiveClass?: string;
prefetchedClass?: string;
};
export type NuxtLinkProps = {
to?: string | RouteLocationRaw;
href?: string | RouteLocationRaw;
external?: boolean;
replace?: boolean;
custom?: boolean;
target?: '_blank' | '_parent' | '_self' | '_top' | (string & {}) | null;
rel?: string | null;
noRel?: boolean;
prefetch?: boolean;
noPrefetch?: boolean;
activeClass?: string;
exactActiveClass?: string;
ariaCurrentValue?: string;
};
export declare function defineNuxtLink(options: NuxtLinkOptions): DefineComponent<NuxtLinkProps, {}, {}, import("vue").ComputedOptions, import("vue").MethodOptions, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<NuxtLinkProps>, {}>;
declare const _default: DefineComponent<NuxtLinkProps, {}, {}, import("vue").ComputedOptions, import("vue").MethodOptions, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<NuxtLinkProps>, {}>;
export default _default;
+248
View File
@@ -0,0 +1,248 @@
import { defineComponent, h, ref, resolveComponent, computed, onMounted, onBeforeUnmount } from "vue";
import { hasProtocol } from "ufo";
import { preloadRouteComponents } from "../composables/preload.mjs";
import { navigateTo, useRouter } from "../composables/router.mjs";
import { useNuxtApp } from "../nuxt.mjs";
const firstNonUndefined = (...args) => args.find((arg) => arg !== void 0);
const DEFAULT_EXTERNAL_REL_ATTRIBUTE = "noopener noreferrer";
const requestIdleCallback = process.server ? void 0 : globalThis.requestIdleCallback || ((cb) => {
const start = Date.now();
const idleDeadline = {
didTimeout: false,
timeRemaining: () => Math.max(0, 50 - (Date.now() - start))
};
return setTimeout(() => {
cb(idleDeadline);
}, 1);
});
const cancelIdleCallback = process.server ? null : globalThis.cancelIdleCallback || ((id) => {
clearTimeout(id);
});
export function defineNuxtLink(options) {
const componentName = options.componentName || "NuxtLink";
const checkPropConflicts = (props, main, sub) => {
if (process.dev && props[main] !== void 0 && props[sub] !== void 0) {
console.warn(`[${componentName}] \`${main}\` and \`${sub}\` cannot be used together. \`${sub}\` will be ignored.`);
}
};
return defineComponent({
name: componentName,
props: {
to: {
type: [String, Object],
default: void 0,
required: false
},
href: {
type: [String, Object],
default: void 0,
required: false
},
target: {
type: String,
default: void 0,
required: false
},
rel: {
type: String,
default: void 0,
required: false
},
noRel: {
type: Boolean,
default: void 0,
required: false
},
prefetch: {
type: Boolean,
default: void 0,
required: false
},
noPrefetch: {
type: Boolean,
default: void 0,
required: false
},
activeClass: {
type: String,
default: void 0,
required: false
},
exactActiveClass: {
type: String,
default: void 0,
required: false
},
prefetchedClass: {
type: String,
default: void 0,
required: false
},
replace: {
type: Boolean,
default: void 0,
required: false
},
ariaCurrentValue: {
type: String,
default: void 0,
required: false
},
external: {
type: Boolean,
default: void 0,
required: false
},
custom: {
type: Boolean,
default: void 0,
required: false
}
},
setup(props, { slots }) {
const router = useRouter();
const to = computed(() => {
checkPropConflicts(props, "to", "href");
return props.to || props.href || "";
});
const isExternal = computed(() => {
if (props.external) {
return true;
}
if (props.target && props.target !== "_self") {
return true;
}
if (typeof to.value === "object") {
return false;
}
return to.value === "" || hasProtocol(to.value, true);
});
const prefetched = ref(false);
const el = process.server ? void 0 : ref(null);
if (process.client) {
checkPropConflicts(props, "prefetch", "noPrefetch");
const shouldPrefetch = props.prefetch !== false && props.noPrefetch !== true && typeof to.value === "string" && props.target !== "_blank" && !isSlowConnection();
if (shouldPrefetch) {
const nuxtApp = useNuxtApp();
const observer = useObserver();
let idleId;
let unobserve = null;
onMounted(() => {
idleId = requestIdleCallback(() => {
if (el?.value?.tagName) {
unobserve = observer.observe(el.value, async () => {
unobserve?.();
unobserve = null;
await Promise.all([
nuxtApp.hooks.callHook("link:prefetch", to.value).catch(() => {
}),
!isExternal.value && preloadRouteComponents(to.value, router).catch(() => {
})
]);
prefetched.value = true;
});
}
});
});
onBeforeUnmount(() => {
if (idleId) {
cancelIdleCallback(idleId);
}
unobserve?.();
unobserve = null;
});
}
}
return () => {
if (!isExternal.value) {
return h(
resolveComponent("RouterLink"),
{
ref: process.server ? void 0 : (ref2) => {
el.value = ref2?.$el;
},
to: to.value,
...prefetched.value && !props.custom ? { class: props.prefetchedClass || options.prefetchedClass } : {},
activeClass: props.activeClass || options.activeClass,
exactActiveClass: props.exactActiveClass || options.exactActiveClass,
replace: props.replace,
ariaCurrentValue: props.ariaCurrentValue,
custom: props.custom
},
slots.default
);
}
const href = typeof to.value === "object" ? router.resolve(to.value)?.href ?? null : to.value || null;
const target = props.target || null;
checkPropConflicts(props, "noRel", "rel");
const rel = props.noRel ? null : firstNonUndefined(props.rel, options.externalRelAttribute, href ? DEFAULT_EXTERNAL_REL_ATTRIBUTE : "") || null;
const navigate = () => navigateTo(href, { replace: props.replace });
if (props.custom) {
if (!slots.default) {
return null;
}
return slots.default({
href,
navigate,
route: router.resolve(href),
rel,
target,
isExternal: isExternal.value,
isActive: false,
isExactActive: false
});
}
return h("a", { ref: el, href, rel, target }, slots.default?.());
};
}
});
}
export default defineNuxtLink({ componentName: "NuxtLink" });
function useObserver() {
if (process.server) {
return;
}
const nuxtApp = useNuxtApp();
if (nuxtApp._observer) {
return nuxtApp._observer;
}
let observer = null;
const callbacks = /* @__PURE__ */ new Map();
const observe = (element, callback) => {
if (!observer) {
observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
const callback2 = callbacks.get(entry.target);
const isVisible = entry.isIntersecting || entry.intersectionRatio > 0;
if (isVisible && callback2) {
callback2();
}
}
});
}
callbacks.set(element, callback);
observer.observe(element);
return () => {
callbacks.delete(element);
observer.unobserve(element);
if (callbacks.size === 0) {
observer.disconnect();
observer = null;
}
};
};
const _observer = nuxtApp._observer = {
observe
};
return _observer;
}
function isSlowConnection() {
if (process.server) {
return;
}
const cn = navigator.connection;
if (cn && (cn.saveData || /2g/.test(cn.effectiveType))) {
return true;
}
return false;
}
+43
View File
@@ -0,0 +1,43 @@
declare const _default: import("vue").DefineComponent<{
throttle: {
type: NumberConstructor;
default: number;
};
duration: {
type: NumberConstructor;
default: number;
};
height: {
type: NumberConstructor;
default: number;
};
color: {
type: StringConstructor;
default: string;
};
}, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>, unknown, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{
throttle: {
type: NumberConstructor;
default: number;
};
duration: {
type: NumberConstructor;
default: number;
};
height: {
type: NumberConstructor;
default: number;
};
color: {
type: StringConstructor;
default: string;
};
}>>, {
throttle: number;
duration: number;
height: number;
color: string;
}>;
export default _default;
+107
View File
@@ -0,0 +1,107 @@
import { computed, defineComponent, h, onBeforeUnmount, ref } from "vue";
import { useNuxtApp } from "#app";
export default defineComponent({
name: "NuxtLoadingIndicator",
props: {
throttle: {
type: Number,
default: 200
},
duration: {
type: Number,
default: 2e3
},
height: {
type: Number,
default: 3
},
color: {
type: String,
default: "repeating-linear-gradient(to right,#00dc82 0%,#34cdfe 50%,#0047e1 100%)"
}
},
setup(props, { slots }) {
const indicator = useLoadingIndicator({
duration: props.duration,
throttle: props.throttle
});
const nuxtApp = useNuxtApp();
nuxtApp.hook("page:start", indicator.start);
nuxtApp.hook("page:finish", indicator.finish);
onBeforeUnmount(() => indicator.clear);
return () => h("div", {
class: "nuxt-loading-indicator",
style: {
position: "fixed",
top: 0,
right: 0,
left: 0,
pointerEvents: "none",
width: `${indicator.progress.value}%`,
height: `${props.height}px`,
opacity: indicator.isLoading.value ? 1 : 0,
background: props.color,
backgroundSize: `${100 / indicator.progress.value * 100}% auto`,
transition: "width 0.1s, height 0.4s, opacity 0.4s",
zIndex: 999999
}
}, slots);
}
});
function useLoadingIndicator(opts) {
const progress = ref(0);
const isLoading = ref(false);
const step = computed(() => 1e4 / opts.duration);
let _timer = null;
let _throttle = null;
function start() {
clear();
progress.value = 0;
isLoading.value = true;
if (opts.throttle) {
if (process.client) {
_throttle = setTimeout(_startTimer, opts.throttle);
}
} else {
_startTimer();
}
}
function finish() {
progress.value = 100;
_hide();
}
function clear() {
clearInterval(_timer);
clearTimeout(_throttle);
_timer = null;
_throttle = null;
}
function _increase(num) {
progress.value = Math.min(100, progress.value + num);
}
function _hide() {
clear();
if (process.client) {
setTimeout(() => {
isLoading.value = false;
setTimeout(() => {
progress.value = 0;
}, 400);
}, 500);
}
}
function _startTimer() {
if (process.client) {
_timer = setInterval(() => {
_increase(step.value);
}, 100);
}
}
return {
progress,
isLoading,
start,
finish,
clear
};
}
+35
View File
@@ -0,0 +1,35 @@
<template>
<Suspense @resolve="onResolve">
<ErrorComponent v-if="error" :error="error" />
<AppComponent v-else />
</Suspense>
</template>
<script setup>
import { defineAsyncComponent, onErrorCaptured, provide } from 'vue'
import { callWithNuxt, isNuxtError, showError, useError, useRoute, useNuxtApp } from '#app'
import AppComponent from '#build/app-component.mjs'
const ErrorComponent = defineAsyncComponent(() => import('#build/error-component.mjs').then(r => r.default || r))
const nuxtApp = useNuxtApp()
const onResolve = nuxtApp.deferHydration()
// Inject default route (outside of pages) as active route
provide('_route', useRoute())
// vue:setup hook
const results = nuxtApp.hooks.callHookWith(hooks => hooks.map(hook => hook()), 'vue:setup')
if (process.dev && results && results.some(i => i && 'then' in i)) {
console.error('[nuxt] Error in `vue:setup`. Callbacks must be synchronous.')
}
// error handling
const error = useError()
onErrorCaptured((err, target, info) => {
nuxtApp.hooks.callHook('vue:error', err, target, info).catch(hookError => console.error('[nuxt] Error in `vue:error` hook', hookError))
if (process.server || (isNuxtError(err) && (err.fatal || err.unhandled))) {
callWithNuxt(nuxtApp, showError, [err])
}
})
</script>
+2
View File
@@ -0,0 +1,2 @@
declare const _default: import("vue").DefineComponent<{}, {}, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{}>>, {}>;
export default _default;
+7
View File
@@ -0,0 +1,7 @@
import { defineComponent, createElementBlock } from "vue";
export default defineComponent({
name: "ServerPlaceholder",
render() {
return createElementBlock("div");
}
});
+11
View File
@@ -0,0 +1,11 @@
import type { Component } from 'vue';
/**
* Internal utility
*
* @private
*/
export declare const _wrapIf: (component: Component, props: any, slots: any) => {
default: () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>;
};
+9
View File
@@ -0,0 +1,9 @@
import { defineComponent, h } from "vue";
const Fragment = defineComponent({
setup(_props, { slots }) {
return () => slots.default?.();
}
});
export const _wrapIf = (component, props, slots) => {
return { default: () => props ? h(component, props === true ? {} : props, slots) : h(Fragment, {}, slots) };
};
+40
View File
@@ -0,0 +1,40 @@
import type { Ref, WatchSource } from 'vue';
import { NuxtApp } from '../nuxt';
export type _Transform<Input = any, Output = any> = (input: Input) => Output;
export type PickFrom<T, K extends Array<string>> = T extends Array<any> ? T : T extends Record<string, any> ? keyof T extends K[number] ? T : Pick<T, K[number]> : T;
export type KeysOf<T> = Array<T extends T ? keyof T extends string ? keyof T : string : never>;
export type KeyOfRes<Transform extends _Transform> = KeysOf<ReturnType<Transform>>;
type MultiWatchSources = (WatchSource<unknown> | object)[];
export interface AsyncDataOptions<DataT, Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>, PickKeys extends KeyOfRes<_Transform> = KeyOfRes<Transform>> {
server?: boolean;
lazy?: boolean;
default?: () => DataT | Ref<DataT> | null;
transform?: Transform;
pick?: PickKeys;
watch?: MultiWatchSources;
immediate?: boolean;
}
export interface AsyncDataExecuteOptions {
_initial?: boolean;
/**
* Force a refresh, even if there is already a pending request. Previous requests will
* not be cancelled, but their result will not affect the data/pending state - and any
* previously awaited promises will not resolve until this new request resolves.
*/
dedupe?: boolean;
}
export interface _AsyncData<DataT, ErrorT> {
data: Ref<DataT | null>;
pending: Ref<boolean>;
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>;
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>;
error: Ref<ErrorT | null>;
}
export type AsyncData<Data, Error> = _AsyncData<Data, Error> & Promise<_AsyncData<Data, Error>>;
export declare function useAsyncData<DataT, DataE = Error, Transform extends _Transform<DataT> = _Transform<DataT, DataT>, PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>>(handler: (ctx?: NuxtApp) => Promise<DataT>, options?: AsyncDataOptions<DataT, Transform, PickKeys>): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>;
export declare function useAsyncData<DataT, DataE = Error, Transform extends _Transform<DataT> = _Transform<DataT, DataT>, PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>>(key: string, handler: (ctx?: NuxtApp) => Promise<DataT>, options?: AsyncDataOptions<DataT, Transform, PickKeys>): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>;
export declare function useLazyAsyncData<DataT, DataE = Error, Transform extends _Transform<DataT> = _Transform<DataT, DataT>, PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>>(handler: (ctx?: NuxtApp) => Promise<DataT>, options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>;
export declare function useLazyAsyncData<DataT, DataE = Error, Transform extends _Transform<DataT> = _Transform<DataT, DataT>, PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>>(key: string, handler: (ctx?: NuxtApp) => Promise<DataT>, options?: Omit<AsyncDataOptions<DataT, Transform, PickKeys>, 'lazy'>): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null>;
export declare function refreshNuxtData(keys?: string | string[]): Promise<void>;
export declare function clearNuxtData(keys?: string | string[] | ((key: string) => boolean)): void;
export {};
+169
View File
@@ -0,0 +1,169 @@
import { onBeforeMount, onServerPrefetch, onUnmounted, ref, getCurrentInstance, watch, unref } from "vue";
import { useNuxtApp } from "../nuxt.mjs";
import { createError } from "./error.mjs";
const getDefault = () => null;
export function useAsyncData(...args) {
const autoKey = typeof args[args.length - 1] === "string" ? args.pop() : void 0;
if (typeof args[0] !== "string") {
args.unshift(autoKey);
}
let [key, handler, options = {}] = args;
if (typeof key !== "string") {
throw new TypeError("[nuxt] [asyncData] key must be a string.");
}
if (typeof handler !== "function") {
throw new TypeError("[nuxt] [asyncData] handler must be a function.");
}
options.server = options.server ?? true;
options.default = options.default ?? getDefault;
options.lazy = options.lazy ?? false;
options.immediate = options.immediate ?? true;
const nuxt = useNuxtApp();
const getCachedData = () => nuxt.isHydrating ? nuxt.payload.data[key] : nuxt.static.data[key];
const hasCachedData = () => getCachedData() !== void 0;
if (!nuxt._asyncData[key]) {
nuxt._asyncData[key] = {
data: ref(getCachedData() ?? options.default?.() ?? null),
pending: ref(!hasCachedData()),
error: ref(nuxt.payload._errors[key] ? createError(nuxt.payload._errors[key]) : null)
};
}
const asyncData = { ...nuxt._asyncData[key] };
asyncData.refresh = asyncData.execute = (opts = {}) => {
if (nuxt._asyncDataPromises[key]) {
if (opts.dedupe === false) {
return nuxt._asyncDataPromises[key];
}
nuxt._asyncDataPromises[key].cancelled = true;
}
if (opts._initial && hasCachedData()) {
return getCachedData();
}
asyncData.pending.value = true;
const promise = new Promise(
(resolve, reject) => {
try {
resolve(handler(nuxt));
} catch (err) {
reject(err);
}
}
).then((result) => {
if (promise.cancelled) {
return nuxt._asyncDataPromises[key];
}
if (options.transform) {
result = options.transform(result);
}
if (options.pick) {
result = pick(result, options.pick);
}
asyncData.data.value = result;
asyncData.error.value = null;
}).catch((error) => {
if (promise.cancelled) {
return nuxt._asyncDataPromises[key];
}
asyncData.error.value = error;
asyncData.data.value = unref(options.default?.() ?? null);
}).finally(() => {
if (promise.cancelled) {
return;
}
asyncData.pending.value = false;
nuxt.payload.data[key] = asyncData.data.value;
if (asyncData.error.value) {
nuxt.payload._errors[key] = createError(asyncData.error.value);
}
delete nuxt._asyncDataPromises[key];
});
nuxt._asyncDataPromises[key] = promise;
return nuxt._asyncDataPromises[key];
};
const initialFetch = () => asyncData.refresh({ _initial: true });
const fetchOnServer = options.server !== false && nuxt.payload.serverRendered;
if (process.server && fetchOnServer && options.immediate) {
const promise = initialFetch();
onServerPrefetch(() => promise);
}
if (process.client) {
const instance = getCurrentInstance();
if (instance && !instance._nuxtOnBeforeMountCbs) {
instance._nuxtOnBeforeMountCbs = [];
const cbs = instance._nuxtOnBeforeMountCbs;
if (instance) {
onBeforeMount(() => {
cbs.forEach((cb) => {
cb();
});
cbs.splice(0, cbs.length);
});
onUnmounted(() => cbs.splice(0, cbs.length));
}
}
if (fetchOnServer && nuxt.isHydrating && hasCachedData()) {
asyncData.pending.value = false;
} else if (instance && (nuxt.payload.serverRendered && nuxt.isHydrating || options.lazy) && options.immediate) {
instance._nuxtOnBeforeMountCbs.push(initialFetch);
} else if (options.immediate) {
initialFetch();
}
if (options.watch) {
watch(options.watch, () => asyncData.refresh());
}
const off = nuxt.hook("app:data:refresh", (keys) => {
if (!keys || keys.includes(key)) {
return asyncData.refresh();
}
});
if (instance) {
onUnmounted(off);
}
}
const asyncDataPromise = Promise.resolve(nuxt._asyncDataPromises[key]).then(() => asyncData);
Object.assign(asyncDataPromise, asyncData);
return asyncDataPromise;
}
export function useLazyAsyncData(...args) {
const autoKey = typeof args[args.length - 1] === "string" ? args.pop() : void 0;
if (typeof args[0] !== "string") {
args.unshift(autoKey);
}
const [key, handler, options] = args;
return useAsyncData(key, handler, { ...options, lazy: true }, null);
}
export async function refreshNuxtData(keys) {
if (process.server) {
return Promise.resolve();
}
const _keys = keys ? Array.isArray(keys) ? keys : [keys] : void 0;
await useNuxtApp().hooks.callHookParallel("app:data:refresh", _keys);
}
export function clearNuxtData(keys) {
const nuxtApp = useNuxtApp();
const _allKeys = Object.keys(nuxtApp.payload.data);
const _keys = !keys ? _allKeys : typeof keys === "function" ? _allKeys.filter(keys) : Array.isArray(keys) ? keys : [keys];
for (const key of _keys) {
if (key in nuxtApp.payload.data) {
nuxtApp.payload.data[key] = void 0;
}
if (key in nuxtApp.payload._errors) {
nuxtApp.payload._errors[key] = void 0;
}
if (nuxtApp._asyncData[key]) {
nuxtApp._asyncData[key].data.value = void 0;
nuxtApp._asyncData[key].error.value = void 0;
nuxtApp._asyncData[key].pending.value = false;
}
if (key in nuxtApp._asyncDataPromises) {
nuxtApp._asyncDataPromises[key] = void 0;
}
}
}
function pick(obj, keys) {
const newObj = {};
for (const key of keys) {
newObj[key] = obj[key];
}
return newObj;
}
+3
View File
@@ -0,0 +1,3 @@
import { defineComponent } from 'vue';
export declare const NuxtComponentIndicator = "__nuxt_component";
export declare const defineNuxtComponent: typeof defineComponent;
+46
View File
@@ -0,0 +1,46 @@
import { getCurrentInstance, reactive, toRefs } from "vue";
import { useNuxtApp } from "../nuxt.mjs";
import { useAsyncData } from "./asyncData.mjs";
import { useRoute } from "./router.mjs";
import { useHead } from "#head";
export const NuxtComponentIndicator = "__nuxt_component";
async function runLegacyAsyncData(res, fn) {
const nuxt = useNuxtApp();
const route = useRoute();
const vm = getCurrentInstance();
const { fetchKey } = vm.proxy.$options;
const key = typeof fetchKey === "function" ? fetchKey(() => "") : fetchKey || route.fullPath;
const { data } = await useAsyncData(`options:asyncdata:${key}`, () => fn(nuxt));
if (data.value && typeof data.value === "object") {
Object.assign(await res, toRefs(reactive(data.value)));
} else if (process.dev) {
console.warn("[nuxt] asyncData should return an object", data);
}
}
export const defineNuxtComponent = function defineNuxtComponent2(options) {
const { setup } = options;
if (!setup && !options.asyncData && !options.head) {
return {
[NuxtComponentIndicator]: true,
...options
};
}
return {
[NuxtComponentIndicator]: true,
...options,
setup(props, ctx) {
const res = setup?.(props, ctx) || {};
const promises = [];
if (options.asyncData) {
promises.push(runLegacyAsyncData(res, options.asyncData));
}
if (options.head) {
const nuxtApp = useNuxtApp();
useHead(typeof options.head === "function" ? () => options.head(nuxtApp) : options.head);
}
return Promise.resolve(res).then(() => Promise.all(promises)).then(() => res).finally(() => {
promises.length = 0;
});
}
};
};
+12
View File
@@ -0,0 +1,12 @@
import { Ref } from 'vue';
import { CookieParseOptions, CookieSerializeOptions } from 'cookie-es';
type _CookieOptions = Omit<CookieSerializeOptions & CookieParseOptions, 'decode' | 'encode'>;
export interface CookieOptions<T = any> extends _CookieOptions {
decode?(value: string): T;
encode?(value: T): string;
default?: () => T | Ref<T>;
}
export interface CookieRef<T> extends Ref<T | null> {
}
export declare function useCookie<T = string>(name: string, _opts?: CookieOptions<T>): CookieRef<T>;
export {};
+58
View File
@@ -0,0 +1,58 @@
import { ref, watch } from "vue";
import { parse, serialize } from "cookie-es";
import { appendHeader } from "h3";
import destr from "destr";
import { isEqual } from "ohash";
import { useNuxtApp } from "../nuxt.mjs";
import { useRequestEvent } from "./ssr.mjs";
const CookieDefaults = {
path: "/",
decode: (val) => destr(decodeURIComponent(val)),
encode: (val) => encodeURIComponent(typeof val === "string" ? val : JSON.stringify(val))
};
export function useCookie(name, _opts) {
const opts = { ...CookieDefaults, ..._opts };
const cookies = readRawCookies(opts) || {};
const cookie = ref(cookies[name] ?? opts.default?.());
if (process.client) {
watch(cookie, () => {
writeClientCookie(name, cookie.value, opts);
});
} else if (process.server) {
const nuxtApp = useNuxtApp();
const writeFinalCookieValue = () => {
if (!isEqual(cookie.value, cookies[name])) {
writeServerCookie(useRequestEvent(nuxtApp), name, cookie.value, opts);
}
};
const unhook = nuxtApp.hooks.hookOnce("app:rendered", writeFinalCookieValue);
nuxtApp.hooks.hookOnce("app:redirected", () => {
unhook();
return writeFinalCookieValue();
});
}
return cookie;
}
function readRawCookies(opts = {}) {
if (process.server) {
return parse(useRequestEvent()?.req.headers.cookie || "", opts);
} else if (process.client) {
return parse(document.cookie, opts);
}
}
function serializeCookie(name, value, opts = {}) {
if (value === null || value === void 0) {
return serialize(name, value, { ...opts, maxAge: -1 });
}
return serialize(name, value, opts);
}
function writeClientCookie(name, value, opts = {}) {
if (process.client) {
document.cookie = serializeCookie(name, value, opts);
}
}
function writeServerCookie(event, name, value, opts = {}) {
if (event) {
appendHeader(event, "Set-Cookie", serializeCookie(name, value, opts));
}
}
+17
View File
@@ -0,0 +1,17 @@
import { H3Error } from 'h3';
export declare const useError: () => import("vue").Ref<Error | {
url: string;
statusCode: string;
statusMessage: string;
message: string;
description: string;
data?: any;
} | null | undefined>;
export interface NuxtError extends H3Error {
}
export declare const showError: (_err: string | Error | Partial<NuxtError>) => NuxtError;
export declare const clearError: (options?: {
redirect?: string;
}) => Promise<void>;
export declare const isNuxtError: (err?: string | object) => err is NuxtError;
export declare const createError: (err: string | Partial<NuxtError>) => NuxtError;
+31
View File
@@ -0,0 +1,31 @@
import { createError as _createError } from "h3";
import { toRef } from "vue";
import { useNuxtApp } from "../nuxt.mjs";
export const useError = () => toRef(useNuxtApp().payload, "error");
export const showError = (_err) => {
const err = createError(_err);
try {
const nuxtApp = useNuxtApp();
nuxtApp.callHook("app:error", err);
const error = useError();
error.value = error.value || err;
} catch {
throw err;
}
return err;
};
export const clearError = async (options = {}) => {
const nuxtApp = useNuxtApp();
const error = useError();
nuxtApp.callHook("app:error:cleared", options);
if (options.redirect) {
await nuxtApp.$router.replace(options.redirect);
}
error.value = null;
};
export const isNuxtError = (err) => !!(err && typeof err === "object" && "__nuxt_error" in err);
export const createError = (err) => {
const _err = _createError(err);
_err.__nuxt_error = true;
return _err;
};
+15
View File
@@ -0,0 +1,15 @@
import type { FetchError, FetchOptions } from 'ofetch';
import type { TypedInternalResponse, NitroFetchRequest } from 'nitropack';
import { Ref } from 'vue';
import type { AsyncDataOptions, _Transform, KeyOfRes, AsyncData, PickFrom } from './asyncData';
export type FetchResult<ReqT extends NitroFetchRequest> = TypedInternalResponse<ReqT, unknown>;
type ComputedOptions<T extends Record<string, any>> = {
[K in keyof T]: T[K] extends Function ? T[K] : T[K] extends Record<string, any> ? ComputedOptions<T[K]> | Ref<T[K]> | T[K] : Ref<T[K]> | T[K];
};
type ComputedFetchOptions = ComputedOptions<FetchOptions>;
export interface UseFetchOptions<DataT, Transform extends _Transform<DataT, any> = _Transform<DataT, DataT>, PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>> extends AsyncDataOptions<DataT, Transform, PickKeys>, ComputedFetchOptions {
key?: string;
}
export declare function useFetch<ResT = void, ErrorT = FetchError, ReqT extends NitroFetchRequest = NitroFetchRequest, _ResT = ResT extends void ? FetchResult<ReqT> : ResT, Transform extends (res: _ResT) => any = (res: _ResT) => _ResT, PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>>(request: Ref<ReqT> | ReqT | (() => ReqT), opts?: UseFetchOptions<_ResT, Transform, PickKeys>): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null>;
export declare function useLazyFetch<ResT = void, ErrorT = FetchError, ReqT extends NitroFetchRequest = NitroFetchRequest, _ResT = ResT extends void ? FetchResult<ReqT> : ResT, Transform extends (res: _ResT) => any = (res: _ResT) => _ResT, PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>>(request: Ref<ReqT> | ReqT | (() => ReqT), opts?: Omit<UseFetchOptions<_ResT, Transform, PickKeys>, 'lazy'>): AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, ErrorT | null>;
export {};
+66
View File
@@ -0,0 +1,66 @@
import { computed, unref, reactive } from "vue";
import { hash } from "ohash";
import { useAsyncData } from "./asyncData.mjs";
export function useFetch(request, arg1, arg2) {
const [opts = {}, autoKey] = typeof arg1 === "string" ? [{}, arg1] : [arg1, arg2];
const _key = opts.key || hash([autoKey, unref(opts.baseURL), typeof request === "string" ? request : "", unref(opts.params)]);
if (!_key || typeof _key !== "string") {
throw new TypeError("[nuxt] [useFetch] key must be a string: " + _key);
}
if (!request) {
throw new Error("[nuxt] [useFetch] request is missing.");
}
const key = _key === autoKey ? "$f" + _key : _key;
const _request = computed(() => {
let r = request;
if (typeof r === "function") {
r = r();
}
return unref(r);
});
const {
server,
lazy,
default: defaultFn,
transform,
pick,
watch,
immediate,
...fetchOptions
} = opts;
const _fetchOptions = reactive({
...fetchOptions,
cache: typeof opts.cache === "boolean" ? void 0 : opts.cache
});
const _asyncDataOptions = {
server,
lazy,
default: defaultFn,
transform,
pick,
immediate,
watch: [
_fetchOptions,
_request,
...watch || []
]
};
let controller;
const asyncData = useAsyncData(key, () => {
controller?.abort?.();
controller = typeof AbortController !== "undefined" ? new AbortController() : {};
return $fetch(_request.value, { signal: controller.signal, ..._fetchOptions });
}, _asyncDataOptions);
return asyncData;
}
export function useLazyFetch(request, arg1, arg2) {
const [opts, autoKey] = typeof arg1 === "string" ? [{}, arg1] : [arg1, arg2];
return useFetch(
request,
{
...opts,
lazy: true
},
autoKey
);
}
+8
View File
@@ -0,0 +1,8 @@
/**
* Allows full control of the hydration cycle to set and receive data from the server.
*
* @param key a unique key to identify the data in the Nuxt payload
* @param get a function that returns the value to set the initial data
* @param set a function that will receive the data on the client-side
*/
export declare const useHydration: <T>(key: string, get: () => T, set: (value: T) => void) => void;
+14
View File
@@ -0,0 +1,14 @@
import { useNuxtApp } from "../nuxt.mjs";
export const useHydration = (key, get, set) => {
const nuxt = useNuxtApp();
if (process.server) {
nuxt.hooks.hook("app:rendered", () => {
nuxt.payload[key] = get();
});
}
if (process.client) {
nuxt.hooks.hook("app:created", () => {
set(nuxt.payload[key]);
});
}
};
+16
View File
@@ -0,0 +1,16 @@
export { defineNuxtComponent } from './component';
export { useAsyncData, useLazyAsyncData, refreshNuxtData, clearNuxtData } from './asyncData';
export type { AsyncDataOptions, AsyncData } from './asyncData';
export { useHydration } from './hydrate';
export { useState } from './state';
export { clearError, createError, isNuxtError, showError, useError } from './error';
export type { NuxtError } from './error';
export { useFetch, useLazyFetch } from './fetch';
export type { FetchResult, UseFetchOptions } from './fetch';
export { useCookie } from './cookie';
export type { CookieOptions, CookieRef } from './cookie';
export { useRequestHeaders, useRequestEvent, setResponseStatus } from './ssr';
export { abortNavigation, addRouteMiddleware, defineNuxtRouteMiddleware, onBeforeRouteLeave, onBeforeRouteUpdate, setPageLayout, navigateTo, useRoute, useRouter } from './router';
export type { AddRouteMiddlewareOptions, RouteMiddleware } from './router';
export { preloadComponents, prefetchComponents, preloadRouteComponents } from './preload';
export { isPrerendered, loadPayload, preloadPayload } from './payload';
+11
View File
@@ -0,0 +1,11 @@
export { defineNuxtComponent } from "./component.mjs";
export { useAsyncData, useLazyAsyncData, refreshNuxtData, clearNuxtData } from "./asyncData.mjs";
export { useHydration } from "./hydrate.mjs";
export { useState } from "./state.mjs";
export { clearError, createError, isNuxtError, showError, useError } from "./error.mjs";
export { useFetch, useLazyFetch } from "./fetch.mjs";
export { useCookie } from "./cookie.mjs";
export { useRequestHeaders, useRequestEvent, setResponseStatus } from "./ssr.mjs";
export { abortNavigation, addRouteMiddleware, defineNuxtRouteMiddleware, onBeforeRouteLeave, onBeforeRouteUpdate, setPageLayout, navigateTo, useRoute, useRouter } from "./router.mjs";
export { preloadComponents, prefetchComponents, preloadRouteComponents } from "./preload.mjs";
export { isPrerendered, loadPayload, preloadPayload } from "./payload.mjs";
+8
View File
@@ -0,0 +1,8 @@
interface LoadPayloadOptions {
fresh?: boolean;
hash?: string;
}
export declare function loadPayload(url: string, opts?: LoadPayloadOptions): any;
export declare function preloadPayload(url: string, opts?: LoadPayloadOptions): void;
export declare function isPrerendered(): boolean;
export {};
+58
View File
@@ -0,0 +1,58 @@
import { joinURL } from "ufo";
import { useNuxtApp } from "../nuxt.mjs";
import { useHead, useRuntimeConfig } from "../index.mjs";
export function loadPayload(url, opts = {}) {
if (process.server) {
return null;
}
const payloadURL = _getPayloadURL(url, opts);
const nuxtApp = useNuxtApp();
const cache = nuxtApp._payloadCache = nuxtApp._payloadCache || {};
if (cache[url]) {
return cache[url];
}
cache[url] = _importPayload(payloadURL).then((payload) => {
if (!payload) {
delete cache[url];
return null;
}
return payload;
});
return cache[url];
}
export function preloadPayload(url, opts = {}) {
const payloadURL = _getPayloadURL(url, opts);
useHead({
link: [
{ rel: "modulepreload", href: payloadURL }
]
});
}
function _getPayloadURL(url, opts = {}) {
const u = new URL(url, "http://localhost");
if (u.search) {
throw new Error("Payload URL cannot contain search params: " + url);
}
if (u.host !== "localhost") {
throw new Error("Payload URL cannot contain host: " + url);
}
const hash = opts.hash || (opts.fresh ? Date.now() : "");
return joinURL(useRuntimeConfig().app.baseURL, u.pathname, hash ? `_payload.${hash}.js` : "_payload.js");
}
async function _importPayload(payloadURL) {
if (process.server) {
return null;
}
const res = await import(
/* webpackIgnore: true */
/* @vite-ignore */
payloadURL
).catch((err) => {
console.warn("[nuxt] Cannot load payload ", payloadURL, err);
});
return res?.default || null;
}
export function isPrerendered() {
const nuxtApp = useNuxtApp();
return !!nuxtApp.payload.prerenderedAt;
}
+17
View File
@@ -0,0 +1,17 @@
import type { Router } from 'vue-router';
/**
* Preload a component or components that have been globally registered.
*
* @param components Pascal-cased name or names of components to prefetch
*/
export declare const preloadComponents: (components: string | string[]) => Promise<void>;
/**
* Prefetch a component or components that have been globally registered.
*
* @param components Pascal-cased name or names of components to prefetch
*/
export declare const prefetchComponents: (components: string | string[]) => Promise<void>;
export declare function preloadRouteComponents(to: string, router?: Router & {
_routePreloaded?: Set<string>;
_preloadPromises?: Array<Promise<any>>;
}): Promise<void>;
+41
View File
@@ -0,0 +1,41 @@
import { useNuxtApp } from "../nuxt.mjs";
import { useRouter } from "./router.mjs";
export const preloadComponents = async (components) => {
if (process.server) {
return;
}
const nuxtApp = useNuxtApp();
components = Array.isArray(components) ? components : [components];
await Promise.all(components.map((name) => _loadAsyncComponent(nuxtApp.vueApp._context.components[name])));
};
export const prefetchComponents = (components) => {
return preloadComponents(components);
};
function _loadAsyncComponent(component) {
if (component?.__asyncLoader && !component.__asyncResolved) {
return component.__asyncLoader();
}
}
export async function preloadRouteComponents(to, router = useRouter()) {
if (process.server) {
return;
}
if (!router._routePreloaded) {
router._routePreloaded = /* @__PURE__ */ new Set();
}
if (router._routePreloaded.has(to)) {
return;
}
router._routePreloaded.add(to);
const promises = router._preloadPromises = router._preloadPromises || [];
if (promises.length > 4) {
return Promise.all(promises).then(() => preloadRouteComponents(to, router));
}
const components = router.resolve(to).matched.map((component) => component.components?.default).filter((component) => typeof component === "function");
for (const component of components) {
const promise = Promise.resolve(component()).catch(() => {
}).finally(() => promises.splice(promises.indexOf(promise)));
promises.push(promise);
}
await Promise.all(promises);
}
+28
View File
@@ -0,0 +1,28 @@
import type { Router, RouteLocationNormalizedLoaded, NavigationGuard, RouteLocationNormalized, RouteLocationRaw, NavigationFailure } from 'vue-router';
import { NuxtError } from './error';
export declare const useRouter: () => Router;
export declare const useRoute: () => RouteLocationNormalizedLoaded;
export declare const onBeforeRouteLeave: (guard: NavigationGuard) => void;
export declare const onBeforeRouteUpdate: (guard: NavigationGuard) => void;
export interface RouteMiddleware {
(to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard>;
}
export declare const defineNuxtRouteMiddleware: (middleware: RouteMiddleware) => RouteMiddleware;
export interface AddRouteMiddlewareOptions {
global?: boolean;
}
interface AddRouteMiddleware {
(name: string, middleware: RouteMiddleware, options?: AddRouteMiddlewareOptions): void;
(middleware: RouteMiddleware): void;
}
export declare const addRouteMiddleware: AddRouteMiddleware;
export interface NavigateToOptions {
replace?: boolean;
redirectCode?: number;
external?: boolean;
}
export declare const navigateTo: (to: RouteLocationRaw | undefined | null, options?: NavigateToOptions) => Promise<void | NavigationFailure> | RouteLocationRaw;
/** This will abort navigation within a Nuxt route middleware handler. */
export declare const abortNavigation: (err?: string | Partial<NuxtError>) => boolean;
export declare const setPageLayout: (layout: string) => void;
export {};
+111
View File
@@ -0,0 +1,111 @@
import { getCurrentInstance, inject, onUnmounted } from "vue";
import { sendRedirect } from "h3";
import { hasProtocol, joinURL, parseURL } from "ufo";
import { useNuxtApp, useRuntimeConfig } from "../nuxt.mjs";
import { createError } from "./error.mjs";
import { useState } from "./state.mjs";
export const useRouter = () => {
return useNuxtApp()?.$router;
};
export const useRoute = () => {
if (getCurrentInstance()) {
return inject("_route", useNuxtApp()._route);
}
return useNuxtApp()._route;
};
export const onBeforeRouteLeave = (guard) => {
const unsubscribe = useRouter().beforeEach((to, from, next) => {
if (to === from) {
return;
}
return guard(to, from, next);
});
onUnmounted(unsubscribe);
};
export const onBeforeRouteUpdate = (guard) => {
const unsubscribe = useRouter().beforeEach(guard);
onUnmounted(unsubscribe);
};
export const defineNuxtRouteMiddleware = (middleware) => middleware;
export const addRouteMiddleware = (name, middleware, options = {}) => {
const nuxtApp = useNuxtApp();
if (options.global || typeof name === "function") {
nuxtApp._middleware.global.push(typeof name === "function" ? name : middleware);
} else {
nuxtApp._middleware.named[name] = middleware;
}
};
const isProcessingMiddleware = () => {
try {
if (useNuxtApp()._processingMiddleware) {
return true;
}
} catch {
return true;
}
return false;
};
export const navigateTo = (to, options) => {
if (!to) {
to = "/";
}
const toPath = typeof to === "string" ? to : to.path || "/";
const isExternal = hasProtocol(toPath, true);
if (isExternal && !options?.external) {
throw new Error("Navigating to external URL is not allowed by default. Use `nagivateTo (url, { external: true })`.");
}
if (isExternal && parseURL(toPath).protocol === "script:") {
throw new Error("Cannot navigate to an URL with script protocol.");
}
if (process.client && !isExternal && isProcessingMiddleware()) {
return to;
}
const router = useRouter();
if (process.server) {
const nuxtApp = useNuxtApp();
if (nuxtApp.ssrContext && nuxtApp.ssrContext.event) {
const redirectLocation = isExternal ? toPath : joinURL(useRuntimeConfig().app.baseURL, router.resolve(to).fullPath || "/");
return nuxtApp.callHook("app:redirected").then(() => sendRedirect(nuxtApp.ssrContext.event, redirectLocation, options?.redirectCode || 302));
}
}
if (isExternal) {
if (options?.replace) {
location.replace(toPath);
} else {
location.href = toPath;
}
return Promise.resolve();
}
return options?.replace ? router.replace(to) : router.push(to);
};
export const abortNavigation = (err) => {
if (process.dev && !isProcessingMiddleware()) {
throw new Error("abortNavigation() is only usable inside a route middleware handler.");
}
if (err) {
throw createError(err);
}
return false;
};
export const setPageLayout = (layout) => {
if (process.server) {
if (process.dev && getCurrentInstance() && useState("_layout").value !== layout) {
console.warn("[warn] [nuxt] `setPageLayout` should not be called to change the layout on the server within a component as this will cause hydration errors.");
}
useState("_layout").value = layout;
}
const nuxtApp = useNuxtApp();
if (process.dev && nuxtApp.isHydrating && useState("_layout").value !== layout) {
console.warn("[warn] [nuxt] `setPageLayout` should not be called to change the layout during hydration as this will cause hydration errors.");
}
const inMiddleware = isProcessingMiddleware();
if (inMiddleware || process.server || nuxtApp.isHydrating) {
const unsubscribe = useRouter().beforeResolve((to) => {
to.meta.layout = layout;
unsubscribe();
});
}
if (!inMiddleware) {
useRoute().meta.layout = layout;
}
};
+6
View File
@@ -0,0 +1,6 @@
import type { H3Event } from 'h3';
import { NuxtApp } from '../nuxt';
export declare function useRequestHeaders<K extends string = string>(include: K[]): Record<Lowercase<K>, string | undefined>;
export declare function useRequestHeaders(): Readonly<Record<string, string | undefined>>;
export declare function useRequestEvent(nuxtApp?: NuxtApp): H3Event;
export declare function setResponseStatus(code: number, message?: string): void;
+23
View File
@@ -0,0 +1,23 @@
import { useNuxtApp } from "../nuxt.mjs";
export function useRequestHeaders(include) {
if (process.client) {
return {};
}
const headers = useNuxtApp().ssrContext?.event.node.req.headers ?? {};
if (!include) {
return headers;
}
return Object.fromEntries(include.map((key) => key.toLowerCase()).filter((key) => headers[key]).map((key) => [key, headers[key]]));
}
export function useRequestEvent(nuxtApp = useNuxtApp()) {
return nuxtApp.ssrContext?.event;
}
export function setResponseStatus(code, message) {
const event = process.server && useRequestEvent();
if (event) {
event.node.res.statusCode = code;
if (message) {
event.node.res.statusMessage = message;
}
}
}
+9
View File
@@ -0,0 +1,9 @@
import type { Ref } from 'vue';
/**
* Create a global reactive ref that will be hydrated but not shared across ssr requests
*
* @param key a unique key ensuring that data fetching can be properly de-duplicated across requests
* @param init a function that provides initial value for the state when it's not initiated
*/
export declare function useState<T>(key?: string, init?: (() => T | Ref<T>)): Ref<T>;
export declare function useState<T>(init?: (() => T | Ref<T>)): Ref<T>;
+27
View File
@@ -0,0 +1,27 @@
import { isRef, toRef } from "vue";
import { useNuxtApp } from "../nuxt.mjs";
export function useState(...args) {
const autoKey = typeof args[args.length - 1] === "string" ? args.pop() : void 0;
if (typeof args[0] !== "string") {
args.unshift(autoKey);
}
const [_key, init] = args;
if (!_key || typeof _key !== "string") {
throw new TypeError("[nuxt] [useState] key must be a string: " + _key);
}
if (init !== void 0 && typeof init !== "function") {
throw new Error("[nuxt] [useState] init must be a function: " + init);
}
const key = "$s" + _key;
const nuxt = useNuxtApp();
const state = toRef(nuxt.payload.state, key);
if (state.value === void 0 && init) {
const initialValue = init();
if (isRef(initialValue)) {
nuxt.payload.state[key] = initialValue;
return initialValue;
}
state.value = initialValue;
}
return state;
}
+13
View File
@@ -0,0 +1,13 @@
import type { AppConfig } from '@nuxt/schema';
type DeepPartial<T> = T extends Function ? T : T extends Record<string, any> ? {
[P in keyof T]?: DeepPartial<T[P]>;
} : T;
export declare const _getAppConfig: () => AppConfig;
export declare function useAppConfig(): AppConfig;
/**
* Deep assign the current appConfig with the new one.
*
* Will preserve existing properties.
*/
export declare function updateAppConfig(appConfig: DeepPartial<AppConfig>): void;
export {};
+56
View File
@@ -0,0 +1,56 @@
import { reactive } from "vue";
import { useNuxtApp } from "./nuxt.mjs";
import __appConfig from "#build/app.config.mjs";
export const _getAppConfig = () => __appConfig;
function deepDelete(obj, newObj) {
for (const key in obj) {
const val = newObj[key];
if (!(key in newObj)) {
delete obj[key];
}
if (val !== null && typeof val === "object") {
deepDelete(obj[key], newObj[key]);
}
}
}
function deepAssign(obj, newObj) {
for (const key in newObj) {
const val = newObj[key];
if (val !== null && typeof val === "object") {
deepAssign(obj[key], val);
} else {
obj[key] = val;
}
}
}
export function useAppConfig() {
const nuxtApp = useNuxtApp();
if (!nuxtApp._appConfig) {
nuxtApp._appConfig = reactive(__appConfig);
}
return nuxtApp._appConfig;
}
export function updateAppConfig(appConfig) {
const _appConfig = useAppConfig();
deepAssign(_appConfig, appConfig);
}
if (process.dev) {
let applyHMR = function(newConfig) {
const appConfig = useAppConfig();
if (newConfig && appConfig) {
deepAssign(appConfig, newConfig);
deepDelete(appConfig, newConfig);
}
};
if (import.meta.hot) {
import.meta.hot.accept((newModule) => {
const newConfig = newModule._getAppConfig();
applyHMR(newConfig);
});
}
if (import.meta.webpackHot) {
import.meta.webpackHot.accept("#build/app.config.mjs", () => {
applyHMR(__appConfig);
});
}
}
+2
View File
@@ -0,0 +1,2 @@
declare const entry: (ctx?: any) => Promise<any>;
export default entry;
+5
View File
@@ -0,0 +1,5 @@
const entry = process.server ? (ctx) => import("#app/entry").then((m) => m.default(ctx)) : () => import("#app/entry").then((m) => m.default);
if (process.client) {
entry();
}
export default entry;
+3
View File
@@ -0,0 +1,3 @@
import '#build/css';
declare const _default: (ctx?: any) => any;
export default _default;
+59
View File
@@ -0,0 +1,59 @@
import { createSSRApp, createApp, nextTick } from "vue";
import { $fetch } from "ofetch";
import { baseURL } from "#build/paths.mjs";
import { createNuxtApp, applyPlugins, normalizePlugins } from "#app";
import "#build/css";
import _plugins from "#build/plugins";
import RootComponent from "#build/root-component.mjs";
import { appRootId } from "#build/nuxt.config.mjs";
if (!globalThis.$fetch) {
globalThis.$fetch = $fetch.create({
baseURL: baseURL()
});
}
let entry;
const plugins = normalizePlugins(_plugins);
if (process.server) {
entry = async function createNuxtAppServer(ssrContext) {
const vueApp = createApp(RootComponent);
const nuxt = createNuxtApp({ vueApp, ssrContext });
try {
await applyPlugins(nuxt, plugins);
await nuxt.hooks.callHook("app:created", vueApp);
} catch (err) {
await nuxt.callHook("app:error", err);
nuxt.payload.error = nuxt.payload.error || err;
}
return vueApp;
};
}
if (process.client) {
if (process.dev && import.meta.webpackHot) {
import.meta.webpackHot.accept();
}
entry = async function initApp() {
const isSSR = Boolean(window.__NUXT__?.serverRendered);
const vueApp = isSSR ? createSSRApp(RootComponent) : createApp(RootComponent);
const nuxt = createNuxtApp({ vueApp });
try {
await applyPlugins(nuxt, plugins);
} catch (err) {
await nuxt.callHook("app:error", err);
nuxt.payload.error = nuxt.payload.error || err;
}
try {
await nuxt.hooks.callHook("app:created", vueApp);
await nuxt.hooks.callHook("app:beforeMount", vueApp);
vueApp.mount("#" + appRootId);
await nuxt.hooks.callHook("app:mounted", vueApp);
await nextTick();
} catch (err) {
await nuxt.callHook("app:error", err);
nuxt.payload.error = nuxt.payload.error || err;
}
};
entry().catch((error) => {
console.error("Error while mounting app:", error);
});
}
export default (ctx) => entry(ctx);
+10
View File
@@ -0,0 +1,10 @@
/// <reference path="types/augments.d.ts" />
export * from './nuxt';
export * from './composables';
export * from './components';
export * from './config';
export type { PageMeta } from '../pages/runtime';
export type { MetaObject } from '../head/runtime';
export { useHead } from '#head';
export declare const isVue2 = false;
export declare const isVue3 = true;
+7
View File
@@ -0,0 +1,7 @@
export * from "./nuxt.mjs";
export * from "./composables/index.mjs";
export * from "./components/index.mjs";
export * from "./config.mjs";
export { useHead } from "#head";
export const isVue2 = false;
export const isVue3 = true;
+122
View File
@@ -0,0 +1,122 @@
import { Ref } from 'vue';
import type { App, onErrorCaptured, VNode } from 'vue';
import { Hookable } from 'hookable';
import type { RuntimeConfig, AppConfigInput } from '@nuxt/schema';
import type { SSRContext } from 'vue-bundle-renderer/runtime';
import type { H3Event } from 'h3';
type NuxtMeta = {
htmlAttrs?: string;
headAttrs?: string;
bodyAttrs?: string;
headTags?: string;
bodyScriptsPrepend?: string;
bodyScripts?: string;
};
type HookResult = Promise<void> | void;
type AppRenderedContext = {
ssrContext: NuxtApp['ssrContext'];
};
export interface RuntimeNuxtHooks {
'app:created': (app: App<Element>) => HookResult;
'app:beforeMount': (app: App<Element>) => HookResult;
'app:mounted': (app: App<Element>) => HookResult;
'app:rendered': (ctx: AppRenderedContext) => HookResult;
'app:redirected': () => HookResult;
'app:suspense:resolve': (Component?: VNode) => HookResult;
'app:error': (err: any) => HookResult;
'app:error:cleared': (options: {
redirect?: string;
}) => HookResult;
'app:data:refresh': (keys?: string[]) => HookResult;
'link:prefetch': (link: string) => HookResult;
'page:start': (Component?: VNode) => HookResult;
'page:finish': (Component?: VNode) => HookResult;
'page:transition:finish': (Component?: VNode) => HookResult;
'vue:setup': () => void;
'vue:error': (...args: Parameters<Parameters<typeof onErrorCaptured>[0]>) => HookResult;
}
export interface NuxtSSRContext extends SSRContext {
url: string;
event: H3Event;
runtimeConfig: RuntimeConfig;
noSSR: boolean;
/** whether we are rendering an SSR error */
error?: boolean;
nuxt: _NuxtApp;
payload: _NuxtApp['payload'];
teleports?: Record<string, string>;
renderMeta?: () => Promise<NuxtMeta> | NuxtMeta;
}
interface _NuxtApp {
vueApp: App<Element>;
globalName: string;
hooks: Hookable<RuntimeNuxtHooks>;
hook: _NuxtApp['hooks']['hook'];
callHook: _NuxtApp['hooks']['callHook'];
[key: string]: any;
_asyncDataPromises: Record<string, Promise<any> | undefined>;
_asyncData: Record<string, {
data: Ref<any>;
pending: Ref<boolean>;
error: Ref<any>;
} | undefined>;
isHydrating?: boolean;
deferHydration: () => () => void | Promise<void>;
ssrContext?: NuxtSSRContext;
payload: {
serverRendered?: boolean;
prerenderedAt?: number;
data: Record<string, any>;
state: Record<string, any>;
rendered?: Function;
error?: Error | {
url: string;
statusCode: string;
statusMessage: string;
message: string;
description: string;
data?: any;
} | null;
[key: string]: any;
};
static: {
data: Record<string, any>;
};
provide: (name: string, value: any) => void;
}
export interface NuxtApp extends _NuxtApp {
}
export declare const NuxtPluginIndicator = "__nuxt_plugin";
export interface Plugin<Injections extends Record<string, any> = Record<string, any>> {
(nuxt: _NuxtApp): Promise<void> | Promise<{
provide?: Injections;
}> | void | {
provide?: Injections;
};
[NuxtPluginIndicator]?: true;
}
export interface CreateOptions {
vueApp: NuxtApp['vueApp'];
ssrContext?: NuxtApp['ssrContext'];
globalName?: NuxtApp['globalName'];
}
export declare function createNuxtApp(options: CreateOptions): NuxtApp;
export declare function applyPlugin(nuxtApp: NuxtApp, plugin: Plugin): Promise<void>;
export declare function applyPlugins(nuxtApp: NuxtApp, plugins: Plugin[]): Promise<void>;
export declare function normalizePlugins(_plugins: Plugin[]): Plugin<Record<string, any>>[];
export declare function defineNuxtPlugin<T extends Record<string, any>>(plugin: Plugin<T>): Plugin<T>;
export declare function isNuxtPlugin(plugin: unknown): boolean;
/**
* Ensures that the setup function passed in has access to the Nuxt instance via `useNuxt`.
*
* @param nuxt A Nuxt instance
* @param setup The function to call
*/
export declare function callWithNuxt<T extends (...args: any[]) => any>(nuxt: NuxtApp | _NuxtApp, setup: T, args?: Parameters<T>): any;
/**
* Returns the current Nuxt instance.
*/
export declare function useNuxtApp(): NuxtApp;
export declare function useRuntimeConfig(): RuntimeConfig;
export declare function defineAppConfig<C extends AppConfigInput>(config: C): C;
export {};
+168
View File
@@ -0,0 +1,168 @@
import { getCurrentInstance, reactive } from "vue";
import { createHooks } from "hookable";
import { getContext } from "unctx";
const nuxtAppCtx = getContext("nuxt-app");
export const NuxtPluginIndicator = "__nuxt_plugin";
export function createNuxtApp(options) {
let hydratingCount = 0;
const nuxtApp = {
provide: void 0,
globalName: "nuxt",
payload: reactive({
data: {},
state: {},
_errors: {},
...process.client ? window.__NUXT__ : { serverRendered: true }
}),
static: {
data: {}
},
isHydrating: process.client,
deferHydration() {
if (!nuxtApp.isHydrating) {
return () => {
};
}
hydratingCount++;
let called = false;
return () => {
if (called) {
return;
}
called = true;
hydratingCount--;
if (hydratingCount === 0) {
nuxtApp.isHydrating = false;
return nuxtApp.callHook("app:suspense:resolve");
}
};
},
_asyncDataPromises: {},
_asyncData: {},
...options
};
nuxtApp.hooks = createHooks();
nuxtApp.hook = nuxtApp.hooks.hook;
nuxtApp.callHook = nuxtApp.hooks.callHook;
nuxtApp.provide = (name, value) => {
const $name = "$" + name;
defineGetter(nuxtApp, $name, value);
defineGetter(nuxtApp.vueApp.config.globalProperties, $name, value);
};
defineGetter(nuxtApp.vueApp, "$nuxt", nuxtApp);
defineGetter(nuxtApp.vueApp.config.globalProperties, "$nuxt", nuxtApp);
if (process.server) {
if (nuxtApp.ssrContext) {
nuxtApp.ssrContext.nuxt = nuxtApp;
}
nuxtApp.ssrContext = nuxtApp.ssrContext || {};
if (nuxtApp.ssrContext.payload) {
Object.assign(nuxtApp.payload, nuxtApp.ssrContext.payload);
}
nuxtApp.ssrContext.payload = nuxtApp.payload;
nuxtApp.payload.config = {
public: options.ssrContext.runtimeConfig.public,
app: options.ssrContext.runtimeConfig.app
};
}
const runtimeConfig = process.server ? options.ssrContext.runtimeConfig : reactive(nuxtApp.payload.config);
const compatibilityConfig = new Proxy(runtimeConfig, {
get(target, prop) {
if (prop === "public") {
return target.public;
}
return target[prop] ?? target.public[prop];
},
set(target, prop, value) {
if (process.server || prop === "public" || prop === "app") {
return false;
}
target[prop] = value;
target.public[prop] = value;
return true;
}
});
nuxtApp.provide("config", compatibilityConfig);
return nuxtApp;
}
export async function applyPlugin(nuxtApp, plugin) {
if (typeof plugin !== "function") {
return;
}
const { provide } = await callWithNuxt(nuxtApp, plugin, [nuxtApp]) || {};
if (provide && typeof provide === "object") {
for (const key in provide) {
nuxtApp.provide(key, provide[key]);
}
}
}
export async function applyPlugins(nuxtApp, plugins) {
for (const plugin of plugins) {
await applyPlugin(nuxtApp, plugin);
}
}
export function normalizePlugins(_plugins) {
const unwrappedPlugins = [];
const legacyInjectPlugins = [];
const invalidPlugins = [];
const plugins = _plugins.map((plugin) => {
if (typeof plugin !== "function") {
invalidPlugins.push(plugin);
return null;
}
if (plugin.length > 1) {
legacyInjectPlugins.push(plugin);
return (nuxtApp) => plugin(nuxtApp, nuxtApp.provide);
}
if (!isNuxtPlugin(plugin)) {
unwrappedPlugins.push(plugin);
}
return plugin;
}).filter(Boolean);
if (process.dev && legacyInjectPlugins.length) {
console.warn("[warn] [nuxt] You are using a plugin with legacy Nuxt 2 format (context, inject) which is likely to be broken. In the future they will be ignored:", legacyInjectPlugins.map((p) => p.name || p).join(","));
}
if (process.dev && invalidPlugins.length) {
console.warn("[warn] [nuxt] Some plugins are not exposing a function and skipped:", invalidPlugins);
}
if (process.dev && unwrappedPlugins.length) {
console.warn("[warn] [nuxt] You are using a plugin that has not been wrapped in `defineNuxtPlugin`. It is advised to wrap your plugins as in the future this may enable enhancements:", unwrappedPlugins.map((p) => p.name || p).join(","));
}
return plugins;
}
export function defineNuxtPlugin(plugin) {
plugin[NuxtPluginIndicator] = true;
return plugin;
}
export function isNuxtPlugin(plugin) {
return typeof plugin === "function" && NuxtPluginIndicator in plugin;
}
export function callWithNuxt(nuxt, setup, args) {
const fn = () => args ? setup(...args) : setup();
if (process.server) {
return nuxtAppCtx.callAsync(nuxt, fn);
} else {
nuxtAppCtx.set(nuxt);
return fn();
}
}
export function useNuxtApp() {
const nuxtAppInstance = nuxtAppCtx.tryUse();
if (!nuxtAppInstance) {
const vm = getCurrentInstance();
if (!vm) {
throw new Error("nuxt instance unavailable");
}
return vm.appContext.app.$nuxt;
}
return nuxtAppInstance;
}
export function useRuntimeConfig() {
return useNuxtApp().$config;
}
function defineGetter(obj, key, val) {
Object.defineProperty(obj, key, { get: () => val });
}
export function defineAppConfig(config) {
return config;
}
+2
View File
@@ -0,0 +1,2 @@
declare const _default: any;
export default _default;
+28
View File
@@ -0,0 +1,28 @@
import { ref } from "vue";
import { parseURL } from "ufo";
import { defineNuxtPlugin, useHead } from "#app";
export default defineNuxtPlugin((nuxtApp) => {
const externalURLs = ref(/* @__PURE__ */ new Set());
useHead({
script: [
() => ({
type: "speculationrules",
innerHTML: JSON.stringify({
prefetch: [
{
source: "list",
urls: [...externalURLs.value],
requires: ["anonymous-client-ip-when-cross-origin"]
}
]
})
})
]
});
nuxtApp.hook("link:prefetch", (url) => {
const { protocol } = parseURL(url);
if (protocol && ["http:", "https:"].includes(protocol)) {
externalURLs.value.add(url);
}
});
});
+2
View File
@@ -0,0 +1,2 @@
declare const _default: any;
export default _default;
+5
View File
@@ -0,0 +1,5 @@
import { createDebugger } from "hookable";
import { defineNuxtPlugin } from "#app";
export default defineNuxtPlugin((nuxtApp) => {
createDebugger(nuxtApp.hooks, { tag: "nuxt-app" });
});
+2
View File
@@ -0,0 +1,2 @@
declare const _default: any;
export default _default;
+22
View File
@@ -0,0 +1,22 @@
import { parseURL } from "ufo";
import { defineNuxtPlugin, loadPayload, isPrerendered, useRouter } from "#app";
export default defineNuxtPlugin((nuxtApp) => {
if (!isPrerendered()) {
return;
}
nuxtApp.hooks.hook("link:prefetch", (url) => {
if (!parseURL(url).protocol) {
return loadPayload(url);
}
});
useRouter().beforeResolve(async (to, from) => {
if (to.path === from.path) {
return;
}
const payload = await loadPayload(to.path);
if (!payload) {
return;
}
Object.assign(nuxtApp.static.data, payload.data);
});
});
+2
View File
@@ -0,0 +1,2 @@
declare const _default: any;
export default _default;
+10
View File
@@ -0,0 +1,10 @@
import { defineNuxtPlugin } from "#app";
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.mixin({
beforeCreate() {
const { _registeredComponents } = this.$nuxt.ssrContext;
const { __moduleIdentifier } = this.$options;
_registeredComponents.add(__moduleIdentifier);
}
});
});
+53
View File
@@ -0,0 +1,53 @@
interface Route {
/** Percentage encoded pathname section of the URL. */
path: string;
/** The whole location including the `search` and `hash`. */
fullPath: string;
/** Object representation of the `search` property of the current location. */
query: Record<string, any>;
/** Hash of the current location. If present, starts with a `#`. */
hash: string;
/** Name of the matched record */
name: string | null | undefined;
/** Object of decoded params extracted from the `path`. */
params: Record<string, any>;
/**
* The location we were initially trying to access before ending up
* on the current location.
*/
redirectedFrom: Route | undefined;
/** Merged `meta` properties from all of the matched route records. */
meta: Record<string, any>;
}
type RouteGuardReturn = void | Error | string | false;
interface RouterHooks {
'resolve:before': (to: Route, from: Route) => RouteGuardReturn | Promise<RouteGuardReturn>;
'navigate:before': (to: Route, from: Route) => RouteGuardReturn | Promise<RouteGuardReturn>;
'navigate:after': (to: Route, from: Route) => void | Promise<void>;
'error': (err: any) => void | Promise<void>;
}
interface Router {
currentRoute: Route;
isReady: () => Promise<void>;
options: {};
install: () => Promise<void>;
push: (url: string) => Promise<void>;
replace: (url: string) => Promise<void>;
back: () => void;
go: (delta: number) => void;
forward: () => void;
beforeResolve: (guard: RouterHooks['resolve:before']) => () => void;
beforeEach: (guard: RouterHooks['navigate:before']) => () => void;
afterEach: (guard: RouterHooks['navigate:after']) => () => void;
onError: (handler: RouterHooks['error']) => () => void;
resolve: (url: string | Partial<Route>) => Route;
addRoute: (parentName: string, route: Route) => void;
getRoutes: () => any[];
hasRoute: (name: string) => boolean;
removeRoute: (name: string) => void;
}
declare const _default: import("..").Plugin<{
route: Route;
router: Router;
}>;
export default _default;
+176
View File
@@ -0,0 +1,176 @@
import { reactive, h } from "vue";
import { parseURL, stringifyParsedURL, parseQuery, stringifyQuery, withoutBase, isEqual, joinURL } from "ufo";
import { createError } from "h3";
import { defineNuxtPlugin, clearError, navigateTo, showError, useRuntimeConfig, useState } from "../index.mjs";
import { callWithNuxt } from "../nuxt.mjs";
import { globalMiddleware } from "#build/middleware";
function getRouteFromPath(fullPath) {
if (typeof fullPath === "object") {
fullPath = stringifyParsedURL({
pathname: fullPath.path || "",
search: stringifyQuery(fullPath.query || {}),
hash: fullPath.hash || ""
});
}
const url = parseURL(fullPath.toString());
return {
path: url.pathname,
fullPath,
query: parseQuery(url.search),
hash: url.hash,
params: {},
name: void 0,
matched: [],
redirectedFrom: void 0,
meta: {},
href: fullPath
};
}
export default defineNuxtPlugin((nuxtApp) => {
const initialURL = process.client ? withoutBase(window.location.pathname, useRuntimeConfig().app.baseURL) + window.location.search + window.location.hash : nuxtApp.ssrContext.url;
const routes = [];
const hooks = {
"navigate:before": [],
"resolve:before": [],
"navigate:after": [],
error: []
};
const registerHook = (hook, guard) => {
hooks[hook].push(guard);
return () => hooks[hook].splice(hooks[hook].indexOf(guard), 1);
};
const baseURL = useRuntimeConfig().app.baseURL;
const route = reactive(getRouteFromPath(initialURL));
async function handleNavigation(url, replace) {
try {
const to = getRouteFromPath(url);
for (const middleware of hooks["navigate:before"]) {
const result = await middleware(to, route);
if (result === false || result instanceof Error) {
return;
}
if (result) {
return handleNavigation(result, true);
}
}
for (const handler of hooks["resolve:before"]) {
await handler(to, route);
}
Object.assign(route, to);
if (process.client) {
window.history[replace ? "replaceState" : "pushState"]({}, "", joinURL(baseURL, to.fullPath));
if (!nuxtApp.isHydrating) {
await callWithNuxt(nuxtApp, clearError);
}
}
for (const middleware of hooks["navigate:after"]) {
await middleware(to, route);
}
} catch (err) {
if (process.dev && !hooks.error.length) {
console.warn("No error handlers registered to handle middleware errors. You can register an error handler with `router.onError()`", err);
}
for (const handler of hooks.error) {
await handler(err);
}
}
}
const router = {
currentRoute: route,
isReady: () => Promise.resolve(),
options: {},
install: () => Promise.resolve(),
push: (url) => handleNavigation(url, false),
replace: (url) => handleNavigation(url, true),
back: () => window.history.go(-1),
go: (delta) => window.history.go(delta),
forward: () => window.history.go(1),
beforeResolve: (guard) => registerHook("resolve:before", guard),
beforeEach: (guard) => registerHook("navigate:before", guard),
afterEach: (guard) => registerHook("navigate:after", guard),
onError: (handler) => registerHook("error", handler),
resolve: getRouteFromPath,
addRoute: (parentName, route2) => {
routes.push(route2);
},
getRoutes: () => routes,
hasRoute: (name) => routes.some((route2) => route2.name === name),
removeRoute: (name) => {
const index = routes.findIndex((route2) => route2.name === name);
if (index !== -1) {
routes.splice(index, 1);
}
}
};
nuxtApp.vueApp.component("RouterLink", {
functional: true,
props: {
to: String,
custom: Boolean,
replace: Boolean,
activeClass: String,
exactActiveClass: String,
ariaCurrentValue: String
},
setup: (props, { slots }) => {
const navigate = () => handleNavigation(props.to, props.replace);
return () => {
const route2 = router.resolve(props.to);
return props.custom ? slots.default?.({ href: props.to, navigate, route: route2 }) : h("a", { href: props.to, onClick: (e) => {
e.preventDefault();
return navigate();
} }, slots);
};
}
});
if (process.client) {
window.addEventListener("popstate", (event) => {
const location = event.target.location;
router.replace(location.href.replace(location.origin, ""));
});
}
nuxtApp._route = route;
nuxtApp._middleware = nuxtApp._middleware || {
global: [],
named: {}
};
const initialLayout = useState("_layout");
nuxtApp.hooks.hookOnce("app:created", async () => {
router.beforeEach(async (to, from) => {
to.meta = reactive(to.meta || {});
if (nuxtApp.isHydrating) {
to.meta.layout = initialLayout.value ?? to.meta.layout;
}
nuxtApp._processingMiddleware = true;
const middlewareEntries = /* @__PURE__ */ new Set([...globalMiddleware, ...nuxtApp._middleware.global]);
for (const middleware of middlewareEntries) {
const result = await callWithNuxt(nuxtApp, middleware, [to, from]);
if (process.server) {
if (result === false || result instanceof Error) {
const error = result || createError({
statusCode: 404,
statusMessage: `Page Not Found: ${initialURL}`
});
return callWithNuxt(nuxtApp, showError, [error]);
}
}
if (result || result === false) {
return result;
}
}
});
router.afterEach(() => {
delete nuxtApp._processingMiddleware;
});
await router.replace(initialURL);
if (!isEqual(route.fullPath, initialURL)) {
await callWithNuxt(nuxtApp, navigateTo, [route.fullPath]);
}
});
return {
provide: {
route,
router
}
};
});
+28
View File
@@ -0,0 +1,28 @@
import { NuxtApp } from '../nuxt'
declare global {
namespace NodeJS {
interface Process {
browser: boolean
client: boolean
dev: boolean
mode: 'spa' | 'universal'
server: boolean
static: boolean
}
}
interface Window {
__NUXT__?: Record<string, any>
}
}
declare module '@vue/runtime-core' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface App<HostElement> {
$nuxt: NuxtApp
}
interface ComponentInternalInstance {
_nuxtOnBeforeMountCbs: Function[]
}
}
+3
View File
@@ -0,0 +1,3 @@
import type { NitroErrorHandler } from 'nitropack';
declare const _default: NitroErrorHandler;
export default _default;
+58
View File
@@ -0,0 +1,58 @@
import { joinURL, withQuery } from "ufo";
import { setResponseHeader, getRequestHeaders } from "h3";
import { useNitroApp, useRuntimeConfig } from "#internal/nitro";
import { normalizeError, isJsonRequest } from "#internal/nitro/utils";
export default (async function errorhandler(error, event) {
const { stack, statusCode, statusMessage, message } = normalizeError(error);
const errorObject = {
url: event.node.req.url,
statusCode,
statusMessage,
message,
stack: process.dev && statusCode !== 404 ? `<pre>${stack.map((i) => `<span class="stack${i.internal ? " internal" : ""}">${i.text}</span>`).join("\n")}</pre>` : "",
data: error.data
};
event.node.res.statusCode = errorObject.statusCode !== 200 && errorObject.statusCode || 500;
if (errorObject.statusMessage) {
event.node.res.statusMessage = errorObject.statusMessage;
}
if (error.unhandled || error.fatal) {
const tags = [
"[nuxt]",
"[request error]",
error.unhandled && "[unhandled]",
error.fatal && "[fatal]",
Number(errorObject.statusCode) !== 200 && `[${errorObject.statusCode}]`
].filter(Boolean).join(" ");
console.error(tags, errorObject.message + "\n" + stack.map((l) => " " + l.text).join(" \n"));
}
if (isJsonRequest(event)) {
event.node.res.setHeader("Content-Type", "application/json");
event.node.res.end(JSON.stringify(errorObject));
return;
}
const isErrorPage = event.node.req.url?.startsWith("/__nuxt_error");
const res = !isErrorPage ? await useNitroApp().localFetch(withQuery(joinURL(useRuntimeConfig().app.baseURL, "/__nuxt_error"), errorObject), {
headers: getRequestHeaders(event),
redirect: "manual"
}).catch(() => null) : null;
if (!res) {
const { template } = process.dev ? await import("@nuxt/ui-templates/templates/error-dev.mjs") : await import("@nuxt/ui-templates/templates/error-500.mjs");
if (process.dev) {
errorObject.description = errorObject.message;
}
event.node.res.setHeader("Content-Type", "text/html;charset=UTF-8");
event.node.res.end(template(errorObject));
return;
}
for (const [header, value] of res.headers.entries()) {
setResponseHeader(event, header, value);
}
if (res.status && res.status !== 200) {
event.node.res.statusCode = res.status;
}
if (res.statusText) {
event.node.res.statusMessage = res.statusText;
}
event.node.res.end(await res.text());
});
+4
View File
@@ -0,0 +1,4 @@
export declare function baseURL(): string;
export declare function buildAssetsDir(): string;
export declare function buildAssetsURL(...path: string[]): string;
export declare function publicAssetsURL(...path: string[]): string;
+15
View File
@@ -0,0 +1,15 @@
import { joinURL } from "ufo";
import { useRuntimeConfig } from "#internal/nitro";
export function baseURL() {
return useRuntimeConfig().app.baseURL;
}
export function buildAssetsDir() {
return useRuntimeConfig().app.buildAssetsDir;
}
export function buildAssetsURL(...path) {
return joinURL(publicAssetsURL(), useRuntimeConfig().app.buildAssetsDir, ...path);
}
export function publicAssetsURL(...path) {
const publicBase = useRuntimeConfig().app.cdnURL || useRuntimeConfig().app.baseURL;
return path.length ? joinURL(publicBase, ...path) : publicBase;
}
+16
View File
@@ -0,0 +1,16 @@
export interface NuxtRenderHTMLContext {
htmlAttrs: string[];
head: string[];
bodyAttrs: string[];
bodyPrepend: string[];
body: string[];
bodyAppend: string[];
}
export interface NuxtRenderResponse {
body: string;
statusCode: number;
statusMessage?: string;
headers: Record<string, string>;
}
declare const _default: any;
export default _default;
+219
View File
@@ -0,0 +1,219 @@
import { createRenderer, renderResourceHeaders } from "vue-bundle-renderer/runtime";
import { appendHeader, createError, getQuery, writeEarlyHints } from "h3";
import devalue from "@nuxt/devalue";
import { joinURL } from "ufo";
import { renderToString as _renderToString } from "vue/server-renderer";
import { useRuntimeConfig, useNitroApp, defineRenderHandler, getRouteRules } from "#internal/nitro";
import { appRootId, appRootTag } from "#internal/nuxt.config.mjs";
import { buildAssetsURL, publicAssetsURL } from "#paths";
globalThis.__buildAssetsURL = buildAssetsURL;
globalThis.__publicAssetsURL = publicAssetsURL;
const getClientManifest = () => import("#build/dist/server/client.manifest.mjs").then((r) => r.default || r).then((r) => typeof r === "function" ? r() : r);
const getStaticRenderedHead = () => import("#head-static").then((r) => r.default || r);
const getServerEntry = () => import("#build/dist/server/server.mjs").then((r) => r.default || r);
const getSSRStyles = () => import("#build/dist/server/styles.mjs").then((r) => r.default || r);
const getSSRRenderer = lazyCachedFunction(async () => {
const manifest = await getClientManifest();
if (!manifest) {
throw new Error("client.manifest is not available");
}
const createSSRApp = await getServerEntry();
if (!createSSRApp) {
throw new Error("Server bundle is not available");
}
const options = {
manifest,
renderToString,
buildAssetsURL
};
const renderer = createRenderer(createSSRApp, options);
async function renderToString(input, context) {
const html = await _renderToString(input, context);
if (process.dev && process.env.NUXT_VITE_NODE_OPTIONS) {
renderer.rendererContext.updateManifest(await getClientManifest());
}
return `<${appRootTag} id="${appRootId}">${html}</${appRootTag}>`;
}
return renderer;
});
const getSPARenderer = lazyCachedFunction(async () => {
const manifest = await getClientManifest();
const options = {
manifest,
renderToString: () => `<${appRootTag} id="${appRootId}"></${appRootTag}>`,
buildAssetsURL
};
const renderer = createRenderer(() => () => {
}, options);
const result = await renderer.renderToString({});
const renderToString = (ssrContext) => {
const config = useRuntimeConfig();
ssrContext.payload = {
serverRendered: false,
config: {
public: config.public,
app: config.app
},
data: {},
state: {}
};
ssrContext.renderMeta = ssrContext.renderMeta ?? getStaticRenderedHead;
return Promise.resolve(result);
};
return {
rendererContext: renderer.rendererContext,
renderToString
};
});
const PAYLOAD_CACHE = process.env.NUXT_PAYLOAD_EXTRACTION && process.env.prerender ? /* @__PURE__ */ new Map() : null;
const PAYLOAD_URL_RE = /\/_payload(\.[a-zA-Z0-9]+)?.js(\?.*)?$/;
const PRERENDER_NO_SSR_ROUTES = /* @__PURE__ */ new Set(["/index.html", "/200.html", "/404.html"]);
export default defineRenderHandler(async (event) => {
const ssrError = event.node.req.url?.startsWith("/__nuxt_error") ? getQuery(event) : null;
if (ssrError && event.node.req.socket.readyState !== "readOnly") {
throw createError("Cannot directly render error page!");
}
let url = ssrError?.url || event.node.req.url;
const isRenderingPayload = PAYLOAD_URL_RE.test(url);
if (isRenderingPayload) {
url = url.substring(0, url.lastIndexOf("/")) || "/";
event.node.req.url = url;
if (process.env.prerender && PAYLOAD_CACHE.has(url)) {
return PAYLOAD_CACHE.get(url);
}
}
const routeOptions = getRouteRules(event);
const ssrContext = {
url,
event,
runtimeConfig: useRuntimeConfig(),
noSSR: !!process.env.NUXT_NO_SSR || !!event.node.req.headers["x-nuxt-no-ssr"] || routeOptions.ssr === false || (process.env.prerender ? PRERENDER_NO_SSR_ROUTES.has(url) : false),
error: !!ssrError,
nuxt: void 0,
payload: ssrError ? { error: ssrError } : {}
};
const _PAYLOAD_EXTRACTION = process.env.prerender && process.env.NUXT_PAYLOAD_EXTRACTION && !ssrContext.noSSR;
const payloadURL = _PAYLOAD_EXTRACTION ? joinURL(useRuntimeConfig().app.baseURL, url, "_payload.js") : void 0;
if (process.env.prerender) {
ssrContext.payload.prerenderedAt = Date.now();
}
const renderer = process.env.NUXT_NO_SSR || ssrContext.noSSR ? await getSPARenderer() : await getSSRRenderer();
if (process.env.NUXT_EARLY_HINTS && !isRenderingPayload && !process.env.prerender) {
const { link } = renderResourceHeaders({}, renderer.rendererContext);
writeEarlyHints(event, link);
}
const _rendered = await renderer.renderToString(ssrContext).catch((error) => {
throw !ssrError && ssrContext.payload?.error || error;
});
await ssrContext.nuxt?.hooks.callHook("app:rendered", { ssrContext });
if (ssrContext.payload?.error && !ssrError) {
throw ssrContext.payload.error;
}
if (isRenderingPayload) {
const response2 = renderPayloadResponse(ssrContext);
if (process.env.prerender) {
PAYLOAD_CACHE.set(url, response2);
}
return response2;
}
if (_PAYLOAD_EXTRACTION) {
appendHeader(event, "x-nitro-prerender", joinURL(url, "_payload.js"));
PAYLOAD_CACHE.set(url, renderPayloadResponse(ssrContext));
}
const renderedMeta = await ssrContext.renderMeta?.() ?? {};
const inlinedStyles = process.env.NUXT_INLINE_STYLES ? await renderInlineStyles(ssrContext.modules ?? ssrContext._registeredComponents ?? []) : "";
const htmlContext = {
htmlAttrs: normalizeChunks([renderedMeta.htmlAttrs]),
head: normalizeChunks([
renderedMeta.headTags,
_PAYLOAD_EXTRACTION ? `<link rel="modulepreload" href="${payloadURL}">` : null,
_rendered.renderResourceHints(),
_rendered.renderStyles(),
inlinedStyles,
ssrContext.styles
]),
bodyAttrs: normalizeChunks([renderedMeta.bodyAttrs]),
bodyPrepend: normalizeChunks([
renderedMeta.bodyScriptsPrepend,
ssrContext.teleports?.body
]),
body: [
_rendered.html
],
bodyAppend: normalizeChunks([
process.env.NUXT_NO_SCRIPTS ? void 0 : _PAYLOAD_EXTRACTION ? `<script type="module">import p from "${payloadURL}";window.__NUXT__={...p,...(${devalue(splitPayload(ssrContext).initial)})}<\/script>` : `<script>window.__NUXT__=${devalue(ssrContext.payload)}<\/script>`,
_rendered.renderScripts(),
renderedMeta.bodyScripts
])
};
const nitroApp = useNitroApp();
await nitroApp.hooks.callHook("render:html", htmlContext, { event });
const response = {
body: renderHTMLDocument(htmlContext),
statusCode: event.node.res.statusCode,
statusMessage: event.node.res.statusMessage,
headers: {
"Content-Type": "text/html;charset=UTF-8",
"X-Powered-By": "Nuxt"
}
};
return response;
});
function lazyCachedFunction(fn) {
let res = null;
return () => {
if (res === null) {
res = fn().catch((err) => {
res = null;
throw err;
});
}
return res;
};
}
function normalizeChunks(chunks) {
return chunks.filter(Boolean).map((i) => i.trim());
}
function joinTags(tags) {
return tags.join("");
}
function joinAttrs(chunks) {
return chunks.join(" ");
}
function renderHTMLDocument(html) {
return `<!DOCTYPE html>
<html ${joinAttrs(html.htmlAttrs)}>
<head>${joinTags(html.head)}</head>
<body ${joinAttrs(html.bodyAttrs)}>${joinTags(html.bodyPrepend)}${joinTags(html.body)}${joinTags(html.bodyAppend)}</body>
</html>`;
}
async function renderInlineStyles(usedModules) {
const styleMap = await getSSRStyles();
const inlinedStyles = /* @__PURE__ */ new Set();
for (const mod of usedModules) {
if (mod in styleMap) {
for (const style of await styleMap[mod]()) {
inlinedStyles.add(`<style>${style}</style>`);
}
}
}
return Array.from(inlinedStyles).join("");
}
function renderPayloadResponse(ssrContext) {
return {
body: `export default ${devalue(splitPayload(ssrContext).payload)}`,
statusCode: ssrContext.event.node.res.statusCode,
statusMessage: ssrContext.event.node.res.statusMessage,
headers: {
"content-type": "text/javascript;charset=UTF-8",
"x-powered-by": "Nuxt"
}
};
}
function splitPayload(ssrContext) {
const { data, prerenderedAt, ...initial } = ssrContext.payload;
return {
initial: { ...initial, prerenderedAt },
payload: { data, prerenderedAt }
};
}
+796
View File
@@ -0,0 +1,796 @@
import type { PropType } from 'vue';
import type { CrossOrigin, FetchPriority, HTTPEquiv, LinkRelationship, ReferrerPolicy, Target } from './types';
export declare const NoScript: import("vue").DefineComponent<{
title: StringConstructor;
body: BooleanConstructor;
renderPriority: (StringConstructor | NumberConstructor)[];
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
nonce: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
translate: StringConstructor;
}, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>[] | null | undefined, unknown, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, import("vue").EmitsOptions, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{
title: StringConstructor;
body: BooleanConstructor;
renderPriority: (StringConstructor | NumberConstructor)[];
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
nonce: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
translate: StringConstructor;
}>>, {
body: boolean;
autofocus: boolean;
contenteditable: boolean;
draggable: boolean;
hidden: boolean;
spellcheck: boolean;
}>;
export declare const Link: import("vue").DefineComponent<{
as: StringConstructor;
crossorigin: PropType<CrossOrigin>;
disabled: BooleanConstructor;
fetchpriority: PropType<FetchPriority>;
href: StringConstructor;
hreflang: StringConstructor;
imagesizes: StringConstructor;
imagesrcset: StringConstructor;
integrity: StringConstructor;
media: StringConstructor;
prefetch: {
type: BooleanConstructor;
default: undefined;
};
referrerpolicy: PropType<ReferrerPolicy>;
rel: PropType<LinkRelationship>;
sizes: StringConstructor;
title: StringConstructor;
type: StringConstructor;
/** @deprecated **/
methods: StringConstructor;
/** @deprecated **/
target: PropType<Target>;
body: BooleanConstructor;
renderPriority: (StringConstructor | NumberConstructor)[];
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
nonce: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
translate: StringConstructor;
}, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>[] | null | undefined, unknown, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, import("vue").EmitsOptions, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{
as: StringConstructor;
crossorigin: PropType<CrossOrigin>;
disabled: BooleanConstructor;
fetchpriority: PropType<FetchPriority>;
href: StringConstructor;
hreflang: StringConstructor;
imagesizes: StringConstructor;
imagesrcset: StringConstructor;
integrity: StringConstructor;
media: StringConstructor;
prefetch: {
type: BooleanConstructor;
default: undefined;
};
referrerpolicy: PropType<ReferrerPolicy>;
rel: PropType<LinkRelationship>;
sizes: StringConstructor;
title: StringConstructor;
type: StringConstructor;
/** @deprecated **/
methods: StringConstructor;
/** @deprecated **/
target: PropType<Target>;
body: BooleanConstructor;
renderPriority: (StringConstructor | NumberConstructor)[];
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
nonce: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
translate: StringConstructor;
}>>, {
prefetch: boolean;
body: boolean;
autofocus: boolean;
contenteditable: boolean;
draggable: boolean;
hidden: boolean;
spellcheck: boolean;
disabled: boolean;
}>;
export declare const Base: import("vue").DefineComponent<{
href: StringConstructor;
target: PropType<Target>;
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
nonce: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
title: StringConstructor;
translate: StringConstructor;
}, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>[] | null | undefined, unknown, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, import("vue").EmitsOptions, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{
href: StringConstructor;
target: PropType<Target>;
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
nonce: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
title: StringConstructor;
translate: StringConstructor;
}>>, {
autofocus: boolean;
contenteditable: boolean;
draggable: boolean;
hidden: boolean;
spellcheck: boolean;
}>;
export declare const Title: import("vue").DefineComponent<{
[x: string]: any;
}, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>[] | null | undefined, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, import("vue").EmitsOptions, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{
[x: string]: any;
}>>, {
[x: string]: any;
}>;
export declare const Meta: import("vue").DefineComponent<{
charset: StringConstructor;
content: StringConstructor;
httpEquiv: PropType<HTTPEquiv>;
name: StringConstructor;
body: BooleanConstructor;
renderPriority: (StringConstructor | NumberConstructor)[];
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
nonce: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
title: StringConstructor;
translate: StringConstructor;
}, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>[] | null | undefined, unknown, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, import("vue").EmitsOptions, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{
charset: StringConstructor;
content: StringConstructor;
httpEquiv: PropType<HTTPEquiv>;
name: StringConstructor;
body: BooleanConstructor;
renderPriority: (StringConstructor | NumberConstructor)[];
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
nonce: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
title: StringConstructor;
translate: StringConstructor;
}>>, {
body: boolean;
autofocus: boolean;
contenteditable: boolean;
draggable: boolean;
hidden: boolean;
spellcheck: boolean;
}>;
export declare const Style: import("vue").DefineComponent<{
type: StringConstructor;
media: StringConstructor;
nonce: StringConstructor;
title: StringConstructor;
/** @deprecated **/
scoped: {
type: BooleanConstructor;
default: undefined;
};
body: BooleanConstructor;
renderPriority: (StringConstructor | NumberConstructor)[];
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
translate: StringConstructor;
}, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>[] | null | undefined, unknown, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, import("vue").EmitsOptions, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{
type: StringConstructor;
media: StringConstructor;
nonce: StringConstructor;
title: StringConstructor;
/** @deprecated **/
scoped: {
type: BooleanConstructor;
default: undefined;
};
body: BooleanConstructor;
renderPriority: (StringConstructor | NumberConstructor)[];
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
translate: StringConstructor;
}>>, {
body: boolean;
autofocus: boolean;
contenteditable: boolean;
draggable: boolean;
hidden: boolean;
spellcheck: boolean;
scoped: boolean;
}>;
export declare const Head: 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").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{}>>, {}>;
export declare const Html: import("vue").DefineComponent<{
manifest: StringConstructor;
version: StringConstructor;
xmlns: StringConstructor;
renderPriority: (StringConstructor | NumberConstructor)[];
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
nonce: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
title: StringConstructor;
translate: StringConstructor;
}, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>[] | null | undefined, unknown, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, import("vue").EmitsOptions, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{
manifest: StringConstructor;
version: StringConstructor;
xmlns: StringConstructor;
renderPriority: (StringConstructor | NumberConstructor)[];
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
nonce: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
title: StringConstructor;
translate: StringConstructor;
}>>, {
autofocus: boolean;
contenteditable: boolean;
draggable: boolean;
hidden: boolean;
spellcheck: boolean;
}>;
export declare const Body: import("vue").DefineComponent<{
renderPriority: (StringConstructor | NumberConstructor)[];
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
nonce: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
title: StringConstructor;
translate: StringConstructor;
}, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>[] | null | undefined, unknown, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, import("vue").EmitsOptions, string, import("vue").VNodeProps & import("vue").AllowedComponentProps & import("vue").ComponentCustomProps, Readonly<import("vue").ExtractPropTypes<{
renderPriority: (StringConstructor | NumberConstructor)[];
accesskey: StringConstructor;
autocapitalize: StringConstructor;
autofocus: {
type: BooleanConstructor;
default: undefined;
};
class: StringConstructor;
contenteditable: {
type: BooleanConstructor;
default: undefined;
};
contextmenu: StringConstructor;
dir: StringConstructor;
draggable: {
type: BooleanConstructor;
default: undefined;
};
enterkeyhint: StringConstructor;
exportparts: StringConstructor;
hidden: {
type: BooleanConstructor;
default: undefined;
};
id: StringConstructor;
inputmode: StringConstructor;
is: StringConstructor;
itemid: StringConstructor;
itemprop: StringConstructor;
itemref: StringConstructor;
itemscope: StringConstructor;
itemtype: StringConstructor;
lang: StringConstructor;
nonce: StringConstructor;
part: StringConstructor;
slot: StringConstructor;
spellcheck: {
type: BooleanConstructor;
default: undefined;
};
style: StringConstructor;
tabindex: StringConstructor;
title: StringConstructor;
translate: StringConstructor;
}>>, {
autofocus: boolean;
contenteditable: boolean;
draggable: boolean;
hidden: boolean;
spellcheck: boolean;
}>;
+209
View File
@@ -0,0 +1,209 @@
import { defineComponent } from "vue";
import { useHead } from "./composables.mjs";
const removeUndefinedProps = (props) => Object.fromEntries(Object.entries(props).filter(([, value]) => value !== void 0));
const setupForUseMeta = (metaFactory, renderChild) => (props, ctx) => {
useHead(() => metaFactory({ ...removeUndefinedProps(props), ...ctx.attrs }, ctx));
return () => renderChild ? ctx.slots.default?.() : null;
};
const globalProps = {
accesskey: String,
autocapitalize: String,
autofocus: {
type: Boolean,
default: void 0
},
class: String,
contenteditable: {
type: Boolean,
default: void 0
},
contextmenu: String,
dir: String,
draggable: {
type: Boolean,
default: void 0
},
enterkeyhint: String,
exportparts: String,
hidden: {
type: Boolean,
default: void 0
},
id: String,
inputmode: String,
is: String,
itemid: String,
itemprop: String,
itemref: String,
itemscope: String,
itemtype: String,
lang: String,
nonce: String,
part: String,
slot: String,
spellcheck: {
type: Boolean,
default: void 0
},
style: String,
tabindex: String,
title: String,
translate: String
};
export const NoScript = defineComponent({
name: "NoScript",
inheritAttrs: false,
props: {
...globalProps,
title: String,
body: Boolean,
renderPriority: [String, Number]
},
setup: setupForUseMeta((props, { slots }) => {
const noscript = { ...props };
const textContent = (slots.default?.() || []).filter(({ children }) => children).map(({ children }) => children).join("");
if (textContent) {
noscript.children = textContent;
}
return {
noscript: [noscript]
};
})
});
export const Link = defineComponent({
name: "Link",
inheritAttrs: false,
props: {
...globalProps,
as: String,
crossorigin: String,
disabled: Boolean,
fetchpriority: String,
href: String,
hreflang: String,
imagesizes: String,
imagesrcset: String,
integrity: String,
media: String,
prefetch: {
type: Boolean,
default: void 0
},
referrerpolicy: String,
rel: String,
sizes: String,
title: String,
type: String,
methods: String,
target: String,
body: Boolean,
renderPriority: [String, Number]
},
setup: setupForUseMeta((link) => ({
link: [link]
}))
});
export const Base = defineComponent({
name: "Base",
inheritAttrs: false,
props: {
...globalProps,
href: String,
target: String
},
setup: setupForUseMeta((base) => ({
base
}))
});
export const Title = defineComponent({
name: "Title",
inheritAttrs: false,
setup: setupForUseMeta((_, { slots }) => {
const title = slots.default?.()?.[0]?.children || null;
if (process.dev && title && typeof title !== "string") {
console.error("<Title> can only take a string in its default slot.");
}
return {
title
};
})
});
export const Meta = defineComponent({
name: "Meta",
inheritAttrs: false,
props: {
...globalProps,
charset: String,
content: String,
httpEquiv: String,
name: String,
body: Boolean,
renderPriority: [String, Number]
},
setup: setupForUseMeta((props) => {
const meta = { ...props };
if (meta.httpEquiv) {
meta["http-equiv"] = meta.httpEquiv;
delete meta.httpEquiv;
}
return {
meta: [meta]
};
})
});
export const Style = defineComponent({
name: "Style",
inheritAttrs: false,
props: {
...globalProps,
type: String,
media: String,
nonce: String,
title: String,
scoped: {
type: Boolean,
default: void 0
},
body: Boolean,
renderPriority: [String, Number]
},
setup: setupForUseMeta((props, { slots }) => {
const style = { ...props };
const textContent = slots.default?.()?.[0]?.children;
if (textContent) {
if (process.dev && typeof textContent !== "string") {
console.error("<Style> can only take a string in its default slot.");
}
style.children = textContent;
}
return {
style: [style]
};
})
});
export const Head = defineComponent({
name: "Head",
inheritAttrs: false,
setup: (_props, ctx) => () => ctx.slots.default?.()
});
export const Html = defineComponent({
name: "Html",
inheritAttrs: false,
props: {
...globalProps,
manifest: String,
version: String,
xmlns: String,
renderPriority: [String, Number]
},
setup: setupForUseMeta((htmlAttrs) => ({ htmlAttrs }), true)
});
export const Body = defineComponent({
name: "Body",
inheritAttrs: false,
props: {
...globalProps,
renderPriority: [String, Number]
},
setup: setupForUseMeta((bodyAttrs) => ({ bodyAttrs }), true)
});
+10
View File
@@ -0,0 +1,10 @@
import type { HeadEntryOptions, UseHeadInput, ActiveHeadEntry } from '@vueuse/head';
import type { HeadAugmentations } from '@nuxt/schema';
/**
* You can pass in a meta object, which has keys corresponding to meta tags:
* `title`, `base`, `script`, `style`, `meta` and `link`, as well as `htmlAttrs` and `bodyAttrs`.
*
* Alternatively, for reactive meta state, you can pass in a function
* that returns a meta object.
*/
export declare function useHead<T extends HeadAugmentations>(input: UseHeadInput<T>, options?: HeadEntryOptions): ActiveHeadEntry<UseHeadInput<T>> | void;
+4
View File
@@ -0,0 +1,4 @@
import { useNuxtApp } from "#app";
export function useHead(input, options) {
return useNuxtApp()._useHead(input, options);
}
+4
View File
@@ -0,0 +1,4 @@
import type { UseHeadInput } from '@vueuse/head';
import type { HeadAugmentations } from '@nuxt/schema';
export * from './composables';
export type MetaObject = UseHeadInput<HeadAugmentations>;
+1
View File
@@ -0,0 +1 @@
export * from "./composables.mjs";
+2
View File
@@ -0,0 +1,2 @@
declare const _default: any;
export default _default;
+31
View File
@@ -0,0 +1,31 @@
import { createApp } from "vue";
import { createMetaManager } from "vue-meta";
import { defineNuxtPlugin } from "#app";
import { appHead } from "#build/nuxt.config.mjs";
export default defineNuxtPlugin((nuxtApp) => {
const manager = createMetaManager(process.server);
manager.addMeta(appHead);
nuxtApp.vueApp.use(manager);
nuxtApp._useHead = (meta) => manager.addMeta(meta);
if (process.client) {
const teleportTarget = document.createElement("div");
teleportTarget.id = "head-target";
document.body.appendChild(teleportTarget);
createApp({ render: () => manager.render({}) }).mount("#head-target");
}
if (process.server) {
nuxtApp.ssrContext.renderMeta = async () => {
const { renderMetaToString } = await import("vue-meta/ssr");
nuxtApp.ssrContext.teleports = nuxtApp.ssrContext.teleports || {};
await renderMetaToString(nuxtApp.app, nuxtApp.ssrContext);
return {
htmlAttrs: nuxtApp.ssrContext.teleports.htmlAttrs || "",
headAttrs: nuxtApp.ssrContext.teleports.headAttrs || "",
bodyAttrs: nuxtApp.ssrContext.teleports.bodyAttrs || "",
headTags: nuxtApp.ssrContext.teleports.head || "",
bodyScriptsPrepend: nuxtApp.ssrContext.teleports["body-prepend"] || "",
bodyScripts: nuxtApp.ssrContext.teleports.body || ""
};
};
}
});
+2
View File
@@ -0,0 +1,2 @@
declare const _default: any;
export default _default;
+35
View File
@@ -0,0 +1,35 @@
import { createHead, useHead } from "@vueuse/head";
import { defineNuxtPlugin } from "#app";
import { appHead } from "#build/nuxt.config.mjs";
export default defineNuxtPlugin((nuxtApp) => {
const head = createHead();
head.push(appHead);
nuxtApp.vueApp.use(head);
if (process.client) {
let pauseDOMUpdates = true;
const unpauseDom = () => {
pauseDOMUpdates = false;
head.internalHooks.callHook("entries:updated", head.unhead);
};
head.internalHooks.hook("dom:beforeRender", (context) => {
context.shouldRender = !pauseDOMUpdates;
});
nuxtApp.hooks.hook("page:start", () => {
pauseDOMUpdates = true;
});
nuxtApp.hooks.hook("page:finish", unpauseDom);
nuxtApp.hooks.hook("app:mounted", unpauseDom);
}
nuxtApp._useHead = useHead;
if (process.server) {
nuxtApp.ssrContext.renderMeta = async () => {
const { renderSSRHead } = await import("@unhead/ssr");
const meta = await renderSSRHead(head.unhead);
return {
...meta,
bodyScriptsPrepend: meta.bodyTagsOpen,
bodyScripts: meta.bodyTags
};
};
}
});
+7
View File
@@ -0,0 +1,7 @@
export type Props = Readonly<Record<string, any>>;
export type FetchPriority = 'high' | 'low' | 'auto';
export type CrossOrigin = '' | 'anonymous' | 'use-credentials';
export type HTTPEquiv = 'content-security-policy' | 'content-type' | 'default-style' | 'refresh' | 'x-ua-compatible';
export type ReferrerPolicy = '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'same-origin' | 'origin' | 'strict-origin' | 'origin-when-cross-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url';
export type LinkRelationship = 'alternate' | 'author' | 'canonical' | 'dns-prefetch' | 'help' | 'icon' | 'license' | 'manifest' | 'me' | 'modulepreload' | 'next' | 'pingback' | 'preconnect' | 'prefetch' | 'preload' | 'prerender' | 'prev' | 'search' | 'stylesheet' | (string & {});
export type Target = '_blank' | '_self' | '_parent' | '_top' | (string & {});
View File
+9
View File
@@ -0,0 +1,9 @@
import { NuxtOptions, Nuxt } from '@nuxt/schema';
import { LoadNuxtOptions } from '@nuxt/kit';
declare function createNuxt(options: NuxtOptions): Nuxt;
declare function loadNuxt(opts: LoadNuxtOptions): Promise<Nuxt>;
declare function build(nuxt: Nuxt): Promise<void>;
export { build, createNuxt, loadNuxt };
+2272
View File
File diff suppressed because it is too large Load Diff
+5
View File
@@ -0,0 +1,5 @@
<template>
<NuxtLayout>
<NuxtPage />
</NuxtLayout>
</template>
+42
View File
@@ -0,0 +1,42 @@
import { KeepAliveProps, TransitionProps, UnwrapRef } from 'vue';
import type { RouteLocationNormalized, RouteLocationNormalizedLoaded, RouteRecordRedirectOption } from 'vue-router';
import type { NuxtError } from '#app';
export interface PageMeta {
[key: string]: any;
/**
* 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 | Promise<boolean> | Partial<NuxtError> | Promise<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;
/** Set to `false` to avoid scrolling to top on page navigations */
scrollToTop?: boolean;
}
declare module 'vue-router' {
interface RouteMeta extends UnwrapRef<PageMeta> {
}
}
export declare const definePageMeta: (meta: PageMeta) => void;
+8
View File
@@ -0,0 +1,8 @@
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 (process.dev) {
warnRuntimeUsage("definePageMeta");
}
};
+1
View File
@@ -0,0 +1 @@
export * from './composables';

Some files were not shown because too many files have changed in this diff Show More