@torpor/build 1.9.0 → 1.11.0

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 (107) hide show
  1. package/README.md +1 -1
  2. package/dist/{SessionHelper-MaodMaLU.d.mts → CacheOptions-C4-ebVt9.d.mts} +58 -8
  3. package/dist/CacheOptions-C4-ebVt9.d.mts.map +1 -0
  4. package/dist/{MiddlewareFunction-BZilnEei.d.mts → MiddlewareFunction-DMYxjzF4.d.mts} +31 -2
  5. package/dist/MiddlewareFunction-DMYxjzF4.d.mts.map +1 -0
  6. package/dist/{Router-By9Nlg39.d.mts → Router-DyK3DTWQ.d.mts} +4 -4
  7. package/dist/Router-DyK3DTWQ.d.mts.map +1 -0
  8. package/dist/{Server-dcRbdPXf.mjs → Server-BCijhgZp.mjs} +3 -3
  9. package/dist/{Server-dcRbdPXf.mjs.map → Server-BCijhgZp.mjs.map} +1 -1
  10. package/dist/{Server-qn5Ws_d0.d.mts → Server-ClwvuilS.d.mts} +2 -2
  11. package/dist/{Server-qn5Ws_d0.d.mts.map → Server-ClwvuilS.d.mts.map} +1 -1
  12. package/dist/{ServerEvent-BY4f3RVF.mjs → ServerEvent-BBRkd4Ya.mjs} +136 -31
  13. package/dist/ServerEvent-BBRkd4Ya.mjs.map +1 -0
  14. package/dist/{ServerHook-W111nEhe.d.mts → ServerHook-DY-NSG6n.d.mts} +2 -2
  15. package/dist/{ServerHook-W111nEhe.d.mts.map → ServerHook-DY-NSG6n.d.mts.map} +1 -1
  16. package/dist/{ServerLoadEvent-BH6oG1o6.d.mts → ServerLoadEvent-CpcgsKCU.d.mts} +32 -8
  17. package/dist/ServerLoadEvent-CpcgsKCU.d.mts.map +1 -0
  18. package/dist/{Site-DGZJB7Do.d.mts → Site-BEMQW1_y.d.mts} +216 -11
  19. package/dist/Site-BEMQW1_y.d.mts.map +1 -0
  20. package/dist/{basePath-DQnbHc7o.mjs → basePath-B6hmOMl4.mjs} +89 -4
  21. package/dist/basePath-B6hmOMl4.mjs.map +1 -0
  22. package/dist/bin/index.js +37 -2
  23. package/dist/bin/index.js.map +1 -1
  24. package/dist/clientEntry.mjs +10 -5
  25. package/dist/clientEntry.mjs.map +1 -1
  26. package/dist/dev.d.mts +2 -2
  27. package/dist/dev.mjs +2 -2
  28. package/dist/{devPlugin-lLzauETn.mjs → devPlugin-BGrTpcC2.mjs} +3 -3
  29. package/dist/{devPlugin-lLzauETn.mjs.map → devPlugin-BGrTpcC2.mjs.map} +1 -1
  30. package/dist/discovery.d.mts +1 -1
  31. package/dist/discovery.mjs +1 -1
  32. package/dist/index.d.mts +22 -6
  33. package/dist/index.d.mts.map +1 -1
  34. package/dist/index.mjs +10 -0
  35. package/dist/index.mjs.map +1 -1
  36. package/dist/{load-BODDzmH0.mjs → load-Dw187nJ_.mjs} +95 -52
  37. package/dist/load-Dw187nJ_.mjs.map +1 -0
  38. package/dist/nav.d.mts +30 -3
  39. package/dist/nav.d.mts.map +1 -1
  40. package/dist/nav.mjs +40 -12
  41. package/dist/nav.mjs.map +1 -1
  42. package/dist/nodeDev.d.mts +1 -1
  43. package/dist/nodeDev.mjs +1 -1
  44. package/dist/openapi.d.mts +24 -80
  45. package/dist/openapi.d.mts.map +1 -1
  46. package/dist/openapi.mjs +36 -1
  47. package/dist/openapi.mjs.map +1 -0
  48. package/dist/{plugin-D8Www11B.mjs → plugin-BQsMnkTj.mjs} +42 -3
  49. package/dist/plugin-BQsMnkTj.mjs.map +1 -0
  50. package/dist/{read-DxMVAh5Y.mjs → read-CPW2iPum.mjs} +21 -2
  51. package/dist/read-CPW2iPum.mjs.map +1 -0
  52. package/dist/{response-C5EZsszY.mjs → response-B4UoOJvv.mjs} +3 -24
  53. package/dist/response-B4UoOJvv.mjs.map +1 -0
  54. package/dist/response.mjs +2 -2
  55. package/dist/run.d.mts +1 -1
  56. package/dist/run.d.mts.map +1 -1
  57. package/dist/run.mjs +1 -1
  58. package/dist/{runHooks-D5p1Rh7i.mjs → runHooks-C7kt7SEo.mjs} +36 -2
  59. package/dist/runHooks-C7kt7SEo.mjs.map +1 -0
  60. package/dist/{runOpenApi-C5yMpQU1.mjs → runOpenApi-DK-QnYEr.mjs} +279 -35
  61. package/dist/runOpenApi-DK-QnYEr.mjs.map +1 -0
  62. package/dist/server/Server.d.mts +1 -1
  63. package/dist/server/Server.mjs +1 -1
  64. package/dist/server.d.mts +30 -6
  65. package/dist/server.d.mts.map +1 -1
  66. package/dist/server.mjs +47 -3
  67. package/dist/server.mjs.map +1 -1
  68. package/dist/{serverEntry-BGii8bB6.d.mts → serverEntry-BFad1k1C.d.mts} +3 -3
  69. package/dist/serverEntry-BFad1k1C.d.mts.map +1 -0
  70. package/dist/{serverEntry-D1hE-Jzt.mjs → serverEntry-DAT7o7o2.mjs} +3 -5
  71. package/dist/serverEntry-DAT7o7o2.mjs.map +1 -0
  72. package/dist/serverEntry.d.mts +1 -1
  73. package/dist/serverEntry.mjs +1 -1
  74. package/dist/{serverHandlers-CSBUEgJt.mjs → serverHandlers-B1L8I72-.mjs} +434 -202
  75. package/dist/serverHandlers-B1L8I72-.mjs.map +1 -0
  76. package/dist/{sitemap-xmE0zfme.d.mts → sitemap-CKmagPyL.d.mts} +2 -2
  77. package/dist/{sitemap-xmE0zfme.d.mts.map → sitemap-CKmagPyL.d.mts.map} +1 -1
  78. package/dist/{sitemap-4imxJVrG.mjs → sitemap-DdzFjGlo.mjs} +2 -2
  79. package/dist/{sitemap-4imxJVrG.mjs.map → sitemap-DdzFjGlo.mjs.map} +1 -1
  80. package/dist/state.d.mts +1 -4
  81. package/dist/state.d.mts.map +1 -1
  82. package/dist/state.mjs +1 -1
  83. package/dist/test.d.mts +2 -2
  84. package/dist/test.mjs +2 -2
  85. package/dist/{unprocessable-DwAG44Rh.mjs → unprocessable-BZXwyN0n.mjs} +23 -2
  86. package/dist/unprocessable-BZXwyN0n.mjs.map +1 -0
  87. package/package.json +10 -7
  88. package/src/types/manifest.d.ts +3 -0
  89. package/dist/MiddlewareFunction-BZilnEei.d.mts.map +0 -1
  90. package/dist/Router-By9Nlg39.d.mts.map +0 -1
  91. package/dist/ServerEvent-BY4f3RVF.mjs.map +0 -1
  92. package/dist/ServerLoadEvent-BH6oG1o6.d.mts.map +0 -1
  93. package/dist/SessionHelper-MaodMaLU.d.mts.map +0 -1
  94. package/dist/Site-DGZJB7Do.d.mts.map +0 -1
  95. package/dist/_page-CW6SLuT4.mjs +0 -14
  96. package/dist/_page-CW6SLuT4.mjs.map +0 -1
  97. package/dist/basePath-DQnbHc7o.mjs.map +0 -1
  98. package/dist/load-BODDzmH0.mjs.map +0 -1
  99. package/dist/plugin-D8Www11B.mjs.map +0 -1
  100. package/dist/read-DxMVAh5Y.mjs.map +0 -1
  101. package/dist/response-C5EZsszY.mjs.map +0 -1
  102. package/dist/runHooks-D5p1Rh7i.mjs.map +0 -1
  103. package/dist/runOpenApi-C5yMpQU1.mjs.map +0 -1
  104. package/dist/serverEntry-BGii8bB6.d.mts.map +0 -1
  105. package/dist/serverEntry-D1hE-Jzt.mjs.map +0 -1
  106. package/dist/serverHandlers-CSBUEgJt.mjs.map +0 -1
  107. package/dist/unprocessable-DwAG44Rh.mjs.map +0 -1
@@ -1,3 +1,37 @@
1
+ //#region src/site/requestBase.ts
2
+ /**
3
+ * The base path of the site handling a request.
4
+ *
5
+ * Unlike the client runtime (one site per page), a server process can host
6
+ * several sites with different base paths (tests, multi-tenant servers), so
7
+ * the server must not read the module-global `getBasePath()`. The site's
8
+ * `createServerLoad` handler tags each event with its base here, and response
9
+ * finalization (`ServerEvent.addHeaders`) reads it back.
10
+ *
11
+ * Keyed weakly by the event, so no cleanup is needed when a request ends.
12
+ */
13
+ const bases = /* @__PURE__ */ new WeakMap();
14
+ /** Records the base path of the site handling `ev`. */
15
+ function setRequestBase(ev, base) {
16
+ bases.set(ev, base);
17
+ }
18
+ /** The base path of the site handling `ev` ("" when unset). */
19
+ function requestBase(ev) {
20
+ return bases.get(ev) ?? "";
21
+ }
22
+ const preloads = /* @__PURE__ */ new WeakMap();
23
+ /**
24
+ * Records the client chunks of the site handling `ev`, which page renders
25
+ * preload (kept per request for the same reason as the base path).
26
+ */
27
+ function setRequestPreloads(ev, value) {
28
+ if (value) preloads.set(ev, value);
29
+ }
30
+ /** The client chunks of the site handling `ev`, if it was built with them. */
31
+ function requestPreloads(ev) {
32
+ return preloads.get(ev);
33
+ }
34
+ //#endregion
1
35
  //#region src/server/runHooks.ts
2
36
  /**
3
37
  * Runs hooks around a request handler — the shared implementation of the
@@ -56,6 +90,6 @@ async function runHooks(phases, handler, options) {
56
90
  };
57
91
  }
58
92
  //#endregion
59
- export { runHooks as t };
93
+ export { setRequestPreloads as a, setRequestBase as i, requestBase as n, requestPreloads as r, runHooks as t };
60
94
 
61
- //# sourceMappingURL=runHooks-D5p1Rh7i.mjs.map
95
+ //# sourceMappingURL=runHooks-C7kt7SEo.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runHooks-C7kt7SEo.mjs","names":[],"sources":["../src/site/requestBase.ts","../src/server/runHooks.ts"],"sourcesContent":["import type ServerEvent from \"../server/ServerEvent\";\nimport type ModulePreloads from \"../types/ModulePreloads\";\n\n/**\n * The base path of the site handling a request.\n *\n * Unlike the client runtime (one site per page), a server process can host\n * several sites with different base paths (tests, multi-tenant servers), so\n * the server must not read the module-global `getBasePath()`. The site's\n * `createServerLoad` handler tags each event with its base here, and response\n * finalization (`ServerEvent.addHeaders`) reads it back.\n *\n * Keyed weakly by the event, so no cleanup is needed when a request ends.\n */\nconst bases = new WeakMap<ServerEvent, string>();\n\n/** Records the base path of the site handling `ev`. */\nexport function setRequestBase(ev: ServerEvent, base: string): void {\n\tbases.set(ev, base);\n}\n\n/** The base path of the site handling `ev` (\"\" when unset). */\nexport function requestBase(ev: ServerEvent): string {\n\treturn bases.get(ev) ?? \"\";\n}\n\nconst preloads = new WeakMap<ServerEvent, ModulePreloads>();\n\n/**\n * Records the client chunks of the site handling `ev`, which page renders\n * preload (kept per request for the same reason as the base path).\n */\nexport function setRequestPreloads(ev: ServerEvent, value: ModulePreloads | undefined): void {\n\tif (value) preloads.set(ev, value);\n}\n\n/** The client chunks of the site handling `ev`, if it was built with them. */\nexport function requestPreloads(ev: ServerEvent): ModulePreloads | undefined {\n\treturn preloads.get(ev);\n}\n","import type ServerEvent from \"./ServerEvent\";\n\n/**\n * One entry in a hook list: middleware (`MiddlewareFunction`) and server hooks\n * (`ServerHook`) are structurally identical — an optional enter and exit.\n */\ninterface Hook {\n\tenter?: (arg: any) => any;\n\texit?: (arg: any) => any;\n}\n\n/**\n * A phase of hooks around a request: a hook list plus the argument its\n * enter/exit functions take (a ServerEvent for middleware, a ServerLoadEvent\n * for server hooks). Multiple phases run their enters in order; exits run in\n * the exact reverse of entry order, across phases too.\n */\nexport interface HookPhase {\n\thooks: Hook[];\n\targ: any;\n}\n\n/**\n * Runs hooks around a request handler — the shared implementation of the\n * enter/exit machine for both middleware (site.middleware, endpoint\n * middleware) and server hooks (_hook.server.ts):\n *\n * - enter hooks run in phase order, then list order, until one returns a\n * Response (short-circuit: the handler and remaining enters are skipped)\n * - the handler runs only if no enter hook responded\n * - exit hooks run in reverse entry order — for the hooks that were entered,\n * even when the handler or an enter hook threw\n *\n * Errors are captured (and set on `options.event.error`) rather than thrown,\n * so `options.onError` can render an error response before the exit hooks run\n * (exits inspect `ev.error` to handle it). Callers rethrow `error` when the\n * result carries no response.\n *\n * With `options.event` (the middleware flavor), `ev.response` is kept in sync\n * with the running response, and an exit hook's returned Response replaces\n * it — per the `MiddlewareFunction` contract. The server-hook flavor passes\n * no event, and its exits return void.\n */\nexport default async function runHooks(\n\tphases: HookPhase[],\n\thandler: () => Promise<Response | undefined>,\n\toptions?: {\n\t\tevent?: ServerEvent;\n\t\tonError?: (ev: ServerEvent, error: unknown) => Promise<Response | undefined>;\n\t},\n): Promise<{ response: Response | undefined; error: unknown }> {\n\tconst flat = phases.flatMap((phase) => phase.hooks.map((hook) => ({ hook, arg: phase.arg })));\n\tlet entered = 0;\n\tlet response: Response | undefined = undefined;\n\tlet error: unknown = undefined;\n\tconst ev = options?.event;\n\ttry {\n\t\tfor (; entered < flat.length && !response; entered++) {\n\t\t\t// A hook returns a Response to short-circuit the request\n\t\t\tconst result = await flat[entered].hook.enter?.(flat[entered].arg);\n\t\t\tif (result) {\n\t\t\t\tresponse = result;\n\t\t\t}\n\t\t}\n\t\tif (!response) {\n\t\t\tresponse = await handler();\n\t\t}\n\t} catch (e) {\n\t\t// Exits can handle the error by returning a Response (via\n\t\t// `onError`/the caller); if none does, the caller rethrows it\n\t\terror = e;\n\t\tif (ev) {\n\t\t\tev.error = e;\n\t\t}\n\t\tif (options?.onError) {\n\t\t\tresponse = await options.onError(ev!, e);\n\t\t}\n\t} finally {\n\t\tif (ev && response) {\n\t\t\tev.response = response;\n\t\t}\n\t\t// Run exit hooks in reverse order for the hooks that were entered.\n\t\t// An exit hook can return a Response to replace the response, or to\n\t\t// handle ev.error\n\t\twhile (entered > 0) {\n\t\t\tentered--;\n\t\t\tconst result = await flat[entered].hook.exit?.(flat[entered].arg);\n\t\t\tif (result && ev) {\n\t\t\t\tresponse = result;\n\t\t\t\tev.response = result;\n\t\t\t}\n\t\t}\n\t}\n\treturn { response, error };\n}\n"],"mappings":";;;;;;;;;;;;AAcA,MAAM,wBAAQ,IAAI,QAA6B;;AAG/C,SAAgB,eAAe,IAAiB,MAAoB;CACnE,MAAM,IAAI,IAAI,IAAI;AACnB;;AAGA,SAAgB,YAAY,IAAyB;CACpD,OAAO,MAAM,IAAI,EAAE,KAAK;AACzB;AAEA,MAAM,2BAAW,IAAI,QAAqC;;;;;AAM1D,SAAgB,mBAAmB,IAAiB,OAAyC;CAC5F,IAAI,OAAO,SAAS,IAAI,IAAI,KAAK;AAClC;;AAGA,SAAgB,gBAAgB,IAA6C;CAC5E,OAAO,SAAS,IAAI,EAAE;AACvB;;;;;;;;;;;;;;;;;;;;;;;;ACIA,eAA8B,SAC7B,QACA,SACA,SAI8D;CAC9D,MAAM,OAAO,OAAO,SAAS,UAAU,MAAM,MAAM,KAAK,UAAU;EAAE;EAAM,KAAK,MAAM;CAAI,EAAE,CAAC;CAC5F,IAAI,UAAU;CACd,IAAI,WAAiC,KAAA;CACrC,IAAI,QAAiB,KAAA;CACrB,MAAM,KAAK,SAAS;CACpB,IAAI;EACH,OAAO,UAAU,KAAK,UAAU,CAAC,UAAU,WAAW;GAErD,MAAM,SAAS,MAAM,KAAK,QAAQ,CAAC,KAAK,QAAQ,KAAK,QAAQ,CAAC,GAAG;GACjE,IAAI,QACH,WAAW;EAEb;EACA,IAAI,CAAC,UACJ,WAAW,MAAM,QAAQ;CAE3B,SAAS,GAAG;EAGX,QAAQ;EACR,IAAI,IACH,GAAG,QAAQ;EAEZ,IAAI,SAAS,SACZ,WAAW,MAAM,QAAQ,QAAQ,IAAK,CAAC;CAEzC,UAAU;EACT,IAAI,MAAM,UACT,GAAG,WAAW;EAKf,OAAO,UAAU,GAAG;GACnB;GACA,MAAM,SAAS,MAAM,KAAK,QAAQ,CAAC,KAAK,OAAO,KAAK,QAAQ,CAAC,GAAG;GAChE,IAAI,UAAU,IAAI;IACjB,WAAW;IACX,GAAG,WAAW;GACf;EACD;CACD;CACA,OAAO;EAAE;EAAU;CAAM;AAC1B"}
@@ -1,10 +1,11 @@
1
- import { i as normalizeOrigin, r as normalizeBasePath } from "./basePath-DQnbHc7o.mjs";
2
- import { i as buildOpenApiDocument, t as OPEN_API_STATE_KEY } from "./plugin-D8Www11B.mjs";
3
- import { r as serverError } from "./response-C5EZsszY.mjs";
4
- import { i as siteEntryPaths, n as prepareTemplate, r as detectSourceMode, t as devPlugin } from "./devPlugin-lLzauETn.mjs";
5
- import { t as ServerEvent } from "./ServerEvent-BY4f3RVF.mjs";
6
- import { n as sitemapXml } from "./sitemap-4imxJVrG.mjs";
7
- import { t as Server } from "./Server-dcRbdPXf.mjs";
1
+ import { t as Router } from "./Router-C4ADUfhv.mjs";
2
+ import { i as normalizeOrigin, r as normalizeBasePath, t as addBaseToPath } from "./basePath-B6hmOMl4.mjs";
3
+ import { i as buildOpenApiDocument, t as OPEN_API_STATE_KEY } from "./plugin-BQsMnkTj.mjs";
4
+ import { r as serverError } from "./response-B4UoOJvv.mjs";
5
+ import { i as siteEntryPaths, n as prepareTemplate, r as detectSourceMode, t as devPlugin } from "./devPlugin-BGrTpcC2.mjs";
6
+ import { t as ServerEvent } from "./ServerEvent-BBRkd4Ya.mjs";
7
+ import { n as sitemapXml } from "./sitemap-DdzFjGlo.mjs";
8
+ import { t as Server } from "./Server-BCijhgZp.mjs";
8
9
  import { createRequire, isBuiltin } from "node:module";
9
10
  import fs, { existsSync, promises, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
10
11
  import fpath from "node:path";
@@ -12,6 +13,7 @@ import torpor from "@torpor/unplugin/vite";
12
13
  import { configDotenv } from "dotenv";
13
14
  import { build, createServer, defineConfig } from "vite";
14
15
  import { parse } from "@torpor/view/compile";
16
+ import { gzipSync } from "node:zlib";
15
17
  import { pathToFileURL } from "node:url";
16
18
  import { createHash } from "node:crypto";
17
19
  import { writeFile } from "node:fs/promises";
@@ -96,6 +98,7 @@ function stripJsonc(text) {
96
98
  //#region src/site/checkRoutes.ts
97
99
  const ENDPOINT_TYPES = [
98
100
  "PageServerEndPoint",
101
+ "LayoutServerEndPoint",
99
102
  "PageEndPoint",
100
103
  "ServerEndPoint",
101
104
  "ServerHook"
@@ -352,8 +355,8 @@ function expectedAnnotationPath(route) {
352
355
  }
353
356
  function typeNameFor(route) {
354
357
  switch (route.type) {
355
- case 1:
356
- case 5: return "PageServerEndPoint";
358
+ case 1: return "PageServerEndPoint";
359
+ case 5: return "LayoutServerEndPoint";
357
360
  case 3: return "ServerEndPoint";
358
361
  case 6:
359
362
  case 7: return "ServerHook";
@@ -517,7 +520,7 @@ function hasLoadExport(source) {
517
520
  * A Vite plugin that provides information about the app to both clientEntry and
518
521
  * serverEntry.
519
522
  */
520
- function manifest(site, server = false, dev = false) {
523
+ function manifest(site, server = false, dev = false, preloads) {
521
524
  return {
522
525
  name: "torpor-manifest",
523
526
  resolveId: {
@@ -568,6 +571,7 @@ export default {
568
571
  viewTransitions: ${!!site.viewTransitions},
569
572
  dev: ${!!dev},
570
573
  ${serverRequest && hasMiddleware ? "middleware: __site.middleware ?? []," : ""}
574
+ ${serverRequest && preloads ? `preloads: ${JSON.stringify(preloads)},` : ""}
571
575
  routes: [
572
576
  ${site.routes.map((r) => {
573
577
  let endPoint;
@@ -594,13 +598,12 @@ export default {
594
598
  }
595
599
  /**
596
600
  * Generates the module code for the OpenAPI document endpoint: a map of
597
- * route path to endpoint loader, and a cached handler that loads every
598
- * endpoint and builds the document on first use.
601
+ * route path to endpoint loader, and a handler (from `createOpenApiHandler`)
602
+ * that builds the document from them. Exported so its wiring can be tested.
599
603
  */
600
604
  function openApiGlueCode(site, options) {
601
605
  return `
602
- import { buildOpenApiDocument, OPEN_API_STATE_KEY } from "@torpor/build/openapi";
603
- let __openApiDoc;
606
+ import { createOpenApiHandler, OPEN_API_STATE_KEY } from "@torpor/build/openapi";
604
607
  const __openApiRoutes = {
605
608
  ${site.routes.filter((r) => r.type === 3).filter((r) => r.path !== options.docs).map((r) => {
606
609
  if (!r.file) {
@@ -611,18 +614,12 @@ const __openApiRoutes = {
611
614
  return `${JSON.stringify(r.path)}: () => import(${JSON.stringify(filePath)})`;
612
615
  }).join(",\n ")}
613
616
  };
614
- async function __openApiGet() {
615
- if (!__openApiDoc) {
616
- const __entries = [];
617
- for (const [__path, __loader] of Object.entries(__openApiRoutes)) {
618
- __entries.push({ path: __path, endPoint: (await __loader()).default });
619
- }
620
- __openApiDoc = buildOpenApiDocument(__entries, __site.pluginState.get(OPEN_API_STATE_KEY));
621
- }
622
- return new Response(JSON.stringify(__openApiDoc), {
623
- headers: { "Content-Type": "application/json" },
624
- });
625
- }
617
+ // The handler is called with the request's event, so the extend hook can
618
+ // build a document from it (e.g. one document per route param)
619
+ const __openApiGet = createOpenApiHandler(
620
+ __openApiRoutes,
621
+ () => __site.pluginState.get(OPEN_API_STATE_KEY),
622
+ );
626
623
  `;
627
624
  }
628
625
  //#endregion
@@ -763,6 +760,175 @@ function resolveFromNodeModules(name, require) {
763
760
  }
764
761
  }
765
762
  //#endregion
763
+ //#region src/run/clientPreloads.ts
764
+ /**
765
+ * Works out which chunks each page needs, from the client build's manifest,
766
+ * so the server can emit `<link rel="modulepreload">` tags for them.
767
+ *
768
+ * Without them the browser only sees the client entry script (at the end of
769
+ * the HTML), and finds the page's own chunks once the entry has downloaded
770
+ * and run: a waterfall of HTML, then the entry, then the route's chunks,
771
+ * then their imports. Each list is a chunk's file plus everything it
772
+ * statically imports, transitively; dynamic imports are left to load when
773
+ * they're needed.
774
+ *
775
+ * @param manifest The parsed `.vite/manifest.json`
776
+ * @param root The client build's resolved Vite root, which manifest keys
777
+ * and `src` paths are relative to
778
+ * @param routes Route paths and their absolute source files (page and
779
+ * layout components)
780
+ * @param readStylesheet Reads a stylesheet by its output path (e.g.
781
+ * `assets/x.css`), to find the component styles it contains
782
+ */
783
+ function clientPreloads(manifest, root, routes, readStylesheet = () => "") {
784
+ const closure = (key, seen = /* @__PURE__ */ new Set()) => {
785
+ if (seen.has(key)) return [];
786
+ seen.add(key);
787
+ const chunk = manifest[key];
788
+ if (!chunk) return [];
789
+ const files = [`/${chunk.file}`];
790
+ for (const imported of chunk.imports ?? []) files.push(...closure(imported, seen));
791
+ return files;
792
+ };
793
+ const keysByFile = /* @__PURE__ */ new Map();
794
+ for (const [key, chunk] of Object.entries(manifest)) keysByFile.set(fpath.resolve(root, chunk.src ?? key), key);
795
+ const entryKey = Object.keys(manifest).find((key) => manifest[key].isEntry && manifest[key].name === "clientEntry");
796
+ const entry = entryKey ? closure(entryKey) : [];
797
+ const inEntry = new Set(entry);
798
+ const stylesClosure = (key, seen = /* @__PURE__ */ new Set()) => {
799
+ if (seen.has(key)) return [];
800
+ seen.add(key);
801
+ const chunk = manifest[key];
802
+ if (!chunk) return [];
803
+ const files = (chunk.css ?? []).map((file) => `/${file}`);
804
+ for (const imported of chunk.imports ?? []) files.push(...stylesClosure(imported, seen));
805
+ return files;
806
+ };
807
+ const entryStyles = entryKey ? unique(stylesClosure(entryKey)) : [];
808
+ const inEntryStyles = new Set(entryStyles);
809
+ const preloads = {};
810
+ const routeStyles = {};
811
+ for (const route of routes) {
812
+ const key = keysByFile.get(fpath.resolve(route.file));
813
+ if (!key) continue;
814
+ const files = closure(key).filter((file) => !inEntry.has(file));
815
+ if (files.length > 0) preloads[route.path] = files;
816
+ const styles = unique(stylesClosure(key)).filter((file) => !inEntryStyles.has(file));
817
+ if (styles.length > 0) routeStyles[route.path] = styles;
818
+ }
819
+ const hashes = {};
820
+ for (const file of /* @__PURE__ */ new Set([...entryStyles, ...Object.values(routeStyles).flat()])) {
821
+ const found = /* @__PURE__ */ new Set();
822
+ for (const match of readStylesheet(file.slice(1)).matchAll(/\.torp-([a-z0-9]+)/g)) found.add(match[1]);
823
+ if (found.size > 0) hashes[file] = [...found];
824
+ }
825
+ return {
826
+ entry,
827
+ routes: preloads,
828
+ styles: {
829
+ entry: entryStyles,
830
+ routes: routeStyles,
831
+ hashes
832
+ }
833
+ };
834
+ }
835
+ function unique(files) {
836
+ return [...new Set(files)];
837
+ }
838
+ //#endregion
839
+ //#region src/run/pageSizes.ts
840
+ /** How many of the heaviest pages the build report lists. */
841
+ const REPORT_LIMIT = 10;
842
+ /**
843
+ * Works out how much JavaScript each page route loads before it hydrates:
844
+ * the client entry's chunks, its layouts' and its own, as preloaded by the
845
+ * server (see clientPreloads). Chunks loaded later through dynamic imports
846
+ * aren't counted.
847
+ *
848
+ * @param preloads The client chunks per route, from the client build
849
+ * @param routes The site's routes (path, type and sub folder)
850
+ * @param clientFolder The client build's output folder (`dist/client`)
851
+ */
852
+ function pageSizes(preloads, routes, clientFolder) {
853
+ const router = new Router().addPages(routes.map((r) => ({
854
+ path: r.path,
855
+ type: r.type,
856
+ endPoint: () => Promise.resolve({}),
857
+ subFolder: r.subFolder
858
+ })));
859
+ const sizes = /* @__PURE__ */ new Map();
860
+ const sizeOf = (file) => {
861
+ let size = sizes.get(file);
862
+ if (!size) {
863
+ const content = readFileSync(fpath.join(clientFolder, file));
864
+ size = {
865
+ raw: content.length,
866
+ gzip: gzipSync(content).length
867
+ };
868
+ sizes.set(file, size);
869
+ }
870
+ return size;
871
+ };
872
+ const result = [];
873
+ for (const route of router.routes) {
874
+ if (route.handler.type !== 0) continue;
875
+ const handler = router.match(route.path, new URLSearchParams())?.handler;
876
+ const files = new Set(preloads.entry);
877
+ for (const layout of handler?.path === route.path ? handler.layouts ?? [] : []) for (const file of preloads.routes[layout.path] ?? []) files.add(file);
878
+ for (const file of preloads.routes[route.path] ?? []) files.add(file);
879
+ let raw = 0;
880
+ let gzip = 0;
881
+ for (const file of files) {
882
+ const size = sizeOf(file);
883
+ raw += size.raw;
884
+ gzip += size.gzip;
885
+ }
886
+ result.push({
887
+ path: route.path,
888
+ files: files.size,
889
+ raw,
890
+ gzip
891
+ });
892
+ }
893
+ return result.sort((a, b) => b.gzip - a.gzip || a.path.localeCompare(b.path));
894
+ }
895
+ /** The pages over the JavaScript budget, if one is set. */
896
+ function overBudget(pages, budgets) {
897
+ const limit = budgets?.js;
898
+ if (limit === void 0) return [];
899
+ return pages.filter((page) => page.gzip > limit);
900
+ }
901
+ /**
902
+ * The build report: the heaviest pages (all of them, when there are few),
903
+ * then every page over the budget.
904
+ */
905
+ function formatPageSizes(pages, budgets) {
906
+ if (pages.length === 0) return "";
907
+ const over = overBudget(pages, budgets);
908
+ const shown = pages.slice(0, REPORT_LIMIT);
909
+ const width = Math.max(...shown.map((page) => page.path.length));
910
+ const row = (page) => ` ${page.path.padEnd(width)} ${kb(page.gzip).padStart(9)} (${kb(page.raw)} raw, ${page.files} file${page.files === 1 ? "" : "s"})`;
911
+ let lines = ["[torpor] JavaScript loaded by each page before it hydrates (gzipped):"];
912
+ lines.push(...shown.map(row));
913
+ if (pages.length > shown.length) {
914
+ const rest = pages.length - shown.length;
915
+ const lightest = pages[pages.length - 1];
916
+ lines.push(` ...and ${rest} more page${rest === 1 ? "" : "s"}, down to ${kb(lightest.gzip)} (${lightest.path})`);
917
+ }
918
+ if (budgets?.js !== void 0) {
919
+ if (over.length === 0) lines.push(` All pages are within the ${kb(budgets.js)} budget.`);
920
+ else {
921
+ lines.push(`[torpor] ${over.length} page${over.length === 1 ? " is" : "s are"} over the ${kb(budgets.js)} JavaScript budget (site.budgets.js):`);
922
+ const overWidth = Math.max(...over.map((page) => page.path.length));
923
+ lines.push(...over.map((page) => ` ${page.path.padEnd(overWidth)} ${kb(page.gzip).padStart(9)} (+${kb(page.gzip - budgets.js)})`));
924
+ }
925
+ }
926
+ return lines.join("\n");
927
+ }
928
+ function kb(bytes) {
929
+ return `${(bytes / 1e3).toFixed(1)} kB`;
930
+ }
931
+ //#endregion
766
932
  //#region src/run/runPrerender.ts
767
933
  /**
768
934
  * Resolves which page paths should be prerendered, from the routes of a
@@ -831,12 +997,13 @@ async function runPrerender(site) {
831
997
  template = prepareTemplate(await promises.readFile(siteHtml, "utf-8"), `/assets/${clientScript}`);
832
998
  }
833
999
  const entries = await resolvePrerenderPaths(routes, site.prerender);
1000
+ const base = normalizeBasePath(site.basePath);
834
1001
  globalThis.adapter ??= { env: process.env };
835
1002
  const failures = [];
836
1003
  const skipped = [];
837
1004
  let written = 0;
838
1005
  for (const entry of entries) {
839
- const url = `http://torpor.build${entry.path}`;
1006
+ const url = `http://torpor.build${addBaseToPath(entry.path, base)}`;
840
1007
  const request = new Request(url);
841
1008
  const serverEvent = new ServerEvent(request, entry.params, new URL(url));
842
1009
  const response = await serverEntry.load(serverEvent, template);
@@ -856,7 +1023,7 @@ async function runPrerender(site) {
856
1023
  written++;
857
1024
  }
858
1025
  if (routes.find((r) => r.type === 8) && template !== void 0) for (const status of [404, 500]) {
859
- const url = `http://torpor.build/_error?status=${status}`;
1026
+ const url = `http://torpor.build${addBaseToPath("/_error", base)}?status=${status}`;
860
1027
  const serverEvent = new ServerEvent(new Request(url), void 0, new URL(url));
861
1028
  const response = await serverEntry.load(serverEvent, template);
862
1029
  if (isRedirect(response)) {
@@ -869,7 +1036,6 @@ async function runPrerender(site) {
869
1036
  if (skipped.length) console.log(`Skipped prerendering ${skipped.length} route${skipped.length === 1 ? "" : "s"} (redirected):\n` + skipped.map((s) => ` - ${s}`).join("\n"));
870
1037
  if (failures.length) throw new Error(`Prerendering failed for ${failures.length} route${failures.length === 1 ? "" : "s"}:\n` + failures.map((f) => ` - ${f}`).join("\n"));
871
1038
  if (site.sitemap && site.origin && entries.length > 0) {
872
- const base = site.basePath;
873
1039
  const sitemap = sitemapXml(site.origin, base, entries.map((entry) => entry.path));
874
1040
  await promises.writeFile(fpath.join(clientFolder, typeof site.sitemap === "string" ? site.sitemap.slice(1) : "sitemap.xml"), sitemap);
875
1041
  }
@@ -969,13 +1135,22 @@ async function runBuild(site) {
969
1135
  clientConfig.resolve ??= {};
970
1136
  clientConfig.resolve.tsconfigPaths ??= true;
971
1137
  clientConfig.resolve.alias = [...asAliasArray$1(clientConfig.resolve.alias), ...tsconfigAliases(site.root)];
1138
+ let clientRoot = site.root;
972
1139
  clientConfig.plugins = [
973
1140
  manifest(site),
974
1141
  torpor(),
975
- ...site.vitePlugins
1142
+ ...site.vitePlugins,
1143
+ {
1144
+ name: "torpor-client-root",
1145
+ configResolved(config) {
1146
+ clientRoot = config.root;
1147
+ }
1148
+ }
976
1149
  ];
977
1150
  clientConfig.build ??= {};
978
1151
  clientConfig.build.outDir = clientFolder;
1152
+ const base = normalizeBasePath(site.basePath);
1153
+ if (base) clientConfig.base ??= base + "/";
979
1154
  const publicDir = fpath.resolve(site.root, "src/public");
980
1155
  if (existsSync(publicDir)) clientConfig.publicDir = publicDir;
981
1156
  clientConfig.build.rollupOptions ??= {};
@@ -986,13 +1161,28 @@ async function runBuild(site) {
986
1161
  ...site.inputs.filter((f) => !/server\.(ts|js)$/.test(f))
987
1162
  ];
988
1163
  clientConfig.build.ssrManifest = true;
1164
+ clientConfig.build.manifest ??= true;
989
1165
  await build(defineConfig(clientConfig));
1166
+ const manifestFile = fpath.join(clientFolder, typeof clientConfig.build.manifest === "string" ? clientConfig.build.manifest : ".vite/manifest.json");
1167
+ const preloads = existsSync(manifestFile) ? clientPreloads(JSON.parse(await promises.readFile(manifestFile, "utf-8")), clientRoot, site.routes.filter((r) => r.file && !/server\.(ts|js)$/.test(r.file)).map((r) => ({
1168
+ path: r.path,
1169
+ file: fpath.resolve(site.root, r.file)
1170
+ })), (file) => readFileSync(fpath.join(clientFolder, file), "utf-8")) : void 0;
990
1171
  const serverConfig = structuredClone(site.viteConfig ?? {});
991
1172
  serverConfig.resolve ??= {};
992
1173
  serverConfig.resolve.tsconfigPaths ??= true;
993
1174
  serverConfig.resolve.alias = [...asAliasArray$1(serverConfig.resolve.alias), ...tsconfigAliases(site.root)];
1175
+ if (preloads) {
1176
+ const pages = pageSizes(preloads, site.routes, clientFolder);
1177
+ const report = formatPageSizes(pages, site.budgets);
1178
+ const over = overBudget(pages, site.budgets);
1179
+ if (over.length > 0) {
1180
+ console.warn(report);
1181
+ if (site.budgets?.fail) throw new Error(`${over.length} page${over.length === 1 ? " is" : "s are"} over the JavaScript budget (see above)`);
1182
+ } else if (report) console.log(report);
1183
+ }
994
1184
  serverConfig.plugins = [
995
- manifest(site, true),
1185
+ manifest(site, true, false, preloads),
996
1186
  torpor(),
997
1187
  ...site.vitePlugins
998
1188
  ];
@@ -1366,6 +1556,7 @@ async function runDev(site, configVite) {
1366
1556
  if (!Number.isNaN(envPort)) config.server.port ??= envPort;
1367
1557
  const connectingUrl = `${process.env.PROTOCOL}//${process.env.HOST}:${process.env.PORT}`;
1368
1558
  console.log(`\nConnecting to ${connectingUrl}`);
1559
+ silenceRollupOptionsDeprecation();
1369
1560
  const vite = await createServer(config);
1370
1561
  await warmServerEntry(vite, site, sourceMode);
1371
1562
  await vite.listen();
@@ -1506,6 +1697,34 @@ function addTorpOptimizerSettings(optimizeDeps) {
1506
1697
  optimizeDeps.rolldownOptions ??= {};
1507
1698
  optimizeDeps.rolldownOptions.plugins ??= [torpor()];
1508
1699
  }
1700
+ /**
1701
+ * Drops Vite's `optimizeDeps.rollupOptions` deprecation warning, which it
1702
+ * prints on every dev start (and on internal restarts) even though the config
1703
+ * above sets the new key, and nothing ever sets the old one.
1704
+ *
1705
+ * It's a bug in vite-plus-core's compat proxy, present through 8.3.8000: to
1706
+ * migrate `rollupOptions` to `rolldownOptions` it defines `rollupOptions` as an
1707
+ * enumerable getter that returns `rolldownOptions`; `resolveDepOptimizationOptions`
1708
+ * then merges the config's `optimizeDeps` into the defaults (`for...in` sees the
1709
+ * getter, `rolldownOptions` is merged into a *new* object), and the two keys
1710
+ * end up pointing at different objects -- which is the warning's condition.
1711
+ * It only fires when the config pre-sets `optimizeDeps.rolldownOptions`, as
1712
+ * `addTorpOptimizerSettings` must to run the torpor plugin in the dep
1713
+ * optimizer, so it's the framework's config that trips it on every app.
1714
+ *
1715
+ * The message is noise (the optimizer runs on `rolldownOptions`, the torpor
1716
+ * plugin included), so it's filtered. A user debugging dep optimization can
1717
+ * still see the underlying trace with `VITE_DEPRECATION_TRACE=1`, which goes
1718
+ * through `console.trace` and is left alone. Remove this once the proxy stops
1719
+ * resurrecting the deprecated key.
1720
+ */
1721
+ function silenceRollupOptionsDeprecation() {
1722
+ const warn = console.warn;
1723
+ console.warn = (...args) => {
1724
+ if (typeof args[0] === "string" && args[0].startsWith("`optimizeDeps.rollupOptions`")) return;
1725
+ warn.apply(console, args);
1726
+ };
1727
+ }
1509
1728
  //#endregion
1510
1729
  //#region src/server/contentType.ts
1511
1730
  function contentType(extension) {
@@ -1591,6 +1810,29 @@ const types = {
1591
1810
  ".7z": "application/x-7z-compressed"
1592
1811
  };
1593
1812
  //#endregion
1813
+ //#region src/run/assetHeaders.ts
1814
+ /**
1815
+ * The cache policy for content-hashed build assets. Their names change
1816
+ * whenever their content does, so browsers and CDNs can keep them for a year
1817
+ * without revalidating; a new deploy references new names.
1818
+ */
1819
+ const IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable";
1820
+ /**
1821
+ * Whether a file in `assets/` has a Vite content hash in its name (e.g.
1822
+ * `clientEntry-BUKMQ_H9.js`). Files a site's `src/public/assets` folder put
1823
+ * there keep their own names, so they're not hashed and must not be cached
1824
+ * forever.
1825
+ */
1826
+ function isHashedAsset(file) {
1827
+ return /-[A-Za-z0-9_-]{8}\.[A-Za-z0-9]+$/.test(fpath.basename(file));
1828
+ }
1829
+ /** The response headers for a file served from `dist/client/assets`. */
1830
+ function assetHeaders(file) {
1831
+ const headers = { "Content-Type": contentType(fpath.extname(file)) };
1832
+ if (isHashedAsset(file)) headers["Cache-Control"] = IMMUTABLE_CACHE_CONTROL;
1833
+ return headers;
1834
+ }
1835
+ //#endregion
1594
1836
  //#region src/run/runPreview.ts
1595
1837
  async function runPreview(site) {
1596
1838
  await runBuild(site);
@@ -1607,15 +1849,16 @@ async function runPreview(site) {
1607
1849
  template = prepareTemplate(template, clientScript);
1608
1850
  }
1609
1851
  const server = new Server();
1610
- server.add("/assets/*", async (ev) => {
1852
+ const base = normalizeBasePath(site.basePath);
1853
+ server.add(`${base}/assets/*`, async (ev) => {
1611
1854
  try {
1612
1855
  const url = new URL(ev.request.url);
1613
- const file = fpath.join(clientFolder, url.pathname);
1856
+ const file = fpath.join(clientFolder, url.pathname.slice(base.length));
1614
1857
  if (existsSync(file)) {
1615
1858
  const body = await promises.readFile(file);
1616
1859
  return new Response(body, {
1617
1860
  status: 200,
1618
- headers: { "Content-Type": contentType(fpath.extname(file)) }
1861
+ headers: assetHeaders(file)
1619
1862
  });
1620
1863
  }
1621
1864
  } catch (e) {
@@ -1689,9 +1932,10 @@ async function runOpenApi(site, vite, outFile = "openapi.json") {
1689
1932
  }
1690
1933
  const doc = buildOpenApiDocument(entries, options);
1691
1934
  await writeFile(fpath.resolve(site.root, outFile), JSON.stringify(doc, null, 2) + "\n");
1935
+ if (options.extend) console.log("Note: the openApi() \"extend\" hook runs per request, so the written document is the base document");
1692
1936
  console.log(`OpenAPI document written to ${outFile} (${Object.keys(doc.paths ?? {}).length} paths)`);
1693
1937
  }
1694
1938
  //#endregion
1695
1939
  export { loadSite as a, runDev as i, run as n, runBuild as o, runPreview as r, runOpenApi as t };
1696
1940
 
1697
- //# sourceMappingURL=runOpenApi-C5yMpQU1.mjs.map
1941
+ //# sourceMappingURL=runOpenApi-DK-QnYEr.mjs.map