import { createRenderer, getRequestDependencies, getPreloadLinks, getPrefetchLinks } from 'vue-bundle-renderer/runtime'; import { b as buildAssetsURL, p as publicAssetsURL, a as appRootTag, c as appRootAttrs, u as useRuntimeConfig, d as appId, e as encodePath, f as defineRenderHandler, g as appTeleportTag, h as appTeleportAttrs, i as getQuery, j as createError, k as appHead, l as getRouteRules, m as getResponseStatusText, n as getResponseStatus, o as useNitroApp } from '../nitro/nitro.mjs'; import { renderToString } from 'vue/server-renderer'; import { createHead as createHead$1, propsToString, renderSSRHead } from 'unhead/server'; import { stringify, uneval } from 'devalue'; import { walkResolver } from 'unhead/utils'; import { isRef, toValue, hasInjectionContext, inject, ref, watchEffect, getCurrentInstance, onBeforeUnmount, onDeactivated, onActivated } from 'vue'; import { DeprecationsPlugin, PromisesPlugin, TemplateParamsPlugin, AliasSortingPlugin } from 'unhead/plugins'; const VueResolver = (_, value) => { return isRef(value) ? toValue(value) : value; }; const headSymbol = "usehead"; // @__NO_SIDE_EFFECTS__ function vueInstall(head) { const plugin = { install(app) { app.config.globalProperties.$unhead = head; app.config.globalProperties.$head = head; app.provide(headSymbol, head); } }; return plugin.install; } // @__NO_SIDE_EFFECTS__ function injectHead() { if (hasInjectionContext()) { const instance = inject(headSymbol); if (instance) { return instance; } } throw new Error("useHead() was called without provide context, ensure you call it through the setup() function."); } function useHead(input, options = {}) { const head = options.head || /* @__PURE__ */ injectHead(); return head.ssr ? head.push(input || {}, options) : clientUseHead(head, input, options); } function clientUseHead(head, input, options = {}) { const deactivated = ref(false); let entry; watchEffect(() => { const i = deactivated.value ? {} : walkResolver(input, VueResolver); if (entry) { entry.patch(i); } else { entry = head.push(i, options); } }); const vm = getCurrentInstance(); if (vm) { onBeforeUnmount(() => { entry.dispose(); }); onDeactivated(() => { deactivated.value = true; }); onActivated(() => { deactivated.value = false; }); } return entry; } // @__NO_SIDE_EFFECTS__ function createHead(options = {}) { const head = createHead$1({ ...options, propResolvers: [VueResolver] }); head.install = vueInstall(head); return head; } const NUXT_RUNTIME_PAYLOAD_EXTRACTION = false; // @ts-expect-error private property consumed by vite-generated url helpers globalThis.__buildAssetsURL = buildAssetsURL; // @ts-expect-error private property consumed by vite-generated url helpers globalThis.__publicAssetsURL = publicAssetsURL; const APP_ROOT_OPEN_TAG = `<${appRootTag}${propsToString(appRootAttrs)}>`; const APP_ROOT_CLOSE_TAG = ``; // @ts-expect-error file will be produced after app build const getServerEntry = () => import('../build/server.mjs').then((r) => r.default || r); // @ts-expect-error file will be produced after app build const getPrecomputedDependencies = () => import('../build/client.precomputed.mjs').then((r) => r.default || r).then((r) => typeof r === "function" ? r() : r); const getSSRRenderer = lazyCachedFunction(async () => { const createSSRApp = await getServerEntry(); if (!createSSRApp) { throw new Error("Server bundle is not available"); } const precomputed = await getPrecomputedDependencies(); const renderer = createRenderer(createSSRApp, { precomputed, manifest: undefined, renderToString: renderToString$1, buildAssetsURL }); async function renderToString$1(input, context) { const html = await renderToString(input, context); return APP_ROOT_OPEN_TAG + html + APP_ROOT_CLOSE_TAG; } return renderer; }); const getSPARenderer = lazyCachedFunction(async () => { const precomputed = await getPrecomputedDependencies(); // @ts-expect-error virtual file const spaTemplate = await import('../virtual/_virtual_spa-template.mjs').then((r) => r.template).catch(() => "").then((r) => { { return APP_ROOT_OPEN_TAG + r + APP_ROOT_CLOSE_TAG; } }); const renderer = createRenderer(() => () => {}, { precomputed, manifest: undefined, renderToString: () => spaTemplate, buildAssetsURL }); const result = await renderer.renderToString({}); const renderToString = (ssrContext) => { const config = useRuntimeConfig(ssrContext.event); ssrContext.modules ||= new Set(); ssrContext.payload.serverRendered = false; ssrContext.config = { public: config.public, app: config.app }; return Promise.resolve(result); }; return { rendererContext: renderer.rendererContext, renderToString }; }); function lazyCachedFunction(fn) { let res = null; return () => { if (res === null) { res = fn().catch((err) => { res = null; throw err; }); } return res; }; } function getRenderer(ssrContext) { return ssrContext.noSSR ? getSPARenderer() : getSSRRenderer(); } // @ts-expect-error file will be produced after app build const getSSRStyles = lazyCachedFunction(() => import('../build/styles.mjs').then((r) => r.default || r)); function renderPayloadJsonScript(opts) { const contents = opts.data ? encodeForwardSlashes(stringify(opts.data, opts.ssrContext["~payloadReducers"])) : ""; const payload = { "type": "application/json", "innerHTML": contents, "data-nuxt-data": appId, "data-ssr": !(opts.ssrContext.noSSR) }; { payload.id = "__NUXT_DATA__"; } if (opts.src) { payload["data-src"] = opts.src; } const config = uneval(opts.ssrContext.config); return [payload, { innerHTML: `window.__NUXT__={};window.__NUXT__.config=${config}` }]; } function encodeForwardSlashes(str) { return str.replaceAll("/", "\\u002F"); } const unheadOptions = { disableDefaults: true, disableCapoSorting: false, plugins: [DeprecationsPlugin, PromisesPlugin, TemplateParamsPlugin, AliasSortingPlugin], }; function encodeEventPath(path) { const queryIndex = path.indexOf("?"); if (queryIndex === -1) { return encodePath(path); } return encodePath(path.slice(0, queryIndex)) + path.slice(queryIndex); } function createSSRContext(event) { const url = encodeEventPath(event.path); const ssrContext = { url, event, runtimeConfig: useRuntimeConfig(event), noSSR: event.context.nuxt?.noSSR || (false), head: createHead(unheadOptions), error: false, nuxt: undefined, payload: {}, ["~payloadReducers"]: Object.create(null), modules: new Set() }; return ssrContext; } function setSSRError(ssrContext, error) { ssrContext.error = true; ssrContext.payload = { error }; ssrContext.url = error.url; } async function renderInlineStyles(usedModules) { const styleMap = await getSSRStyles(); const inlinedStyles = new Set(); for (const mod of usedModules) { if (mod in styleMap && styleMap[mod]) { for (const style of await styleMap[mod]()) { inlinedStyles.add(style); } } } return Array.from(inlinedStyles).map((style) => ({ innerHTML: style })); } const renderSSRHeadOptions = {"omitLineBreaks":false}; const entryIds = ["node_modules/nuxt/dist/app/entry.js"]; // @ts-expect-error private property consumed by vite-generated url helpers globalThis.__buildAssetsURL = buildAssetsURL; // @ts-expect-error private property consumed by vite-generated url helpers globalThis.__publicAssetsURL = publicAssetsURL; const HAS_APP_TELEPORTS = !!(appTeleportAttrs.id); const APP_TELEPORT_OPEN_TAG = HAS_APP_TELEPORTS ? `<${appTeleportTag}${propsToString(appTeleportAttrs)}>` : ""; const APP_TELEPORT_CLOSE_TAG = HAS_APP_TELEPORTS ? `` : ""; const handler = defineRenderHandler((event) => { const ssrError = event.path.startsWith("/__nuxt_error") ? getQuery(event) : null; if (ssrError && !("__unenv__" in event.node.req)) { throw createError({ status: 404, statusText: "Page Not Found: /__nuxt_error", message: "Page Not Found: /__nuxt_error" }); } return renderRoute(event, ssrError); }); async function renderRoute(event, ssrError) { const nitroApp = useNitroApp(); const ssrContext = createSSRContext(event); const headEntryOptions = { mode: "server" }; ssrContext.head.push(appHead, headEntryOptions); if (ssrError) { const status = ssrError.status || ssrError.statusCode; if (status) { ssrError.status = ssrError.statusCode = Number.parseInt(status); } setSSRError(ssrContext, ssrError); } const routeOptions = getRouteRules(event); if (routeOptions.ssr === false) { ssrContext.noSSR = true; } !ssrContext.noSSR && (NUXT_RUNTIME_PAYLOAD_EXTRACTION); const renderer = await getRenderer(ssrContext); { for (const id of entryIds) { ssrContext.modules.add(id); } } const _rendered = await renderer.renderToString(ssrContext).catch(async (error) => { if ((ssrContext["~renderResponse"] || ssrContext._renderResponse) && error.message === "skipping render") { return {}; } const _err = !ssrError && ssrContext.payload?.error || error; await ssrContext.nuxt?.hooks.callHook("app:error", _err); throw _err; }); const inlinedStyles = !ssrContext["~renderResponse"] && !ssrContext._renderResponse && true ? await renderInlineStyles(ssrContext.modules ?? []) : []; await ssrContext.nuxt?.hooks.callHook("app:rendered", { ssrContext, renderResult: _rendered }); if (ssrContext["~renderResponse"] || ssrContext._renderResponse) { return ssrContext["~renderResponse"] || ssrContext._renderResponse; } if (ssrContext.payload?.error && !ssrError) { throw ssrContext.payload.error; } const NO_SCRIPTS = routeOptions.noScripts; const { styles, scripts } = getRequestDependencies(ssrContext, renderer.rendererContext); if (ssrContext["~preloadManifest"] && !NO_SCRIPTS) { ssrContext.head.push({ link: [{ rel: "preload", as: "fetch", fetchpriority: "low", crossorigin: "anonymous", href: buildAssetsURL(`builds/meta/${ssrContext.runtimeConfig.app.buildId}.json`) }] }, { ...headEntryOptions, tagPriority: "low" }); } if (inlinedStyles.length) { ssrContext.head.push({ style: inlinedStyles }); } const link = []; for (const resource of Object.values(styles)) { link.push({ rel: "stylesheet", href: renderer.rendererContext.buildAssetsURL(resource.file), crossorigin: "" }); } if (link.length) { ssrContext.head.push({ link }, headEntryOptions); } if (!NO_SCRIPTS) { if (ssrContext["~lazyHydratedModules"]) { for (const id of ssrContext["~lazyHydratedModules"]) { ssrContext.modules?.delete(id); } } ssrContext.head.push({ link: getPreloadLinks(ssrContext, renderer.rendererContext) }, headEntryOptions); ssrContext.head.push({ link: getPrefetchLinks(ssrContext, renderer.rendererContext) }, headEntryOptions); ssrContext.head.push({ script: renderPayloadJsonScript({ ssrContext, data: ssrContext.payload }) }, { ...headEntryOptions, tagPosition: "bodyClose", tagPriority: "high" }); } if (!routeOptions.noScripts) { const tagPosition = "head"; ssrContext.head.push({ script: Object.values(scripts).map((resource) => ({ type: resource.module ? "module" : null, src: renderer.rendererContext.buildAssetsURL(resource.file), defer: resource.module ? null : true, tagPosition, crossorigin: "" })) }, headEntryOptions); } const { headTags, bodyTags, bodyTagsOpen, htmlAttrs, bodyAttrs } = await renderSSRHead(ssrContext.head, renderSSRHeadOptions); const htmlContext = { htmlAttrs: htmlAttrs ? [htmlAttrs] : [], head: normalizeChunks([headTags]), bodyAttrs: bodyAttrs ? [bodyAttrs] : [], bodyPrepend: normalizeChunks([bodyTagsOpen, ssrContext.teleports?.body]), body: [_rendered.html, APP_TELEPORT_OPEN_TAG + (HAS_APP_TELEPORTS ? joinTags([ssrContext.teleports?.[`#${appTeleportAttrs.id}`]]) : "") + APP_TELEPORT_CLOSE_TAG], bodyAppend: [bodyTags] }; await nitroApp.hooks.callHook("render:html", htmlContext, { event }); return { body: renderHTMLDocument(htmlContext), statusCode: getResponseStatus(event), statusMessage: getResponseStatusText(event), headers: { "content-type": "text/html;charset=utf-8", "x-powered-by": "Nuxt" } }; } function normalizeChunks(chunks) { const result = []; for (const _chunk of chunks) { const chunk = _chunk?.trim(); if (chunk) { result.push(chunk); } } return result; } function joinTags(tags) { return tags.join(""); } function joinAttrs(chunks) { if (chunks.length === 0) { return ""; } return " " + chunks.join(" "); } function renderHTMLDocument(html) { return "" + `` + `${joinTags(html.head)}` + `${joinTags(html.bodyPrepend)}${joinTags(html.body)}${joinTags(html.bodyAppend)}` + ""; } const renderer = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ __proto__: null, default: handler }, Symbol.toStringTag, { value: 'Module' })); export { headSymbol as h, renderer as r, useHead as u }; //# sourceMappingURL=renderer.mjs.map