@analogjs/vite-plugin-nitro 3.0.0-alpha.91 → 3.0.0-alpha.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/migrations/migration.json +7 -1
  2. package/migrations/update-nitro-options/update-nitro-options.d.ts +2 -0
  3. package/migrations/update-nitro-options/update-nitro-options.js +122 -0
  4. package/migrations/update-nitro-options/update-nitro-options.js.map +1 -0
  5. package/package.json +5 -10
  6. package/src/index.d.ts +5 -5
  7. package/src/index.js +1 -2
  8. package/src/index.js.map +1 -1
  9. package/src/lib/build-server.d.ts +2 -3
  10. package/src/lib/build-server.js +88 -35
  11. package/src/lib/build-server.js.map +1 -1
  12. package/src/lib/build-sitemap.d.ts +8 -8
  13. package/src/lib/build-sitemap.js +77 -116
  14. package/src/lib/build-sitemap.js.map +1 -1
  15. package/src/lib/build-ssr.d.ts +1 -2
  16. package/src/lib/build-ssr.js +6 -15
  17. package/src/lib/build-ssr.js.map +1 -1
  18. package/src/lib/hooks/post-rendering-hook.d.ts +1 -1
  19. package/src/lib/hooks/post-rendering-hook.js +1 -3
  20. package/src/lib/hooks/post-rendering-hook.js.map +1 -1
  21. package/src/lib/options.d.ts +30 -25
  22. package/src/lib/plugins/dev-server-plugin.d.ts +1 -1
  23. package/src/lib/plugins/dev-server-plugin.js +13 -11
  24. package/src/lib/plugins/dev-server-plugin.js.map +1 -1
  25. package/src/lib/plugins/page-endpoints.js +10 -14
  26. package/src/lib/plugins/page-endpoints.js.map +1 -1
  27. package/src/lib/plugins/server-fn-id-plugin.d.ts +4 -1
  28. package/src/lib/plugins/server-fn-id-plugin.js.map +1 -1
  29. package/src/lib/runtime/locale-worker-entry.mjs +71 -0
  30. package/src/lib/runtime/locale-workers.mjs +193 -0
  31. package/src/lib/utils/get-content-files.js +1 -1
  32. package/src/lib/utils/get-content-files.js.map +1 -1
  33. package/src/lib/utils/get-page-handlers.d.ts +10 -7
  34. package/src/lib/utils/get-page-handlers.js +10 -7
  35. package/src/lib/utils/get-page-handlers.js.map +1 -1
  36. package/src/lib/utils/i18n-prerender.d.ts +1 -0
  37. package/src/lib/utils/i18n-prerender.js +48 -1
  38. package/src/lib/utils/i18n-prerender.js.map +1 -1
  39. package/src/lib/utils/i18n-workers.d.ts +6 -0
  40. package/src/lib/utils/i18n-workers.js +55 -0
  41. package/src/lib/utils/i18n-workers.js.map +1 -0
  42. package/src/lib/utils/register-dev-middleware.d.ts +32 -4
  43. package/src/lib/utils/register-dev-middleware.js +34 -21
  44. package/src/lib/utils/register-dev-middleware.js.map +1 -1
  45. package/src/lib/utils/renderers.d.ts +5 -33
  46. package/src/lib/utils/renderers.js +121 -75
  47. package/src/lib/utils/renderers.js.map +1 -1
  48. package/src/lib/utils/server-fn-endpoints.js +3 -1
  49. package/src/lib/utils/server-fn-endpoints.js.map +1 -1
  50. package/src/lib/vite-plugin-nitro.d.ts +9 -2
  51. package/src/lib/vite-plugin-nitro.js +187 -562
  52. package/src/lib/vite-plugin-nitro.js.map +1 -1
  53. package/src/lib/utils/debug.d.ts +0 -5
  54. package/src/lib/utils/debug.js +0 -15
  55. package/src/lib/utils/debug.js.map +0 -1
  56. package/src/lib/utils/node-web-bridge.d.ts +0 -3
  57. package/src/lib/utils/node-web-bridge.js +0 -55
  58. package/src/lib/utils/node-web-bridge.js.map +0 -1
  59. package/src/lib/utils/rolldown.d.ts +0 -2
  60. package/src/lib/utils/rolldown.js +0 -12
  61. package/src/lib/utils/rolldown.js.map +0 -1
@@ -1,136 +1,97 @@
1
1
  import { resolve } from "node:path";
2
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { writeFileSync } from "node:fs";
3
3
  import { create } from "xmlbuilder2";
4
4
  //#region packages/vite-plugin-nitro/src/lib/build-sitemap.ts
5
- async function buildSitemap(_config, sitemapConfig, routes, outputDir, routeSitemaps, buildOptions = {}) {
6
- const host = normalizeSitemapHost(sitemapConfig.host);
7
- const sitemapData = await resolveSitemapEntries(await collectSitemapRoutes(routes, sitemapConfig.include), host, routeSitemaps, sitemapConfig, buildOptions);
8
- if (!sitemapData.length) return;
9
- const sitemap = createXml("urlset");
10
- for (const item of sitemapData) {
11
- const page = sitemap.ele("url");
12
- page.ele("loc").txt(item.loc);
13
- if (item.lastmod) page.ele("lastmod").txt(item.lastmod);
14
- if (item.changefreq) page.ele("changefreq").txt(item.changefreq);
15
- if (item.priority !== void 0) page.ele("priority").txt(String(item.priority));
16
- }
17
- const resolvedOutputDir = resolve(outputDir);
18
- const mapPath = resolve(resolvedOutputDir, "sitemap.xml");
19
- try {
20
- if (!resolvedOutputDir || resolvedOutputDir === resolve()) throw new Error("Refusing to write the sitemap to the current working directory. Expected the Nitro public output directory instead.");
21
- if (!existsSync(resolvedOutputDir)) mkdirSync(resolvedOutputDir, { recursive: true });
22
- console.log(`Writing sitemap at ${mapPath}`);
23
- writeFileSync(mapPath, sitemap.end({ prettyPrint: true }));
24
- } catch (e) {
25
- console.error(`Unable to write file at ${mapPath}`, e);
5
+ async function buildSitemap(config, sitemapConfig, routes, outputDir, routeSitemaps, i18nOptions) {
6
+ const routeList = await optionHasRoutes(routes);
7
+ if (routeList.length) {
8
+ const slash = checkSlash(sitemapConfig.host || "");
9
+ const sitemapData = routeList.map((page) => {
10
+ const url = `${slash}${page.replace(/^\/+/g, "")}`;
11
+ const config = routeSitemaps[url];
12
+ const props = typeof config === "object" ? config : config?.();
13
+ return {
14
+ page: `${sitemapConfig.host}${url}`,
15
+ lastMod: props?.lastmod ?? (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
16
+ changefreq: props?.changefreq,
17
+ priority: props?.priority
18
+ };
19
+ });
20
+ const hasI18n = i18nOptions && i18nOptions.locales.length > 1;
21
+ const sitemap = createXml("urlset", hasI18n);
22
+ for (const item of sitemapData) {
23
+ const page = sitemap.ele("url");
24
+ page.ele("loc").txt(item.page);
25
+ page.ele("lastmod").txt(item.lastMod);
26
+ if (item.changefreq) page.ele("changefreq").txt(item.changefreq);
27
+ if (item.priority) page.ele("priority").txt(item.priority);
28
+ if (hasI18n) {
29
+ const alternates = getHreflangAlternates(item.page, sitemapConfig.host, i18nOptions);
30
+ for (const alt of alternates) page.ele("xhtml:link").att("rel", "alternate").att("hreflang", alt.locale).att("href", alt.href);
31
+ }
32
+ }
33
+ const mapPath = `${resolve(outputDir)}/sitemap.xml`;
34
+ try {
35
+ console.log(`Writing sitemap at ${mapPath}`);
36
+ writeFileSync(mapPath, sitemap.end({ prettyPrint: true }));
37
+ } catch (e) {
38
+ console.error(`Unable to write file at ${mapPath}`, e);
39
+ }
26
40
  }
27
41
  }
28
- async function resolveSitemapEntries(routes, host, routeSitemaps, sitemapConfig, buildOptions) {
29
- const defaults = sitemapConfig.defaults ?? {};
30
- const seen = /* @__PURE__ */ new Set();
31
- const entries = [];
32
- for (const route of routes) {
33
- const entry = await toSitemapEntry(route, host, routeSitemaps, defaults, sitemapConfig.transform);
34
- if (!entry) continue;
35
- if (isInternalSitemapRoute(entry.route, buildOptions.apiPrefix) || await isExcludedSitemapRoute(entry, sitemapConfig.exclude)) continue;
36
- if (seen.has(entry.loc)) continue;
37
- seen.add(entry.loc);
38
- entries.push(entry);
42
+ /**
43
+ * Generates hreflang alternate URLs for a given page URL.
44
+ * For a URL like `https://example.com/fr/about`, it produces alternates
45
+ * for all configured locales.
46
+ */
47
+ function getHreflangAlternates(pageUrl, host, i18n) {
48
+ const alternates = [];
49
+ const normalizedHost = host.replace(/\/+$/, "");
50
+ const basePath = stripLocalePrefix(pageUrl.replace(normalizedHost, ""), i18n.locales);
51
+ for (const locale of i18n.locales) {
52
+ const localizedPath = basePath === "/" || basePath === "" ? `/${locale}` : `/${locale}${basePath}`;
53
+ alternates.push({
54
+ locale,
55
+ href: `${normalizedHost}${localizedPath}`
56
+ });
39
57
  }
40
- return entries;
41
- }
42
- async function toSitemapEntry(route, host, routeSitemaps, defaults, transform) {
43
- const normalizedRoute = normalizeSitemapRoute(typeof route === "string" ? route : route?.route);
44
- if (!normalizedRoute) return;
45
- const baseEntry = createSitemapEntry({
46
- ...defaults,
47
- ...resolveRouteSitemapConfig(routeSitemaps[normalizedRoute]),
48
- ...typeof route === "object" ? route : {},
49
- route: normalizedRoute
50
- }, host);
51
- if (!transform) return baseEntry;
52
- const transformed = await transform(baseEntry);
53
- if (!transformed) return;
54
- return createSitemapEntry({
55
- ...baseEntry,
56
- ...transformed
57
- }, host);
58
- }
59
- function createSitemapEntry(routeDefinition, host) {
60
- const route = normalizeSitemapRoute(routeDefinition.route) ?? "/";
61
- return {
62
- route,
63
- loc: new URL(route, ensureTrailingSlash(host)).toString(),
64
- lastmod: routeDefinition.lastmod,
65
- changefreq: routeDefinition.changefreq,
66
- priority: routeDefinition.priority
67
- };
68
- }
69
- function resolveRouteSitemapConfig(config) {
70
- if (!config) return {};
71
- return typeof config === "function" ? config() : config;
58
+ const defaultPath = basePath === "/" || basePath === "" ? `/${i18n.defaultLocale}` : `/${i18n.defaultLocale}${basePath}`;
59
+ alternates.push({
60
+ locale: "x-default",
61
+ href: `${normalizedHost}${defaultPath}`
62
+ });
63
+ return alternates;
72
64
  }
73
- function normalizeSitemapHost(host) {
74
- const resolvedHost = new URL(host);
75
- resolvedHost.hash = "";
76
- return resolvedHost.toString();
77
- }
78
- function ensureTrailingSlash(host) {
79
- return host.endsWith("/") ? host : `${host}/`;
80
- }
81
- function normalizeSitemapRoute(route) {
82
- if (!route) return;
83
- const trimmedRoute = route.trim();
84
- if (!trimmedRoute) return;
85
- const [pathname, search] = (trimmedRoute.split("#", 1)[0] ?? "").split("?", 2);
86
- const normalizedPathname = pathname ? `/${pathname.replace(/^\/+/, "").replace(/\/{2,}/g, "/")}` : "/";
87
- return search ? `${normalizedPathname}?${search}` : normalizedPathname;
88
- }
89
- function isInternalSitemapRoute(route, apiPrefix = "api") {
90
- const normalizedApiPrefix = normalizeSitemapRoute(`/${apiPrefix}`) ?? "/api";
91
- return route === `${normalizedApiPrefix}/_analog/pages` || route.startsWith(`${normalizedApiPrefix}/_analog/pages/`);
92
- }
93
- async function isExcludedSitemapRoute(entry, excludeRules) {
94
- if (!excludeRules?.length) return false;
95
- for (const rule of excludeRules) {
96
- if (typeof rule === "function") {
97
- if (await rule(entry)) return true;
98
- continue;
99
- }
100
- if (rule instanceof RegExp) {
101
- if (rule.test(entry.route)) return true;
102
- continue;
103
- }
104
- if (toGlobRegExp(rule).test(entry.route)) return true;
65
+ /**
66
+ * Strips a locale prefix from a URL path.
67
+ * E.g., '/fr/about' -> '/about', '/en' -> '/'
68
+ */
69
+ function stripLocalePrefix(path, locales) {
70
+ const segments = path.split("/").filter(Boolean);
71
+ if (segments.length > 0 && locales.includes(segments[0])) {
72
+ const rest = segments.slice(1).join("/");
73
+ return rest ? `/${rest}` : "/";
105
74
  }
106
- return false;
75
+ return path || "/";
107
76
  }
108
- function toGlobRegExp(pattern) {
109
- const doubleStarToken = "__ANALOG_DOUBLE_STAR__";
110
- const singleStarToken = "__ANALOG_SINGLE_STAR__";
111
- const regexPattern = pattern.replace(/\*\*/g, doubleStarToken).replace(/\*/g, singleStarToken).replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(new RegExp(doubleStarToken, "g"), ".*").replace(new RegExp(singleStarToken, "g"), "[^/]*");
112
- return new RegExp(`^${regexPattern}$`);
77
+ function createXml(elementName, includeXhtml = false) {
78
+ const attrs = { xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9" };
79
+ if (includeXhtml) attrs["xmlns:xhtml"] = "http://www.w3.org/1999/xhtml";
80
+ return create({
81
+ version: "1.0",
82
+ encoding: "UTF-8"
83
+ }).ele(elementName, attrs).com(`This file was automatically generated by Analog.`);
113
84
  }
114
- async function collectSitemapRoutes(routes, include) {
115
- const routeList = await resolveRouteInputs(routes);
116
- const includedRoutes = include ? await resolveRouteInputs(include) : [];
117
- return [...routeList, ...includedRoutes];
85
+ function checkSlash(host) {
86
+ return host.slice(-1) === "/" ? "" : "/";
118
87
  }
119
- async function resolveRouteInputs(routes) {
88
+ async function optionHasRoutes(routes) {
120
89
  let routeList;
121
90
  if (typeof routes === "function") routeList = await routes();
122
91
  else if (Array.isArray(routes)) routeList = routes;
123
92
  else routeList = [];
124
93
  return routeList.filter(Boolean);
125
94
  }
126
- function createXml(elementName, includeXhtml = false) {
127
- const attrs = { xmlns: "https://www.sitemaps.org/schemas/sitemap/0.9" };
128
- if (includeXhtml) attrs["xmlns:xhtml"] = "https://www.w3.org/1999/xhtml";
129
- return create({
130
- version: "1.0",
131
- encoding: "UTF-8"
132
- }).ele(elementName, attrs).com(`This file was automatically generated by Analog.`);
133
- }
134
95
  //#endregion
135
96
  export { buildSitemap };
136
97
 
@@ -1 +1 @@
1
- {"version":3,"file":"build-sitemap.js","names":[],"sources":["../../../src/lib/build-sitemap.ts"],"sourcesContent":["import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { create } from 'xmlbuilder2';\nimport { XMLBuilder } from 'xmlbuilder2/lib/interfaces';\nimport { UserConfig } from 'vite';\nimport {\n I18nPrerenderOptions,\n PrerenderSitemapConfig,\n SitemapConfig,\n SitemapEntry,\n SitemapExcludeRule,\n SitemapRouteDefinition,\n SitemapRouteInput,\n SitemapRouteSource,\n} from './options';\n\ntype RouteSitemapConfig =\n | PrerenderSitemapConfig\n | (() => PrerenderSitemapConfig)\n | undefined;\n\nexport type PagesJson = SitemapEntry;\n\nexport interface BuildSitemapOptions {\n apiPrefix?: string;\n}\n\nexport async function buildSitemap(\n _config: UserConfig,\n sitemapConfig: SitemapConfig,\n routes: (string | undefined)[] | (() => Promise<(string | undefined)[]>),\n outputDir: string,\n routeSitemaps: Record<string, RouteSitemapConfig>,\n buildOptions: BuildSitemapOptions = {},\n): Promise<void> {\n const host = normalizeSitemapHost(sitemapConfig.host);\n const routeList = await collectSitemapRoutes(routes, sitemapConfig.include);\n const sitemapData = await resolveSitemapEntries(\n routeList,\n host,\n routeSitemaps,\n sitemapConfig,\n buildOptions,\n );\n\n if (!sitemapData.length) {\n return;\n }\n\n const sitemap = createXml('urlset');\n\n for (const item of sitemapData) {\n const page = sitemap.ele('url');\n page.ele('loc').txt(item.loc);\n\n if (item.lastmod) {\n page.ele('lastmod').txt(item.lastmod);\n }\n\n if (item.changefreq) {\n page.ele('changefreq').txt(item.changefreq);\n }\n\n if (item.priority !== undefined) {\n page.ele('priority').txt(String(item.priority));\n }\n }\n\n const resolvedOutputDir = resolve(outputDir);\n const mapPath = resolve(resolvedOutputDir, 'sitemap.xml');\n try {\n if (!resolvedOutputDir || resolvedOutputDir === resolve()) {\n throw new Error(\n 'Refusing to write the sitemap to the current working directory. Expected the Nitro public output directory instead.',\n );\n }\n\n if (!existsSync(resolvedOutputDir)) {\n mkdirSync(resolvedOutputDir, { recursive: true });\n }\n console.log(`Writing sitemap at ${mapPath}`);\n writeFileSync(mapPath, sitemap.end({ prettyPrint: true }));\n } catch (e) {\n console.error(`Unable to write file at ${mapPath}`, e);\n }\n}\n\nasync function resolveSitemapEntries(\n routes: SitemapRouteInput[],\n host: string,\n routeSitemaps: Record<string, RouteSitemapConfig>,\n sitemapConfig: SitemapConfig,\n buildOptions: BuildSitemapOptions,\n): Promise<SitemapEntry[]> {\n const defaults = sitemapConfig.defaults ?? {};\n const seen = new Set<string>();\n const entries: SitemapEntry[] = [];\n\n for (const route of routes) {\n const entry = await toSitemapEntry(\n route,\n host,\n routeSitemaps,\n defaults,\n sitemapConfig.transform,\n );\n\n if (!entry) {\n continue;\n }\n\n if (\n isInternalSitemapRoute(entry.route, buildOptions.apiPrefix) ||\n (await isExcludedSitemapRoute(entry, sitemapConfig.exclude))\n ) {\n continue;\n }\n\n if (seen.has(entry.loc)) {\n continue;\n }\n\n seen.add(entry.loc);\n entries.push(entry);\n }\n\n return entries;\n}\n\nasync function toSitemapEntry(\n route: SitemapRouteInput,\n host: string,\n routeSitemaps: Record<string, RouteSitemapConfig>,\n defaults: PrerenderSitemapConfig,\n transform: SitemapConfig['transform'],\n): Promise<SitemapEntry | undefined> {\n const normalizedRoute = normalizeSitemapRoute(\n typeof route === 'string' ? route : route?.route,\n );\n if (!normalizedRoute) {\n return undefined;\n }\n\n const baseEntry = createSitemapEntry(\n {\n ...defaults,\n ...resolveRouteSitemapConfig(routeSitemaps[normalizedRoute]),\n ...(typeof route === 'object' ? route : {}),\n route: normalizedRoute,\n },\n host,\n );\n\n if (!transform) {\n return baseEntry;\n }\n\n const transformed = await transform(baseEntry);\n if (!transformed) {\n return undefined;\n }\n\n return createSitemapEntry(\n {\n ...baseEntry,\n ...transformed,\n },\n host,\n );\n}\n\nfunction createSitemapEntry(\n routeDefinition: SitemapRouteDefinition,\n host: string,\n): SitemapEntry {\n const route = normalizeSitemapRoute(routeDefinition.route) ?? '/';\n\n return {\n route,\n loc: new URL(route, ensureTrailingSlash(host)).toString(),\n lastmod: routeDefinition.lastmod,\n changefreq: routeDefinition.changefreq,\n priority: routeDefinition.priority,\n };\n}\n\nfunction resolveRouteSitemapConfig(\n config: RouteSitemapConfig,\n): PrerenderSitemapConfig {\n if (!config) {\n return {};\n }\n\n return typeof config === 'function' ? config() : config;\n}\n\nfunction normalizeSitemapHost(host: string): string {\n const resolvedHost = new URL(host);\n resolvedHost.hash = '';\n return resolvedHost.toString();\n}\n\nfunction ensureTrailingSlash(host: string): string {\n return host.endsWith('/') ? host : `${host}/`;\n}\n\nfunction normalizeSitemapRoute(route: string | undefined): string | undefined {\n if (!route) {\n return undefined;\n }\n\n const trimmedRoute = route.trim();\n if (!trimmedRoute) {\n return undefined;\n }\n\n const pathWithQuery = trimmedRoute.split('#', 1)[0] ?? '';\n const [pathname, search] = pathWithQuery.split('?', 2);\n const normalizedPathname = pathname\n ? `/${pathname.replace(/^\\/+/, '').replace(/\\/{2,}/g, '/')}`\n : '/';\n\n return search ? `${normalizedPathname}?${search}` : normalizedPathname;\n}\n\nfunction isInternalSitemapRoute(route: string, apiPrefix = 'api'): boolean {\n const normalizedApiPrefix = normalizeSitemapRoute(`/${apiPrefix}`) ?? '/api';\n return (\n route === `${normalizedApiPrefix}/_analog/pages` ||\n route.startsWith(`${normalizedApiPrefix}/_analog/pages/`)\n );\n}\n\nasync function isExcludedSitemapRoute(\n entry: SitemapEntry,\n excludeRules: SitemapExcludeRule[] | undefined,\n): Promise<boolean> {\n if (!excludeRules?.length) {\n return false;\n }\n\n for (const rule of excludeRules) {\n if (typeof rule === 'function') {\n if (await rule(entry)) {\n return true;\n }\n continue;\n }\n\n if (rule instanceof RegExp) {\n if (rule.test(entry.route)) {\n return true;\n }\n continue;\n }\n\n if (toGlobRegExp(rule).test(entry.route)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction toGlobRegExp(pattern: string): RegExp {\n const doubleStarToken = '__ANALOG_DOUBLE_STAR__';\n const singleStarToken = '__ANALOG_SINGLE_STAR__';\n const escapedPattern = pattern\n .replace(/\\*\\*/g, doubleStarToken)\n .replace(/\\*/g, singleStarToken)\n .replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&');\n const regexPattern = escapedPattern\n .replace(new RegExp(doubleStarToken, 'g'), '.*')\n .replace(new RegExp(singleStarToken, 'g'), '[^/]*');\n return new RegExp(`^${regexPattern}$`);\n}\n\nasync function collectSitemapRoutes(\n routes: (string | undefined)[] | (() => Promise<(string | undefined)[]>),\n include?: SitemapRouteSource,\n): Promise<SitemapRouteInput[]> {\n const routeList = await resolveRouteInputs(routes);\n const includedRoutes = include ? await resolveRouteInputs(include) : [];\n return [...routeList, ...includedRoutes];\n}\n\nasync function resolveRouteInputs(\n routes:\n | SitemapRouteSource\n | (string | undefined)[]\n | (() => Promise<(string | undefined)[]>),\n): Promise<SitemapRouteInput[]> {\n let routeList: SitemapRouteInput[];\n\n if (typeof routes === 'function') {\n routeList = await routes();\n } else if (Array.isArray(routes)) {\n routeList = routes;\n } else {\n routeList = [];\n }\n\n return routeList.filter(Boolean);\n}\n\n/**\n * Generates hreflang alternate URLs for a given page URL.\n * For a URL like `https://example.com/fr/about`, it produces alternates\n * for all configured locales.\n */\nexport function getHreflangAlternates(\n pageUrl: string,\n host: string,\n i18n: I18nPrerenderOptions,\n): { locale: string; href: string }[] {\n const alternates: { locale: string; href: string }[] = [];\n const normalizedHost = host.replace(/\\/+$/, '');\n\n // Extract the path portion after the host\n const path = pageUrl.replace(normalizedHost, '');\n\n // Strip locale prefix to get the base path\n const basePath = stripLocalePrefix(path, i18n.locales);\n\n for (const locale of i18n.locales) {\n const localizedPath =\n basePath === '/' || basePath === ''\n ? `/${locale}`\n : `/${locale}${basePath}`;\n alternates.push({\n locale,\n href: `${normalizedHost}${localizedPath}`,\n });\n }\n\n // Add x-default pointing to the default locale variant\n const defaultPath =\n basePath === '/' || basePath === ''\n ? `/${i18n.defaultLocale}`\n : `/${i18n.defaultLocale}${basePath}`;\n alternates.push({\n locale: 'x-default',\n href: `${normalizedHost}${defaultPath}`,\n });\n\n return alternates;\n}\n\n/**\n * Strips a locale prefix from a URL path.\n * E.g., '/fr/about' -> '/about', '/en' -> '/'\n */\nexport function stripLocalePrefix(path: string, locales: string[]): string {\n const segments = path.split('/').filter(Boolean);\n if (segments.length > 0 && locales.includes(segments[0])) {\n const rest = segments.slice(1).join('/');\n return rest ? `/${rest}` : '/';\n }\n return path || '/';\n}\n\nfunction createXml(\n elementName: 'urlset' | 'sitemapindex',\n includeXhtml = false,\n): XMLBuilder {\n const attrs: Record<string, string> = {\n xmlns: 'https://www.sitemaps.org/schemas/sitemap/0.9',\n };\n if (includeXhtml) {\n attrs['xmlns:xhtml'] = 'https://www.w3.org/1999/xhtml';\n }\n\n return create({ version: '1.0', encoding: 'UTF-8' })\n .ele(elementName, attrs)\n .com(`This file was automatically generated by Analog.`);\n}\n"],"mappings":";;;;AA2BA,eAAsB,aACpB,SACA,eACA,QACA,WACA,eACA,eAAoC,EAAE,EACvB;CACf,MAAM,OAAO,qBAAqB,cAAc,KAAK;CAErD,MAAM,cAAc,MAAM,sBADR,MAAM,qBAAqB,QAAQ,cAAc,QAAQ,EAGzE,MACA,eACA,eACA,a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;;AA2DlC,SAAS,UACP,aACA,eAAe,OACH;CACZ,MAAM,QAAgC,EACpC,OAAO,gDACR;AACD,KAAI,aACF,OAAM,iBAAiB;AAGzB,QAAO,OAAO;EAAE,SAAS;EAAO,UAAU;EAAS,CAAC,CACjD,IAAI,aAAa,MAAM,CACvB,IAAI,mDAAmD"}
1
+ {"version":3,"file":"build-sitemap.js","names":[],"sources":["../../../src/lib/build-sitemap.ts"],"sourcesContent":["import { writeFileSync } from 'node:fs';\nimport { XMLBuilder } from 'xmlbuilder2/lib/interfaces';\nimport { create } from 'xmlbuilder2';\nimport { UserConfig } from 'vite';\nimport { resolve } from 'node:path';\nimport {\n I18nPrerenderOptions,\n PrerenderContentFile,\n PrerenderSitemapConfig,\n SitemapConfig,\n} from './options';\n\nexport type PagesJson = {\n page: string;\n lastMod: string;\n changefreq?: string;\n priority?: string;\n};\n\nexport async function buildSitemap(\n config: UserConfig,\n sitemapConfig: SitemapConfig,\n routes: (string | undefined)[] | (() => Promise<(string | undefined)[]>),\n outputDir: string,\n routeSitemaps: Record<\n string,\n PrerenderSitemapConfig | (() => PrerenderSitemapConfig) | undefined\n >,\n i18nOptions?: I18nPrerenderOptions,\n): Promise<void> {\n const routeList: string[] = await optionHasRoutes(routes);\n\n if (routeList.length) {\n const slash = checkSlash(sitemapConfig.host || '');\n const sitemapData: PagesJson[] = routeList.map((page: string) => {\n const url = `${slash}${page.replace(/^\\/+/g, '')}`;\n const config = routeSitemaps[url];\n const props = typeof config === 'object' ? config : config?.();\n\n return {\n page: `${sitemapConfig.host}${url}`,\n lastMod: props?.lastmod ?? new Date().toISOString().split('T')[0],\n changefreq: props?.changefreq,\n priority: props?.priority,\n };\n });\n\n const hasI18n = i18nOptions && i18nOptions.locales.length > 1;\n const sitemap = createXml('urlset', hasI18n);\n\n for (const item of sitemapData) {\n const page = sitemap.ele('url');\n page.ele('loc').txt(item.page);\n page.ele('lastmod').txt(item.lastMod);\n\n if (item.changefreq) {\n page.ele('changefreq').txt(item.changefreq);\n }\n\n if (item.priority) {\n page.ele('priority').txt(item.priority);\n }\n\n // Add hreflang alternate links for each locale\n if (hasI18n) {\n const alternates = getHreflangAlternates(\n item.page,\n sitemapConfig.host,\n i18nOptions,\n );\n for (const alt of alternates) {\n page\n .ele('xhtml:link')\n .att('rel', 'alternate')\n .att('hreflang', alt.locale)\n .att('href', alt.href);\n }\n }\n }\n\n const mapPath = `${resolve(outputDir)}/sitemap.xml`;\n try {\n console.log(`Writing sitemap at ${mapPath}`);\n writeFileSync(mapPath, sitemap.end({ prettyPrint: true }));\n } catch (e) {\n console.error(`Unable to write file at ${mapPath}`, e);\n }\n }\n}\n\n/**\n * Generates hreflang alternate URLs for a given page URL.\n * For a URL like `https://example.com/fr/about`, it produces alternates\n * for all configured locales.\n */\nexport function getHreflangAlternates(\n pageUrl: string,\n host: string,\n i18n: I18nPrerenderOptions,\n): { locale: string; href: string }[] {\n const alternates: { locale: string; href: string }[] = [];\n const normalizedHost = host.replace(/\\/+$/, '');\n\n // Extract the path portion after the host\n const path = pageUrl.replace(normalizedHost, '');\n\n // Strip locale prefix to get the base path\n const basePath = stripLocalePrefix(path, i18n.locales);\n\n for (const locale of i18n.locales) {\n const localizedPath =\n basePath === '/' || basePath === ''\n ? `/${locale}`\n : `/${locale}${basePath}`;\n alternates.push({\n locale,\n href: `${normalizedHost}${localizedPath}`,\n });\n }\n\n // Add x-default pointing to the default locale variant\n const defaultPath =\n basePath === '/' || basePath === ''\n ? `/${i18n.defaultLocale}`\n : `/${i18n.defaultLocale}${basePath}`;\n alternates.push({\n locale: 'x-default',\n href: `${normalizedHost}${defaultPath}`,\n });\n\n return alternates;\n}\n\n/**\n * Strips a locale prefix from a URL path.\n * E.g., '/fr/about' -> '/about', '/en' -> '/'\n */\nexport function stripLocalePrefix(path: string, locales: string[]): string {\n const segments = path.split('/').filter(Boolean);\n if (segments.length > 0 && locales.includes(segments[0])) {\n const rest = segments.slice(1).join('/');\n return rest ? `/${rest}` : '/';\n }\n return path || '/';\n}\n\nfunction createXml(\n elementName: 'urlset' | 'sitemapindex',\n includeXhtml = false,\n): XMLBuilder {\n const attrs: Record<string, string> = {\n xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9',\n };\n if (includeXhtml) {\n attrs['xmlns:xhtml'] = 'http://www.w3.org/1999/xhtml';\n }\n\n return create({ version: '1.0', encoding: 'UTF-8' })\n .ele(elementName, attrs)\n .com(`This file was automatically generated by Analog.`);\n}\n\nfunction checkSlash(host: string): string {\n const finalChar = host.slice(-1);\n return finalChar === '/' ? '' : '/';\n}\n\nasync function optionHasRoutes(\n routes: (string | undefined)[] | (() => Promise<(string | undefined)[]>),\n): Promise<string[]> {\n let routeList: (string | undefined)[];\n\n if (typeof routes === 'function') {\n // returns an array or undefined\n routeList = await routes();\n } else if (Array.isArray(routes)) {\n // returns an array of strings\n routeList = routes;\n } else {\n // default it to an empty of array\n routeList = [];\n }\n\n return routeList.filter(Boolean) as string[];\n}\n"],"mappings":";;;;AAmBA,eAAsB,aACpB,QACA,eACA,QACA,WACA,eAIA,aACe;CACf,MAAM,YAAsB,MAAM,gBAAgB,OAAO;AAEzD,KAAI,UAAU,QAAQ;EACpB,MAAM,QAAQ,WAAW,cAAc,QAAQ,GAAG;EAClD,MAAM,cAA2B,UAAU,KAAK,SAAiB;GAC/D,MAAM,MAAM,GAAG,QAAQ,KAAK,QAAQ,SAAS,GAAG;GAChD,MAAM,SAAS,cAAc;GAC7B,MAAM,QAAQ,OAAO,WAAW,WAAW,SAAS,UAAU;AAE9D,UAAO;IACL,MAAM,GAAG,cAAc,OAAO;IAC9B,SAAS,OAAO,4BAAW,IAAI,MAAM,EAAC,aAAa,CAAC,MAAM,IAAI,CAAC;IAC/D,YAAY,OAAO;IACnB,UAAU,OAAO;IAClB;IACD;EAEF,MAAM,UAAU,eAAe,YAAY,QAAQ,SAAS;EAC5D,MAAM,UAAU,UAAU,UAAU,QAAQ;AAE5C,OAAK,MAAM,QAAQ,aAAa;GAC9B,MAAM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;CACzE,MAAM,WAAW,KAAK,MAAM,IAAI,CAAC,OAAO,QAAQ;AAChD,KAAI,SAAS,SAAS,KAAK,QAAQ,SAAS,SAAS,GAAG,EAAE;EACxD,MAAM,OAAO,SAAS,MAAM,EAAE,CAAC,KAAK,IAAI;AACxC,SAAO,OAAO,IAAI,SAAS;;AAE7B,QAAO,QAAQ;;AAGjB,SAAS,UACP,aACA,eAAe,OACH;CACZ,MAAM,QAAgC,EACpC,OAAO,+CACR;AACD,KAAI,aACF,OAAM,iBAAiB;AAGzB,QAAO,OAAO;EAAE,SAAS;EAAO,UAAU;EAAS,CAAC,CACjD,IAAI,aAAa,MAAM,CACvB,IAAI,mDAAmD;;AAG5D,SAAS,WAAW,MAAsB;AAExC,QADkB,KAAK,MAAM,GAAG,KACX,MAAM,KAAK;;AAGlC,eAAe,gBACb,QACmB;CACnB,IAAI;AAEJ,KAAI,OAAO,WAAW,WAEpB,aAAY,MAAM,QAAQ;UACjB,MAAM,QAAQ,OAAO,CAE9B,aAAY;KAGZ,aAAY,EAAE;AAGhB,QAAO,UAAU,OAAO,QAAQ"}
@@ -1,4 +1,3 @@
1
1
  import { UserConfig } from "vite";
2
2
  import { Options } from "./options.js";
3
- export declare function buildClientApp(config: UserConfig, options?: Options): Promise<void>;
4
- export declare function buildSSRApp(config: UserConfig, options?: Options): Promise<void>;
3
+ export declare function buildSSRApp(config: UserConfig, options?: Options, i18nWorkers?: boolean): Promise<void>;
@@ -1,28 +1,19 @@
1
- import { getBundleOptionsKey } from "./utils/rolldown.js";
1
+ import { I18N_WORKER_SSR_ENTRY } from "./utils/i18n-workers.js";
2
+ import * as vite from "vite";
2
3
  import { build, mergeConfig } from "vite";
3
4
  import { relative, resolve } from "node:path";
4
5
  //#region packages/vite-plugin-nitro/src/lib/build-ssr.ts
5
- async function buildClientApp(config, options) {
6
- const workspaceRoot = options?.workspaceRoot ?? process.cwd();
7
- const rootDir = relative(workspaceRoot, config.root || ".") || ".";
8
- await build(mergeConfig(config, { build: {
9
- ssr: false,
10
- outDir: config.build?.outDir || resolve(workspaceRoot, "dist", rootDir, "client"),
11
- emptyOutDir: true
12
- } }));
13
- }
14
- async function buildSSRApp(config, options) {
6
+ async function buildSSRApp(config, options, i18nWorkers = false) {
15
7
  const workspaceRoot = options?.workspaceRoot ?? process.cwd();
16
8
  const sourceRoot = options?.sourceRoot ?? "src";
17
9
  const rootDir = relative(workspaceRoot, config.root || ".") || ".";
18
10
  await build(mergeConfig(config, { build: {
19
11
  ssr: true,
20
- [getBundleOptionsKey()]: { input: options?.entryServer || resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`) },
21
- outDir: options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, "ssr"),
22
- emptyOutDir: false
12
+ [vite.rolldownVersion ? "rolldownOptions" : "rollupOptions"]: { input: i18nWorkers ? { "main.server": I18N_WORKER_SSR_ENTRY } : options?.entryServer || resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`) },
13
+ outDir: options?.ssrBuildDir || resolve(workspaceRoot, "dist", rootDir, "ssr")
23
14
  } }));
24
15
  }
25
16
  //#endregion
26
- export { buildClientApp, buildSSRApp };
17
+ export { buildSSRApp };
27
18
 
28
19
  //# sourceMappingURL=build-ssr.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"build-ssr.js","names":[],"sources":["../../../src/lib/build-ssr.ts"],"sourcesContent":["import { build, mergeConfig, UserConfig } from 'vite';\nimport { relative, resolve } from 'node:path';\n\nimport { Options } from './options.js';\nimport { getBundleOptionsKey } from './utils/rolldown.js';\n\nexport async function buildClientApp(\n config: UserConfig,\n options?: Options,\n): Promise<void> {\n const workspaceRoot = options?.workspaceRoot ?? process.cwd();\n const rootDir = relative(workspaceRoot, config.root || '.') || '.';\n const clientBuildConfig = mergeConfig(config, <UserConfig>{\n build: {\n ssr: false,\n outDir:\n config.build?.outDir ||\n resolve(workspaceRoot, 'dist', rootDir, 'client'),\n emptyOutDir: true,\n },\n });\n\n await build(clientBuildConfig);\n}\n\nexport async function buildSSRApp(\n config: UserConfig,\n options?: Options,\n): Promise<void> {\n const workspaceRoot = options?.workspaceRoot ?? process.cwd();\n const sourceRoot = options?.sourceRoot ?? 'src';\n const rootDir = relative(workspaceRoot, config.root || '.') || '.';\n const bundleOptionsKey = getBundleOptionsKey();\n\n /**\n * SSR is built as a second pass from the already prepared Analog/Vite config.\n *\n * That means we intentionally start from the same base config used for the\n * client build and then merge only the SSR-specific overrides (entry, outDir,\n * `build.ssr`, etc).\n *\n * A side effect of this design is that the resolved SSR config can expose the\n * same high-level Analog plugin chain more than once when Vite/Nitro replays\n * shared plugins for the server environment. In particular,\n * `@analogjs/vite-plugin-angular` may appear twice in `config.plugins` during\n * SSR resolution:\n * - once from the normal Analog platform plugin expansion\n * - once from the reused/shared plugin graph for the SSR pass\n *\n * That does NOT imply the client build has two competing style registries.\n * The client-side duplicate-registration guard in `vite-plugin-angular`\n * therefore explicitly ignores `build.ssr === true` to avoid treating this\n * valid SSR orchestration detail as a style-map bug.\n */\n const ssrBuildConfig = mergeConfig(config, <UserConfig>{\n build: {\n ssr: true,\n [bundleOptionsKey]: {\n input:\n options?.entryServer ||\n resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`),\n },\n outDir:\n options?.ssrBuildDir || resolve(workspaceRoot, 'dist', rootDir, 'ssr'),\n // Preserve the client build output. The client pass already handled its\n // own cleanup, and on Windows this nested SSR build can otherwise remove\n // sibling artifacts that Nitro needs to read immediately afterward.\n emptyOutDir: false,\n },\n });\n\n await build(ssrBuildConfig);\n}\n"],"mappings":";;;;AAMA,eAAsB,eACpB,QACA,SACe;CACf,MAAM,gBAAgB,SAAS,iBAAiB,QAAQ,KAAK;CAC7D,MAAM,UAAU,SAAS,eAAe,OAAO,QAAQ,IAAI,IAAI;AAW/D,OAAM,MAVoB,YAAY,QAAoB,EACxD,OAAO;EACL,KAAK;EACL,QACE,OAAO,OAAO,UACd,QAAQ,eAAe,QAAQ,SAAS,SAAS;EACnD,aAAa;EACd,EACF,CAAC,CAE4B;;AAGhC,eAAsB,YACpB,QACA,SACe;CACf,MAAM,gBAAgB,SAAS,iBAAiB,QAAQ,KAAK;CAC7D,MAAM,aAAa,SAAS,cAAc;CAC1C,MAAM,UAAU,SAAS,eAAe,OAAO,QAAQ,IAAI,IAAI;AAwC/D,OAAM,MAjBiB,YAAY,QAAoB,EACrD,OAAO;EACL,KAAK;GAxBgB,qBAAqB,GAyBtB,EAClB,OACE,SAAS,eACT,QAAQ,eAAe,SAAS,GAAG,WAAW,iBAAiB,EAClE;EACD,QACE,SAAS,eAAe,QAAQ,eAAe,QAAQ,SAAS,MAAM;EAIxE,aAAa;EACd,EACF,CAAC,CAEyB"}
1
+ {"version":3,"file":"build-ssr.js","names":[],"sources":["../../../src/lib/build-ssr.ts"],"sourcesContent":["import { build, mergeConfig, UserConfig } from 'vite';\nimport * as vite from 'vite';\nimport { relative, resolve } from 'node:path';\n\nimport { Options } from './options.js';\nimport { I18N_WORKER_SSR_ENTRY } from './utils/i18n-workers.js';\n\nexport async function buildSSRApp(\n config: UserConfig,\n options?: Options,\n i18nWorkers = false,\n): Promise<void> {\n const workspaceRoot = options?.workspaceRoot ?? process.cwd();\n const sourceRoot = options?.sourceRoot ?? 'src';\n const rootDir = relative(workspaceRoot, config.root || '.') || '.';\n const ssrBuildConfig = mergeConfig(config, <UserConfig>{\n build: {\n ssr: true,\n [vite.rolldownVersion ? 'rolldownOptions' : 'rollupOptions']: {\n input: i18nWorkers\n ? { 'main.server': I18N_WORKER_SSR_ENTRY }\n : options?.entryServer ||\n resolve(workspaceRoot, rootDir, `${sourceRoot}/main.server.ts`),\n },\n outDir:\n options?.ssrBuildDir || resolve(workspaceRoot, 'dist', rootDir, 'ssr'),\n },\n });\n\n await build(ssrBuildConfig);\n}\n"],"mappings":";;;;;AAOA,eAAsB,YACpB,QACA,SACA,cAAc,OACC;CACf,MAAM,gBAAgB,SAAS,iBAAiB,QAAQ,KAAK;CAC7D,MAAM,aAAa,SAAS,cAAc;CAC1C,MAAM,UAAU,SAAS,eAAe,OAAO,QAAQ,IAAI,IAAI;AAe/D,OAAM,MAdiB,YAAY,QAAoB,EACrD,OAAO;EACL,KAAK;GACJ,KAAK,kBAAkB,oBAAoB,kBAAkB,EAC5D,OAAO,cACH,EAAE,eAAe,uBAAuB,GACxC,SAAS,eACT,QAAQ,eAAe,SAAS,GAAG,WAAW,iBAAiB,EACpE;EACD,QACE,SAAS,eAAe,QAAQ,eAAe,QAAQ,SAAS,MAAM;EACzE,EACF,CAAC,CAEyB"}
@@ -1,2 +1,2 @@
1
- import type { Nitro, PrerenderRoute } from "nitro/types";
1
+ import { Nitro, PrerenderRoute } from "nitropack";
2
2
  export declare function addPostRenderingHooks(nitro: Nitro, hooks: ((pr: PrerenderRoute) => Promise<void>)[]): void;
@@ -1,9 +1,7 @@
1
1
  //#region packages/vite-plugin-nitro/src/lib/hooks/post-rendering-hook.ts
2
2
  function addPostRenderingHooks(nitro, hooks) {
3
3
  hooks.forEach((hook) => {
4
- nitro.hooks.hook("prerender:generate", (route) => {
5
- hook(route);
6
- });
4
+ nitro.hooks.hook("prerender:generate", hook);
7
5
  });
8
6
  }
9
7
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"post-rendering-hook.js","names":[],"sources":["../../../../src/lib/hooks/post-rendering-hook.ts"],"sourcesContent":["import type { Nitro, PrerenderRoute } from 'nitro/types';\n\nexport function addPostRenderingHooks(\n nitro: Nitro,\n hooks: ((pr: PrerenderRoute) => Promise<void>)[],\n): void {\n hooks.forEach((hook: (preRoute: PrerenderRoute) => void) => {\n nitro.hooks.hook('prerender:generate', (route: PrerenderRoute) => {\n hook(route);\n });\n });\n}\n"],"mappings":";AAEA,SAAgB,sBACd,OACA,OACM;AACN,OAAM,SAAS,SAA6C;AAC1D,QAAM,MAAM,KAAK,uBAAuB,UAA0B;AAChE,QAAK,MAAM;IACX;GACF"}
1
+ {"version":3,"file":"post-rendering-hook.js","names":[],"sources":["../../../../src/lib/hooks/post-rendering-hook.ts"],"sourcesContent":["import { Nitro, PrerenderRoute } from 'nitropack';\n\nexport function addPostRenderingHooks(\n nitro: Nitro,\n hooks: ((pr: PrerenderRoute) => Promise<void>)[],\n): void {\n hooks.forEach((hook) => {\n nitro.hooks.hook('prerender:generate', hook);\n });\n}\n"],"mappings":";AAEA,SAAgB,sBACd,OACA,OACM;AACN,OAAM,SAAS,SAAS;AACtB,QAAM,MAAM,KAAK,sBAAsB,KAAK;GAC5C"}
@@ -1,6 +1,9 @@
1
- import type { PrerenderRoute } from "nitro/types";
2
- import type { UserConfig } from "vite";
1
+ import { PrerenderRoute } from "nitropack";
3
2
  export interface I18nPrerenderOptions {
3
+ /** Path to the translation loader module, relative to the app root. */
4
+ loader?: string;
5
+ /** Automatic when eligible; false disables workers, true requires them. */
6
+ workers?: boolean;
4
7
  /**
5
8
  * The default/source locale for the application.
6
9
  */
@@ -44,11 +47,31 @@ export interface Options {
44
47
  additionalServerFnDirs?: string[];
45
48
  apiPrefix?: string;
46
49
  /**
47
- * Vite-native build passthrough. Rolldown-only options such as
48
- * `build.rolldownOptions.output.codeSplitting` are forwarded when present.
50
+ * Toggles internal API middleware.
51
+ * If disabled, a proxy request is used to route /api
52
+ * requests to / in the production server build.
53
+ *
54
+ * @deprecated
55
+ * Use the src/server/routes/api folder
56
+ * for API routes.
57
+ */
58
+ useAPIMiddleware?: boolean;
59
+ /**
60
+ * i18n configuration for locale-aware prerendering.
61
+ * When set, routes are expanded with locale prefixes and
62
+ * prerendered HTML receives the appropriate `lang` attribute.
63
+ */
64
+ i18n?: I18nPrerenderOptions;
65
+ /**
66
+ * Opt-in experimental features that are not yet stable.
49
67
  */
50
- vite?: {
51
- build?: UserConfig["build"];
68
+ experimental?: {
69
+ /**
70
+ * Use the streaming SSR renderer (`ssrStreamRenderer`) so the server entry's
71
+ * `renderStream` default export streams the response. Requires the server
72
+ * entry to use `renderStream` from `@analogjs/router/server`.
73
+ */
74
+ streaming?: boolean;
52
75
  };
53
76
  }
54
77
  export interface PrerenderOptions {
@@ -64,26 +87,8 @@ export interface PrerenderOptions {
64
87
  /** List of functions that run for each route after pre-rendering is complete. */
65
88
  postRenderingHooks?: ((routes: PrerenderRoute) => Promise<void>)[];
66
89
  }
67
- export type SitemapPriority = number | `${number}`;
68
- export interface SitemapRouteDefinition {
69
- route: string;
70
- lastmod?: string;
71
- changefreq?: "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
72
- priority?: SitemapPriority;
73
- }
74
- export interface SitemapEntry extends SitemapRouteDefinition {
75
- loc: string;
76
- }
77
- export type SitemapRouteInput = string | SitemapRouteDefinition | undefined;
78
- export type SitemapRouteSource = SitemapRouteInput[] | (() => Promise<SitemapRouteInput[]>);
79
- export type SitemapExcludeRule = string | RegExp | ((entry: SitemapEntry) => boolean | Promise<boolean>);
80
- export type SitemapTransform = (entry: SitemapEntry) => SitemapRouteDefinition | false | Promise<SitemapRouteDefinition | false>;
81
90
  export interface SitemapConfig {
82
91
  host: string;
83
- include?: SitemapRouteSource;
84
- exclude?: SitemapExcludeRule[];
85
- defaults?: PrerenderSitemapConfig;
86
- transform?: SitemapTransform;
87
92
  }
88
93
  export interface PrerenderContentDir {
89
94
  /**
@@ -140,7 +145,7 @@ export interface PrerenderContentFile {
140
145
  export interface PrerenderSitemapConfig {
141
146
  lastmod?: string;
142
147
  changefreq?: "always" | "hourly" | "daily" | "weekly" | "monthly" | "yearly" | "never";
143
- priority?: SitemapPriority;
148
+ priority?: string;
144
149
  }
145
150
  export interface PrerenderRouteConfig {
146
151
  route: string;
@@ -3,5 +3,5 @@ import { Options } from "../options.js";
3
3
  type ServerOptions = Options & {
4
4
  routeRules?: Record<string, any> | undefined;
5
5
  };
6
- export declare function devServerPlugin(options: ServerOptions): Plugin;
6
+ export declare function devServerPlugin(getOptions: () => ServerOptions): Plugin;
7
7
  export {};
@@ -1,33 +1,35 @@
1
- import { writeWebResponseToNode } from "../utils/node-web-bridge.js";
2
1
  import { registerDevServerMiddleware } from "../utils/register-dev-middleware.js";
3
2
  import { registerI18nWatcher } from "../utils/register-i18n-watcher.js";
4
3
  import { detectLocaleFromRoute, setHtmlLang } from "../utils/i18n-prerender.js";
4
+ import { createEvent, sendWebResponse } from "h3";
5
5
  import { normalizePath } from "vite";
6
6
  import { resolve } from "node:path";
7
7
  import { readFileSync } from "node:fs";
8
8
  import { createRouter, toRouteMatcher } from "radix3";
9
9
  import { defu } from "defu";
10
10
  //#region packages/vite-plugin-nitro/src/lib/plugins/dev-server-plugin.ts
11
- function devServerPlugin(options) {
12
- const workspaceRoot = options?.workspaceRoot || process.cwd();
13
- const sourceRoot = options?.sourceRoot ?? "src";
14
- const index = options.index || "index.html";
11
+ function devServerPlugin(getOptions) {
12
+ let options;
13
+ let sourceRoot;
14
+ let index;
15
15
  let config;
16
16
  let root;
17
17
  let isTest = false;
18
18
  return {
19
19
  name: "analogjs-dev-ssr-plugin",
20
20
  config(userConfig, { mode }) {
21
+ options = getOptions();
22
+ if (!options.ssr) return;
23
+ const workspaceRoot = options.workspaceRoot || process.cwd();
24
+ sourceRoot = options.sourceRoot ?? "src";
25
+ index = options.index || "index.html";
21
26
  config = userConfig;
22
27
  root = normalizePath(resolve(workspaceRoot, config.root || ".") || ".");
23
28
  isTest = isTest ? isTest : mode === "test";
24
- return {
25
- appType: "custom",
26
- resolve: { alias: { "~analog/entry-server": options.entryServer || `${root}/${sourceRoot}/main.server.ts` } }
27
- };
29
+ return { resolve: { alias: { "~analog/entry-server": options.entryServer || `${root}/${sourceRoot}/main.server.ts` } } };
28
30
  },
29
31
  configureServer(viteServer) {
30
- if (isTest) return;
32
+ if (isTest || !options.ssr) return;
31
33
  return async () => {
32
34
  remove_html_middlewares(viteServer.middlewares);
33
35
  registerDevServerMiddleware(root, sourceRoot, viteServer);
@@ -48,7 +50,7 @@ function devServerPlugin(options) {
48
50
  });
49
51
  }
50
52
  if (result instanceof Response) {
51
- await writeWebResponseToNode(res, result);
53
+ sendWebResponse(createEvent(req, res), result);
52
54
  return;
53
55
  }
54
56
  let html = typeof result === "string" ? result : template;
@@ -1 +1 @@
1
- {"version":3,"file":"dev-server-plugin.js","names":[],"sources":["../../../../src/lib/plugins/dev-server-plugin.ts"],"sourcesContent":["// SSR dev server, middleware and error page source modified from\n// https://github.com/solidjs/solid-start/blob/main/packages/start/dev/server.js\n\nimport {\n Connect,\n Plugin,\n UserConfig,\n ViteDevServer,\n normalizePath,\n} from 'vite';\nimport { resolve } from 'node:path';\nimport { readFileSync } from 'node:fs';\nimport { createRouter as createRadixRouter, toRouteMatcher } from 'radix3';\nimport { defu } from 'defu';\nimport type { NitroRouteRules } from 'nitro/types';\n\nimport { registerDevServerMiddleware } from '../utils/register-dev-middleware.js';\nimport { registerI18nWatcher } from '../utils/register-i18n-watcher.js';\nimport { writeWebResponseToNode } from '../utils/node-web-bridge.js';\nimport { Options } from '../options.js';\nimport { detectLocaleFromRoute, setHtmlLang } from '../utils/i18n-prerender.js';\n\ntype ServerOptions = Options & { routeRules?: Record<string, any> | undefined };\n\nexport function devServerPlugin(options: ServerOptions): Plugin {\n const workspaceRoot = options?.workspaceRoot || process.cwd();\n const sourceRoot = options?.sourceRoot ?? 'src';\n const index = options.index || 'index.html';\n let config: UserConfig;\n let root: string;\n let isTest = false;\n\n return {\n name: 'analogjs-dev-ssr-plugin',\n config(userConfig, { mode }) {\n config = userConfig;\n root = normalizePath(resolve(workspaceRoot, config.root || '.') || '.');\n isTest = isTest ? isTest : mode === 'test';\n return {\n appType: 'custom',\n resolve: {\n alias: {\n '~analog/entry-server':\n options.entryServer || `${root}/${sourceRoot}/main.server.ts`,\n },\n },\n };\n },\n configureServer(viteServer) {\n if (isTest) {\n return;\n }\n\n return async () => {\n remove_html_middlewares(viteServer.middlewares);\n registerDevServerMiddleware(root, sourceRoot, viteServer);\n\n if (options.i18n) {\n registerI18nWatcher(viteServer);\n }\n\n viteServer.middlewares.use(async (req, res) => {\n let template = readFileSync(\n resolve(viteServer.config.root, index),\n 'utf-8',\n );\n\n template = await viteServer.transformIndexHtml(\n req.originalUrl as string,\n template,\n );\n\n const _routeRulesMatcher = toRouteMatcher(\n createRadixRouter({ routes: options.routeRules }),\n );\n const _getRouteRules = (path: string) =>\n defu(\n {},\n ..._routeRulesMatcher.matchAll(path).reverse(),\n ) as NitroRouteRules;\n\n try {\n let result: string | Response;\n // Check for route rules explicitly disabling SSR\n if (_getRouteRules(req.originalUrl as string).ssr === false) {\n result = template;\n } else {\n const entryServer = (\n await viteServer.ssrLoadModule('~analog/entry-server')\n )['default'];\n result = await entryServer(req.originalUrl, template, {\n req,\n res,\n });\n }\n\n if (result instanceof Response) {\n await writeWebResponseToNode(res, result);\n return;\n }\n\n // Inject lang attribute when i18n is configured\n let html = typeof result === 'string' ? result : template;\n if (options.i18n) {\n const locale = detectLocaleFromRoute(\n req.originalUrl as string,\n options.i18n,\n );\n html = setHtmlLang(html, locale);\n }\n\n res.setHeader('Content-Type', 'text/html');\n res.end(html);\n } catch (e) {\n viteServer.ssrFixStacktrace(e as Error);\n res.statusCode = 500;\n res.end(`\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Error</title>\n <script type=\"module\">\n import { ErrorOverlay } from '/@vite/client'\n document.body.appendChild(new ErrorOverlay(${JSON.stringify(\n prepareError(req, e),\n ).replace(/</g, '\\\\u003c')}))\n </script>\n </head>\n <body>\n </body>\n </html>\n `);\n }\n });\n };\n },\n };\n}\n\n/**\n * Removes Vite internal middleware\n *\n * @param server\n */\nfunction remove_html_middlewares(server: ViteDevServer['middlewares']) {\n const html_middlewares = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n 'viteHtmlFallbackMiddleware',\n ];\n for (let i = server.stack.length - 1; i > 0; i--) {\n const handler = server.stack[i]?.handle;\n const handlerName =\n typeof handler === 'function' ? handler.name : undefined;\n if (handlerName && html_middlewares.includes(handlerName)) {\n server.stack.splice(i, 1);\n }\n }\n}\n\n/**\n * Formats error for SSR message in error overlay\n * @param req\n * @param error\n * @returns\n */\nfunction prepareError(req: Connect.IncomingMessage, error: unknown) {\n const e = error as Error;\n return {\n message: `An error occured while server rendering ${req.url}:\\n\\n\\t${\n typeof e === 'string' ? e : e.message\n } `,\n stack: typeof e === 'string' ? '' : e.stack,\n };\n}\n"],"mappings":";;;;;;;;;;AAwBA,SAAgB,gBAAgB,SAAgC;CAC9D,MAAM,gBAAgB,SAAS,iBAAiB,QAAQ,KAAK;CAC7D,MAAM,aAAa,SAAS,cAAc;CAC1C,MAAM,QAAQ,QAAQ,SAAS;CAC/B,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS;AAEb,QAAO;EACL,MAAM;EACN,OAAO,YAAY,EAAE,QAAQ;AAC3B,YAAS;AACT,UAAO,cAAc,QAAQ,eAAe,OAAO,QAAQ,IAAI,IAAI,IAAI;AACvE,YAAS,SAAS,SAAS,SAAS;AACpC,UAAO;IACL,SAAS;IACT,SAAS,EACP,OAAO,EACL,wBACE,QAAQ,eAAe,GAAG,KAAK,GAAG,WAAW,kBAChD,EACF;IACF;;EAEH,gBAAgB,YAAY;AAC1B,OAAI,OACF;AAGF,UAAO,YAAY;AACjB,4BAAwB,WAAW,YAAY;AAC/C,gCAA4B,MAAM,YAAY,WAAW;AAEzD,QAAI,QAAQ,KACV,qBAAoB,WAAW;AAGjC,eAAW,YAAY,IAAI,OAAO,KAAK,QAAQ;KAC7C,IAAI,WAAW,aACb,QAAQ,WAAW,OAAO,MAAM,MAAM,EACtC,QACD;AAED,gBAAW,MAAM,WAAW,mBAC1B,IAAI,aACJ,SACD;KAED,MAAM,qBAAqB,eACzB,aAAkB,EAAE,QAAQ,QAAQ,YAAY,CAAC,CAClD;KACD,MAAM,kBAAkB,SACtB,KACE,EAAE,EACF,GAAG,mBAAmB,SAAS,KAAK,CAAC,SAAS,CAC/C;AAEH,SAAI;MACF,IAAI;AAEJ,UAAI,eAAe,IAAI,YAAsB,CAAC,QAAQ,MACpD,UAAS;WACJ;OACL,MAAM,eACJ,MAAM,WAAW,cAAc,uBAAuB,EACtD;AACF,gBAAS,MAAM,YAAY,IAAI,aAAa,UAAU;QACpD;QACA;QACD,CAAC;;AAGJ,UAAI,kBAAkB,UAAU;AAC9B,aAAM,uBAAuB,KAAK,OAAO;AACzC;;MAIF,IAAI,OAAO,OAAO,WAAW,WAAW,SAAS;AACjD,UAAI,QAAQ,MAAM;OAChB,MAAM,SAAS,sBACb,IAAI,aACJ,QAAQ,KACT;AACD,cAAO,YAAY,MAAM,OAAO;;AAGlC,UAAI,UAAU,gBAAgB,YAAY;AAC1C,UAAI,IAAI,KAAK;cACN,GAAG;AACV,iBAAW,iBAAiB,EAAW;AACvC,UAAI,aAAa;AACjB,UAAI,IAAI;;;;;;;;iEAQ6C,KAAK,UAChD,aAAa,KAAK,EAAE,CACrB,CAAC,QAAQ,MAAM,UAAU,CAAC;;;;;;cAMjC;;MAEJ;;;EAGP;;;;;;;AAQH,SAAS,wBAAwB,QAAsC;CACrE,MAAM,mBAAmB;EACvB;EACA;EACA;EACA;EACD;AACD,MAAK,IAAI,IAAI,OAAO,MAAM,SAAS,GAAG,IAAI,GAAG,KAAK;EAChD,MAAM,UAAU,OAAO,MAAM,IAAI;EACjC,MAAM,cACJ,OAAO,YAAY,aAAa,QAAQ,OAAO,KAAA;AACjD,MAAI,eAAe,iBAAiB,SAAS,YAAY,CACvD,QAAO,MAAM,OAAO,GAAG,EAAE;;;;;;;;;AAW/B,SAAS,aAAa,KAA8B,OAAgB;CAClE,MAAM,IAAI;AACV,QAAO;EACL,SAAS,2CAA2C,IAAI,IAAI,SAC1D,OAAO,MAAM,WAAW,IAAI,EAAE,QAC/B;EACD,OAAO,OAAO,MAAM,WAAW,KAAK,EAAE;EACvC"}
1
+ {"version":3,"file":"dev-server-plugin.js","names":[],"sources":["../../../../src/lib/plugins/dev-server-plugin.ts"],"sourcesContent":["// SSR dev server, middleware and error page source modified from\n// https://github.com/solidjs/solid-start/blob/main/packages/start/dev/server.js\n\nimport {\n Connect,\n Plugin,\n UserConfig,\n ViteDevServer,\n normalizePath,\n} from 'vite';\nimport { resolve } from 'node:path';\nimport { readFileSync } from 'node:fs';\nimport { createEvent, sendWebResponse } from 'h3';\nimport { createRouter as createRadixRouter, toRouteMatcher } from 'radix3';\nimport { defu } from 'defu';\nimport { NitroRouteRules } from 'nitropack';\n\nimport { registerDevServerMiddleware } from '../utils/register-dev-middleware.js';\nimport { registerI18nWatcher } from '../utils/register-i18n-watcher.js';\nimport { Options } from '../options.js';\nimport { detectLocaleFromRoute, setHtmlLang } from '../utils/i18n-prerender.js';\n\ntype ServerOptions = Options & { routeRules?: Record<string, any> | undefined };\n\nexport function devServerPlugin(getOptions: () => ServerOptions): Plugin {\n let options: ServerOptions;\n let sourceRoot: string;\n let index: string;\n let config: UserConfig;\n let root: string;\n let isTest = false;\n\n return {\n name: 'analogjs-dev-ssr-plugin',\n config(userConfig, { mode }) {\n options = getOptions();\n if (!options.ssr) {\n return;\n }\n const workspaceRoot = options.workspaceRoot || process.cwd();\n sourceRoot = options.sourceRoot ?? 'src';\n index = options.index || 'index.html';\n config = userConfig;\n root = normalizePath(resolve(workspaceRoot, config.root || '.') || '.');\n isTest = isTest ? isTest : mode === 'test';\n return {\n resolve: {\n alias: {\n '~analog/entry-server':\n options.entryServer || `${root}/${sourceRoot}/main.server.ts`,\n },\n },\n };\n },\n configureServer(viteServer) {\n if (isTest || !options.ssr) {\n return;\n }\n\n return async () => {\n remove_html_middlewares(viteServer.middlewares);\n registerDevServerMiddleware(root, sourceRoot, viteServer);\n\n if (options.i18n) {\n registerI18nWatcher(viteServer);\n }\n\n viteServer.middlewares.use(async (req, res) => {\n let template = readFileSync(\n resolve(viteServer.config.root, index),\n 'utf-8',\n );\n\n template = await viteServer.transformIndexHtml(\n req.originalUrl as string,\n template,\n );\n\n const _routeRulesMatcher = toRouteMatcher(\n createRadixRouter({ routes: options.routeRules }),\n );\n const _getRouteRules = (path: string) =>\n defu(\n {},\n ..._routeRulesMatcher.matchAll(path).reverse(),\n ) as NitroRouteRules;\n\n try {\n let result: string | Response;\n // Check for route rules explicitly disabling SSR\n if (_getRouteRules(req.originalUrl as string).ssr === false) {\n result = template;\n } else {\n const entryServer = (\n await viteServer.ssrLoadModule('~analog/entry-server')\n )['default'];\n result = await entryServer(req.originalUrl, template, {\n req,\n res,\n });\n }\n\n if (result instanceof Response) {\n sendWebResponse(createEvent(req, res), result);\n return;\n }\n\n // Inject lang attribute when i18n is configured\n let html = typeof result === 'string' ? result : template;\n if (options.i18n) {\n const locale = detectLocaleFromRoute(\n req.originalUrl as string,\n options.i18n,\n );\n html = setHtmlLang(html, locale);\n }\n\n res.setHeader('Content-Type', 'text/html');\n res.end(html);\n } catch (e) {\n viteServer.ssrFixStacktrace(e as Error);\n res.statusCode = 500;\n res.end(`\n <!DOCTYPE html>\n <html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <title>Error</title>\n <script type=\"module\">\n import { ErrorOverlay } from '/@vite/client'\n document.body.appendChild(new ErrorOverlay(${JSON.stringify(\n prepareError(req, e),\n ).replace(/</g, '\\\\u003c')}))\n </script>\n </head>\n <body>\n </body>\n </html>\n `);\n }\n });\n };\n },\n };\n}\n\n/**\n * Removes Vite internal middleware\n *\n * @param server\n */\nfunction remove_html_middlewares(server: ViteDevServer['middlewares']) {\n const html_middlewares = [\n 'viteIndexHtmlMiddleware',\n 'vite404Middleware',\n 'viteSpaFallbackMiddleware',\n 'viteHtmlFallbackMiddleware',\n ];\n for (let i = server.stack.length - 1; i > 0; i--) {\n const handler = server.stack[i]?.handle;\n const handlerName =\n typeof handler === 'function' ? handler.name : undefined;\n if (handlerName && html_middlewares.includes(handlerName)) {\n server.stack.splice(i, 1);\n }\n }\n}\n\n/**\n * Formats error for SSR message in error overlay\n * @param req\n * @param error\n * @returns\n */\nfunction prepareError(req: Connect.IncomingMessage, error: unknown) {\n const e = error as Error;\n return {\n message: `An error occured while server rendering ${req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AAc,uBAAuB,EACtD;AACF,gBAAS,MAAM,YAAY,IAAI,aAAa,UAAU;QACpD;QACA;QACD,CAAC;;AAGJ,UAAI,kBAAkB,UAAU;AAC9B,uBAAgB,YAAY,KAAK,IAAI,EAAE,OAAO;AAC9C;;MAIF,IAAI,OAAO,OAAO,WAAW,WAAW,SAAS;AACjD,UAAI,QAAQ,MAAM;OAChB,MAAM,SAAS,sBACb,IAAI,aACJ,QAAQ,KACT;AACD,cAAO,YAAY,MAAM,OAAO;;AAGlC,UAAI,UAAU,gBAAgB,YAAY;AAC1C,UAAI,IAAI,KAAK;cACN,GAAG;AACV,iBAAW,iBAAiB,EAAW;AACvC,UAAI,aAAa;AACjB,UAAI,IAAI;;;;;;;;iEAQ6C,KAAK,UAChD,aAAa,KAAK,EAAE,CACrB,CAAC,QAAQ,MAAM,UAAU,CAAC;;;;;;cAMjC;;MAEJ;;;EAGP;;;;;;;AAQH,SAAS,wBAAwB,QAAsC;CACrE,MAAM,mBAAmB;EACvB;EACA;EACA;EACA;EACD;AACD,MAAK,IAAI,IAAI,OAAO,MAAM,SAAS,GAAG,IAAI,GAAG,KAAK;EAChD,MAAM,UAAU,OAAO,MAAM,IAAI;EACjC,MAAM,cACJ,OAAO,YAAY,aAAa,QAAQ,OAAO,KAAA;AACjD,MAAI,eAAe,iBAAiB,SAAS,YAAY,CACvD,QAAO,MAAM,OAAO,GAAG,EAAE;;;;;;;;;AAW/B,SAAS,aAAa,KAA8B,OAAgB;CAClE,MAAM,IAAI;AACV,QAAO;EACL,SAAS,2CAA2C,IAAI,IAAI,SAC1D,OAAO,MAAM,WAAW,IAAI,EAAE,QAC/B;EACD,OAAO,OAAO,MAAM,WAAW,KAAK,EAAE;EACvC"}
@@ -1,4 +1,3 @@
1
- import { SERVER_FETCH_FACTORY_SNIPPET } from "../utils/renderers.js";
2
1
  import { normalizePath } from "vite";
3
2
  import { parseSync } from "oxc-parser";
4
3
  //#region packages/vite-plugin-nitro/src/lib/plugins/page-endpoints.ts
@@ -13,8 +12,7 @@ function pageEndpointsPlugin() {
13
12
  }).module.staticExports.flatMap((e) => e.entries.filter((entry) => entry.exportName.name !== null).map((entry) => entry.exportName.name));
14
13
  return {
15
14
  code: `
16
- import { defineHandler, fetchWithEvent } from 'nitro/h3';
17
- import { createFetch } from 'ofetch';
15
+ import { defineEventHandler } from 'h3';
18
16
 
19
17
  ${fileExports.includes("load") ? _code : `
20
18
  ${_code}
@@ -25,19 +23,17 @@ function pageEndpointsPlugin() {
25
23
  ${fileExports.includes("action") ? "" : `
26
24
  export const action = () => {
27
25
  return {};
28
- }
26
+ }
29
27
  `}
30
28
 
31
- export default defineHandler(async(event) => {
32
- ${SERVER_FETCH_FACTORY_SNIPPET}
33
-
29
+ export default defineEventHandler(async(event) => {
34
30
  if (event.method === 'GET') {
35
31
  try {
36
32
  return await load({
37
33
  params: event.context.params,
38
- req: event.node?.req,
39
- res: event.node?.res,
40
- fetch: serverFetch,
34
+ req: event.node.req,
35
+ res: event.node.res,
36
+ fetch: $fetch,
41
37
  event
42
38
  });
43
39
  } catch(e) {
@@ -48,15 +44,15 @@ function pageEndpointsPlugin() {
48
44
  try {
49
45
  return await action({
50
46
  params: event.context.params,
51
- req: event.node?.req,
52
- res: event.node?.res,
53
- fetch: serverFetch,
47
+ req: event.node.req,
48
+ res: event.node.res,
49
+ fetch: $fetch,
54
50
  event
55
51
  });
56
52
  } catch(e) {
57
53
  console.error(\` An error occurred: \${e}\`)
58
54
  throw e;
59
- }
55
+ }
60
56
  }
61
57
  });
62
58
  `,
@@ -1 +1 @@
1
- {"version":3,"file":"page-endpoints.js","names":[],"sources":["../../../../src/lib/plugins/page-endpoints.ts"],"sourcesContent":["import { parseSync } from 'oxc-parser';\nimport { normalizePath } from 'vite';\nimport { SERVER_FETCH_FACTORY_SNIPPET } from '../utils/renderers.js';\n\nexport function pageEndpointsPlugin() {\n return {\n name: 'analogjs-vite-plugin-nitro-rollup-page-endpoint',\n async transform(\n _code: string,\n id: string,\n ): Promise<{ code: string; map: null } | undefined> {\n if (normalizePath(id).includes('/pages/') && id.endsWith('.server.ts')) {\n const result = parseSync(id, _code, {\n sourceType: 'module',\n lang: 'ts',\n });\n\n const fileExports: string[] = result.module.staticExports.flatMap((e) =>\n e.entries\n .filter((entry) => entry.exportName.name !== null)\n .map((entry) => entry.exportName.name as string),\n );\n\n // In h3 v2 / Nitro v3, event.node is undefined during prerendering\n // (which uses the fetch-based pipeline, not Node.js http). We use\n // optional chaining so that page endpoints work in both Node.js\n // server and fetch-based prerender contexts.\n // Nitro v3 no longer guarantees the private `nitro/deps/ofetch`\n // subpath that older codegen relied on.\n //\n // Page loaders expect Nitro-style `$fetch` semantics (parsed data plus\n // internal relative-route support), so construct a request-local fetch\n // using public APIs:\n // - `createFetch` from `ofetch` for `$fetch` behavior\n // - `fetchWithEvent` from `h3` for internal Nitro request routing\n //\n // This avoids both unstable private Nitro imports and assumptions about\n // a global runtime `$fetch` being available during prerender.\n const code = `\n import { defineHandler, fetchWithEvent } from 'nitro/h3';\n import { createFetch } from 'ofetch';\n\n ${\n fileExports.includes('load')\n ? _code\n : `\n ${_code}\n export const load = () => {\n return {};\n }`\n }\n\n ${\n fileExports.includes('action')\n ? ''\n : `\n export const action = () => {\n return {};\n }\n `\n }\n\n export default defineHandler(async(event) => {\n ${SERVER_FETCH_FACTORY_SNIPPET}\n\n if (event.method === 'GET') {\n try {\n return await load({\n params: event.context.params,\n req: event.node?.req,\n res: event.node?.res,\n fetch: serverFetch,\n event\n });\n } catch(e) {\n console.error(\\` An error occurred: \\${e}\\`)\n throw e;\n }\n } else {\n try {\n return await action({\n params: event.context.params,\n req: event.node?.req,\n res: event.node?.res,\n fetch: serverFetch,\n event\n });\n } catch(e) {\n console.error(\\` An error occurred: \\${e}\\`)\n throw e;\n }\n }\n });\n `;\n\n return {\n code,\n map: null,\n };\n }\n\n return;\n },\n };\n}\n"],"mappings":";;;;AAIA,SAAgB,sBAAsB;AACpC,QAAO;EACL,MAAM;EACN,MAAM,UACJ,OACA,IACkD;AAClD,OAAI,cAAc,GAAG,CAAC,SAAS,UAAU,IAAI,GAAG,SAAS,aAAa,EAAE;IAMtE,MAAM,cALS,UAAU,IAAI,OAAO;KAClC,YAAY;KACZ,MAAM;KACP,CAAC,CAEmC,OAAO,cAAc,SAAS,MACjE,EAAE,QACC,QAAQ,UAAU,MAAM,WAAW,SAAS,KAAK,CACjD,KAAK,UAAU,MAAM,WAAW,KAAe,CACnD;AA0ED,WAAO;KACL,MA1DW;;;;cAKP,YAAY,SAAS,OAAO,GACxB,QACA;kBACA,MAAM;;;mBAIX;;cAGC,YAAY,SAAS,SAAS,GAC1B,KACA;;;;gBAKL;;;gBAGG,6BAA6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAkCnC,KAAK;KACN;;;EAKN"}
1
+ {"version":3,"file":"page-endpoints.js","names":[],"sources":["../../../../src/lib/plugins/page-endpoints.ts"],"sourcesContent":["import { parseSync } from 'oxc-parser';\nimport { normalizePath } from 'vite';\n\nexport function pageEndpointsPlugin() {\n return {\n name: 'analogjs-vite-plugin-nitro-rollup-page-endpoint',\n async transform(\n _code: string,\n id: string,\n ): Promise<{ code: string; map: null } | undefined> {\n if (normalizePath(id).includes('/pages/') && id.endsWith('.server.ts')) {\n const result = parseSync(id, _code, {\n sourceType: 'module',\n lang: 'ts',\n });\n\n const fileExports: string[] = result.module.staticExports.flatMap((e) =>\n e.entries\n .filter((entry) => entry.exportName.name !== null)\n .map((entry) => entry.exportName.name as string),\n );\n\n const code = `\n import { defineEventHandler } from 'h3';\n\n ${\n fileExports.includes('load')\n ? _code\n : `\n ${_code}\n export const load = () => {\n return {};\n }`\n }\n\n ${\n fileExports.includes('action')\n ? ''\n : `\n export const action = () => {\n return {};\n } \n `\n }\n\n export default defineEventHandler(async(event) => {\n if (event.method === 'GET') {\n try {\n return await load({\n params: event.context.params,\n req: event.node.req,\n res: event.node.res,\n fetch: $fetch,\n event\n });\n } catch(e) {\n console.error(\\` An error occurred: \\${e}\\`)\n throw e;\n }\n } else {\n try {\n return await action({\n params: event.context.params,\n req: event.node.req,\n res: event.node.res,\n fetch: $fetch,\n event\n });\n } catch(e) {\n console.error(\\` An error occurred: \\${e}\\`)\n throw e;\n } \n }\n });\n `;\n\n return {\n code,\n map: null,\n };\n }\n\n return;\n },\n };\n}\n"],"mappings":";;;AAGA,SAAgB,sBAAsB;AACpC,QAAO;EACL,MAAM;EACN,MAAM,UACJ,OACA,IACkD;AAClD,OAAI,cAAc,GAAG,CAAC,SAAS,UAAU,IAAI,GAAG,SAAS,aAAa,EAAE;IAMtE,MAAM,cALS,UAAU,IAAI,OAAO;KAClC,YAAY;KACZ,MAAM;KACP,CAAC,CAEmC,OAAO,cAAc,SAAS,MACjE,EAAE,QACC,QAAQ,UAAU,MAAM,WAAW,SAAS,KAAK,CACjD,KAAK,UAAU,MAAM,WAAW,KAAe,CACnD;AAwDD,WAAO;KACL,MAvDW;;;cAIP,YAAY,SAAS,OAAO,GACxB,QACA;kBACA,MAAM;;;mBAIX;;cAGC,YAAY,SAAS,SAAS,GAC1B,KACA;;;;gBAKL;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAmCH,KAAK;KACN;;;EAKN"}