@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 +0,0 @@
1
- {"version":3,"file":"load-BODDzmH0.mjs","names":[],"sources":["../src/state/client.ts","../src/nav/reload.ts","../src/nav/formSubmit.ts","../src/nav/loadData.ts","../src/nav/navigate.ts","../src/nav/load.ts"],"sourcesContent":["import type ClientState from \"../types/ClientState\";\n\nconst CLIENT_SYMBOL: unique symbol = Symbol.for(\"torp.Client\");\n\nconst client: ClientState =\n\t// @ts-ignore\n\t(globalThis[CLIENT_SYMBOL] ??= {\n\t\t// @ts-ignore This will definitely, 100% get set\n\t\trouter: null,\n\t\tlayoutStack: [],\n\t\t// TODO: Probably expire after 30 seconds or something?\n\t\tprefetchedData: {},\n\t\tprefetchedServerData: {},\n\t\tviewTransitions: false,\n\t});\n\nexport default client;\n","import navigate from \"./navigate\";\n\n/**\n * Reloads data for the currently loaded page and rerenders it. Returns whether\n * the page was rendered in place (see `load`).\n */\nexport default async function reload(): Promise<boolean> {\n\tconst url = new URL(document.location.href);\n\treturn (await navigate(url)).type === \"rendered\";\n}\n","import $page from \"../state/$page\";\nimport load from \"./load\";\nimport reload from \"./reload\";\n\n/**\n * The detail of the `torpor:submit-failed` window event.\n */\nexport type SubmitFailureDetail = {\n\t/** The url the form was submitted to. */\n\taction: string;\n\t/** The failure that stopped the submit. */\n\terror?: unknown;\n};\n\nexport default async function formSubmit(e: SubmitEvent): Promise<void> {\n\t// We'll take it from here\n\te.preventDefault();\n\n\t// Reset $page on submit and link navigation\n\t// TODO: Should we put data in $page.data??\n\t$page.form = undefined;\n\n\t// Perform a POST fetch to the form's action location\n\tconst form = e.target as HTMLFormElement;\n\tconst button = e.submitter as HTMLButtonElement | null;\n\t// HACK: submit buttons have their formAction set to the current page if not\n\t// set, so we can't just check whether it's empty and fallback to form action\n\t//const action = button?.formAction ?? form.action;\n\tlet action = form.action || document.URL;\n\tif (button && button.formAction && button.formAction !== document.URL) {\n\t\taction = button.formAction;\n\t}\n\tconst options = {\n\t\tbody: button ? new FormData(form, button) : new FormData(form),\n\t\tmethod: \"POST\",\n\t\tmode: \"cors\",\n\t\tcredentials: \"same-origin\",\n\t\t// Add a special header which tells the server that we want the raw\n\t\t// error response (if applicable) rather than the reloaded page that you\n\t\t// would get if submitting a page without javascript\n\t\theaders: {\n\t\t\t\"X-Torpor-Form-Submit\": \"\",\n\t\t},\n\t};\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(\n\t\t\taction,\n\t\t\t// @ts-ignore -- don't know what it's complaining about here\n\t\t\toptions,\n\t\t);\n\t} catch (error) {\n\t\t// A rejected fetch is a failed submission -- offline, or the server\n\t\t// couldn't be reached. Nothing navigates and the form keeps what the\n\t\t// user typed, so the app can show its own notice and let them retry.\n\t\tconsole.error(\"The form submit failed\", error);\n\t\thandleSubmitFailure(form, action, error);\n\t\treturn;\n\t}\n\n\tif (\n\t\tresponse.status === 200 &&\n\t\tresponse.headers.has(\"Content-Disposition\") &&\n\t\t/attachment;\\s*filename=\"(.+?)\"/.test(response.headers.get(\"Content-Disposition\")!)\n\t) {\n\t\t// TODO: Is this enough to check to see if we have a file that should download?\n\t\t// Download the file by creating a dummy <a> and clicking it\n\t\tconst downloadFileName =\n\t\t\tresponse.headers.get(\"Content-Disposition\")?.match(/attachment;\\s*filename=\"(.+?)\"/)![1] ??\n\t\t\t\"file\";\n\t\tconst downloadLink = document.createElement(\"a\");\n\t\tdownloadLink.href = window.URL.createObjectURL(await response.blob());\n\t\tdownloadLink.download = downloadFileName;\n\t\tdownloadLink.click();\n\t} else if (response.status === 200 && response.headers.has(\"X-Torpor-Form-Redirect\")) {\n\t\t// TODO: Should do the correct type of redirect e.g. seeOther etc\n\t\tconst redirect = response.headers.get(\"Location\")!;\n\t\tawait load(redirect);\n\t\twindow.location.href = redirect;\n\t} else if (\n\t\t(response.status >= 200 && response.status <= 299) ||\n\t\t(response.status >= 400 && response.status <= 499)\n\t) {\n\t\t// Put the response into `$page.form`, and it will be put into `$props` in reload\n\t\tif (response.headers.get(\"Content-Type\") === \"application/json\") {\n\t\t\t$page.form = await response.json();\n\t\t}\n\t\tawait reload();\n\t} else if (response.status >= 500) {\n\t\t// A server error: like a no-javascript submit, the response is the\n\t\t// error page rendered at this url with the error status. Swap the\n\t\t// document for it -- the url stays, so a transient failure can be\n\t\t// retried with a refresh. Without an error page, reload, which will\n\t\t// show the raw error response instead\n\t\tif (response.headers.get(\"Content-Type\")?.includes(\"text/html\")) {\n\t\t\tconst html = await response.text();\n\t\t\tdocument.open();\n\t\t\tdocument.write(html);\n\t\t\tdocument.close();\n\t\t} else {\n\t\t\twindow.location.reload();\n\t\t}\n\t}\n}\n\n/**\n * Tells the app that a client form submission failed (offline, or the server\n * couldn't be reached), so it can show its own notice. The form keeps the\n * values the user typed, ready for the app to retry.\n *\n * Dispatched on `window` as a cancelable `torpor:submit-failed` `CustomEvent`.\n * An app that cancels it asks for a native form submission after all, e.g. a\n * service worker serves the POST, or the browser's own offline handling is\n * preferred.\n */\nfunction handleSubmitFailure(form: HTMLFormElement, action: string, error: unknown): void {\n\tconst event = new CustomEvent<SubmitFailureDetail>(\"torpor:submit-failed\", {\n\t\tcancelable: true,\n\t\tdetail: { action, error },\n\t});\n\t// `dispatchEvent` returns false when a handler cancelled it\n\tif (!window.dispatchEvent(event)) {\n\t\t// The prototype call, because a field named \"submit\" shadows `form.submit`\n\t\tHTMLFormElement.prototype.submit.call(form);\n\t\treturn;\n\t}\n\n\tconsole.warn(\n\t\t`The form submission to ${action} failed; staying on the current page. ` +\n\t\t\t\"Listen for torpor:submit-failed to show your own notice.\",\n\t);\n}\n","import { type DeferredMeta, setAtPath } from \"../deferred.ts\";\nimport { DATA_REUSE_HEADER, DATA_REQUEST_HEADER } from \"../dataRequest.ts\";\nimport { readResponseBody } from \"../response/read.ts\";\nimport { getBasePath } from \"../site/basePath\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport type RouteHandler from \"../types/RouteHandler\";\nimport client from \"../state/client\";\n\n/**\n * The result of loading a route's data. `error` is set when a load function\n * returned an error response (redirects excluded) -- the caller renders the\n * error page instead of the route.\n */\nexport type LoadDataResult = {\n\tdata: Record<string, any>;\n\terror?: {\n\t\tstatus: number;\n\t\tmessage: string;\n\t};\n};\n\n/**\n * Loads a route's data for a client-side navigation.\n *\n * One request (`GET <page url>/~server` with the data header) returns the\n * server data for the page and all of its layouts, with hooks running once\n * against the page url. The client then runs its own load functions (layout\n * by layout, then the page), merging each route's fresh server data in the\n * same order the server render does.\n */\nexport default async function loadData(\n\thandler: RouteHandler,\n\tparams: Record<string, string>,\n\tpath: string,\n\tquery: URLSearchParams,\n\tnewLayoutStack: LayoutPath[],\n\tclientEndPoint: PageEndPoint | undefined,\n\tprefetch = false,\n): Promise<LoadDataResult | void> {\n\tlet data = {};\n\n\t// Work out up front which layouts are already rendered (their data is\n\t// reused), so the data request can skip loading them. A prefetch also skips\n\t// their server loads (they're already in the client stack) but must not\n\t// adopt their live slot regions: it may never be followed by a navigation\n\tconst layoutStack = client.layoutStack;\n\tconst layouts = (handler.layouts ?? []).map((layout, index) => {\n\t\tconst layoutPath = resolveLayoutPath(layout.path, params);\n\t\tconst previous = layoutStack.at(index);\n\t\tconst rendered = previous?.path === layoutPath;\n\t\tconst reuse = !prefetch && rendered;\n\t\treturn { layout, index, layoutPath, previous, rendered, reuse };\n\t});\n\n\t// A page can opt out of the data request when it has no server load of its\n\t// own and every layout is already rendered (e.g. a tab switch under a\n\t// session hook that doesn't gate access). Its client load still runs.\n\tconst skipServerData =\n\t\tclientEndPoint?.serverData === false &&\n\t\t!handler.serverEndPoint &&\n\t\tlayouts.every((layout) => layout.rendered);\n\n\t// One request for all the (non-reused) server data\n\tconst server = skipServerData\n\t\t? {}\n\t\t: await loadServerData(\n\t\t\t\thandler,\n\t\t\t\tpath,\n\t\t\t\tquery,\n\t\t\t\tlayouts.filter((l) => l.rendered).map((l) => l.layoutPath),\n\t\t\t\tprefetch,\n\t\t\t);\n\tif (server === undefined) {\n\t\t// A load redirected: the client can't follow it through fetch, so the\n\t\t// caller falls back to a full page load\n\t\treturn;\n\t}\n\tif (\"error\" in server) {\n\t\treturn { data, error: server.error };\n\t}\n\n\tfor (const { layout, index, layoutPath, previous, rendered, reuse } of layouts) {\n\t\tconst stackLayout: LayoutPath = {\n\t\t\tpath: layoutPath,\n\t\t\tdata: {},\n\t\t\treuse,\n\t\t\tslotRegion: null,\n\t\t};\n\n\t\tif (rendered && previous) {\n\t\t\t// The layout is already rendered: keep its data. Only a real\n\t\t\t// navigation reuses its slot region; a prefetch must leave it alone\n\t\t\t// (and not run its client load again)\n\t\t\tif (reuse) stackLayout.slotRegion = previous.slotRegion;\n\t\t\tObject.assign(stackLayout.data, previous.data);\n\t\t} else {\n\t\t\t// A new layout: run its client load (its server data already\n\t\t\t// arrived in the single request)\n\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await layout.endPoint())?.default;\n\t\t\tconst loaded = await runClientLoad(\n\t\t\t\tlayoutEndPoint,\n\t\t\t\tclientLocation(layoutPath),\n\t\t\t\tquery,\n\t\t\t\tparams,\n\t\t\t\tstackLayout.data,\n\t\t\t\tprefetch,\n\t\t\t);\n\t\t\tif (loaded?.redirect) return;\n\t\t\tif (loaded?.error) return { data, error: loaded.error };\n\t\t\tconst serverData = server.loads?.[index];\n\t\t\tif (serverData) Object.assign(stackLayout.data, serverData);\n\t\t}\n\n\t\tObject.assign(data, stackLayout.data);\n\t\tnewLayoutStack.push(stackLayout);\n\t}\n\n\t// The page's client load, then its server data\n\tconst loaded = await runClientLoad(\n\t\tclientEndPoint,\n\t\tclientLocation(path),\n\t\tquery,\n\t\tparams,\n\t\tdata,\n\t\tprefetch,\n\t);\n\tif (loaded?.redirect) return;\n\tif (loaded?.error) return { data, error: loaded.error };\n\tconst pageServerData = server.loads?.[handler.layouts?.length ?? 0];\n\tif (pageServerData) Object.assign(data, pageServerData);\n\n\treturn { data };\n}\n\n/** The path of a layout with its `[param]` segments substituted. */\nfunction resolveLayoutPath(path: string, params: Record<string, string>): string {\n\tfor (let key in params) {\n\t\tpath = path.replace(`[${key}]`, params[key]);\n\t}\n\treturn path;\n}\n\n/**\n * Builds the layout stack for an error page whose own loads can't run (offline,\n * or the server is down): layouts already on screen keep their data and slot\n * regions, so the error renders over the shell instead of the shell being\n * replaced by a document load that would fail too. Layouts that aren't on\n * screen render with no data.\n */\nexport function errorLayoutStack(\n\thandler: RouteHandler,\n\tparams: Record<string, string>,\n): LayoutPath[] {\n\tconst stack: LayoutPath[] = [];\n\t(handler.layouts ?? []).forEach((layout, index) => {\n\t\tconst path = resolveLayoutPath(layout.path, params);\n\t\tconst previous = client.layoutStack.at(index);\n\t\tconst rendered = previous?.path === path;\n\t\tstack.push({\n\t\t\tpath,\n\t\t\tdata: rendered && previous ? { ...previous.data } : {},\n\t\t\treuse: rendered,\n\t\t\tslotRegion: rendered && previous ? previous.slotRegion : null,\n\t\t});\n\t});\n\treturn stack;\n}\n\ntype ServerData = {\n\tloads?: (Record<string, any> | null)[];\n\t/** Promise-valued properties streamed after the critical loads. */\n\tdeferred?: DeferredMeta[];\n};\n\ntype ServerDataFrame = {\n\ttype?: string;\n\tid?: string;\n\tvalue?: unknown;\n\tmessage?: string;\n} & ServerData;\n\n/**\n * A request-local registry of deferred promises. Values arrive after the first\n * frame (client navigation) or in inline scripts (initial hydration), and\n * resolve the promises already placed in the page's `data`.\n */\nclass DeferredStore {\n\t#entries = new Map<\n\t\tstring,\n\t\t{\n\t\t\tpromise: Promise<unknown>;\n\t\t\tresolve: (value: unknown) => void;\n\t\t\treject: (error: unknown) => void;\n\t\t}\n\t>();\n\n\tget(id: string): Promise<unknown> {\n\t\tlet entry = this.#entries.get(id);\n\t\tif (!entry) {\n\t\t\tlet resolve!: (value: unknown) => void;\n\t\t\tlet reject!: (error: unknown) => void;\n\t\t\tconst promise = new Promise<unknown>((res, rej) => {\n\t\t\t\tresolve = res;\n\t\t\t\treject = rej;\n\t\t\t});\n\t\t\t// A prefetch (or a navigation the user leaves) may never read the\n\t\t\t// promise; don't let its rejection surface as unhandled\n\t\t\tpromise.catch(() => {});\n\t\t\tentry = { promise, resolve, reject };\n\t\t\tthis.#entries.set(id, entry);\n\t\t}\n\t\treturn entry.promise;\n\t}\n\n\tresolve(id: string, value: unknown): void {\n\t\tconst entry = this.#entries.get(id);\n\t\tif (!entry) return;\n\t\tthis.#entries.delete(id);\n\t\tentry.resolve(value);\n\t}\n\n\treject(id: string, error: unknown): void {\n\t\tconst entry = this.#entries.get(id);\n\t\tif (!entry) return;\n\t\tthis.#entries.delete(id);\n\t\tentry.reject(error instanceof Error ? error : new Error(String(error)));\n\t}\n\n\trejectAll(error: unknown): void {\n\t\tfor (const id of this.#entries.keys()) {\n\t\t\tthis.reject(id, error);\n\t\t}\n\t}\n\n\t/** Places a promise for each deferred entry into the load that owns it. */\n\tattach(server: ServerData, get: (id: string) => Promise<unknown>): ServerData {\n\t\tfor (const entry of server.deferred ?? []) {\n\t\t\tconst load = server.loads?.[entry.index];\n\t\t\tif (!load) continue;\n\t\t\tsetAtPath(load, entry.path, get(entry.id));\n\t\t}\n\t\treturn server;\n\t}\n}\n\n/**\n * Fetches the page's combined server data for a navigation, reusing a prefetch\n * when there is one.\n *\n * A prefetch warms this request for the navigation that follows, and a\n * navigation consumes it (once). So a hover costs one request, a click that\n * lands while the prefetch is still in flight awaits the same promise instead\n * of issuing a second one, and a prefetched response is never served to more\n * than the one navigation it was loaded for (no stale data on later visits).\n */\nasync function loadServerData(\n\thandler: RouteHandler,\n\tpath: string,\n\tquery: URLSearchParams,\n\treusedLayouts: string[],\n\tprefetch: boolean,\n): Promise<ServerData | { error: { status: number; message: string } } | undefined> {\n\t// The server embeds the first render's data in the HTML (see the render\n\t// path in site/serverHandlers.ts), so the initial hydration can read it\n\t// instead of making a round trip. The element is consumed once, so later\n\t// navigations use the fetch below\n\tconst embedded = takeEmbeddedServerData();\n\tif (embedded !== undefined) {\n\t\treturn attachEmbeddedDeferred(embedded);\n\t}\n\n\tif (!hasServerData(handler)) {\n\t\treturn {};\n\t}\n\n\tconst key = serverDataKey(path, query);\n\n\tif (prefetch) {\n\t\tconst cached = client.prefetchedServerData[key];\n\t\tif (cached) return cached;\n\n\t\tconst pending = requestServerData(path, query, reusedLayouts);\n\t\tclient.prefetchedServerData[key] = pending;\n\t\t// A failed prefetch mustn't poison the navigation that follows it: drop\n\t\t// the entry so that navigation retries. One that is already awaiting\n\t\t// this promise still sees the failure and renders the error page.\n\t\tvoid pending.then(\n\t\t\t(result) => {\n\t\t\t\tif (isLoadError(result)) dropPrefetch(client.prefetchedServerData, key, pending);\n\t\t\t},\n\t\t\t() => dropPrefetch(client.prefetchedServerData, key, pending),\n\t\t);\n\t\treturn pending;\n\t}\n\n\tconst prefetched = client.prefetchedServerData[key];\n\tif (prefetched) {\n\t\tdelete client.prefetchedServerData[key];\n\t\treturn prefetched;\n\t}\n\n\treturn requestServerData(path, query, reusedLayouts);\n}\n\n/** The `/~server` request cache key: the page path and its query. */\nfunction serverDataKey(path: string, query: URLSearchParams): string {\n\treturn path + (query.size > 0 ? `?${query}` : \"\");\n}\n\n/** Whether a load resolved to an error result (as opposed to data/nothing). */\nfunction isLoadError(value: unknown): value is { error: { status: number; message: string } } {\n\treturn typeof value === \"object\" && value !== null && \"error\" in value;\n}\n\n/** Removes a failed prefetch, unless the navigation has already consumed it. */\nfunction dropPrefetch(prefetches: Record<string, any>, key: string, pending: unknown): void {\n\tif (prefetches[key] === pending) {\n\t\tdelete prefetches[key];\n\t}\n}\n\n/**\n * The posted data request: `GET <page url>/~server` carrying the data header,\n * which the server answers with the page's and its layouts' server data as one\n * JSON body.\n */\nasync function requestServerData(\n\tpath: string,\n\tquery: URLSearchParams,\n\treusedLayouts: string[],\n): Promise<ServerData | { error: { status: number; message: string } } | undefined> {\n\tconst url = new URL(\n\t\tdocument.location.origin + getBasePath() + path.replace(/\\/$/, \"\") + \"/~server\",\n\t);\n\tfor (let [name, value] of query) {\n\t\turl.searchParams.append(name, value);\n\t}\n\n\tconst headers: Record<string, string> = { [DATA_REQUEST_HEADER]: \"1\" };\n\tif (reusedLayouts.length > 0) {\n\t\theaders[DATA_REUSE_HEADER] = JSON.stringify(reusedLayouts);\n\t}\n\n\t// A rejected fetch is the common offline failure (as is a body that fails\n\t// mid-read, e.g. the connection drops while streaming). Render it as an\n\t// error in place rather than throwing away the shell with a document load\n\t// that would fail too.\n\ttry {\n\t\tconst response = await fetch(url, {\n\t\t\tredirect: \"manual\",\n\t\t\theaders,\n\t\t});\n\t\tif (isRedirect(response)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!response.ok) {\n\t\t\treturn { error: await errorOf(response) };\n\t\t}\n\t\t// A site without a server (e.g. a static host) responds with the page's\n\t\t// html rather than json; there's nothing to merge\n\t\tconst type = response.headers.get(\"Content-Type\");\n\t\tif (type?.includes(\"application/x-ndjson\")) {\n\t\t\treturn await readServerDataStream(response);\n\t\t}\n\t\tif (!type?.includes(\"application/json\")) {\n\t\t\treturn {};\n\t\t}\n\t\treturn (await response.json()) as ServerData;\n\t} catch (error) {\n\t\tconsole.error(\"The server data request failed\", error);\n\t\treturn { error: unreachableError() };\n\t}\n}\n\n/** The error rendered when the server can't be reached at all. */\nfunction unreachableError(): { status: number; message: string } {\n\treturn {\n\t\tstatus: 503,\n\t\tmessage: navigator.onLine === false ? \"You're offline.\" : \"Could not reach the server.\",\n\t};\n}\n\n/**\n * Reads a streamed data response: the first frame carries the critical loads\n * and the list of deferred paths, later frames resolve those promises. The\n * function returns as soon as the first frame is read, so a navigation mounts\n * before slow values arrive.\n */\nasync function readServerDataStream(response: Response): Promise<ServerData> {\n\tconst reader = response.body?.getReader();\n\tif (!reader) return {};\n\n\tconst decoder = new TextDecoder();\n\tlet buffer = \"\";\n\tconst readFrame = async (): Promise<ServerDataFrame | undefined> => {\n\t\twhile (true) {\n\t\t\tconst newline = buffer.indexOf(\"\\n\");\n\t\t\tif (newline >= 0) {\n\t\t\t\tconst line = buffer.slice(0, newline).trim();\n\t\t\t\tbuffer = buffer.slice(newline + 1);\n\t\t\t\tif (line) return JSON.parse(line) as ServerDataFrame;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tconst line = buffer.trim();\n\t\t\t\tbuffer = \"\";\n\t\t\t\treturn line ? (JSON.parse(line) as ServerDataFrame) : undefined;\n\t\t\t}\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t}\n\t};\n\n\tconst first = await readFrame();\n\tif (!first) return {};\n\tif (first.loads === undefined) return {};\n\tconst store = new DeferredStore();\n\tconst server = store.attach(first, (id) => store.get(id));\n\n\t// Keep reading in the background. The view is already mounted; values\n\t// resolve their promises as the frames arrive.\n\tvoid (async () => {\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst frame = await readFrame();\n\t\t\t\tif (!frame) break;\n\t\t\t\tif (frame.type === \"value\" && frame.id !== undefined) {\n\t\t\t\t\tstore.resolve(frame.id, frame.value);\n\t\t\t\t} else if (frame.type === \"error\" && frame.id !== undefined) {\n\t\t\t\t\tstore.reject(frame.id, frame.message ?? \"Deferred data failed\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tstore.rejectAll(new Error(\"The deferred data stream ended before a value arrived\"));\n\t\t} catch (error) {\n\t\t\tstore.rejectAll(error);\n\t\t}\n\t})();\n\n\treturn server;\n}\n\n/**\n * Recreates the promises for a page's embedded server data. The server emits\n * a bootstrap store before the inline resolve scripts, so by the time this\n * runs a value may already be resolved (or still be in flight).\n */\nfunction attachEmbeddedDeferred(server: ServerData): ServerData {\n\tif (!server.deferred?.length) return server;\n\tconst globalStore = (\n\t\tglobalThis as {\n\t\t\t__torporDeferred?: { get(id: string): Promise<unknown> };\n\t\t}\n\t).__torporDeferred;\n\t// The bootstrap is only emitted with a deferred payload; fall back to\n\t// never-resolving promises rather than throwing if it is missing\n\tconst store = new DeferredStore();\n\tconst get = globalStore ? (id: string) => globalStore.get(id) : (id: string) => store.get(id);\n\treturn store.attach(server, get);\n}\n\n/**\n * Reads and removes the server data the initial render embedded in the HTML\n * (a `t-server-data` script tag), or `undefined` when there is none (a later\n * navigation, or a page with no server data).\n */\nfunction takeEmbeddedServerData(): ServerData | undefined {\n\tconst element = document.getElementById(\"t-server-data\");\n\tif (element === null) {\n\t\treturn undefined;\n\t}\n\telement.remove();\n\ttry {\n\t\treturn JSON.parse(element.textContent ?? \"\") as ServerData;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Whether the route has any server-side code to run (a page or layout server\n * load, or a folder hook). Without any, there's no data request to make.\n */\nfunction hasServerData(handler: RouteHandler): boolean {\n\tif (handler.serverHooks && handler.serverHooks.length > 0) return true;\n\tif (handler.serverEndPoint) return true;\n\treturn (handler.layouts ?? []).some((layout) => !!layout.serverEndPoint);\n}\n\n/**\n * The result of running a route's client load: the json it returned (if any),\n * a redirect the client can't follow, or an error to render in place. Cached\n * as a whole when a prefetch warms it, because a Response body can only be\n * read once.\n */\ntype ClientLoadResult = {\n\t/** The json the load returned, if any. */\n\tdata?: Record<string, any>;\n\t/** The load redirected: only a document load can follow it. */\n\tredirect?: true;\n\t/** The load failed: render the nearest error page. */\n\terror?: { status: number; message: string };\n};\n\n/**\n * Runs a route's client-side load, merging its json data into `data` and\n * returning the redirect or error for the caller to handle.\n *\n * A prefetch caches the in-flight promise, not its resolved value, so a\n * navigation that lands while the load is still running continues the same\n * request instead of running it a second time. The navigation that follows\n * consumes (and clears) the entry; a failed prefetch is dropped so the\n * navigation retries.\n */\nasync function runClientLoad(\n\tendPoint: PageEndPoint | undefined,\n\tlocation: string,\n\tquery: URLSearchParams,\n\tparams: Record<string, string>,\n\tdata: Record<string, any>,\n\tprefetch: boolean,\n): Promise<ClientLoadResult | undefined> {\n\tif (!endPoint?.load) return;\n\n\tconst clientKey = location + (query.size > 0 ? `?${query}` : \"\");\n\tconst prefetchedData = client.prefetchedData;\n\tlet pending = prefetchedData[clientKey] as Promise<ClientLoadResult> | undefined;\n\n\tif (!pending) {\n\t\t// Only a prefetch warms the cache. A navigation runs its own load\n\t\t// directly, so a result is never left behind for a later visit.\n\t\tif (!prefetch) {\n\t\t\tconst result = await loadClientResponse(endPoint.load, query, params, data);\n\t\t\treturn mergeClientLoad(result, data);\n\t\t}\n\n\t\tconst promise = loadClientResponse(endPoint.load, query, params, data);\n\t\tprefetchedData[clientKey] = promise;\n\t\tpending = promise;\n\t\t// A failed prefetch mustn't poison the navigation that follows it\n\t\tvoid promise.then(\n\t\t\t(result) => {\n\t\t\t\tif (result.error) dropPrefetch(prefetchedData, clientKey, promise);\n\t\t\t},\n\t\t\t() => dropPrefetch(prefetchedData, clientKey, promise),\n\t\t);\n\t} else if (!prefetch) {\n\t\t// The navigation consumes the warm entry\n\t\tdelete prefetchedData[clientKey];\n\t}\n\n\treturn mergeClientLoad(await pending, data);\n}\n\nasync function loadClientResponse(\n\tload: NonNullable<PageEndPoint[\"load\"]>,\n\tquery: URLSearchParams,\n\tparams: Record<string, string>,\n\tdata: Record<string, any>,\n): Promise<ClientLoadResult> {\n\tconst clientUrl = new URL(document.location.href);\n\tfor (let [name, value] of query) {\n\t\tclientUrl.searchParams.append(name, value);\n\t}\n\ttry {\n\t\tconst response = await load({ url: clientUrl, params, data });\n\t\tif (!response) return {};\n\t\tif (isRedirect(response)) return { redirect: true };\n\t\tif (!response.ok) return { error: await errorOf(response) };\n\t\tconst body = await readResponseBody(response);\n\t\treturn body ? { data: body } : {};\n\t} catch (error) {\n\t\t// A throwing load (or a body that fails mid-read) is a page error, not\n\t\t// a navigation failure: render the error page over the shell rather\n\t\t// than blanking it with a document load that would run the same load\n\t\t// again\n\t\tconsole.error(\"The client load failed\", error);\n\t\treturn { error: { status: 500, message: \"Internal error\" } };\n\t}\n}\n\nfunction mergeClientLoad(result: ClientLoadResult, data: Record<string, any>): ClientLoadResult {\n\tif (result.data) Object.assign(data, result.data);\n\treturn result;\n}\n\nfunction clientLocation(path: string): string {\n\treturn document.location.origin + getBasePath() + path;\n}\n\nfunction isRedirect(response: Response): boolean {\n\t// A `redirect: \"manual\"` fetch surfaces a cross-navigation redirect as an\n\t// opaque (\"opaqueredirect\") response in browsers, with status 0\n\treturn (response.status >= 300 && response.status < 400) || response.type === \"opaqueredirect\";\n}\n\n/**\n * The status and message of a failed load response. The body only becomes\n * the message when it's a `message`-carrying json body or plain text -- an\n * html body is a whole page (e.g. a static host's 404), not a message.\n */\nasync function errorOf(response: Response): Promise<{ status: number; message: string }> {\n\tlet message = \"\";\n\tconst type = response.headers.get(\"Content-Type\");\n\tif (type?.includes(\"application/json\")) {\n\t\ttry {\n\t\t\tconst data = await response.json();\n\t\t\tif (typeof data.message === \"string\") {\n\t\t\t\tmessage = data.message;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Not actually json\n\t\t}\n\t} else if (type?.includes(\"text/plain\")) {\n\t\tmessage = await response.text();\n\t}\n\treturn { status: response.status, message: message || response.statusText };\n}\n","import { clearLayoutSlot, fillLayoutSlot, hydrate } from \"@torpor/view\";\nimport { type Component, type SlotRender } from \"@torpor/view\";\nimport { mount, unmount } from \"@torpor/view\";\nimport $page from \"../state/$page\";\nimport client from \"../state/client\";\nimport { getBasePath, stripBaseFromUrl } from \"../site/basePath\";\nimport findErrorRoute from \"../site/findErrorRoute\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport formSubmit from \"./formSubmit\";\nimport loadData, { errorLayoutStack } from \"./loadData\";\n\n/**\n * What a navigation did, so its caller knows whether the page is rendered or\n * the document has to take over.\n *\n * - `rendered`: the route (or its nearest error page) is in place.\n * - `server-only`: the route has no client component (e.g. a `+server` route),\n * so only a document load can handle it.\n * - `redirect`: a load redirected, which a fetch can't follow.\n * - `failed`: nothing rendered; the caller keeps the current page and decides\n * between a document load and telling the app (see `handleNavigationFailure`).\n */\nexport type NavigationResult =\n\t| { type: \"rendered\" }\n\t| { type: \"server-only\" }\n\t| { type: \"redirect\" }\n\t| { type: \"failed\"; error?: unknown };\n\n/**\n * Navigations run one at a time. Each mutates shared client state\n * (`client.layoutStack`) and the live DOM, so two in flight at once can have\n * one clear a layout's slot region that the other is about to reuse (the\n * `slotRegion.startNode!` in `render` then throws). Requests are chained, so a\n * rapid second click -- or a popstate while a form submit reloads -- waits for\n * the first to finish instead of interleaving.\n */\nlet pendingNavigation: Promise<unknown> = Promise.resolve();\n\nexport default function navigate(rawUrl: URL, withHydration = false): Promise<NavigationResult> {\n\tconst result = pendingNavigation.then(() => navigateNow(rawUrl, withHydration));\n\t// Keep the chain alive even when a navigation fails, so one bad navigation\n\t// can't wedge every later one\n\tpendingNavigation = result.catch(() => {});\n\treturn result;\n}\n\nasync function navigateNow(rawUrl: URL, withHydration: boolean): Promise<NavigationResult> {\n\t// A failed route-module import (e.g. a stale dev dep hash), a throwing\n\t// load or a failed render must not reject the click handler's promise: the\n\t// caller's fallback would never run and the link would appear dead.\n\tconst previousUrl = $page.url;\n\tconst previousStatus = $page.status;\n\tconst previousError = $page.error;\n\tlet result: NavigationResult;\n\ttry {\n\t\tresult = await renderNavigation(rawUrl, withHydration);\n\t} catch (error) {\n\t\tconsole.error(error);\n\t\tresult = { type: \"failed\", error };\n\t}\n\tif (result.type === \"failed\" && !withHydration) {\n\t\t// Nothing is on screen for this url: point the reactive state back at\n\t\t// the page that is still there, in case the caller keeps it (e.g. a\n\t\t// failed navigation while offline). The initial hydration already has\n\t\t// its server-rendered page on screen, so there is nothing to restore.\n\t\t$page.url = previousUrl;\n\t\t$page.status = previousStatus;\n\t\t$page.error = previousError;\n\t}\n\treturn result;\n}\n\nasync function renderNavigation(rawUrl: URL, withHydration: boolean): Promise<NavigationResult> {\n\tlet parent = document.getElementById(\"app\");\n\tif (!parent) {\n\t\t// TODO: 500\n\t\tconsole.log(\"500\");\n\t\treturn { type: \"failed\" };\n\t}\n\n\t// The base path is stripped before matching (routes are base-free), but\n\t// kept in browser state: the caller pushes the original URL. When the\n\t// url doesn't carry the base there will be no matching route anyway\n\tconst url = stripBaseFromUrl(rawUrl, getBasePath()) ?? rawUrl;\n\tconst path = url.pathname;\n\tconst query = url.searchParams;\n\n\t//console.log(`navigating to '${path}'${query.size ? ` with ${query}` : \"\"}`);\n\n\tlet route = client.router.match(path, query);\n\n\t// Update $page before building the components\n\t$page.url = url;\n\tif (route) {\n\t\tif (path.endsWith(\"/_error\")) {\n\t\t\t// A direct visit to the error page (e.g. a bookmark of the url it\n\t\t\t// used to be redirected to). Make it look a bit classier by\n\t\t\t// stripping the query, which carries the status and message\n\t\t\t$page.status = parseInt(query.get(\"status\") ?? \"404\");\n\t\t\t$page.error = { message: query.get(\"message\") ?? \"\" };\n\t\t\twindow.history.replaceState({}, \"\", rawUrl.toString().split(\"?\")[0]);\n\t\t} else {\n\t\t\t$page.status = 200;\n\t\t\t$page.error = { message: \"\" };\n\t\t}\n\t} else {\n\t\t// There's no page at this url -- render the nearest error page at it,\n\t\t// so the address bar keeps the url the user asked for: a transient\n\t\t// failure can be refreshed, and a typo can be seen and fixed\n\t\tconst errorPath = findErrorRoute(client.router, path);\n\t\tconst errorRoute = errorPath && client.router.match(errorPath, query);\n\t\tif (!errorRoute) {\n\t\t\t// Leave the current page alone; the caller falls back to a full\n\t\t\t// page load, and the server renders the error page (or passes the\n\t\t\t// raw response through, when it has no error page)\n\t\t\treturn { type: \"failed\" };\n\t\t}\n\t\troute = errorRoute;\n\t\t$page.status = 404;\n\t\t$page.error = { message: \"Not found\" };\n\t}\n\tlet handler = route.handler;\n\tlet params = route.params || {};\n\n\t// There must be a client endpoint with a component. Routes with no client\n\t// component (a pure `+server` route like `/logout`) can't be rendered\n\t// client-side, so report `server-only` and let the caller do a full page\n\t// load\n\tlet clientEndPoint: PageEndPoint | undefined = handler.endPoint\n\t\t? (await handler.endPoint())?.default\n\t\t: undefined;\n\tif (!clientEndPoint?.component) {\n\t\treturn { type: \"server-only\" };\n\t}\n\n\tlet newLayoutStack: LayoutPath[] = [];\n\n\t// Pass the data into $props\n\t// TODO: Don't load if this is the first time -- it should have been passed\n\t// to us, somehow...\n\tconst result = await loadData(handler, params, path, query, newLayoutStack, clientEndPoint);\n\tif (result === undefined) {\n\t\t// A load redirected: the client can't follow it through fetch, so the\n\t\t// caller falls back to a full page load, which does\n\t\treturn { type: \"redirect\" };\n\t}\n\tlet data = result.data;\n\tif (result.error) {\n\t\tif (withHydration) {\n\t\t\t// The server rendered this page fine moments ago -- keep its\n\t\t\t// markup rather than hydrating an error page over it\n\t\t\treturn { type: \"failed\" };\n\t\t}\n\t\t// The load failed -- render the nearest error page at this url, so\n\t\t// the address bar keeps the url the user asked for: a transient\n\t\t// failure (a random db hiccup, say) can be retried with a refresh\n\t\tconst errorPath = findErrorRoute(client.router, path);\n\t\tconst errorRoute = errorPath && client.router.match(errorPath, query);\n\t\tif (!errorRoute) {\n\t\t\t// No error page -- the caller falls back to a full page load,\n\t\t\t// where the server passes the error response through\n\t\t\treturn { type: \"failed\" };\n\t\t}\n\t\troute = errorRoute;\n\t\thandler = errorRoute.handler;\n\t\tparams = errorRoute.params || {};\n\t\tclientEndPoint = handler.endPoint ? (await handler.endPoint())?.default : undefined;\n\t\tif (!clientEndPoint?.component) {\n\t\t\treturn { type: \"failed\" };\n\t\t}\n\n\t\t$page.status = result.error.status;\n\t\t$page.error = { message: result.error.message };\n\n\t\t// The error page starts fresh: drop the layouts collected for the\n\t\t// route that failed (the error route's own layouts are loaded into\n\t\t// the empty stack, reusing whatever the current page shares)\n\t\tnewLayoutStack = [];\n\t\tconst errorResult = await loadData(\n\t\t\thandler,\n\t\t\tparams,\n\t\t\tpath,\n\t\t\tquery,\n\t\t\tnewLayoutStack,\n\t\t\tclientEndPoint,\n\t\t);\n\t\tif (errorResult === undefined) {\n\t\t\t// The error page's own load redirected: only a document load can\n\t\t\t// follow it\n\t\t\treturn { type: \"redirect\" };\n\t\t}\n\t\tif (errorResult.error) {\n\t\t\t// The error page's own data can't load either (offline, or the\n\t\t\t// server is down). Render it over the shell with the layouts and\n\t\t\t// data that are already on screen rather than blanking the page\n\t\t\t// with a document load that would fail too.\n\t\t\tnewLayoutStack = errorLayoutStack(handler, params);\n\t\t\tdata = {};\n\t\t} else {\n\t\t\tdata = errorResult.data;\n\t\t}\n\t}\n\t// We may have form data in a hidden input -- not sure if this is the best\n\t// way to do it\n\tlet formInput = document.getElementById(\"t-form-data\") as HTMLInputElement;\n\tlet form: Record<string, string> | undefined;\n\tif (formInput) {\n\t\tform = JSON.parse(formInput.value);\n\t\t$page.form = form;\n\t\tformInput.remove();\n\t}\n\tlet $props: Record<string, any> = { data };\n\n\t// We may have form data in $page.form, either from the hidden input\n\t// (above), or added via onformsubmit (below)\n\t$props.form = $page.form;\n\n\t// Add some special context for submitting Forms client-side\n\tconst $context = {\n\t\tTorporBuildContext: { onformsubmit: formSubmit },\n\t};\n\n\tclient.layoutStack.push({ path: route.handler.path, data: {}, reuse: false, slotRegion: null });\n\tclient.layoutStack = newLayoutStack;\n\tlet layoutStack = client.layoutStack;\n\n\t// If there are layouts, work our way upwards, pushing each component into\n\t// the default slot of its parent\n\t// TODO: There's probably a nicer way to do this with reducers or something\n\tlet component = clientEndPoint.component as Component;\n\tlet slots: Record<string, SlotRender> | undefined = undefined;\n\t// The index of the innermost layout that can actually be reused. It must\n\t// be on the same path (loadData marked it) *and* its slot region must still\n\t// be live: a released region has no `startNode`, and one whose window was\n\t// left pointing at a removed node has a detached `startNode`. A reactive\n\t// update inside the layout during this navigation — e.g. an @if branch\n\t// before the <slot> being cleared because $page.url changed — can cascade\n\t// through `clearRegion` and release the slot region; a post-hydration\n\t// re-render can remove the node it starts at. Reusing either throws on\n\t// `slotRegion.startNode!.parentNode`, so treat such layouts as new instead:\n\t// keep the nearest live ancestor layout, or fully re-render the chain below.\n\tlet reusedIndex = -1;\n\tfor (let i = layoutStack.length - 1; i >= 0; i--) {\n\t\tconst stackLayout = layoutStack[i];\n\t\tif (stackLayout.reuse && stackLayout.slotRegion?.startNode?.parentNode != null) {\n\t\t\treusedIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tlet reused = reusedIndex !== -1;\n\tif (handler.layouts) {\n\t\tlet slotFunctions: SlotRender[] = [];\n\t\t// The last slot function will render the client component\n\t\tslotFunctions[handler.layouts.length] = function clientComponent(parent, anchor) {\n\t\t\tlet i = layoutStack.length - 1;\n\t\t\tlayoutStack[i].slotRegion = fillLayoutSlot(\n\t\t\t\tclientEndPoint.component!,\n\t\t\t\tslotFunctions[i + 1],\n\t\t\t\tparent,\n\t\t\t\tanchor,\n\t\t\t\t$props,\n\t\t\t\t$context,\n\t\t\t);\n\t\t};\n\n\t\t// Each earlier slot function will render a layout\n\t\tfor (let i = handler.layouts.length - 1; i >= 0; i--) {\n\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await handler.layouts[i].endPoint())\n\t\t\t\t?.default;\n\t\t\tif (layoutEndPoint?.component) {\n\t\t\t\tif (i === reusedIndex) {\n\t\t\t\t\t// Reuse this layout — clear and refill its slot (done in\n\t\t\t\t\t// the try block below so a failure doesn't leave the slot\n\t\t\t\t\t// half-cleared)\n\t\t\t\t\tcomponent = slotFunctions[i + 1] as Component;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (i === 0) {\n\t\t\t\t\tcomponent = layoutEndPoint.component as Component;\n\t\t\t\t\tslots = { _: slotFunctions[i + 1] };\n\t\t\t\t} else {\n\t\t\t\t\tslotFunctions[i] = function layoutComponent(parent, anchor, _, $context) {\n\t\t\t\t\t\tlayoutStack[i - 1].slotRegion = fillLayoutSlot(\n\t\t\t\t\t\t\tlayoutEndPoint.component!,\n\t\t\t\t\t\t\tslotFunctions[i + 1],\n\t\t\t\t\t\t\tparent,\n\t\t\t\t\t\t\tanchor,\n\t\t\t\t\t\t\t$props,\n\t\t\t\t\t\t\t$context,\n\t\t\t\t\t\t);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// A definite alias, so that the render closure's type checks hold\n\tlet app: HTMLElement = parent;\n\t// The DOM update, wrapped by the view transitions API when navigating\n\t// (but not on the initial hydration)\n\tconst render = () => {\n\t\ttry {\n\t\t\tif (reused) {\n\t\t\t\t// The layout is being reused — clear the old slot content, then\n\t\t\t\t// call the slot function directly to fill it with the new page.\n\t\t\t\t// We must not go through `mount` here: the slot's container still\n\t\t\t\t// holds the layout's own children (e.g. a header), which `mount`\n\t\t\t\t// refuses to mount into. Both the clear and the fill are inside\n\t\t\t\t// the try so that a failure doesn't leave the slot half-cleared.\n\t\t\t\tconst slotRegion = layoutStack[reusedIndex].slotRegion;\n\t\t\t\tif (\n\t\t\t\t\tslotRegion === null ||\n\t\t\t\t\tslotRegion.startNode === null ||\n\t\t\t\t\tslotRegion.startNode.parentNode === null\n\t\t\t\t) {\n\t\t\t\t\t// The region died after we planned to reuse it (a layout\n\t\t\t\t\t// update ran while an endpoint was being imported). Don't\n\t\t\t\t\t// paint an error over the current page — reload so the\n\t\t\t\t\t// server renders the requested page.\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\"The layout slot was cleared during navigation; falling back to a full page load\",\n\t\t\t\t\t);\n\t\t\t\t\twindow.location.reload();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tapp = slotRegion.startNode.parentNode as HTMLElement;\n\t\t\t\tclearLayoutSlot(slotRegion);\n\t\t\t\tcomponent(app, null);\n\t\t\t} else if (withHydration) {\n\t\t\t\thydrate(app, component, $props, slots);\n\t\t\t} else {\n\t\t\t\t// The layout chain changed (or there was no previous layout to\n\t\t\t\t// reuse): tear down the previous UI entirely — disposing its\n\t\t\t\t// region tree and clearing `#app` — so `mount` starts fresh.\n\t\t\t\t// Without this, `mount` throws because `#app` still holds the\n\t\t\t\t// previous render's children, and it would reuse a stale root\n\t\t\t\t// region.\n\t\t\t\tunmount(app);\n\t\t\t\tmount(app, component, $props, slots);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// TODO: Show a proper Error component\n\t\t\tapp.innerHTML = '<span style=\"color: red\">Script syntax error</span><p>' + error + \"</p>\";\n\t\t\tconsole.log(error);\n\t\t}\n\n\t\tif (!withHydration) {\n\t\t\t// Scroll back to the top when moving to a different page; keep the\n\t\t\t// scroll position for same-page navigations (query changes,\n\t\t\t// re-renders after form actions)\n\t\t\tconst current = stripBaseFromUrl(new URL(document.location.href), getBasePath())?.pathname;\n\t\t\tif (current !== path) {\n\t\t\t\twindow.scrollTo(0, 0);\n\t\t\t}\n\t\t}\n\t};\n\n\tif (\n\t\t!withHydration &&\n\t\tclient.viewTransitions &&\n\t\ttypeof document.startViewTransition === \"function\"\n\t) {\n\t\tdocument.startViewTransition(render);\n\t} else {\n\t\trender();\n\t}\n\n\t// Reset prefetched data on each navigation\n\tclient.prefetchedData = {};\n\n\treturn { type: \"rendered\" };\n}\n","import navigate from \"./navigate\";\n\n/**\n * Loads and renders the page at the supplied path. Returns whether the page\n * was rendered in place: `false` when the document has to take over (a\n * `+server` route, a redirect, or a failed navigation).\n */\nexport default async function load(path: string): Promise<boolean> {\n\tconst url = new URL(path, document.location.href);\n\treturn (await navigate(url)).type === \"rendered\";\n}\n"],"mappings":";;;;;;AAEA,MAAM,gBAA+B,OAAO,IAAI,aAAa;AAE7D,MAAM,SAEJ,WAAW,mBAAmB;CAE9B,QAAQ;CACR,aAAa,CAAC;CAEd,gBAAgB,CAAC;CACjB,sBAAsB,CAAC;CACvB,iBAAiB;AAClB;;;;;;;ACRD,eAA8B,SAA2B;CAExD,QAAQ,MAAM,SAAS,IADP,IAAI,SAAS,SAAS,IACf,CAAG,EAAA,CAAG,SAAS;AACvC;;;ACKA,eAA8B,WAAW,GAA+B;CAEvE,EAAE,eAAe;CAIjB,MAAM,OAAO,KAAA;CAGb,MAAM,OAAO,EAAE;CACf,MAAM,SAAS,EAAE;CAIjB,IAAI,SAAS,KAAK,UAAU,SAAS;CACrC,IAAI,UAAU,OAAO,cAAc,OAAO,eAAe,SAAS,KACjE,SAAS,OAAO;CAEjB,MAAM,UAAU;EACf,MAAM,SAAS,IAAI,SAAS,MAAM,MAAM,IAAI,IAAI,SAAS,IAAI;EAC7D,QAAQ;EACR,MAAM;EACN,aAAa;EAIb,SAAS,EACR,wBAAwB,GACzB;CACD;CACA,IAAI;CACJ,IAAI;EACH,WAAW,MAAM,MAChB,QAEA,OACD;CACD,SAAS,OAAO;EAIf,QAAQ,MAAM,0BAA0B,KAAK;EAC7C,oBAAoB,MAAM,QAAQ,KAAK;EACvC;CACD;CAEA,IACC,SAAS,WAAW,OACpB,SAAS,QAAQ,IAAI,qBAAqB,KAC1C,iCAAiC,KAAK,SAAS,QAAQ,IAAI,qBAAqB,CAAE,GACjF;EAGD,MAAM,mBACL,SAAS,QAAQ,IAAI,qBAAqB,CAAC,EAAE,MAAM,gCAAgC,CAAC,CAAE,MACtF;EACD,MAAM,eAAe,SAAS,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-D8Www11B.mjs","names":[],"sources":["../src/openapi/document.ts","../src/openapi/docsHtml.ts","../src/openapi/plugin.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"../types/StandardSchema\";\nimport type { OpenApiPluginOptions, OpenApiRouteEntry, JsonSchema } from \"./types\";\n\n// The endpoint handler names, in the order they appear in docs\nconst METHODS = [\"get\", \"post\", \"patch\", \"put\", \"del\", \"options\", \"head\"] as const;\ntype Method = (typeof METHODS)[number];\n\n// Handlers whose schema validates the query string; all others validate the\n// json request body\nconst QUERY_METHODS: readonly string[] = [\"get\", \"head\"];\nconst BODY_METHODS: readonly string[] = [\"post\", \"patch\", \"put\", \"del\", \"options\"];\n\n/**\n * Builds an OpenAPI 3.1 document from a list of +server endpoints.\n *\n * Each endpoint's route path (`/api/posts/[id]`) is converted to OpenAPI\n * syntax (`/api/posts/{id}`); its `params` schema becomes path parameters,\n * its `get`/`head` schema becomes query parameters, and its `post`/`patch`/\n * `put`/`del`/`options` schema becomes a json request body. Responses are\n * stubbed: a `200` for every handler, plus a `422` when the handler declares\n * an input schema (validation errors are returned automatically).\n *\n * Throws if any endpoint declares a schema but the options have no\n * `toJsonSchema` converter.\n */\nexport default function buildOpenApiDocument(\n\tentries: OpenApiRouteEntry[],\n\toptions: OpenApiPluginOptions,\n): Record<string, unknown> {\n\tif (!options.toJsonSchema) {\n\t\tconst withSchema = entries.find(hasSchemas);\n\t\tif (withSchema) {\n\t\t\tthrow new Error(\n\t\t\t\t`The endpoint at ${withSchema.path} declares schema(s), but the openApi() plugin ` +\n\t\t\t\t\t`was not given a \"toJsonSchema\" converter. Pass one, e.g. ` +\n\t\t\t\t\t`openApi({ toJsonSchema: (s) => z.toJSONSchema(s) })`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst paths: Record<string, Record<string, unknown>> = {};\n\tfor (const entry of entries) {\n\t\tconst pathItem = buildPathItem(entry, options);\n\t\tif (pathItem) {\n\t\t\tpaths[openApiPath(entry.path)] = pathItem;\n\t\t}\n\t}\n\n\treturn {\n\t\topenapi: \"3.1.0\",\n\t\tinfo: {\n\t\t\ttitle: options.title ?? \"API\",\n\t\t\tversion: options.version ?? \"1.0.0\",\n\t\t},\n\t\tpaths,\n\t};\n}\n\nfunction hasSchemas(entry: OpenApiRouteEntry): boolean {\n\tconst schema = entry.endPoint?.schema;\n\tif (!schema) return false;\n\treturn METHODS.some((method) => schema[method]) || !!schema.params;\n}\n\nfunction buildPathItem(\n\tentry: OpenApiRouteEntry,\n\toptions: OpenApiPluginOptions,\n): Record<string, unknown> | undefined {\n\tconst endPoint = entry.endPoint;\n\tconst pathItem: Record<string, unknown> = {};\n\tlet count = 0;\n\n\tfor (const method of METHODS) {\n\t\tif (typeof endPoint[method] !== \"function\") {\n\t\t\tcontinue;\n\t\t}\n\t\tcount++;\n\n\t\tconst schema = endPoint.schema?.[method];\n\t\tconst paramsSchema = endPoint.schema?.params;\n\n\t\tconst parameters: Record<string, unknown>[] = [];\n\t\tif (paramsSchema) {\n\t\t\tparameters.push(...flattenObject(convert(paramsSchema, options), \"path\"));\n\t\t}\n\t\tif (schema && QUERY_METHODS.includes(method)) {\n\t\t\tparameters.push(...flattenObject(convert(schema, options), \"query\"));\n\t\t}\n\n\t\tconst responses: Record<string, unknown> = { \"200\": { description: \"OK\" } };\n\t\tif (schema) {\n\t\t\tresponses[\"422\"] = { description: \"Validation failed\" };\n\t\t}\n\n\t\tpathItem[method === \"del\" ? \"delete\" : method] = {\n\t\t\toperationId: operationId(method, entry.path),\n\t\t\t...(parameters.length ? { parameters } : {}),\n\t\t\t...(schema && BODY_METHODS.includes(method)\n\t\t\t\t? {\n\t\t\t\t\t\trequestBody: {\n\t\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: convert(schema, options) } },\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tresponses,\n\t\t};\n\t}\n\n\treturn count > 0 ? pathItem : undefined;\n}\n\nfunction convert(schema: StandardSchemaV1, options: OpenApiPluginOptions): JsonSchema {\n\treturn options.toJsonSchema!(schema);\n}\n\n/**\n * Flattens a converted object schema into OpenAPI parameters. Path\n * parameters are always required; query parameters take their `required`\n * flag from the schema's `required` array.\n */\nfunction flattenObject(\n\tjsonSchema: JsonSchema,\n\tlocation: \"path\" | \"query\",\n): Record<string, unknown>[] {\n\tconst properties = jsonSchema.properties;\n\tif (!properties || typeof properties !== \"object\") {\n\t\treturn [];\n\t}\n\tconst required = Array.isArray(jsonSchema.required) ? jsonSchema.required : [];\n\treturn Object.entries(properties as Record<string, JsonSchema>).map(([name, propSchema]) => ({\n\t\tname,\n\t\tin: location,\n\t\trequired: location === \"path\" ? true : required.includes(name),\n\t\tschema: propSchema,\n\t}));\n}\n\n/**\n * Converts a route path to OpenAPI syntax: `/api/posts/[id]` becomes\n * `/api/posts/{id}`.\n */\nfunction openApiPath(routePath: string): string {\n\treturn routePath.replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, \"{$1}\").replace(/\\[([^\\]]+)\\]/g, \"{$1}\");\n}\n\nfunction operationId(method: Method, routePath: string): string {\n\tconst segments = openApiPath(routePath)\n\t\t.split(/[^a-zA-Z0-9]+/)\n\t\t.filter((s) => s.length > 0)\n\t\t.map((s) => s.charAt(0).toUpperCase() + s.slice(1));\n\tconst verb = method === \"del\" ? \"delete\" : method;\n\treturn verb + (segments.join(\"\") || \"Root\");\n}\n","/**\n * A standalone HTML page loading Swagger UI from a CDN, pointed at the\n * OpenAPI document endpoint.\n */\nexport default function openApiDocsHtml(docPath: string): string {\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n\t<meta charset=\"utf-8\" />\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n\t<title>API Docs</title>\n\t<link rel=\"stylesheet\" href=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui.css\" />\n</head>\n<body>\n\t<div id=\"swagger-ui\"></div>\n\t<script src=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js\" crossorigin></script>\n\t<script>\n\t\twindow.addEventListener(\"DOMContentLoaded\", () => {\n\t\t\tSwaggerUIBundle({ url: ${JSON.stringify(docPath)}, dom_id: \"#swagger-ui\" });\n\t\t});\n\t</script>\n</body>\n</html>\n`;\n}\n","import type SitePlugin from \"../types/SitePlugin\";\nimport openApiDocsHtml from \"./docsHtml\";\nimport type { OpenApiPluginOptions, ResolvedOpenApiOptions } from \"./types\";\n\n/**\n * The `site.pluginState` key the openApi plugin stores its resolved options\n * under. A registry symbol (`Symbol.for`), so that the user's config, the\n * manifest plugin and the generated runtime code all resolve to the same\n * key even when they are loaded as separate module instances.\n */\nexport const OPEN_API_STATE_KEY: symbol = Symbol.for(\"@torpor/build/openapi\");\n\n/**\n * Serves an OpenAPI 3.1 document for the site's `+server` endpoints, plus an\n * optional interactive docs page.\n *\n * ```ts\n * import { Site } from \"@torpor/build\";\n * import { openApi } from \"@torpor/build/openapi\";\n * import { z } from \"zod\";\n *\n * const site = new Site();\n * site.addRouteFolder(\"src/routes\");\n * site.plugins = [\n * \topenApi({\n * \t\ttitle: \"My API\",\n * \t\ttoJsonSchema: (s) => z.toJSONSchema(s as z.ZodType, { io: \"input\" }),\n * \t}),\n * ];\n * export default site;\n * ```\n *\n * The document is served at `/openapi.json` (configurable with `path`) and\n * the docs page at `/docs` (set `docs: false` to disable). Endpoints are\n * picked up from every `+server.ts` route: its `params` schema becomes path\n * parameters, `get`/`head` schemas become query parameters, and\n * `post`/`patch`/`put`/`del`/`options` schemas become request bodies.\n *\n * The resolved options are stored in `site.pluginState` under\n * `OPEN_API_STATE_KEY`, which the manifest plugin reads at build time to\n * generate the document endpoint.\n */\nexport function openApi(options: OpenApiPluginOptions = {}): SitePlugin {\n\treturn (site) => {\n\t\tconst docPath = withLeadingSlash(options.path ?? \"/openapi.json\");\n\t\tif (site.routes.some((route) => route.path === docPath)) {\n\t\t\tthrow new Error(\n\t\t\t\t`There is already a route registered at ${docPath}, so the OpenAPI document can't be ` +\n\t\t\t\t\t`served there. Pass a different \"path\" to the openApi() plugin`,\n\t\t\t);\n\t\t}\n\n\t\tconst resolved: ResolvedOpenApiOptions = {\n\t\t\tpath: docPath,\n\t\t\tdocs: options.docs === false ? undefined : withLeadingSlash(options.docs ?? \"/docs\"),\n\t\t\ttitle: options.title ?? \"API\",\n\t\t\tversion: options.version ?? \"1.0.0\",\n\t\t\ttoJsonSchema: options.toJsonSchema,\n\t\t};\n\t\tsite.pluginState.set(OPEN_API_STATE_KEY, resolved);\n\n\t\tif (resolved.docs) {\n\t\t\tconst html = openApiDocsHtml(docPath);\n\t\t\tsite.addRoute(resolved.docs, {\n\t\t\t\tserver: {\n\t\t\t\t\tget: () =>\n\t\t\t\t\t\tnew Response(html, {\n\t\t\t\t\t\t\theaders: { \"Content-Type\": \"text/html; charset=utf-8\" },\n\t\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t};\n}\n\nfunction withLeadingSlash(pathName: string): string {\n\treturn pathName.startsWith(\"/\") ? pathName : \"/\" + pathName;\n}\n"],"mappings":";AAIA,MAAM,UAAU;CAAC;CAAO;CAAQ;CAAS;CAAO;CAAO;CAAW;AAAM;AAKxE,MAAM,gBAAmC,CAAC,OAAO,MAAM;AACvD,MAAM,eAAkC;CAAC;CAAQ;CAAS;CAAO;CAAO;AAAS;;;;;;;;;;;;;;AAejF,SAAwB,qBACvB,SACA,SAC0B;CAC1B,IAAI,CAAC,QAAQ,cAAc;EAC1B,MAAM,aAAa,QAAQ,KAAK,UAAU;EAC1C,IAAI,YACH,MAAM,IAAI,MACT,mBAAmB,WAAW,KAAK,2JAGpC;CAEF;CAEA,MAAM,QAAiD,CAAC;CACxD,KAAK,MAAM,SAAS,SAAS;EAC5B,MAAM,WAAW,cAAc,OAAO,OAAO;EAC7C,IAAI,UACH,MAAM,YAAY,MAAM,IAAI,KAAK;CAEnC;CAEA,OAAO;EACN,SAAS;EACT,MAAM;GACL,OAAO,QAAQ,SAAS;GACxB,S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SAAS,QAAQ,WAAW;GAC5B,cAAc,QAAQ;EACvB;EACA,KAAK,YAAY,IAAI,oBAAoB,QAAQ;EAEjD,IAAI,SAAS,MAAM;GAClB,MAAM,OAAO,gBAAgB,OAAO;GACpC,KAAK,SAAS,SAAS,MAAM,EAC5B,QAAQ,EACP,WACC,IAAI,SAAS,MAAM,EAClB,SAAS,EAAE,gBAAgB,2BAA2B,EACvD,CAAC,EACH,EACD,CAAC;EACF;CACD;AACD;AAEA,SAAS,iBAAiB,UAA0B;CACnD,OAAO,SAAS,WAAW,GAAG,IAAI,WAAW,MAAM;AACpD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"read-DxMVAh5Y.mjs","names":[],"sources":["../src/site/findErrorRoute.ts","../src/dataRequest.ts","../src/response/read.ts"],"sourcesContent":["import { ERROR_ROUTE } from \"../types/RouteType\";\nimport type Router from \"./Router\";\n\n/**\n * Finds the path of the nearest error route for a request path: the error\n * route whose base (its path with the `/_error` suffix stripped) is the\n * longest prefix of the request path. E.g. an error route added with\n * `addRoute(\"/admin\", { error })` handles `/admin/nope`, while everything\n * else falls back to the root `/_error`.\n *\n * Returns undefined when the site has no matching error route.\n */\nexport default function findErrorRoute(router: Router, path: string): string | undefined {\n\tlet best: { path: string; length: number } | undefined = undefined;\n\tfor (const route of router.routes) {\n\t\tif (route.handler.type !== ERROR_ROUTE) continue;\n\t\tconst base = route.handler.path.replace(/\\/_error$/, \"\");\n\t\tconst matches = base === \"\" || path === base || path.startsWith(base + \"/\");\n\t\tif (matches && (best === undefined || base.length > best.length)) {\n\t\t\tbest = { path: route.handler.path, length: base.length };\n\t\t}\n\t}\n\treturn best?.path;\n}\n","/**\n * The request header a client data request sets.\n *\n * A GET to `<page url>/~server` carrying this header is handled specially:\n * the server runs the folder hooks once against the page's url and returns the\n * server data for the page and all of its layouts in a single JSON response\n * (`{ loads: [...] }`). This mirrors the server render, where hooks run once\n * with the page url and every layout and the page load in the same request --\n * fetching each `~server` separately would run hooks with internal paths like\n * `/_layout`.\n *\n * The response's `loads` array lines up with the page's layouts (root to leaf)\n * followed by the page itself, so the client can merge each layout's cached\n * client data with its fresh server data.\n */\nexport const DATA_REQUEST_HEADER = \"X-Torpor-Data\";\n\n/**\n * A JSON array of the layout paths a data request is reusing. Reused layouts\n * keep their already-loaded data, so the server skips their loads (their slot\n * in `loads` is `null`), avoiding redundant work and repeated side effects.\n */\nexport const DATA_REUSE_HEADER = \"X-Torpor-Reuse\";\n","import { INTERNAL_RESPONSE_BODY } from \"./internal\";\n\n/**\n * The object an endpoint passed to `response()`/`ok()`, including any\n * promise-valued properties, or `undefined` for a direct `Response.json` (or\n * a non-object body).\n */\nexport function rawResponseBody(response: Response): Record<string, any> | undefined {\n\tconst body = (response as Response & { [INTERNAL_RESPONSE_BODY]?: unknown })[\n\t\tINTERNAL_RESPONSE_BODY\n\t];\n\treturn body !== null && typeof body === \"object\" ? (body as Record<string, any>) : undefined;\n}\n\n/**\n * Reads a load response's data: the original object when the endpoint used\n * `ok()`/`response()` (so deferred promises survive), otherwise its JSON body.\n */\nexport async function readResponseBody(\n\tresponse: Response | undefined,\n): Promise<Record<string, any> | undefined> {\n\tif (!response) return undefined;\n\tconst raw = rawResponseBody(response);\n\tif (raw !== undefined) return raw;\n\tif (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\treturn (await response.json()) as Record<string, any>;\n\t}\n\treturn undefined;\n}\n"],"mappings":";;;;;;;;;;;AAYA,SAAwB,eAAe,QAAgB,MAAkC;CACxF,IAAI,OAAqD,KAAA;CACzD,KAAK,MAAM,SAAS,OAAO,QAAQ;EAClC,IAAI,MAAM,QAAQ,SAAA,GAAsB;EACxC,MAAM,OAAO,MAAM,QAAQ,KAAK,QAAQ,aAAa,EAAE;EAEvD,KADgB,SAAS,MAAM,SAAS,QAAQ,KAAK,WAAW,OAAO,GAAG,OAC1D,SAAS,KAAA,KAAa,KAAK,SAAS,KAAK,SACxD,OAAO;GAAE,MAAM,MAAM,QAAQ;GAAM,QAAQ,KAAK;EAAO;CAEzD;CACA,OAAO,MAAM;AACd;;;;;;;;;;;;;;;;;;ACRA,MAAa,sBAAsB;;;;;;AAOnC,MAAa,oBAAoB;;;;;;;;ACfjC,SAAgB,gBAAgB,UAAqD;CACpF,MAAM,OAAQ,SACb;CAED,OAAO,SAAS,QAAQ,OAAO,SAAS,WAAY,OAA+B,KAAA;AACpF;;;;;AAMA,eAAsB,iBACrB,UAC2C;CAC3C,IAAI,CAAC,UAAU,OAAO,KAAA;CACtB,MAAM,MAAM,gBAAgB,QAAQ;CACpC,IAAI,QAAQ,KAAA,GAAW,OAAO;CAC9B,IAAI,SAAS,QAAQ,IAAI,cAAc,CAAC,EAAE,SAAS,kBAAkB,GACpE,OAAQ,MAAM,SAAS,KAAK;AAG9B"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"response-C5EZsszY.mjs","names":[],"sources":["../src/response/badRequest.ts","../src/response/created.ts","../src/response/forbidden.ts","../src/response/transfer.ts","../src/response/found.ts","../src/response/methodNotAllowed.ts","../src/response/movedPermanently.ts","../src/response/notModified.ts","../src/response/permanentRedirect.ts","../src/response/seeOther.ts","../src/response/serverError.ts","../src/response/temporaryRedirect.ts","../src/response/unauthorized.ts"],"sourcesContent":["import response from \"./response\";\nimport type { Jsonify } from \"../types/Jsonify\";\nimport type TypedResponse from \"./TypedResponse\";\n\ntype BadRequestResponse<T extends object | string | undefined> = T extends object\n\t? TypedResponse<Jsonify<T>>\n\t: Response;\n\n/**\n * 400 Bad Request\n *\n * The HTTP 400 Bad Request client error response status code indicates that the\n * server would not process the request due to something the server considered\n * to be a client error. The reason for a 400 response is typically due to\n * malformed request syntax, invalid request message framing, or deceptive\n * request routing.\n *\n * Clients that receive a 400 response should expect that repeating the request\n * without modification will fail with the same error.\n *\n * An object body is typed: it becomes the page's `$props.form` (with its JSON\n * form) after a form submit, so validation errors can be surfaced with their\n * field types via `PageForm`.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/400\n */\nexport default function badRequest<T extends object | string | undefined>(\n\tbody?: T,\n): BadRequestResponse<T> {\n\treturn response(400, body ?? \"Bad request\") as BadRequestResponse<T>;\n}\n","import type { Jsonify } from \"../types/Jsonify\";\nimport type TypedResponse from \"./TypedResponse\";\nimport response from \"./response\";\n\ntype CreatedResponse<T extends object | string | undefined> = T extends object\n\t? TypedResponse<Jsonify<T>>\n\t: Response;\n\n/**\n * 201 Created\n *\n * The HTTP 201 Created successful response status code indicates that the HTTP\n * request has led to the creation of a resource. This status code is commonly\n * sent as the result of a POST request.\n *\n * The new resource, or a description and link to the new resource, is created\n * before the response is returned. The newly-created items can be returned in\n * the body of the response message, but must be locatable by the URL of the\n * initiating request or by the URL in the value of the Location header provided\n * with the response.\n *\n * An object body is typed: the client sees its JSON form through\n * `makeApi`-created callers.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/201\n */\nexport default function created<T extends object | string | undefined>(\n\tbody?: T,\n): CreatedResponse<T> {\n\treturn response(201, body) as CreatedResponse<T>;\n}\n","import response from \"./response\";\n\n/**\n * 403 Forbidden\n *\n * The HTTP 403 Forbidden client error response status code indicates that the\n * server understood the request but refused to process it. This status is\n * similar to 401, except that for 403 Forbidden responses, authenticating or\n * re-authenticating makes no difference. The request failure is tied to\n * application logic, such as insufficient permissions to a resource or action.\n *\n * Clients that receive a 403 response should expect that repeating the request\n * without modification will fail with the same error. Server owners may decide\n * to send a 404 response instead of a 403 if acknowledging the existence of a\n * resource to clients with insufficient privileges is not desired.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/403\n */\nexport default function forbidden(body?: object | string): Response {\n\treturn response(403, body ?? \"Forbidden\");\n}\n","/**\n * Creates a redirect response with the supplied status code.\n */\nexport default function transfer(\n\tstatus: 300 | 301 | 302 | 303 | 304 | 307 | 308,\n\tlocation: string,\n): Response {\n\treturn new Response(null, {\n\t\tstatus,\n\t\theaders: {\n\t\t\tlocation,\n\t\t},\n\t});\n}\n","import transfer from \"./transfer\";\n\n/**\n * 302 Found\n *\n * The HTTP 302 Found redirection response status code indicates that the\n * requested resource has been temporarily moved to the URL in the Location\n * header.\n *\n * A browser receiving this status will automatically request the resource at\n * the URL in the Location header, redirecting the user to the new page. Search\n * engines receiving this response will not attribute links to the original URL\n * to the new resource, meaning no SEO value is transferred to the new URL.\n *\n * > Note: In the Fetch Standard, when a user agent receives a 302 in response\n * > to a POST request, it uses the GET method in the subsequent redirection\n * > request, as permitted by the HTTP specification. To avoid user agents\n * > modifying the request, use 307 Temporary Redirect instead, as altering the\n * > method after a 307 response is prohibited.\n *\n * > In cases where you want any request method to be changed to GET, use 303\n * > See Other. This is useful when you want to give a response to a PUT method\n * > that is not the uploaded resource but a confirmation message such as: \"you\n * > successfully uploaded XYZ\".\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/302\n */\nexport default function found(location: string): Response {\n\treturn transfer(302, location);\n}\n","import response from \"./response\";\n\n/**\n * 405 Method Not Allowed\n *\n * The HTTP 405 Method Not Allowed client error response status code indicates\n * that the server knows the request method, but the target resource doesn't\n * support this method. The server must generate an Allow header in a 405\n * response with a list of methods that the target resource currently supports.\n *\n * Improper server-side permissions set on files or directories may cause a 405\n * response when the request would otherwise be expected to succeed.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/405\n */\nexport default function methodNotAllowed(body?: object | string): Response {\n\treturn response(405, body ?? \"Method not allowed\");\n}\n","import transfer from \"./transfer\";\n\n/**\n * 301 Moved Permanently\n *\n * The HTTP 301 Moved Permanently redirection response status code indicates\n * that the requested resource has been permanently moved to the URL in the\n * Location header.\n *\n * A browser receiving this status will automatically request the resource at\n * the URL in the Location header, redirecting the user to the new page. Search\n * engines receiving this response will attribute links to the original URL to\n * the redirected resource, passing the SEO ranking to the new URL.\n *\n * > Note: In the Fetch Standard, when a user agent receives a 301 in response\n * > to a POST request, it uses the GET method in the subsequent redirection\n * > request, as permitted by the HTTP specification. To avoid user agents\n * > modifying the request, use 308 Permanent Redirect instead, as altering the\n * > method after a 308 response is prohibited.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/301\n */\nexport default function movedPermanently(location: string): Response {\n\treturn transfer(301, location);\n}\n","import transfer from \"./transfer\";\n\n/**\n * 304 Not Modified\n *\n * The HTTP 304 Not Modified redirection response status code indicates that\n * there is no need to retransmit the requested resources.\n *\n * This response code is sent when the request is a conditional GET or HEAD\n * request with an If-None-Match or an If-Modified-Since header and the\n * condition evaluates to 'false'. It confirms that the resource cached by the\n * client is still valid and that the server would have sent a 200 OK response\n * with the resource if the condition evaluated to 'true'. See HTTP caching for\n * more information.\n *\n * The response must not contain a body and must include the headers that would\n * have been sent in an equivalent 200 response, such as:\n *\n * - Cache-Control\n * - Content-Location\n * - Date\n * - ETag\n * - Expires\n * - Vary\n *\n * > Note: Many developer tools' network panels of browsers create extraneous\n * > requests leading to 304 responses, so that access to the local cache is\n * > visible to developers.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/304\n */\nexport default function notModified(): Response {\n\treturn transfer(304, \"\");\n}\n","import transfer from \"./transfer\";\n\n/**\n * 308 Permanent Redirect\n *\n * The HTTP 308 Permanent Redirect redirection response status code indicates\n * that the requested resource has been permanently moved to the URL given by\n * the Location header.\n *\n * A browser receiving this status will automatically request the resource at\n * the URL in the Location header, redirecting the user to the new page. Search\n * engines receiving this response will attribute links to the original URL to\n * the redirected resource, passing the SEO ranking to the new URL.\n *\n * The request method and the body will not be modified by the client in the\n * redirected request. A 301 Moved Permanently requires the request method and\n * the body to remain unchanged when redirection is performed, but this is\n * incorrectly handled by older clients to use the GET method instead.\n *\n * > Note: Some Web applications may use the 308 Permanent Redirect in a\n * > non-standard way and for different purposes. For example, Google Drive uses\n * > a 308 Resume Incomplete response to indicate to the client when an\n * > unfinished upload has stalled. See Perform a resumable download on the\n * > Google Drive documentation for more information.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/308\n */\nexport default function permanentRedirect(location: string): Response {\n\treturn transfer(308, location);\n}\n","import transfer from \"./transfer\";\n\n/**\n * 303 See Other\n *\n * The HTTP 303 See Other redirection response status code indicates that the\n * browser should redirect to the URL in the Location header instead of\n * rendering the requested resource.\n *\n * This response code is often sent back as a result of PUT or POST methods so\n * the client may retrieve a confirmation, or view a representation of a\n * real-world object (see HTTP range-14). The method to retrieve the redirected\n * resource is always GET.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/303\n */\nexport default function seeOther(location: string): Response {\n\treturn transfer(303, location);\n}\n","import response from \"./response\";\n\n/**\n * 500 Server Error\n *\n * The HTTP 500 Internal Server Error server error response status code\n * indicates that the server encountered an unexpected condition that prevented\n * it from fulfilling the request. This error is a generic \"catch-all\" response\n * to server issues, indicating that the server cannot find a more appropriate\n * 5XX error to respond with.\n *\n * If you're a visitor seeing 500 errors on a web page, these issues require\n * investigation by server owners or administrators. There are many possible\n * causes of 500 errors, including: improper server configuration, out-of-memory\n * (OOM) issues, unhandled exceptions, improper file permissions, or other\n * complex factors. Server administrators may proactively log occurrences of\n * server error responses, like the 500 status code, with details about the\n * initiating requests to improve the stability of a service in the future.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/500\n */\nexport default function serverError(body?: object | string): Response {\n\treturn response(500, body ?? \"Server error\");\n}\n","import transfer from \"./transfer\";\n\n/**\n * 307 Temporary Redirect\n *\n * The HTTP 307 Temporary Redirect redirection response status code indicates\n * that the resource requested has been temporarily moved to the URL in the\n * Location header.\n *\n * A browser receiving this status will automatically request the resource at\n * the URL in the Location header, redirecting the user to the new page. Search\n * engines receiving this response will not attribute links to the original URL\n * to the new resource, meaning no SEO value is transferred to the new URL.\n *\n * The method and the body of the original request are reused to perform the\n * redirected request. In the cases where you want the request method to be\n * changed to GET, use 303 See Other instead. This is useful when you want to\n * give an answer to a successful PUT request that is not the uploaded resource,\n * but a status monitor or confirmation message like \"You have successfully\n * uploaded XYZ\".\n *\n * The difference between 307 and 302 is that 307 guarantees that the client\n * will not change the request method and body when the redirected request is\n * made. With 302, older clients incorrectly changed the method to GET. 307 and\n * 302 responses are identical when the request method is GET.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/307\n */\nexport default function temporaryRedirect(location: string): Response {\n\treturn transfer(307, location);\n}\n","import response from \"./response\";\n\n/**\n * 401 Unauthorized\n *\n * The HTTP 401 Unauthorized client error response status code indicates that a\n * request was not successful because it lacks valid authentication credentials\n * for the requested resource. This status code is sent with an HTTP\n * WWW-Authenticate response header that contains information on the\n * authentication scheme the server expects the client to include to make the\n * request successfully.\n *\n * A 401 Unauthorized is similar to the 403 Forbidden response, except that a\n * 403 is returned when a request contains valid credentials, but the client\n * does not have permissions to perform a certain action.\n *\n * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/401\n */\nexport default function unauthorized(body?: object | string): Response {\n\treturn response(401, body ?? \"Unauthorized\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA0BA,SAAwB,WACvB,MACwB;CACxB,OAAO,SAAS,KAAK,QAAQ,aAAa;AAC3C;;;;;;;;;;;;;;;;;;;;;ACJA,SAAwB,QACvB,MACqB;CACrB,OAAO,SAAS,KAAK,IAAI;AAC1B;;;;;;;;;;;;;;;;;;;ACZA,SAAwB,UAAU,MAAkC;CACnE,OAAO,SAAS,KAAK,QAAQ,WAAW;AACzC;;;;;;ACjBA,SAAwB,SACvB,QACA,UACW;CACX,OAAO,IAAI,SAAS,MAAM;EACzB;EACA,SAAS,EACR,SACD;CACD,CAAC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACcA,SAAwB,MAAM,UAA4B;CACzD,OAAO,SAAS,KAAK,QAAQ;AAC9B;;;;;;;;;;;;;;;;ACdA,SAAwB,iBAAiB,MAAkC;CAC1E,OAAO,SAAS,KAAK,QAAQ,oBAAoB;AAClD;;;;;;;;;;;;;;;;;;;;;;;ACKA,SAAwB,iBAAiB,UAA4B;CACpE,OAAO,SAAS,KAAK,QAAQ;AAC9B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACOA,SAAwB,cAAwB;CAC/C,OAAO,SAAS,KAAK,EAAE;AACxB;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACNA,SAAwB,kBAAkB,UAA4B;CACrE,OAAO,SAAS,KAAK,QAAQ;AAC9B;;;;;;;;;;;;;;;;;ACbA,SAAwB,SAAS,UAA4B;CAC5D,OAAO,SAAS,KAAK,QAAQ;AAC9B;;;;;;;;;;;;;;;;;;;;;;ACGA,SAAwB,YAAY,MAAkC;CACrE,OAAO,SAAS,KAAK,QAAQ,cAAc;AAC5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACKA,SAAwB,kBAAkB,UAA4B;CACrE,OAAO,SAAS,KAAK,QAAQ;AAC9B;;;;;;;;;;;;;;;;;;;ACZA,SAAwB,aAAa,MAAkC;CACtE,OAAO,SAAS,KAAK,QAAQ,cAAc;AAC5C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"runHooks-D5p1Rh7i.mjs","names":[],"sources":["../src/server/runHooks.ts"],"sourcesContent":["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":";;;;;;;;;;;;;;;;;;;;;;AA2CA,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 +0,0 @@
1
- {"version":3,"file":"runOpenApi-C5yMpQU1.mjs","names":["path","path","path","path","path","dependencyNames","path","fs","fs","path","asAliasArray","path","path","createViteServer","isInside","path","path","createViteServer","path","fs","path"],"sources":["../src/utils/tsconfigAliases.ts","../src/site/checkRoutes.ts","../src/site/checkLayoutSlots.ts","../src/site/manifest.ts","../src/utils/torporPackages.ts","../src/run/runPrerender.ts","../src/run/runBuild.ts","../src/run/depCache.ts","../src/run/loadSite.ts","../src/run/staleTorpCopies.ts","../src/run/runDev.ts","../src/server/contentType.ts","../src/run/runPreview.ts","../src/run/run.ts","../src/run/runOpenApi.ts"],"sourcesContent":["import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface AliasEntry {\n\tfind: string | RegExp;\n\treplacement: string;\n}\n\n/**\n * Reads `tsconfig.json` `compilerOptions.paths` (relative to `baseUrl`,\n * defaulting to the tsconfig directory) and converts them to Vite\n * `resolve.alias` entries. Only handles paths declared in the root tsconfig\n * (not inherited via `extends`).\n */\nexport default function tsconfigAliases(root: string): AliasEntry[] {\n\tconst file = path.join(root, \"tsconfig.json\");\n\tlet paths: Record<string, string[]> | undefined;\n\tlet baseUrl: string;\n\ttry {\n\t\tconst tsconfig = JSON.parse(stripJsonc(readFileSync(file, \"utf-8\")));\n\t\tconst compilerOptions = tsconfig.compilerOptions ?? {};\n\t\tbaseUrl = compilerOptions.baseUrl ? path.resolve(root, compilerOptions.baseUrl) : root;\n\t\tpaths = compilerOptions.paths;\n\t} catch {\n\t\treturn [];\n\t}\n\tif (!paths) return [];\n\n\tconst aliases: AliasEntry[] = [];\n\tfor (const [pattern, targets] of Object.entries(paths)) {\n\t\tconst target = targets?.[0];\n\t\tif (!target) continue;\n\t\tif (pattern.endsWith(\"*\")) {\n\t\t\t// `@/*` -> `./src/*`: match the literal prefix (`@/`) and rewrite to\n\t\t\t// the target dir. A string `find` is used (not a RegExp) because\n\t\t\t// Vite applies prefix-string aliases during SSR transform, which is\n\t\t\t// what makes path aliases resolve in the SSR module runner.\n\t\t\tconst find = pattern.slice(0, -1);\n\t\t\tconst targetDir = target.slice(0, -1);\n\t\t\taliases.push({\n\t\t\t\tfind,\n\t\t\t\treplacement: `${path.resolve(baseUrl, targetDir)}/`,\n\t\t\t});\n\t\t} else {\n\t\t\taliases.push({ find: pattern, replacement: path.resolve(baseUrl, target) });\n\t\t}\n\t}\n\treturn aliases;\n}\n\n/**\n * Strips JSONC comments and trailing commas so `tsconfig.json` (which permits\n * both) can be parsed with `JSON.parse`. String contents are preserved.\n */\nexport function stripJsonc(text: string): string {\n\tlet out = \"\";\n\tfor (let i = 0; i < text.length;) {\n\t\tconst c = text[i];\n\t\tif (c === '\"' || c === \"'\") {\n\t\t\tconst quote = c;\n\t\t\tout += c;\n\t\t\ti++;\n\t\t\twhile (i < text.length) {\n\t\t\t\tif (text[i] === \"\\\\\") {\n\t\t\t\t\tout += text[i] + (text[i + 1] ?? \"\");\n\t\t\t\t\ti += 2;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst cc = text[i++];\n\t\t\t\tout += cc;\n\t\t\t\tif (cc === quote) break;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (c === \"/\" && text[i + 1] === \"/\") {\n\t\t\ti += 2;\n\t\t\twhile (i < text.length && text[i] !== \"\\n\") i++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (c === \"/\" && text[i + 1] === \"*\") {\n\t\t\ti += 2;\n\t\t\twhile (i < text.length && !(text[i] === \"*\" && text[i + 1] === \"/\")) i++;\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\t\tout += c;\n\t\ti++;\n\t}\n\treturn out.replace(/,(\\s*[}\\]])/g, \"$1\");\n}\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type Route from \"../types/Route\";\nimport {\n\tERROR_ROUTE,\n\tHOOK_ROUTE,\n\tHOOK_SERVER_ROUTE,\n\tLAYOUT_ROUTE,\n\tLAYOUT_SERVER_ROUTE,\n\tPAGE_SERVER_ROUTE,\n\tSERVER_ROUTE,\n} from \"../types/RouteType\";\nimport tsconfigAliases, { type AliasEntry } from \"../utils/tsconfigAliases\";\nimport type Site from \"./Site\";\n\n/**\n * A problem found in a route file's type annotations by `checkRoutes`.\n */\nexport interface RouteCheckIssue {\n\t/** The route file, relative to the site root */\n\tfile: string;\n\t/** 1-based line number of the annotation */\n\tline: number;\n\tseverity: \"error\" | \"warning\";\n\tmessage: string;\n}\n\nconst ENDPOINT_TYPES = [\"PageServerEndPoint\", \"PageEndPoint\", \"ServerEndPoint\", \"ServerHook\"];\n\nconst USAGE_RE = new RegExp(`\\\\b(satisfies|as|:)\\\\s*\\\\b(${ENDPOINT_TYPES.join(\"|\")})\\\\b`, \"g\");\n\nconst TYPE_NAME_RE = new RegExp(`^(?:${ENDPOINT_TYPES.join(\"|\")})\\\\b`);\n\n/**\n * Checks the route files of a site against their type annotations:\n *\n * - Route path annotations (e.g. `PageServerEndPoint<\"/posts/[id]\">`) must\n * match the route derived from the file's location, so types can't silently\n * lie when files move\n * - Exports that widen the endpoint type (`satisfies T as T`, `as T`, or a\n * variable annotation) are flagged, because they destroy `PageData` /\n * `PageForm` / param inference\n * - Routes with dynamic params but no route annotation are flagged, because\n * their params are loosely typed\n *\n * Only `.ts` route files are checked; annotations are matched by the standard\n * type names (renamed imports are not detected). Best-effort, source-level —\n * comments mentioning these patterns may produce false positives.\n */\nexport function checkRoutes(site: Site): RouteCheckIssue[] {\n\tconst issues: RouteCheckIssue[] = [];\n\tfor (const route of site.routes) {\n\t\tissues.push(...checkRoute(site, route));\n\t}\n\treturn issues;\n}\n\n/**\n * Checks a single route's file. Returns no issues for routes without a `.ts`\n * file (`.torp` components, inline endpoints, `.js` files).\n */\nexport function checkRoute(site: Site, route: Route): RouteCheckIssue[] {\n\tif (!route.file || !route.file.endsWith(\".ts\")) return [];\n\tlet source: string;\n\ttry {\n\t\tsource = readFileSync(path.join(site.root, route.file), \"utf8\");\n\t} catch {\n\t\treturn [];\n\t}\n\treturn checkRouteSource(source, route.file, expectedAnnotationPath(route), typeNameFor(route));\n}\n\n/**\n * Checks a single route file's source. Exported for reuse (e.g. re-checking a\n * changed file during dev).\n * @param source The route file's source code\n * @param file The file path, relative to the site root (used in messages)\n * @param expected The route path derived from the file's location\n * @param typeName The endpoint type name conventionally used by this route\n * type (used in suggestions)\n */\nexport function checkRouteSource(\n\tsource: string,\n\tfile: string,\n\texpected: string,\n\ttypeName: string,\n): RouteCheckIssue[] {\n\tconst issues: RouteCheckIssue[] = [];\n\tlet sawAnnotation = false;\n\tUSAGE_RE.lastIndex = 0;\n\tfor (let m = USAGE_RE.exec(source); m; m = USAGE_RE.exec(source)) {\n\t\tsawAnnotation = true;\n\t\tconst kind = m[1];\n\t\tconst usedTypeName = m[2];\n\t\tconst { routePath, end } = parseTypeArgs(source, m.index + m[0].length);\n\t\tconst line = lineOf(source, m.index);\n\t\tif (routePath !== undefined && routePath !== expected) {\n\t\t\tissues.push({\n\t\t\t\tfile,\n\t\t\t\tline,\n\t\t\t\tseverity: \"error\",\n\t\t\t\tmessage: `Route annotation \"${routePath}\" doesn't match this file's route \"${expected}\" (derived from its location). Did the file move?`,\n\t\t\t});\n\t\t}\n\t\tif (kind === \"as\" || kind === \":\") {\n\t\t\tissues.push({\n\t\t\t\tfile,\n\t\t\t\tline,\n\t\t\t\tseverity: \"warning\",\n\t\t\t\tmessage:\n\t\t\t\t\tkind === \"as\"\n\t\t\t\t\t\t? `The \\`as ${usedTypeName}\\` cast widens the exported type, so PageData/PageForm/param inference falls back to loose types. Use \\`satisfies ${usedTypeName}${routePathArg(expected, routePath)}\\` without a cast instead.`\n\t\t\t\t\t\t: `The variable annotation widens the exported type, so PageData/PageForm/param inference falls back to loose types. Use \\`satisfies ${usedTypeName}${routePathArg(expected, routePath)}\\` on the default export instead.`,\n\t\t\t});\n\t\t} else {\n\t\t\tconst cast = parseAsCast(source, end);\n\t\t\tif (cast) {\n\t\t\t\tissues.push({\n\t\t\t\t\tfile,\n\t\t\t\t\tline,\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tmessage: `The \\`as\\` cast after \\`satisfies\\` widens the exported type, so PageData/PageForm/param inference falls back to loose types. Use \\`satisfies ${usedTypeName}${routePathArg(expected, routePath ?? cast.routePath)}\\` on its own.`,\n\t\t\t\t});\n\t\t\t\tif (cast.routePath !== undefined && cast.routePath !== expected) {\n\t\t\t\t\tissues.push({\n\t\t\t\t\t\tfile,\n\t\t\t\t\t\tline,\n\t\t\t\t\t\tseverity: \"error\",\n\t\t\t\t\t\tmessage: `Route annotation \"${cast.routePath}\" doesn't match this file's route \"${expected}\" (derived from its location). Did the file move?`,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\t// Skip the `as T` so it isn't reported again as a separate cast\n\t\t\t\tUSAGE_RE.lastIndex = cast.end;\n\t\t\t} else if (routePath === undefined && expected.includes(\"[\")) {\n\t\t\t\tissues.push({\n\t\t\t\t\tfile,\n\t\t\t\t\tline,\n\t\t\t\t\tseverity: \"warning\",\n\t\t\t\t\tmessage: `No route path on the annotation, so params are loosely typed. Use \\`satisfies ${usedTypeName}<\"${expected}\">\\`.`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\tif (!sawAnnotation && file.endsWith(\".ts\") && expected.includes(\"[\")) {\n\t\tissues.push({\n\t\t\tfile,\n\t\t\tline: 1,\n\t\t\tseverity: \"warning\",\n\t\t\tmessage: `No route annotation, so params are loosely typed. Add \\`satisfies ${typeName}<\"${expected}\">\\` to the default export.`,\n\t\t});\n\t}\n\treturn issues;\n}\n\n/**\n * Prints issues to the console and returns the number of errors.\n */\nexport function reportRouteIssues(issues: RouteCheckIssue[]): number {\n\tfor (const issue of issues) {\n\t\tconsole.error(`[torpor] ${issue.severity}: ${issue.file}:${issue.line} ${issue.message}`);\n\t}\n\treturn issues.filter((i) => i.severity === \"error\").length;\n}\n\nconst MAKE_API_RE = /\\bmakeApi\\s*<\\s*([\"'])([^\"']+)\\1\\s*,\\s*typeof\\s+([A-Za-z_$][\\w$]*)/g;\n\nconst DEFAULT_IMPORT_RE = /\\bimport\\s+(?:type\\s+)?([A-Za-z_$][\\w$]*)\\s+from\\s*([\"'])([^\"']+)\\2/g;\n\nconst SKIP_DIRS = new Set([\"node_modules\", \"dist\", \".git\", \".torpor\", \".vite\", \"coverage\"]);\n\nconst SOURCE_FILE_RE = /\\.(ts|js|torp)$/;\n\n/**\n * Precomputed state for checking `makeApi` calls: the site root, its route\n * files keyed by path, and tsconfig path aliases for resolving imports.\n */\nexport interface ApiCallCheck {\n\troot: string;\n\troutesByFile: Map<string, Route>;\n\taliases: AliasEntry[];\n}\n\n/**\n * Creates the shared state used by `checkApiCallSource`, so per-file checks\n * (e.g. re-checking a changed file during dev) don't rebuild it.\n */\nexport function createApiCallCheck(site: Site): ApiCallCheck {\n\tconst routesByFile = new Map<string, Route>();\n\tfor (const route of site.routes) {\n\t\tif (route.file) routesByFile.set(route.file.replaceAll(\"\\\\\", \"/\"), route);\n\t}\n\treturn { root: site.root, routesByFile, aliases: tsconfigAliases(site.root) };\n}\n\n/**\n * Checks `makeApi<Route, typeof endpoint>` calls across the site's source\n * files: the `Route` argument must match the route derived from the imported\n * endpoint file's location. Calls whose endpoint isn't a type-only import of\n * a known route file are skipped.\n */\nexport function checkApiCalls(site: Site): RouteCheckIssue[] {\n\tconst check = createApiCallCheck(site);\n\tconst issues: RouteCheckIssue[] = [];\n\tfor (const file of walkSourceFiles(site.root)) {\n\t\tlet source: string;\n\t\ttry {\n\t\t\tsource = readFileSync(file, \"utf8\");\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tissues.push(...checkApiCallSource(source, file, check));\n\t}\n\treturn issues;\n}\n\n/**\n * Checks the `makeApi` calls in a single file's source.\n * @param source The file's source code\n * @param file The file's absolute path (used to resolve relative imports and\n * to derive the path shown in messages)\n * @param check Shared state from `createApiCallCheck`\n */\nexport function checkApiCallSource(\n\tsource: string,\n\tfile: string,\n\tcheck: ApiCallCheck,\n): RouteCheckIssue[] {\n\tconst imports = new Map<string, string>();\n\tfor (let m = DEFAULT_IMPORT_RE.exec(source); m; m = DEFAULT_IMPORT_RE.exec(source)) {\n\t\timports.set(m[1], m[3]);\n\t}\n\tconst issues: RouteCheckIssue[] = [];\n\tfor (let m = MAKE_API_RE.exec(source); m; m = MAKE_API_RE.exec(source)) {\n\t\tconst specifier = imports.get(m[3]);\n\t\tif (!specifier) continue;\n\t\tconst resolved = resolveSpecifier(specifier, file, check);\n\t\tif (!resolved) continue;\n\t\tconst relFile = path.relative(check.root, resolved).replaceAll(\"\\\\\", \"/\");\n\t\tconst route = check.routesByFile.get(relFile);\n\t\tif (!route) continue;\n\t\tconst expected = expectedAnnotationPath(route);\n\t\tif (m[2] !== expected) {\n\t\t\tissues.push({\n\t\t\t\tfile: path.relative(check.root, file).replaceAll(\"\\\\\", \"/\"),\n\t\t\t\tline: lineOf(source, m.index),\n\t\t\t\tseverity: \"error\",\n\t\t\t\tmessage: `makeApi route \"${m[2]}\" doesn't match the endpoint's route \"${expected}\" (derived from ${relFile}). Did the endpoint move?`,\n\t\t\t});\n\t\t}\n\t}\n\treturn issues;\n}\n\n/**\n * Resolves an import specifier to an existing file: relative specifiers are\n * resolved against the importing file, others against tsconfig path aliases.\n * Bare module specifiers that match no alias return undefined.\n */\nexport function resolveSpecifier(\n\tspecifier: string,\n\tfromFile: string,\n\tcheck: ApiCallCheck,\n): string | undefined {\n\tlet candidate: string | undefined;\n\tif (specifier.startsWith(\"./\") || specifier.startsWith(\"../\")) {\n\t\tcandidate = path.resolve(path.dirname(fromFile), specifier);\n\t} else {\n\t\tfor (const alias of check.aliases) {\n\t\t\tif (typeof alias.find === \"string\") {\n\t\t\t\tif (specifier.startsWith(alias.find)) {\n\t\t\t\t\tcandidate = path.resolve(alias.replacement, specifier.slice(alias.find.length));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else if (alias.find.test(specifier)) {\n\t\t\t\tcandidate = specifier.replace(alias.find, alias.replacement);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tif (!candidate) return undefined;\n\tconst probes = [\n\t\tcandidate,\n\t\t`${candidate}.ts`,\n\t\t`${candidate}.js`,\n\t\tpath.join(candidate, \"index.ts\"),\n\t\tpath.join(candidate, \"index.js\"),\n\t];\n\tfor (const probe of probes) {\n\t\tif (existsSync(probe) && statSync(probe).isFile()) return probe;\n\t}\n\treturn undefined;\n}\n\nfunction walkSourceFiles(root: string): string[] {\n\tconst files: string[] = [];\n\tconst visit = (dir: string): void => {\n\t\tlet entries;\n\t\ttry {\n\t\t\tentries = readdirSync(dir, { withFileTypes: true });\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tif (!SKIP_DIRS.has(entry.name)) visit(path.join(dir, entry.name));\n\t\t\t} else if (\n\t\t\t\tentry.isFile() &&\n\t\t\t\tSOURCE_FILE_RE.test(entry.name) &&\n\t\t\t\t!entry.name.endsWith(\".d.ts\")\n\t\t\t) {\n\t\t\t\tfiles.push(path.join(dir, entry.name));\n\t\t\t}\n\t\t}\n\t};\n\tvisit(root);\n\treturn files;\n}\n\n/**\n * The route path a file's annotation should use, derived from its manifest\n * entry: internal suffixes (`/~server`, `/_layout` etc) are stripped so e.g.\n * `posts/[id]/+page.server.ts` expects `\"/posts/[id]\"`.\n */\nexport function expectedAnnotationPath(route: Route): string {\n\tlet p = route.path;\n\tswitch (route.type) {\n\t\tcase PAGE_SERVER_ROUTE:\n\t\t\tp = p.replace(/\\/~server$/, \"\");\n\t\t\tbreak;\n\t\tcase LAYOUT_ROUTE:\n\t\t\tp = p.replace(/\\/_layout$/, \"\");\n\t\t\tbreak;\n\t\tcase LAYOUT_SERVER_ROUTE:\n\t\t\tp = p.replace(/\\/_layout\\/~server$/, \"\");\n\t\t\tbreak;\n\t\tcase HOOK_ROUTE:\n\t\t\tp = p.replace(/\\/_hook$/, \"\");\n\t\t\tbreak;\n\t\tcase HOOK_SERVER_ROUTE:\n\t\t\tp = p.replace(/\\/_hook\\/~server$/, \"\");\n\t\t\tbreak;\n\t\tcase ERROR_ROUTE:\n\t\t\tp = p.replace(/\\/_error$/, \"\");\n\t\t\tbreak;\n\t}\n\treturn p === \"\" ? \"/\" : p;\n}\n\nfunction typeNameFor(route: Route): string {\n\tswitch (route.type) {\n\t\tcase PAGE_SERVER_ROUTE:\n\t\tcase LAYOUT_SERVER_ROUTE:\n\t\t\treturn \"PageServerEndPoint\";\n\t\tcase SERVER_ROUTE:\n\t\t\treturn \"ServerEndPoint\";\n\t\tcase HOOK_ROUTE:\n\t\tcase HOOK_SERVER_ROUTE:\n\t\t\treturn \"ServerHook\";\n\t\tdefault:\n\t\t\treturn \"PageEndPoint\";\n\t}\n}\n\n/**\n * Parses the type arguments that follow an endpoint type name, returning the\n * first argument when it is a string literal (the route path), plus the index\n * after the closing `>` (or after the type name when there are no arguments).\n */\nfunction parseTypeArgs(\n\tsource: string,\n\tstart: number,\n): { routePath: string | undefined; end: number } {\n\tlet i = start;\n\twhile (i < source.length && /\\s/.test(source[i])) i++;\n\tif (source[i] !== \"<\") return { routePath: undefined, end: i };\n\ti++;\n\tlet depth = 1;\n\tlet routePath: string | undefined;\n\tlet seenComma = false;\n\twhile (i < source.length) {\n\t\tconst c = source[i];\n\t\tif (c === '\"' || c === \"'\") {\n\t\t\tconst quote = c;\n\t\t\tlet j = i + 1;\n\t\t\twhile (j < source.length && source[j] !== quote) {\n\t\t\t\tif (source[j] === \"\\\\\") j++;\n\t\t\t\tj++;\n\t\t\t}\n\t\t\tif (routePath === undefined && !seenComma) routePath = source.slice(i + 1, j);\n\t\t\ti = j + 1;\n\t\t\tcontinue;\n\t\t}\n\t\tif (c === \"<\") depth++;\n\t\telse if (c === \">\") {\n\t\t\tdepth--;\n\t\t\tif (depth === 0) return { routePath, end: i + 1 };\n\t\t} else if (c === \",\" && routePath === undefined) {\n\t\t\tseenComma = true;\n\t\t}\n\t\ti++;\n\t}\n\treturn { routePath, end: i };\n}\n\n/**\n * Parses an `as T`-style cast that follows a `satisfies T` usage, returning\n * its optional route path argument and the index after the cast.\n */\nfunction parseAsCast(\n\tsource: string,\n\tstart: number,\n): { routePath: string | undefined; end: number } | undefined {\n\tlet i = start;\n\twhile (i < source.length && /\\s/.test(source[i])) i++;\n\tif (!/^as\\b/.test(source.slice(i, i + 3))) return undefined;\n\ti += 2;\n\twhile (i < source.length && /\\s/.test(source[i])) i++;\n\tif (!TYPE_NAME_RE.test(source.slice(i))) return undefined;\n\ti = i + source.slice(i).match(TYPE_NAME_RE)![0].length;\n\treturn parseTypeArgs(source, i);\n}\n\nfunction routePathArg(expected: string, actual: string | undefined): string {\n\t// Keep the user's own (correct) path when widening a properly-annotated\n\t// export; otherwise suggest the path derived from the file's location\n\treturn `<\"${actual ?? expected}\">`;\n}\n\nfunction lineOf(source: string, index: number): number {\n\tlet line = 1;\n\tfor (let i = 0; i < index; i++) {\n\t\tif (source[i] === \"\\n\") line++;\n\t}\n\treturn line;\n}\n","import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { parse } from \"@torpor/view/compile\";\nimport type Route from \"../types/Route\";\nimport { LAYOUT_ROUTE } from \"../types/RouteType\";\nimport type Site from \"./Site\";\nimport { createApiCallCheck, resolveSpecifier, type RouteCheckIssue } from \"./checkRoutes\";\n\n/**\n * The default import of a `.torp` component from a `.ts`/`.js` route file,\n * e.g. `import component from \"@/views/Layout.torp\"`.\n */\nconst DEFAULT_TORP_IMPORT_RE = /import\\s+[A-Za-z_$][\\w$]*\\s+from\\s*[\"']([^\"']+\\.torp)[\"']/;\n\n/**\n * Checks that every `_layout` route renders its default `<slot />`.\n *\n * The layout engine composes pages by passing each layout (and finally the\n * page) as the default slot of its parent, so a layout that never renders\n * `<slot />` drops its entire content: the server renders the layout's own\n * markup with an empty content area (no error), and the first client-side\n * navigation that reuses the layout fails on a null slot region.\n *\n * Runs at build time (failing the build) and at dev startup. Best-effort and\n * static: a layout that renders `<slot />` conditionally (inside `@if`)\n * passes here, and is caught at request time by the server render warning\n * (see site/layoutSlots.ts).\n */\nexport function checkLayoutSlots(site: Site): RouteCheckIssue[] {\n\tconst issues: RouteCheckIssue[] = [];\n\tfor (const route of site.routes) {\n\t\tif (route.type === LAYOUT_ROUTE) {\n\t\t\tissues.push(...checkLayoutSlot(site, route));\n\t\t}\n\t}\n\treturn issues;\n}\n\n/**\n * Checks a single layout route's component (the `.torp` route file itself,\n * or the `.torp` file its `.ts`/`.js` endpoint re-exports as its default\n * import). Routes without a file (inline endpoints) can't hold a component,\n * so they are skipped.\n */\nexport function checkLayoutSlot(site: Site, route: Route): RouteCheckIssue[] {\n\tif (route.type !== LAYOUT_ROUTE || !route.file) return [];\n\n\tconst check = createApiCallCheck(site);\n\n\t// The component is either the route file itself (.torp) or a .ts/.js\n\t// endpoint re-exporting a .torp component as its default export\n\tlet torpFile = path.join(site.root, route.file);\n\tif (!route.file.endsWith(\".torp\")) {\n\t\tconst source = readIfExists(torpFile);\n\t\tif (source === undefined) return [];\n\t\tconst match = DEFAULT_TORP_IMPORT_RE.exec(source);\n\t\tif (!match) return [];\n\t\tconst resolved = resolveSpecifier(match[1], torpFile, check);\n\t\tif (!resolved) return [];\n\t\ttorpFile = resolved;\n\t}\n\n\tconst source = readIfExists(torpFile);\n\tif (source === undefined) return [];\n\n\t// Parse errors are reported when the file is compiled, not here\n\tconst parsed = parse(source);\n\tif (!parsed.ok || !parsed.template) return [];\n\tif (rendersDefaultSlot(parsed.template)) return [];\n\n\treturn [\n\t\t{\n\t\t\tfile: route.file,\n\t\t\tline: 1,\n\t\t\tseverity: \"error\",\n\t\t\tmessage:\n\t\t\t\t\"The layout never renders <slot />, so pages under it render without their content. \" +\n\t\t\t\t\"Every _layout component must render <slot />, or pass it down to a child component \" +\n\t\t\t\t\"it renders.\",\n\t\t},\n\t];\n}\n\nfunction readIfExists(file: string): string | undefined {\n\ttry {\n\t\tif (!existsSync(file) || !statSync(file).isFile()) return undefined;\n\t\treturn readFileSync(file, \"utf8\");\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Walks a parsed template looking for a default `<slot />` anywhere in the\n * render tree — including nested inside a child component element, which is\n * how a layout passes the page slot down (e.g. `<Shell><slot /></Shell>`).\n */\n// HACK: no types on the internal parse tree nodes (same as the prettier plugin)\nfunction rendersDefaultSlot(template: any): boolean {\n\tconst component = template.components?.[0];\n\tif (!component) return false;\n\treturn walk(component.markup);\n}\n\nfunction walk(node: any): boolean {\n\tif (\n\t\t(node.type === \"element\" || node.type === \"special\") &&\n\t\tnode.tagName === \"slot\" &&\n\t\t!node.attributes?.some((a: any) => a.name === \"name\")\n\t) {\n\t\treturn true;\n\t}\n\treturn (node.children ?? []).some(walk);\n}\n","import { readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { Plugin } from \"vite\";\nimport type { ResolvedOpenApiOptions } from \"../openapi/types\";\nimport { OPEN_API_STATE_KEY } from \"../openapi/plugin\";\nimport { normalizeBasePath, normalizeOrigin } from \"./basePath\";\nimport Site from \"./Site\";\nimport { SERVER_ROUTE } from \"../types/RouteType\";\n\nexport const MANIFEST_MODULE_ID = \"@torpor/build/manifest\";\n\nconst moduleId = MANIFEST_MODULE_ID;\n\nconst LOAD_EXPORT_RE =\n\t/[{,]\\s*load\\s*[:(]|\\bexport\\s+(?:async\\s+)?(?:function|const|let|var)\\s+load\\b|\\bexport\\s*\\{[^}]*\\bload\\b/;\n\nexport function hasLoadExport(source: string): boolean {\n\treturn LOAD_EXPORT_RE.test(source);\n}\n\n/**\n * A Vite plugin that provides information about the app to both clientEntry and\n * serverEntry.\n */\nexport default function manifest(site: Site, server = false, dev = false): Plugin {\n\treturn {\n\t\tname: \"torpor-manifest\",\n\t\tresolveId: {\n\t\t\torder: \"pre\",\n\t\t\thandler(id) {\n\t\t\t\tif (id === moduleId) {\n\t\t\t\t\treturn id;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t// @ts-ignore\n\t\tload(id, viteOptions) {\n\t\t\tif (id === moduleId) {\n\t\t\t\tlet serverRequest = server && !!viteOptions?.ssr;\n\n\t\t\t\t// Validate here, so bad config fails the build\n\t\t\t\tconst base = normalizeBasePath(site.basePath);\n\t\t\t\tif (site.sitemap && !site.origin) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`site.sitemap requires site.origin to be set (it is the host of the urls)`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (site.origin) {\n\t\t\t\t\tnormalizeOrigin(site.origin);\n\t\t\t\t}\n\t\t\t\tif (typeof site.sitemap === \"object\" && site.sitemap !== null) {\n\t\t\t\t\tif (site.sitemap.path !== undefined && !site.sitemap.path.startsWith(\"/\")) {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t`The sitemap path must be an absolute path (e.g. \"/sitemap.xml\"), got \"${site.sitemap.path}\"`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} else if (typeof site.sitemap === \"string\" && !site.sitemap.startsWith(\"/\")) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`The sitemap path must be an absolute path (e.g. \"/sitemap.xml\"), got \"${site.sitemap}\"`,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\t// If there are inline endpoints, site plugins, an OpenAPI\n\t\t\t\t// document or an env schema, and we're building for the server,\n\t\t\t\t// we need to import the config file to access them. On the\n\t\t\t\t// client, the config file is never imported, keeping server\n\t\t\t\t// code out of the client bundle.\n\t\t\t\tconst hasInline = site.routes.some((r) => r.endPoint && !r.file);\n\t\t\t\tconst hasPlugins = site.plugins.length > 0;\n\t\t\t\tconst hasOpenApi = site.pluginState.has(OPEN_API_STATE_KEY);\n\t\t\t\tconst hasEnv = !!site.env;\n\t\t\t\tconst hasMiddleware = site.middleware.length > 0;\n\t\t\t\tconst hasRuntimeSitemap = typeof site.sitemap === \"object\" && site.sitemap !== null;\n\t\t\t\tconst configImport =\n\t\t\t\t\thasInline || hasPlugins || hasOpenApi || hasEnv || hasRuntimeSitemap || hasMiddleware\n\t\t\t\t\t\t? serverRequest && site.configFile\n\t\t\t\t\t\t\t? `import __site from ${JSON.stringify(site.configFile)};`\n\t\t\t\t\t\t\t: \"\"\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\t// The env schema is handed to @torpor/build/env at startup, so\n\t\t\t\t// that `env()` calls in route code can validate against it\n\t\t\t\tconst envGlue =\n\t\t\t\t\tserverRequest && hasEnv && site.configFile\n\t\t\t\t\t\t? `import { setEnvSchema } from \"@torpor/build/env\";\nsetEnvSchema(__site.env);`\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\t// Site plugins are run when the server starts up (in dev and in\n\t\t\t\t// production), so that routes they register are available at\n\t\t\t\t// runtime. Top-level await is fine here: this module is only\n\t\t\t\t// loaded through Vite's SSR pipeline\n\t\t\t\tconst pluginLoop =\n\t\t\t\t\tserverRequest && hasPlugins\n\t\t\t\t\t\t? `for (const __plugin of __site.plugins ?? []) { await __plugin(__site); }`\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\t// The OpenAPI document endpoint is generated code (rather than an\n\t\t\t\t// inline endpoint) because it must load each route file -- which\n\t\t\t\t// only works from module code that Vite processes/bundles. The\n\t\t\t\t// options live in `site.pluginState` (set by the plugin), so they\n\t\t\t\t// are available both here and in the generated runtime code\n\t\t\t\tconst openApiOptions = site.pluginState.get(OPEN_API_STATE_KEY) as\n\t\t\t\t\t| ResolvedOpenApiOptions\n\t\t\t\t\t| undefined;\n\t\t\t\tconst openApiGlue =\n\t\t\t\t\tserverRequest && openApiOptions && site.configFile\n\t\t\t\t\t\t? openApiGlueCode(site, openApiOptions)\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\tconst openApiRoute =\n\t\t\t\t\tserverRequest && openApiOptions\n\t\t\t\t\t\t? `{ path: ${JSON.stringify(openApiOptions.path)}, type: ${SERVER_ROUTE}, endPoint: () => Promise.resolve({ default: { get: __openApiGet } }), subFolder: undefined },`\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\t// A runtime sitemap, when `site.sitemap` is a `{ get }` config:\n\t\t\t\t// a server endpoint that reads urls and serves the XML\n\t\t\t\tconst sitemapOptions =\n\t\t\t\t\ttypeof site.sitemap === \"object\" && site.sitemap !== null ? site.sitemap : undefined;\n\t\t\t\tconst sitemapGlue =\n\t\t\t\t\tserverRequest && sitemapOptions && site.configFile\n\t\t\t\t\t\t? `\nimport { sitemapResponse } from \"@torpor/build/discovery\";\nasync function __sitemapGet(event) {\n\treturn await sitemapResponse(__site.sitemap, ${JSON.stringify(base)}, event);\n}\n`\n\t\t\t\t\t\t: \"\";\n\t\t\t\tconst sitemapRoute =\n\t\t\t\t\tserverRequest && sitemapOptions\n\t\t\t\t\t\t? `{ path: ${JSON.stringify(sitemapOptions.path ?? \"/sitemap.xml\")}, type: ${SERVER_ROUTE}, endPoint: () => Promise.resolve({ default: { get: __sitemapGet } }), subFolder: undefined },`\n\t\t\t\t\t\t: \"\";\n\n\t\t\t\treturn `\n${!serverRequest ? \"const load = { default: { load: true } };\" : \"\"}\n${configImport}\n${envGlue}\n${pluginLoop}\n${openApiGlue}\n${sitemapGlue}\nexport default {\n base: ${JSON.stringify(base)},\n viewTransitions: ${!!site.viewTransitions},\n dev: ${!!dev},\n ${serverRequest && hasMiddleware ? \"middleware: __site.middleware ?? [],\" : \"\"}\n routes: [\n ${site.routes\n\t\t\t.map((r) => {\n\t\t\t\tlet endPoint: string;\n\t\t\t\tif (!r.file) {\n\t\t\t\t\t// Inline endpoint (no file)\n\t\t\t\t\tif (serverRequest) {\n\t\t\t\t\t\tconst key = `${r.path}:${r.type}`;\n\t\t\t\t\t\tendPoint = `() => Promise.resolve({ default: __site.inlineEndPoints[${JSON.stringify(key)}] })`;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Client-side stub: check if the inline\n\t\t\t\t\t\t// endpoint has a load function\n\t\t\t\t\t\tconst haveLoad =\n\t\t\t\t\t\t\ttypeof (r.endPoint as Record<string, unknown> | undefined)?.load === \"function\";\n\t\t\t\t\t\tendPoint = haveLoad ? \"() => load\" : \"undefined\";\n\t\t\t\t\t}\n\t\t\t\t} else if (serverRequest || !/server\\.(ts|js)$/.test(r.file)) {\n\t\t\t\t\tconst filePath = path.join(site.root, r.file);\n\t\t\t\t\t// NOTE: No `@vite-ignore` here, so that Vite processes the import:\n\t\t\t\t\t// in dev the module runner transforms the file on the fly, and in\n\t\t\t\t\t// a production build Rollup bundles the route into a chunk and\n\t\t\t\t\t// rewrites the import -- leaving the raw source path in place\n\t\t\t\t\t// would hand Node/wrangler `.ts`/`.torp` files it can't load\n\t\t\t\t\tconst importExpr = `() => import(\"${filePath}\")`;\n\t\t\t\t\t// A .torp file's default export is a component, so wrap it\n\t\t\t\t\t// as a PageEndPoint ({ component }) for the entries\n\t\t\t\t\tendPoint = r.file.endsWith(\".torp\")\n\t\t\t\t\t\t? `${importExpr}.then((m) => ({ default: { component: m.default } }))`\n\t\t\t\t\t\t: importExpr;\n\t\t\t\t} else {\n\t\t\t\t\t// On the client, for a server route, we need to check\n\t\t\t\t\t// whether there's a load function and set a dummy endPoint\n\t\t\t\t\t// if so. The correct endpoint will be hit in clientEntry\n\t\t\t\t\tconst haveLoad = hasLoadExport(readFileSync(path.join(site.root, r.file), \"utf8\"));\n\t\t\t\t\tendPoint = haveLoad ? \"() => load\" : \"undefined\";\n\t\t\t\t}\n\t\t\t\tconst sub = r.subFolder ? `\"${r.subFolder}\"` : \"undefined\";\n\t\t\t\treturn `{ path: \"${r.path}\", type: ${r.type}, endPoint: ${endPoint}, subFolder: ${sub} },`;\n\t\t\t})\n\t\t\t.join(\"\\n \")}\n ${openApiRoute}\n ${sitemapRoute}\n ],\n};\n`;\n\t\t\t}\n\t\t},\n\t};\n}\n\n/**\n * Generates the module code for the OpenAPI document endpoint: a map of\n * route path to endpoint loader, and a cached handler that loads every\n * endpoint and builds the document on first use.\n */\nfunction openApiGlueCode(site: Site, options: ResolvedOpenApiOptions): string {\n\tconst loaders = site.routes\n\t\t.filter((r) => r.type === SERVER_ROUTE)\n\t\t// Don't document the docs page itself\n\t\t.filter((r) => r.path !== options.docs)\n\t\t.map((r) => {\n\t\t\tif (!r.file) {\n\t\t\t\tconst key = `${r.path}:${r.type}`;\n\t\t\t\treturn `${JSON.stringify(r.path)}: () => Promise.resolve({ default: __site.inlineEndPoints[${JSON.stringify(key)}] })`;\n\t\t\t}\n\t\t\tconst filePath = path.join(site.root, r.file);\n\t\t\treturn `${JSON.stringify(r.path)}: () => import(${JSON.stringify(filePath)})`;\n\t\t})\n\t\t.join(\",\\n \");\n\n\treturn `\nimport { buildOpenApiDocument, OPEN_API_STATE_KEY } from \"@torpor/build/openapi\";\nlet __openApiDoc;\nconst __openApiRoutes = {\n ${loaders}\n};\nasync function __openApiGet() {\n if (!__openApiDoc) {\n const __entries = [];\n for (const [__path, __loader] of Object.entries(__openApiRoutes)) {\n __entries.push({ path: __path, endPoint: (await __loader()).default });\n }\n __openApiDoc = buildOpenApiDocument(__entries, __site.pluginState.get(OPEN_API_STATE_KEY));\n }\n return new Response(JSON.stringify(__openApiDoc), {\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n`;\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { createRequire, isBuiltin } from \"node:module\";\nimport path from \"node:path\";\nimport type { UserConfig } from \"vite\";\n\nexport type PackageJson = {\n\tname?: string;\n\ttorpor?: string | boolean;\n\texports?: unknown;\n\tdependencies?: Record<string, string>;\n\tdevDependencies?: Record<string, string>;\n\toptionalDependencies?: Record<string, string>;\n\tpeerDependencies?: Record<string, string>;\n\t[key: string]: unknown;\n};\n\n/**\n * Finds packages installed in the site that ship `.torp` files, e.g. icon\n * libraries like phosphor-torpor. These packages need the torpor compiler, so\n * they can't go through Vite's default pipelines: dep optimization parses\n * their files as plain JavaScript (and fails on torpor syntax like `@render`\n * or `import type` from an uncompiled source), and SSR externalization would\n * leave raw `.torp` imports that neither Node nor workerd can load.\n *\n * A package is a torpor package when it declares a `torpor` entry in its\n * package.json, or when any of its export targets is a `.torp` file. The\n * entry is usually a path (`\"torpor\": \"./lib/index.js\"`, mirroring the\n * `svelte` field convention), but packages that ship compiled output can\n * just mark themselves with `\"torpor\": true`.\n *\n * @param siteRoot The root folder of the site\n * @returns The names of the torpor packages found (may be empty)\n */\nexport default function findTorporPackages(siteRoot: string): string[] {\n\tconst { torporPackages } = collectPackages(siteRoot);\n\treturn [...torporPackages];\n}\n\n/**\n * Walks the site's dependency tree, collecting:\n *\n * - `torporPackages`: packages that ship `.torp` files and so need the torpor\n * compiler (they can't be externalized or prebundled as JavaScript)\n * - `plainDeps`: plain (non-torpor) direct dependencies of those packages.\n * Once a torpor package is bundled into the SSR build, its bare imports of\n * plain dependencies stay in the emitted bundle as external imports -- and\n * under pnpm's strict node_modules layout the app can't resolve them at\n * runtime (they're only linked inside the torpor package's own\n * node_modules), so they must be bundled too. Dependencies *of* a bundled\n * plain package don't need this: they resolve (and inline) at build time\n * from the package's own location.\n */\nfunction collectPackages(siteRoot: string): {\n\ttorporPackages: Set<string>;\n\tplainDeps: Set<string>;\n} {\n\tconst torporPackages = new Set<string>();\n\tconst plainDeps = new Set<string>();\n\n\tconst sitePackageJson = path.resolve(siteRoot, \"package.json\");\n\tif (!existsSync(sitePackageJson)) return { torporPackages, plainDeps };\n\n\tconst pkg: PackageJson = JSON.parse(readFileSync(sitePackageJson, \"utf8\"));\n\tconst visited = new Set<string>();\n\n\tconst rootRequire = createRequire(sitePackageJson);\n\tfor (const name of dependencyNames(pkg)) {\n\t\tcollectPackage(name, rootRequire, torporPackages, plainDeps, visited, false);\n\t}\n\treturn { torporPackages, plainDeps };\n}\n\n/**\n * Adds `optimizeDeps.exclude` and `ssr.noExternal` entries for packages that\n * ship `.torp` files, so that they are served/bundled through the torpor\n * compiler instead.\n *\n * The exclusions are mirrored into the SSR optimizer too: Vite's SSR\n * environment optimizer has its own `optimizeDeps` settings, and without the\n * mirror it still prebundles the package and parses its raw `.torp` files as\n * JavaScript. That only shows up on a cold dep cache (a warm cache from before\n * the package was installed masks it), so the root-level exclusion is not\n * enough.\n */\nexport function addTorporPackageConfig(siteRoot: string, config: UserConfig): void {\n\tconst { torporPackages, plainDeps } = collectPackages(siteRoot);\n\tif (torporPackages.size === 0) return;\n\n\tconfig.optimizeDeps ??= {};\n\tconfig.optimizeDeps.exclude = mergeUnique(config.optimizeDeps.exclude, [...torporPackages]);\n\n\tconfig.ssr ??= {};\n\tconst noExternal = config.ssr.noExternal;\n\t// Plain dependencies of torpor packages go through the normal pipelines in\n\t// the browser/optimizer; they only must not be left external in the SSR\n\t// build (see collectPackages)\n\tconst bundlePackages = [...torporPackages, ...plainDeps];\n\tif (noExternal === undefined) {\n\t\tconfig.ssr.noExternal = bundlePackages;\n\t} else if (Array.isArray(noExternal)) {\n\t\tnoExternal.push(...bundlePackages);\n\t}\n\t// For `true` (bundle everything) or string/regex values there is nothing\n\t// sensible to merge, and they already bundle more than we need\n\n\t// The SSR dep optimizer has its own config (the legacy `ssr.optimizeDeps`\n\t// form and the environment-scoped form used by Vite's environment API).\n\t// Mirror the exclusions into both so a cold start doesn't parse `.torp`\n\t// files as JS.\n\tconfig.ssr.optimizeDeps ??= {};\n\tconfig.ssr.optimizeDeps.exclude = mergeUnique(config.ssr.optimizeDeps.exclude, [\n\t\t...torporPackages,\n\t]);\n\n\tconfig.environments ??= {};\n\tconfig.environments.ssr ??= {};\n\tconfig.environments.ssr.optimizeDeps ??= {};\n\tconfig.environments.ssr.optimizeDeps.exclude = mergeUnique(\n\t\tconfig.environments.ssr.optimizeDeps.exclude,\n\t\t[...torporPackages],\n\t);\n}\n\n/** Appends values to an exclusion list without introducing duplicates. */\nfunction mergeUnique(existing: string[] | undefined, values: string[]): string[] {\n\treturn [...new Set([...(existing ?? []), ...values])];\n}\n\nfunction dependencyNames(pkg: PackageJson): string[] {\n\treturn [\n\t\t...Object.keys(pkg.dependencies ?? {}),\n\t\t...Object.keys(pkg.devDependencies ?? {}),\n\t\t...Object.keys(pkg.optionalDependencies ?? {}),\n\t\t...Object.keys(pkg.peerDependencies ?? {}),\n\t];\n}\n\nfunction collectPackage(\n\tname: string,\n\trequire: NodeRequire,\n\ttorporPackages: Set<string>,\n\tplainDeps: Set<string>,\n\tvisited: Set<string>,\n\tbelowTorpor: boolean,\n): void {\n\t// Some packages shadow Node builtins (e.g. a dependency literally named\n\t// \"path\"), and builtins can't contain .torp files\n\tif (isBuiltin(name)) return;\n\n\tconst packageJsonPath = resolvePackageJson(name, require);\n\tif (!packageJsonPath) return;\n\t// A package can be reached both through a plain path (where nothing needs\n\t// bundling) and through a torpor package (where it does), so the visited\n\t// key includes the path's bundling state\n\tconst visitKey = `${packageJsonPath}\\n${belowTorpor}`;\n\tif (visited.has(visitKey)) return;\n\tvisited.add(visitKey);\n\n\tlet pkg: PackageJson;\n\ttry {\n\t\tpkg = JSON.parse(readFileSync(packageJsonPath, \"utf8\"));\n\t} catch {\n\t\treturn;\n\t}\n\n\tconst isTorpor = isTorporPackage(pkg);\n\tif (isTorpor) {\n\t\ttorporPackages.add(pkg.name ?? name);\n\t} else if (belowTorpor) {\n\t\t// A plain dependency of a package that gets bundled into the SSR build\n\t\tplainDeps.add(pkg.name ?? name);\n\t}\n\n\t// Recurse into the package's own dependencies, resolved relative to it\n\t// (pnpm keeps transitive deps out of the site's top-level node_modules).\n\t// Only the direct dependencies of a bundled (torpor) package are forced\n\t// into the SSR bundle; below a bundled plain package everything resolves\n\t// at build time\n\tconst depRequire = createRequire(packageJsonPath);\n\tfor (const depName of dependencyNames(pkg)) {\n\t\tcollectPackage(depName, depRequire, torporPackages, plainDeps, visited, isTorpor);\n\t}\n}\n\nfunction isTorporPackage(pkg: PackageJson): boolean {\n\tif (pkg.torpor === true || typeof pkg.torpor === \"string\") return true;\n\treturn exportsIncludeTorp(pkg.exports);\n}\n\nfunction exportsIncludeTorp(exports: unknown): boolean {\n\tif (typeof exports === \"string\") return exports.endsWith(\".torp\");\n\tif (Array.isArray(exports)) return exports.some(exportsIncludeTorp);\n\tif (exports && typeof exports === \"object\") {\n\t\treturn Object.values(exports).some(exportsIncludeTorp);\n\t}\n\treturn false;\n}\n\nfunction resolvePackageJson(name: string, require: NodeRequire): string | undefined {\n\t// require.resolve returns the name itself for Node builtins, so guard\n\t// everything below with absolute path checks\n\ttry {\n\t\tconst packageJson = require.resolve(`${name}/package.json`);\n\t\treturn path.isAbsolute(packageJson) ? packageJson : undefined;\n\t} catch {\n\t\tlet entry: string;\n\t\ttry {\n\t\t\tentry = require.resolve(name);\n\t\t} catch {\n\t\t\t// Not resolvable through Node's resolver -- either the package\n\t\t\t// isn't installed (e.g. an optional peer), or its `exports` map\n\t\t\t// has no `.` or `./package.json` entry and both lookups above\n\t\t\t// threw ERR_PACKAGE_PATH_NOT_EXPORTED. Try the standard\n\t\t\t// node_modules lookup paths directly\n\t\t\treturn resolveFromNodeModules(name, require);\n\t\t}\n\t\tif (!path.isAbsolute(entry)) return undefined;\n\t\tlet dir = path.dirname(entry);\n\t\twhile (true) {\n\t\t\tconst packageJson = path.join(dir, \"package.json\");\n\t\t\tif (existsSync(packageJson)) return packageJson;\n\t\t\tconst parent = path.dirname(dir);\n\t\t\tif (parent === dir) return undefined;\n\t\t\tdir = parent;\n\t\t}\n\t}\n}\n\n/**\n * Finds a package's package.json by checking the standard node_modules\n * lookup paths directly, for packages that Node's resolver can't load\n * (`ERR_PACKAGE_PATH_NOT_EXPORTED`).\n */\nfunction resolveFromNodeModules(name: string, require: NodeRequire): string | undefined {\n\tfor (const dir of require.resolve.paths(name) ?? []) {\n\t\tif (!path.isAbsolute(dir)) continue;\n\t\tconst packageJson = path.join(dir, ...name.split(\"/\"), \"package.json\");\n\t\tif (existsSync(packageJson)) return packageJson;\n\t}\n\treturn undefined;\n}\n","import { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport ServerEvent from \"../server/ServerEvent\";\nimport { sitemapXml } from \"../discovery/sitemap\";\nimport prepareTemplate from \"./prepareTemplate\";\nimport type Site from \"../site/Site\";\nimport { ERROR_ROUTE, PAGE_ROUTE, PAGE_SERVER_ROUTE, LAYOUT_ROUTE } from \"../types/RouteType\";\n\n/**\n * How a `prerender` flag can appear on an endpoint: `true`/`false` to\n * include/exclude a page, or a `params` entry list for a dynamic route.\n */\nexport type PrerenderFlag = boolean | { params: Record<string, unknown>[] };\n\n/** The route shapes the prerenderer resolves from (Router.routes, Site.routes). */\ntype RouteLike = {\n\tpath: string;\n\ttype: number;\n\tendPoint: () => Promise<any>;\n\tsubFolder?: string;\n};\n\nexport type PrerenderPath = {\n\tpath: string;\n\tparams: Record<string, string> | undefined;\n};\n\n/**\n * Resolves which page paths should be prerendered, from the routes of a\n * built site, testing in order:\n *\n * 1. the page endpoint's own `prerender` flag, or the inferred-params one\n * on the sibling `+page.server` endpoint\n * 2. the nearest ancestor `_layout` endpoint's flag\n * 3. the site-level `site.prerender` setting: a boolean default, or a\n * longest-match map of exact paths (`/about`) and prefixes (`/blog/**`)\n *\n * @param routes The site's routes, including layouts and page server\n * endpoints, with lazy endpoint loaders\n * @param siteFlag The `site.prerender` value\n * @returns The paths to prerender, with route params for dynamic ones\n */\nexport async function resolvePrerenderPaths(\n\troutes: RouteLike[],\n\tsiteFlag: boolean | Record<string, boolean> | undefined,\n): Promise<PrerenderPath[]> {\n\tconst result: PrerenderPath[] = [];\n\n\tfor (const route of routes.filter((r) => r.type === PAGE_ROUTE)) {\n\t\tconst base = route.path.replace(/\\/$/, \"\");\n\n\t\tconst pageFlag = (await endpointFlag(route.endPoint)) as PrerenderFlag | undefined;\n\t\tconst serverRoute = routes.find(\n\t\t\t(r) => r.type === PAGE_SERVER_ROUTE && r.path === `${base}/~server`,\n\t\t);\n\t\tconst serverFlag = serverRoute\n\t\t\t? ((await endpointFlag(serverRoute.endPoint)) as PrerenderFlag | undefined)\n\t\t\t: undefined;\n\n\t\tconst entries = paramsEntriesOf(pageFlag) ?? paramsEntriesOf(serverFlag);\n\t\tconst ownFlag =\n\t\t\tpageFlag === undefined\n\t\t\t\t? serverFlag === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: Boolean(serverFlag)\n\t\t\t\t: Boolean(pageFlag);\n\t\tconst resolved =\n\t\t\townFlag ?? (await nearestLayoutFlag(routes, route)) ?? siteResolve(route.path, siteFlag);\n\t\tif (!resolved) continue;\n\n\t\tif (/\\[[^\\]]+\\]/.test(route.path)) {\n\t\t\tif (!entries?.length) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`The route \"${route.path}\" is marked for prerendering, but it has dynamic ` +\n\t\t\t\t\t\t`segments and no params entries were declared. Set ` +\n\t\t\t\t\t\t`\\`prerender: { params: [...] }\\` on its endpoint.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const entry of entries) {\n\t\t\t\tresult.push({ path: expandPath(route.path, entry), params: toStringParams(entry) });\n\t\t\t}\n\t\t} else {\n\t\t\tresult.push({ path: route.path || \"/\", params: undefined });\n\t\t}\n\t}\n\n\treturn result;\n}\n\nfunction paramsEntriesOf(flag: PrerenderFlag | undefined): Record<string, unknown>[] | undefined {\n\treturn typeof flag === \"object\" && flag !== null ? flag.params : undefined;\n}\n\n/**\n * Renders the prerenderable routes to static HTML files in the client\n * output, plus the `_error` page as `404.html` when the site has one.\n *\n * Called by `tb build` after the client and server builds, when the built\n * server entry (with its routes) can be imported directly, and before the\n * adapter's postbuild -- so a prerendered site ships as plain files and\n * any static host can serve it.\n *\n * @param site The loaded site config\n * @returns The number of HTML files written\n */\nexport default async function runPrerender(site: Site): Promise<number> {\n\tconst serverFolder = path.join(site.outputFolder, \"server\");\n\tconst clientFolder = path.join(site.outputFolder, \"client\");\n\tconst serverEntryPath = path.join(serverFolder, \"serverEntry.js\");\n\n\t// Load the built server entry, with its routes baked in\n\tconst serverEntry = (await import(pathToFileURL(serverEntryPath).href)) as {\n\t\tload: (ev: unknown, template: string | undefined) => Promise<Response>;\n\t\trouter: { routes: { path: string; handler: RouteLike }[] };\n\t};\n\tconst routes = serverEntry.router.routes.map((r) => r.handler);\n\n\t// Deserialize the client entry asset name the same way the Cloudflare\n\t// adapter does, so the template works the same for prerendered output\n\tlet template: string | undefined;\n\tconst siteHtml = path.join(clientFolder, \"site.html\");\n\tif (existsSync(siteHtml)) {\n\t\tconst assets = path.join(clientFolder, \"assets\");\n\t\tlet clientScript = (await fs.readdir(assets)).find((f) => f.startsWith(\"clientEntry-\"));\n\t\tif (!clientScript) {\n\t\t\tthrow new Error(\"clientEntry.js not found\");\n\t\t}\n\t\ttemplate = prepareTemplate(await fs.readFile(siteHtml, \"utf-8\"), `/assets/${clientScript}`);\n\t}\n\n\tconst entries = await resolvePrerenderPaths(routes, site.prerender);\n\n\t// Load functions may read the environment (env() uses globalThis.adapter)\n\t// @ts-ignore\n\tglobalThis.adapter ??= { env: process.env };\n\n\tconst failures: string[] = [];\n\tconst skipped: string[] = [];\n\tlet written = 0;\n\tfor (const entry of entries) {\n\t\tconst url = `http://torpor.build${entry.path}`;\n\t\tconst request = new Request(url);\n\t\tconst serverEvent = new ServerEvent(request, entry.params, new URL(url));\n\t\t// A page render embeds its server data as a `t-server-data` script (see\n\t\t// serverHandlers.loadView), so a prerendered page with a server load\n\t\t// hydrates with that data on a static host, with no `~server` request\n\t\tconst response = await serverEntry.load(serverEvent, template);\n\n\t\tif (isRedirect(response)) {\n\t\t\t// Load functions redirect for auth and first-run setup, which is\n\t\t\t// expected on a fresh site -- skip the page rather than failing\n\t\t\t// the build, so a site can ship before it's initialized\n\t\t\tskipped.push(`${entry.path} (status ${response.status})`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (response.status < 200 || response.status > 299) {\n\t\t\tfailures.push(`${entry.path} (status ${await responseStatus(response)})`);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!response.headers.get(\"Content-Type\")?.includes(\"text/html\")) {\n\t\t\tfailures.push(`${entry.path} (not an HTML response)`);\n\t\t\tcontinue;\n\t\t}\n\n\t\tawait writeFileForPath(clientFolder, entry.path, await response.text());\n\t\twritten++;\n\t}\n\n\t// The error page is useful on every static host, so render it whenever\n\t// the site has one, even when nothing else is prerendered: 404.html for\n\t// missing pages, and 500.html for the hosts that match error pages by\n\t// status. Requesting each with its status in the query yields that\n\t// status -- that's the page rendering correctly, not a failure\n\tconst errorRoute = routes.find((r) => r.type === ERROR_ROUTE);\n\tif (errorRoute && template !== undefined) {\n\t\tfor (const status of [404, 500]) {\n\t\t\tconst url = `http://torpor.build/_error?status=${status}`;\n\t\t\tconst serverEvent = new ServerEvent(new Request(url), undefined, new URL(url));\n\t\t\tconst response = await serverEntry.load(serverEvent, template);\n\t\t\tif (isRedirect(response)) {\n\t\t\t\t// The layout may redirect before the error page renders (e.g.\n\t\t\t\t// to a setup page on a fresh site) -- skip it; the host's\n\t\t\t\t// default error page is used instead\n\t\t\t\tskipped.push(`/_error (status ${response.status})`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (\n\t\t\t\tresponse.status === status &&\n\t\t\t\tresponse.headers.get(\"Content-Type\")?.includes(\"text/html\")\n\t\t\t) {\n\t\t\t\tawait fs.writeFile(path.join(clientFolder, `${status}.html`), await response.text());\n\t\t\t} else {\n\t\t\t\tfailures.push(`/_error (status ${await responseStatus(response)})`);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (skipped.length) {\n\t\tconsole.log(\n\t\t\t`Skipped prerendering ${skipped.length} route${skipped.length === 1 ? \"\" : \"s\"} ` +\n\t\t\t\t`(redirected):\\n` +\n\t\t\t\tskipped.map((s) => ` - ${s}`).join(\"\\n\"),\n\t\t);\n\t}\n\n\tif (failures.length) {\n\t\tthrow new Error(\n\t\t\t`Prerendering failed for ${failures.length} route${failures.length === 1 ? \"\" : \"s\"}:\\n` +\n\t\t\t\tfailures.map((f) => ` - ${f}`).join(\"\\n\"),\n\t\t);\n\t}\n\n\t// The sitemap, if configured, lists the URLs that were just rendered:\n\t// the set of pages that are actually static, which is exactly what a\n\t// build-time sitemap can honestly represent\n\tif (site.sitemap && site.origin && entries.length > 0) {\n\t\tconst base = site.basePath;\n\t\tconst sitemap = sitemapXml(\n\t\t\tsite.origin,\n\t\t\tbase,\n\t\t\tentries.map((entry) => entry.path),\n\t\t);\n\t\tawait fs.writeFile(\n\t\t\tpath.join(\n\t\t\t\tclientFolder,\n\t\t\t\ttypeof site.sitemap === \"string\" ? site.sitemap.slice(1) : \"sitemap.xml\",\n\t\t\t),\n\t\t\tsitemap,\n\t\t);\n\t}\n\n\treturn written;\n}\n\n/**\n * Writes an HTML file for a route path, e.g. `/` into `index.html` and\n * `/about` into `about/index.html`. Guards against route param values\n * escaping the client folder.\n */\nasync function writeFileForPath(\n\tclientFolder: string,\n\troutePath: string,\n\thtml: string,\n): Promise<void> {\n\tconst rel = routePath === \"/\" ? \"index.html\" : routePath.slice(1) + \"/index.html\";\n\tconst out = path.resolve(clientFolder, rel);\n\tconst relSafe = path.relative(clientFolder, out);\n\tif (relSafe.startsWith(\"..\") || path.isAbsolute(relSafe)) {\n\t\tthrow new Error(`The prerendered path \"${routePath}\" escaped ${clientFolder}`);\n\t}\n\tawait fs.mkdir(path.dirname(out), { recursive: true });\n\tawait fs.writeFile(out, html);\n}\n\nasync function endpointFlag(loader: () => Promise<any>): Promise<PrerenderFlag | undefined> {\n\tconst endPoint = (await loader())?.default;\n\treturn (endPoint as { prerender?: PrerenderFlag } | undefined)?.prerender;\n}\n\n/**\n * The nearest ancestor `_layout`'s flag for a page path, or undefined when\n * no layout sets one. Layouts apply within the same subFolder.\n */\nasync function nearestLayoutFlag(\n\troutes: RouteLike[],\n\troute: RouteLike,\n): Promise<boolean | undefined> {\n\tlet flag: boolean | undefined;\n\tlet flagLength = -1;\n\tfor (const candidate of routes) {\n\t\tif (candidate.type !== LAYOUT_ROUTE || candidate.subFolder !== route.subFolder) continue;\n\t\tconst base = candidate.path.replace(/\\/_layout$/, \"\");\n\t\tconst isAncestor = base === \"\" || route.path === base || route.path.startsWith(base + \"/\");\n\t\tif (!isAncestor) continue;\n\t\tconst flagOfLayout = (await endpointFlag(candidate.endPoint)) as boolean | undefined;\n\t\tif (flagOfLayout !== undefined && base.length > flagLength) {\n\t\t\tflag = flagOfLayout;\n\t\t\tflagLength = base.length;\n\t\t}\n\t}\n\treturn flag;\n}\n\nfunction siteResolve(\n\troutePath: string,\n\tsiteFlag: boolean | Record<string, boolean> | undefined,\n): boolean | undefined {\n\tif (siteFlag === undefined) return undefined;\n\tif (typeof siteFlag === \"boolean\") return siteFlag;\n\n\tlet flag: boolean | undefined;\n\tlet flagLength = -1;\n\tfor (const [pattern, value] of Object.entries(siteFlag)) {\n\t\tconst base = pattern.replace(/\\/\\*\\*$/, \"\");\n\t\tconst isPrefixMatch =\n\t\t\tbase !== pattern && (routePath === base || routePath.startsWith(base + \"/\"));\n\t\tif ((pattern === routePath || isPrefixMatch) && pattern.length > flagLength) {\n\t\t\tflag = value;\n\t\t\tflagLength = pattern.length;\n\t\t}\n\t}\n\treturn flag;\n}\n\nfunction toStringParams(entry: Record<string, unknown>): Record<string, string> {\n\tconst result: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(entry)) {\n\t\tresult[key] = String(value);\n\t}\n\treturn result;\n}\n\n/**\n * Fills a route path's `[param]` and `[...rest]` segments with the values\n * from a params entry.\n */\nexport function expandPath(routePath: string, entry: Record<string, unknown>): string {\n\treturn routePath.replace(/\\[([^\\]]+)\\]/g, (_match, name: string) => {\n\t\tconst key = name.replace(/^\\.\\.\\./, \"\");\n\t\tif (!(key in entry)) {\n\t\t\tthrow new Error(`Missing param \"${key}\" for the route \"${routePath}\" (prerendering)`);\n\t\t}\n\t\treturn String(entry[key]);\n\t});\n}\n\nfunction isRedirect(response: Response): boolean {\n\treturn response.status >= 300 && response.status < 400;\n}\n\nasync function responseStatus(response: Response): Promise<string> {\n\treturn `${response.status}${response.status === 303 ? \" redirect\" : \"\"}`;\n}\n","import torpor from \"@torpor/unplugin/vite\";\nimport { configDotenv } from \"dotenv\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { build, defineConfig, type AliasOptions } from \"vite\";\nimport Site from \"../site/Site\";\nimport { checkApiCalls, checkRoutes, reportRouteIssues } from \"../site/checkRoutes\";\nimport { checkLayoutSlots } from \"../site/checkLayoutSlots\";\nimport manifest from \"../site/manifest.ts\";\nimport tsconfigAliases, { type AliasEntry } from \"../utils/tsconfigAliases\";\nimport { addTorporPackageConfig } from \"../utils/torporPackages\";\nimport { siteEntryPaths } from \"../utils/entryPaths\";\nimport runPrerender from \"./runPrerender\";\n\n// TODO: Don't cache index.html in dev?\n// TODO: Don't reload layouts during client routing\n// TODO: Call the correct +page and +server routes when in the same folder\n\nexport default async function runBuild(site: Site): Promise<void> {\n\t// Load environment variables from a `.env` file, with defaults if not\n\t// set -- prerendering goes through the full load pipeline, so route\n\t// `load` functions can hit the database at build time\n\tconfigDotenv();\n\n\t// Check route type annotations and makeApi calls against the routes\n\t// derived from file locations, and check that layouts render their slot;\n\t// errors fail the build before anything is written\n\tlet errorCount = reportRouteIssues(checkRoutes(site));\n\terrorCount += reportRouteIssues(checkApiCalls(site));\n\terrorCount += reportRouteIssues(checkLayoutSlots(site));\n\tif (errorCount > 0) {\n\t\tthrow new Error(\n\t\t\t`Route type check failed with ${errorCount} error${errorCount === 1 ? \"\" : \"s\"} (see above)`,\n\t\t);\n\t}\n\n\t// Delete the output folder if it exists\n\tconst distFolder = site.outputFolder;\n\tif (existsSync(distFolder)) {\n\t\tawait fs.rm(distFolder, { recursive: true });\n\t}\n\tconst clientFolder = path.join(distFolder, \"client\");\n\tconst serverFolder = path.join(distFolder, \"server\");\n\n\t// HOOK: Prebuild\n\tif (site.adapter.prebuild) {\n\t\tawait site.adapter.prebuild(site);\n\t}\n\n\t// TODO: From a setting\n\t// An endpoints-only site has no site.html, so everything template-related\n\t// is optional\n\tconst siteHtml = path.resolve(site.root, \"src/site.html\");\n\tconst hasSiteHtml = existsSync(siteHtml);\n\n\t// Production always bundles the compiled entry files from the installed\n\t// package, so builds don't depend on (unshipped) framework sources\n\tconst entries = siteEntryPaths(site.root, false);\n\tconst clientScript = entries.clientEntry;\n\tconst serverScript = entries.serverEntry;\n\n\t// Build the client assets, including site.html and the route files\n\t// EXCLUDING anything with `server.js` in the name\n\tconst clientConfig = structuredClone(site.viteConfig ?? {});\n\t// Resolve tsconfig path aliases (e.g. `@/*`). Previously provided by the\n\t// default `vite-tsconfig-paths` plugin on Site; vite-plus handles it inline\n\t// for the client, but hardcodes tsconfigPaths:false on the SSR\n\t// externalization path, so mirror tsconfig `compilerOptions.paths` as Vite\n\t// `resolve.alias` to resolve them during transform for both client and SSR\n\tclientConfig.resolve ??= {};\n\tclientConfig.resolve.tsconfigPaths ??= true;\n\tclientConfig.resolve.alias = [\n\t\t...asAliasArray(clientConfig.resolve.alias),\n\t\t...tsconfigAliases(site.root),\n\t];\n\tclientConfig.plugins = [manifest(site), torpor(), ...site.vitePlugins];\n\tclientConfig.build ??= {};\n\tclientConfig.build.outDir = clientFolder;\n\t// Root-level host files (robots.txt, favicon.ico, .well-known/*, etc) in\n\t// src/public are copied verbatim into the client output root, and served\n\t// from the same folder by the dev server\n\tconst publicDir = path.resolve(site.root, \"src/public\");\n\tif (existsSync(publicDir)) {\n\t\tclientConfig.publicDir = publicDir;\n\t}\n\tclientConfig.build.rollupOptions ??= {};\n\tclientConfig.build.rollupOptions.input = [\n\t\t...(hasSiteHtml ? [siteHtml] : []),\n\t\tclientScript,\n\t\t...site.routes\n\t\t\t.filter((r) => r.file && !/server\\.(ts|js)$/.test(r.file))\n\t\t\t.map((r) => path.resolve(site.root, r.file!)),\n\t\t...site.inputs.filter((f) => !/server\\.(ts|js)$/.test(f)),\n\t];\n\tclientConfig.build.ssrManifest = true;\n\tawait build(defineConfig(clientConfig));\n\n\t// Build the server assets, including the server entry script and the route\n\t// files\n\tconst serverConfig = structuredClone(site.viteConfig ?? {});\n\t// Resolve tsconfig path aliases (e.g. `@/*`), as above\n\tserverConfig.resolve ??= {};\n\tserverConfig.resolve.tsconfigPaths ??= true;\n\tserverConfig.resolve.alias = [\n\t\t...asAliasArray(serverConfig.resolve.alias),\n\t\t...tsconfigAliases(site.root),\n\t];\n\tserverConfig.plugins = [manifest(site, true), torpor(), ...site.vitePlugins];\n\tserverConfig.build ??= {};\n\tserverConfig.build.outDir = serverFolder;\n\t// Bundle packages that ship `.torp` files into the server build, as they\n\t// need the torpor compiler (Node/workerd can't load them externalized)\n\taddTorporPackageConfig(site.root, serverConfig);\n\tserverConfig.build.rollupOptions ??= {};\n\tserverConfig.build.rollupOptions.input = [\n\t\tserverScript,\n\t\t...site.routes.filter((r) => r.file).map((r) => path.resolve(site.root, r.file!)),\n\t\t...site.inputs,\n\t];\n\tserverConfig.build.ssr = serverScript;\n\tawait build(defineConfig(serverConfig));\n\n\t// Move the site.html file into /client\n\t// HACK: Should do this in Rollup if possible?\n\tif (hasSiteHtml) {\n\t\tawait fs.rename(\n\t\t\tpath.join(clientFolder, \"src\", \"site.html\"),\n\t\t\tpath.join(clientFolder, \"site.html\"),\n\t\t);\n\t\tawait fs.rm(path.join(clientFolder, \"src\"), { recursive: true });\n\t}\n\n\t// Prerender routes marked with `prerender` -- including everything\n\t// inherited from layouts and site.prerender -- to static HTML files in\n\t// the client output, plus the error page as 404.html. Any static host\n\t// can then serve dist/client directly\n\tconst prerendered = await runPrerender(site);\n\tif (prerendered > 0) {\n\t\tconsole.log(`[torpor] Prerendered ${prerendered} route${prerendered === 1 ? \"\" : \"s\"}`);\n\t}\n\n\t// HOOK: Postbuild\n\tif (site.adapter.postbuild) {\n\t\tawait site.adapter.postbuild(site);\n\t}\n}\n\nfunction asAliasArray(alias: AliasOptions | undefined): AliasEntry[] {\n\t// Normalize an existing `resolve.alias` value (array | object | undefined)\n\t// into an array so we can concatenate our tsconfig-derived aliases.\n\tif (!alias) return [];\n\tif (Array.isArray(alias)) return alias;\n\treturn Object.entries(alias).map(([find, replacement]) => ({ find, replacement }));\n}\n","import { createHash } from \"node:crypto\";\nimport {\n\texistsSync,\n\treadFileSync,\n\treaddirSync,\n\trealpathSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport type { PackageJson } from \"../utils/torporPackages\";\n\n/**\n * Vite's dep-optimization cache (node_modules/.vite) keys off the lockfile\n * and config, but not the content of workspace packages. When a workspace\n * package is rebuilt while the cache holds prebundled copies of it, dev SSR\n * keeps executing the stale modules -- producing bizarre errors (missing\n * runtime identifiers, \"$cache must be used in a getter\", ...) that only a\n * manual cache delete fixes.\n *\n * clearStaleDepCache runs at `tb --dev` startup: it fingerprints every\n * workspace package the site depends on (path, size and mtime of each file)\n * and, when the fingerprint differs from the previous run, deletes the cache\n * so Vite re-optimizes from the rebuilt packages.\n *\n * Live rebuilds while the server is up are still not hot-invalidated (that\n * needs a watcher feeding Vite's module graph); this closes the \"restart and\n * hope you remember the trick\" gap.\n */\n\nconst STORE_NAME = \".torpor-dev-cache.json\";\n\n/**\n * The dep cache a dev server should use: Vite's default\n * (`<siteRoot>/node_modules/.vite`) would be shared by every app whose\n * `site.root` is the same -- e.g. a workspace package that owns the views and\n * is used by both a web and an Electron app. Those apps have different configs\n * (aliases, plugins, adapter), so they optimize different dep graphs; sharing\n * one directory makes each rewrite the other's `_metadata.json` (browser\n * hashes go stale, Vite answers 504) and lets one app's startup clear the\n * other's running cache. Derive a directory from the config file instead.\n */\nexport function defaultDepCacheDir(siteRoot: string, configFile?: string): string {\n\tconst base = path.join(siteRoot, \"node_modules\", \".vite\");\n\tif (!configFile) return base;\n\tconst absolute = path.resolve(configFile);\n\tconst name = path\n\t\t.basename(absolute)\n\t\t.replace(/\\.[^.]+$/, \"\")\n\t\t.replace(/[^\\w.-]+/g, \"-\");\n\tconst hash = createHash(\"sha1\").update(absolute).digest(\"hex\").slice(0, 8);\n\treturn path.join(base, `${name}-${hash}`);\n}\n\n/**\n * Clears the dev dep cache when workspace packages changed since the last dev\n * run. Returns true when the cache was removed.\n *\n * @param cacheDir The Vite cache directory (see `defaultDepCacheDir`). Defaults\n * to `<siteRoot>/node_modules/.vite`.\n */\nexport function clearStaleDepCache(\n\tsiteRoot: string,\n\tcacheDir: string = path.join(siteRoot, \"node_modules\", \".vite\"),\n\tlog?: (message: string) => void,\n): boolean {\n\ttry {\n\t\tconst workspaceRoot = findWorkspaceRoot(siteRoot);\n\t\tif (!workspaceRoot) return false;\n\n\t\tconst storePath = path.join(siteRoot, \"node_modules\", STORE_NAME);\n\n\t\tconst fingerprint = fingerprintWorkspacePackages(siteRoot, workspaceRoot);\n\t\tif (fingerprint === undefined) return false;\n\n\t\tconst previous = readStore(storePath);\n\n\t\tlet cleared = false;\n\t\tif (existsSync(cacheDir) && previous !== fingerprint) {\n\t\t\trmSync(cacheDir, { recursive: true, force: true });\n\t\t\tcleared = true;\n\t\t\tlog?.(\"Workspace packages changed; clearing the Vite dep cache\");\n\t\t}\n\t\twriteFileSync(storePath, JSON.stringify({ fingerprint }));\n\n\t\treturn cleared;\n\t} catch (e) {\n\t\tif (process.env.TORPOR_DEBUG_CACHE) throw e;\n\t\t// Never break dev startup over cache bookkeeping\n\t\treturn false;\n\t}\n}\n\nexport function findWorkspaceRoot(from: string): string | undefined {\n\tlet dir = path.resolve(from);\n\twhile (true) {\n\t\t// pnpm-style marker, or a root package.json declaring npm workspaces\n\t\tif (existsSync(path.join(dir, \"pnpm-workspace.yaml\"))) {\n\t\t\treturn dir;\n\t\t}\n\t\tif (hasWorkspacesField(dir)) {\n\t\t\treturn dir;\n\t\t}\n\t\tconst parent = path.dirname(dir);\n\t\tif (parent === dir) return undefined;\n\t\tdir = parent;\n\t}\n}\n\nfunction hasWorkspacesField(dir: string): boolean {\n\tconst packageJsonPath = path.join(dir, \"package.json\");\n\tif (!existsSync(packageJsonPath)) return false;\n\ttry {\n\t\tconst pkg: PackageJson = JSON.parse(readFileSync(packageJsonPath, \"utf8\"));\n\t\treturn Array.isArray(pkg.workspaces) && pkg.workspaces.length > 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction readStore(storePath: string): string | undefined {\n\tif (!existsSync(storePath)) return undefined;\n\ttry {\n\t\tconst store = JSON.parse(readFileSync(storePath, \"utf8\")) as { fingerprint?: string };\n\t\treturn store.fingerprint;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Resolves every site dependency that lives inside the workspace to its\n * package folder. Shared with the other dev-startup checks (e.g. the stale\n * .torp copy report), which need the same set of packages.\n */\nexport function workspaceDependencyDirs(siteRoot: string, workspaceRoot: string): string[] {\n\tconst sitePackageJson = path.join(siteRoot, \"package.json\");\n\tif (!existsSync(sitePackageJson)) return [];\n\n\tconst pkg: PackageJson = JSON.parse(readFileSync(sitePackageJson, \"utf8\"));\n\tconst require = createRequire(sitePackageJson);\n\n\tconst packageDirs = new Set<string>();\n\tfor (const name of dependencyNames(pkg)) {\n\t\tconst dir = resolvePackageDir(name, require);\n\t\tif (dir && insideWorkspace(realpathSync(dir), workspaceRoot)) {\n\t\t\tpackageDirs.add(realpathSync(dir));\n\t\t}\n\t}\n\treturn [...packageDirs].sort();\n}\n\nfunction fingerprintWorkspacePackages(siteRoot: string, workspaceRoot: string): string | undefined {\n\tconst sitePackageJson = path.join(siteRoot, \"package.json\");\n\tif (!existsSync(sitePackageJson)) return undefined;\n\n\tconst packageDirs = workspaceDependencyDirs(siteRoot, workspaceRoot);\n\tif (packageDirs.length === 0) return undefined;\n\n\tconst hash = createHash(\"sha1\");\n\tfor (let dir of packageDirs) {\n\t\thash.update(`package:${dir}\\n`);\n\t\tfingerprintDir(dir, dir, hash);\n\t}\n\treturn hash.digest(\"hex\");\n}\n\nfunction dependencyNames(pkg: PackageJson): string[] {\n\treturn [...Object.keys(pkg.dependencies ?? {}), ...Object.keys(pkg.devDependencies ?? {})];\n}\n\nfunction resolvePackageDir(name: string, require: NodeRequire): string | undefined {\n\ttry {\n\t\tconst packageJsonPath = require.resolve(`${name}/package.json`);\n\t\treturn path.dirname(packageJsonPath);\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction insideWorkspace(dir: string, workspaceRoot: string): boolean {\n\tconst relative = path.relative(workspaceRoot, dir);\n\treturn relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative));\n}\n\nfunction fingerprintDir(dir: string, root: string, hash: import(\"node:crypto\").Hash): void {\n\tfor (let entry of readdirSync(dir, { withFileTypes: true })) {\n\t\tif (entry.name === \"node_modules\" || entry.name === \".git\") continue;\n\t\tconst full = path.join(dir, entry.name);\n\t\tif (entry.isDirectory()) {\n\t\t\tfingerprintDir(full, root, hash);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!entry.isFile()) continue;\n\t\tconst stats = statSync(full);\n\t\t// NOTE: hash.update takes (data, encoding) -- join into one string\n\t\thash.update(\n\t\t\t`file:${path.relative(root, full).replaceAll(\"\\\\\", \"/\")}:${stats.size}:${Math.floor(stats.mtimeMs)}\\n`,\n\t\t);\n\t}\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport { createServer as createViteServer, type ViteDevServer } from \"vite\";\nimport Site from \"../site/Site\";\n\n/**\n * Finds the site.config.js/ts file in the given folder.\n */\nexport function findConfigFile(folder: string): string {\n\tconst jsConfigFile = path.join(folder, \"site.config.js\");\n\tconst tsConfigFile = path.join(folder, \"site.config.ts\");\n\tif (fs.existsSync(jsConfigFile)) return jsConfigFile;\n\tif (fs.existsSync(tsConfigFile)) return tsConfigFile;\n\tthrow new Error(\"site.config file not found\");\n}\n\n/**\n * Creates the temporary Vite server used to load the site config, so that\n * local TS imports (e.g. a routes.ts file) and path aliases are resolved\n * correctly. Kept separate from the app's dev server: the config is loaded\n * before that server exists.\n */\nexport function createConfigVite(): Promise<ViteDevServer> {\n\treturn createViteServer({\n\t\tserver: { middlewareMode: true },\n\t\tappType: \"custom\",\n\t\tresolve: { tsconfigPaths: true },\n\t\toptimizeDeps: { noDiscovery: true },\n\t});\n}\n\n/**\n * Loads (or, when the config module has been invalidated, re-loads) the site\n * config through an existing config Vite server and runs its plugins.\n */\nexport async function loadSiteFromVite(vite: ViteDevServer, configFile: string): Promise<Site> {\n\tconst site = (await vite.ssrLoadModule(configFile)).default as Site;\n\tsite.configFile = configFile;\n\n\tif (!site || !site.root || !site.routes) {\n\t\tthrow new Error(\"Invalid site in config file\");\n\t}\n\n\t// Run the site's plugins. The manifest plugin also runs them when the\n\t// server starts up (dev SSR and production), so that plugin routes are\n\t// registered in the runtime as well\n\tfor (const plugin of site.plugins) {\n\t\tawait plugin(site);\n\t}\n\n\treturn site;\n}\n\n/**\n * Looks for and loads a site.config.js/ts file in the working directory,\n * running the site's plugins. The Vite server used to load the config is\n * returned as well, so that (for example) route files can be loaded through\n * it; callers are responsible for closing it.\n */\nexport async function loadSite(folder: string): Promise<{ site: Site; vite: ViteDevServer }> {\n\tconst configFile = findConfigFile(folder);\n\n\tconst vite = await createConfigVite();\n\ttry {\n\t\tconst site = await loadSiteFromVite(vite, configFile);\n\t\treturn { site, vite };\n\t} catch (error) {\n\t\tawait vite.close();\n\t\tthrow error;\n\t}\n}\n\n/**\n * The site-root files the config depends on -- the config itself and any\n * modules it imports (e.g. a `routes.ts` that calls `addRoute`). The dev\n * server watches these so route changes defined in code are picked up, not\n * just edits to `site.config.ts` itself.\n */\nexport function configDependencyFiles(vite: ViteDevServer, root: string): Set<string> {\n\tconst files = new Set<string>();\n\tconst graph = vite.environments.ssr.moduleGraph;\n\tfor (const mod of graph.idToModuleMap.values()) {\n\t\tif (mod.file && isInside(root, mod.file)) {\n\t\t\tfiles.add(mod.file);\n\t\t}\n\t}\n\treturn files;\n}\n\nfunction isInside(dir: string, file: string): boolean {\n\tconst rel = path.relative(dir, file);\n\treturn rel === \"\" || (!rel.startsWith(\"..\") && !path.isAbsolute(rel));\n}\n","import { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { PackageJson } from \"../utils/torporPackages\";\nimport { findWorkspaceRoot, workspaceDependencyDirs } from \"./depCache\";\n\n/**\n * Workspace packages that ship copies of their .torp components (e.g.\n * @torpor/ui copies its src .torp files into dist/ during its build) can go\n * stale: a site resolves the package to its dist folder, so edits to src\n * silently keep serving the OLD components until the package is rebuilt.\n * The symptom is confusing -- e.g. a TypeError about a renamed slot prop\n * after a component's API changed.\n *\n * reportStaleTorpCopies runs at `tb --dev` startup: for every workspace\n * dependency with both src and dist folders, it compares the .torp files and\n * reports anything missing from dist, differing from src, or left over in\n * dist without a src file.\n */\n\n/**\n * Reports stale dist .torp copies in the site's workspace dependencies.\n * Never throws -- a broken check must not break dev startup.\n */\nexport function reportStaleTorpCopies(siteRoot: string, log?: (message: string) => void): void {\n\ttry {\n\t\tconst workspaceRoot = findWorkspaceRoot(siteRoot);\n\t\tif (!workspaceRoot) return;\n\n\t\tfor (const dir of workspaceDependencyDirs(siteRoot, workspaceRoot)) {\n\t\t\tconst srcFolder = path.join(dir, \"src\");\n\t\t\tconst distFolder = path.join(dir, \"dist\");\n\t\t\t// Only packages that ship dist copies of src .torp files are\n\t\t\t// checked; packages without the folders (or with neither .torp\n\t\t\t// set) are skipped\n\t\t\tif (!existsSync(srcFolder) || !existsSync(distFolder)) continue;\n\t\t\tconst src = collectTorpFiles(srcFolder);\n\t\t\tconst dist = collectTorpFiles(distFolder);\n\t\t\tif (src.size === 0 && dist.size === 0) continue;\n\n\t\t\tconst problems: string[] = [];\n\t\t\tfor (const [rel, content] of src) {\n\t\t\t\tconst distContent = dist.get(rel);\n\t\t\t\tif (distContent === undefined) {\n\t\t\t\t\tproblems.push(`${rel} (not copied to dist)`);\n\t\t\t\t} else if (distContent !== content) {\n\t\t\t\t\tproblems.push(`${rel} (differs from src)`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const rel of dist.keys()) {\n\t\t\t\tif (!src.has(rel)) {\n\t\t\t\t\tproblems.push(`${rel} (left over in dist, no src file)`);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (problems.length === 0) continue;\n\n\t\t\tconst shown = problems\n\t\t\t\t.slice(0, 5)\n\t\t\t\t.map((p) => ` ${p}`)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst more = problems.length > 5 ? `\\n ... and ${problems.length - 5} more` : \"\";\n\t\t\tlog?.(\n\t\t\t\t`${packageLabel(dir, workspaceRoot)}'s dist .torp copies are stale, so the site is ` +\n\t\t\t\t\t`serving OLD components:\\n${shown}${more}\\n` +\n\t\t\t\t\t`Rebuild the package (e.g. \\`pnpm build\\` in ` +\n\t\t\t\t\t`${path.relative(workspaceRoot, dir) || \".\"}) and restart \\`tb --dev\\`.`,\n\t\t\t);\n\t\t}\n\t} catch (e) {\n\t\tif (process.env.TORPOR_DEBUG_CACHE) throw e;\n\t}\n}\n\nfunction collectTorpFiles(folder: string): Map<string, string> {\n\tconst files = new Map<string, string>();\n\tcollect(folder, folder, files);\n\treturn files;\n}\n\nfunction collect(folder: string, root: string, files: Map<string, string>): void {\n\tfor (const entry of readdirSync(folder, { withFileTypes: true })) {\n\t\tif (entry.name === \"node_modules\" || entry.name === \".git\") continue;\n\t\tconst full = path.join(folder, entry.name);\n\t\tif (entry.isDirectory()) {\n\t\t\tcollect(full, root, files);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!entry.isFile() || !entry.name.endsWith(\".torp\")) continue;\n\t\tfiles.set(path.relative(root, full).replaceAll(\"\\\\\", \"/\"), readFileSync(full, \"utf8\"));\n\t}\n}\n\nfunction packageLabel(dir: string, workspaceRoot: string): string {\n\ttry {\n\t\tconst pkg: PackageJson = JSON.parse(readFileSync(path.join(dir, \"package.json\"), \"utf8\"));\n\t\tif (pkg.name) return pkg.name;\n\t} catch {\n\t\t// Fall through to the relative path\n\t}\n\treturn path.relative(workspaceRoot, dir) || dir;\n}\n","import torpor from \"@torpor/unplugin/vite\";\nimport { configDotenv } from \"dotenv\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n\ttype AliasOptions,\n\tcreateServer as createViteServer,\n\ttype Plugin,\n\ttype UserConfig,\n\ttype ViteDevServer,\n} from \"vite\";\nimport Site from \"../site/Site.ts\";\nimport {\n\tcheckApiCallSource,\n\tcheckApiCalls,\n\tcheckRoute,\n\tcheckRoutes,\n\tcreateApiCallCheck,\n\ttype RouteCheckIssue,\n\treportRouteIssues,\n} from \"../site/checkRoutes\";\nimport manifest, { MANIFEST_MODULE_ID } from \"../site/manifest.ts\";\nimport { checkLayoutSlot, checkLayoutSlots } from \"../site/checkLayoutSlots\";\nimport { LAYOUT_ROUTE } from \"../types/RouteType\";\nimport tsconfigAliases, { type AliasEntry } from \"../utils/tsconfigAliases\";\nimport { addTorporPackageConfig } from \"../utils/torporPackages\";\nimport { detectSourceMode, siteEntryPaths } from \"../utils/entryPaths\";\nimport devPlugin from \"./devPlugin.ts\";\nimport { clearStaleDepCache, defaultDepCacheDir } from \"./depCache\";\nimport { configDependencyFiles, loadSite } from \"./loadSite.ts\";\nimport { reportStaleTorpCopies } from \"./staleTorpCopies\";\n\n/**\n * @param configVite The Vite server used to load the site config (see\n * `loadSite`). Its module graph tells the dev server which files the config\n * imports, so `addRoute` calls in those files (e.g. a `routes.ts`) trigger a\n * route reload too. Without it, only file-based routes are reloaded.\n */\nexport default async function runDev(site: Site, configVite?: ViteDevServer): Promise<void> {\n\t// Create the Vite dev server. Unlike the previous middleware-mode setup, we\n\t// let Vite own the HTTP server (so HMR/websockets work natively) and let the\n\t// adapter's `dev()` plugin(s) handle SSR via configureServer.\n\tconst config = structuredClone(site.viteConfig ?? {});\n\tconfig.appType = \"custom\";\n\tconfig.server ??= {};\n\tconfig.server.host ??= \"localhost\";\n\t// Give each site config its own dep cache. Vite's default lives under\n\t// `site.root`, which several apps may share (e.g. a web and an Electron app\n\t// that both build from the same views package); sharing it lets them\n\t// rewrite each other's optimized deps and clear each other's cache\n\tconst cacheDir = config.cacheDir\n\t\t? path.resolve(site.root, config.cacheDir)\n\t\t: defaultDepCacheDir(site.root, site.configFile);\n\tconfig.cacheDir = cacheDir;\n\t// Root-level host files (robots.txt, favicon.ico, etc) in src/public are\n\t// served by Vite's middleware in dev and copied into the build output\n\tconst publicDir = path.resolve(site.root, \"src/public\");\n\tif (existsSync(publicDir)) {\n\t\tconfig.publicDir = publicDir;\n\t}\n\t// Resolve tsconfig path aliases (e.g. `@/*`). Previously provided by the\n\t// default `vite-tsconfig-paths` plugin on Site; vite-plus handles it inline\n\tconfig.resolve ??= {};\n\tconfig.resolve.tsconfigPaths ??= true;\n\t// When the framework itself is linked into the app (workspace/link:\n\t// installs), resolve `@torpor/view` and `@torpor/build/dev` from source via\n\t// their `torpor:source` export conditions, so framework changes take effect\n\t// without rebuilding dist. Registry installs run the compiled dist.\n\t//\n\t// Note: this must be a custom condition, not Vite's built-in `development`\n\t// one — Vite's dev server activates `development` by default, which made\n\t// registry installs resolve the unpublished `src/` files and fail.\n\tconst sourceMode = detectSourceMode(site.root);\n\tif (sourceMode) {\n\t\tconfig.resolve.conditions ??= [];\n\t\tconfig.resolve.conditions.push(\"torpor:source\");\n\t}\n\t// vite-plus' `tsconfigPaths` isn't honored by the SSR module-runner's\n\t// externalization path (it hardcodes tsconfigPaths:false), so dev SSR can't\n\t// resolve path aliases. Mirror tsconfig `compilerOptions.paths` as Vite\n\t// `resolve.alias` so they resolve during transform for both client and SSR.\n\tconfig.resolve.alias = [...asAliasArray(config.resolve.alias), ...tsconfigAliases(site.root)];\n\n\t// The adapter provides the dev-runtime plugin(s); fall back to the\n\t// framework's Node-runtime plugin when it doesn't.\n\tconst adapterDev = site.adapter.dev?.(site);\n\tconst devPlugins = normalizePlugins(adapterDev ?? devPlugin(site, sourceMode));\n\n\tconfig.plugins = [\n\t\tmanifest(site, true, true),\n\t\ttorpor({ dev: true }),\n\t\t...devPlugins,\n\t\t...site.vitePlugins,\n\t];\n\n\t// HACK: To be able to import `.torp` files from barrel files in\n\t// node_modules, we need to add their libraries to `ssr.noExternal` in\n\t// site.config.ts, and let the dep optimizer know how to compile them\n\t// here. The optimizer is a rolldown build, so it needs a rolldown-shaped\n\t// plugin (the vite export) -- an esbuild-shaped one is silently ignored\n\taddTorpOptimizerSettings((config.optimizeDeps ??= {}));\n\n\t// Packages that ship `.torp` files (e.g. icon libraries) need the torpor\n\t// compiler: dep optimization would parse them as plain JavaScript and\n\t// fail, and SSR externalization would leave raw `.torp` imports that\n\t// Node/workerd can't load. Exclude them from optimization and mark them\n\t// for SSR bundling so they go through the torpor plugin\n\taddTorporPackageConfig(site.root, config);\n\n\t// The SSR environment optimizer has its own settings; mirror the compiler\n\t// setup there too. Without this, a cold dep cache still prebundles torpor\n\t// packages (and parses their `.torp` files as JS) even though the root\n\t// optimizer excludes them.\n\taddTorpOptimizerSettings(((config.ssr ??= {}).optimizeDeps ??= {}));\n\taddTorpOptimizerSettings((((config.environments ??= {}).ssr ??= {}).optimizeDeps ??= {}));\n\n\t// Workspace packages may have been rebuilt since the last dev run; drop\n\t// this config's Vite dep cache so SSR never executes stale prebundled\n\t// modules\n\tclearStaleDepCache(site.root, cacheDir, (message) => console.log(`\\n${message}`));\n\n\t// A workspace package with dist .torp copies (e.g. @torpor/ui) whose src\n\t// changed without a rebuild serves OLD components to the site, silently;\n\t// report the drift so it can be fixed with a rebuild\n\treportStaleTorpCopies(site.root, (message) => console.log(`\\n${message}`));\n\n\t// Load environment variables from a `.env` file, with defaults if not set\n\tconfigDotenv();\n\n\tprocess.env.PROTOCOL ??= \"http:\";\n\tprocess.env.HOST ??= \"localhost\";\n\tprocess.env.PORT ??= \"7059\";\n\n\t// Honor PORT (env or .env) for the dev server port, matching --preview;\n\t// fall back to the default when it doesn't parse to a number\n\tconst envPort = parseInt(process.env.PORT);\n\tif (!Number.isNaN(envPort)) {\n\t\tconfig.server.port ??= envPort;\n\t}\n\n\tconst connectingUrl = `${process.env.PROTOCOL}//${process.env.HOST}:${process.env.PORT}`;\n\tconsole.log(`\\nConnecting to ${connectingUrl}`);\n\n\tconst vite = await createViteServer(config);\n\n\t// Load the SSR entry once before binding the listener: it triggers Vite's\n\t// first dependency optimization, which otherwise settles down (reloading\n\t// the server) right after \"Listening on ...\" -- dropping any request in\n\t// flight at that moment, so clients see an empty reply\n\tawait warmServerEntry(vite, site, sourceMode);\n\n\tawait vite.listen();\n\n\twatchRoutes(site, vite, configVite);\n\n\tconst listeningUrl = vite.resolvedUrls?.local?.[0] ?? connectingUrl;\n\tconsole.log(`Listening on ${listeningUrl}\\n`);\n}\n\n/**\n * Loads the SSR entry so the first dependency optimization (and any\n * optimizer-driven server reload) happens before the listener is bound,\n * rather than on the first real request.\n */\nasync function warmServerEntry(\n\tvite: ViteDevServer,\n\tsite: Site,\n\tsourceMode: boolean,\n): Promise<void> {\n\ttry {\n\t\tconst { serverEntry } = siteEntryPaths(site.root, sourceMode);\n\t\tawait vite.ssrLoadModule(serverEntry);\n\t} catch (e) {\n\t\t// Never block startup over warmup -- the first real request surfaces\n\t\t// errors as before\n\t\tif (process.env.TORPOR_DEBUG_WARMUP) throw e;\n\t}\n}\n\n/**\n * Reports route type issues at startup, then re-checks route files and\n * `makeApi` calls as they change so annotation problems surface during\n * development without failing the dev server.\n *\n * Also watches the config's import graph and the registered route folders,\n * re-loading the site config when route definitions change (edits to\n * `site.config.ts` or a `routes.ts` it imports) or when route files are added\n * or removed. The re-loaded state is swapped onto the live site, the generated\n * manifest invalidated, and a full client reload triggered, so the running\n * server picks up the change without a restart.\n */\nfunction watchRoutes(site: Site, vite: ViteDevServer, configVite?: ViteDevServer): void {\n\treportRouteIssues(checkRoutes(site));\n\treportRouteIssues(checkApiCalls(site));\n\treportRouteIssues(checkLayoutSlots(site));\n\n\t// Map absolute route file paths to their manifest entries, so changed\n\t// files can be re-checked against their derived route. Layout route files\n\t// are included for their slot check (a .torp layout is its own component)\n\tconst buildRouteFiles = (): Map<string, (typeof site.routes)[number]> =>\n\t\tnew Map(\n\t\t\tsite.routes\n\t\t\t\t.filter(\n\t\t\t\t\t(r) => r.file?.endsWith(\".ts\") || (r.file?.endsWith(\".torp\") && r.type === LAYOUT_ROUTE),\n\t\t\t\t)\n\t\t\t\t.map((r) => [path.resolve(site.root, r.file!), r]),\n\t\t);\n\tlet routeFiles = buildRouteFiles();\n\tconst apiCheck = createApiCallCheck(site);\n\t// Only report when a file's issues change, to avoid repeating the same\n\t// warnings on every save\n\tconst reported = new Map<string, string>();\n\n\tconst report = (file: string, issues: RouteCheckIssue[]) => {\n\t\tconst key = JSON.stringify(issues);\n\t\tif (reported.get(file) === key) return;\n\t\treported.set(file, key);\n\t\treportRouteIssues(issues);\n\t};\n\n\tconst recheck = (file: string): void => {\n\t\tconst route = routeFiles.get(file);\n\t\tif (route) {\n\t\t\treport(\n\t\t\t\tfile,\n\t\t\t\troute.type === LAYOUT_ROUTE ? checkLayoutSlot(site, route) : checkRoute(site, route),\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (!/\\.(ts|js|torp)$/.test(file)) return;\n\t\tlet source: string;\n\t\ttry {\n\t\t\tsource = readFileSync(file, \"utf8\");\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\t\treport(file, checkApiCallSource(source, file, apiCheck));\n\t};\n\n\t// Files that affect the route table: the config's import graph (addRoute\n\t// definitions, plugins, inline endpoints) and the route folders (route\n\t// files are read from disk by addRouteFolder, not imported). Recomputed\n\t// after each reload, since the config may start importing new files.\n\t//\n\t// The config and the modules it imports live beside the config file, which\n\t// can sit outside `site.root` once the config reassigns it (e.g. Mallet\n\t// points `site.root` at a subpackage). Reload and watch from that folder,\n\t// not the mutable `site.root`, so a route change doesn't throw\n\t// \"site.config file not found\" and leave the client stale.\n\tconst configFolder = site.configFile ? path.dirname(site.configFile) : site.root;\n\tlet configDeps =\n\t\tconfigVite && site.configFile\n\t\t\t? configDependencyFiles(configVite, configFolder)\n\t\t\t: new Set<string>();\n\tconst inRouteFolder = (file: string): boolean =>\n\t\tsite.routeFolders.some((f) => isInside(path.resolve(site.root, f.folder), file));\n\n\t// Re-load the site config and swap its route state onto the live site.\n\t// Serialized so concurrent add/unlink events (e.g. a folder rename) can't\n\t// interleave, and guarded so a bad config save doesn't crash the server\n\tlet pending = Promise.resolve();\n\tconst reload = (): void => {\n\t\tif (!site.configFile) return;\n\t\tpending = pending\n\t\t\t.then(async () => {\n\t\t\t\t// Load the config on a fresh server rather than re-loading it\n\t\t\t\t// through the one that first read it: doing that from inside\n\t\t\t\t// its own watcher cycle deadlocks\n\t\t\t\tconst { site: fresh, vite: freshVite } = await loadSite(configFolder);\n\t\t\t\ttry {\n\t\t\t\t\tconfigDeps = configDependencyFiles(freshVite, configFolder);\n\t\t\t\t\tif (!site.applyRouteState(fresh)) return;\n\t\t\t\t} finally {\n\t\t\t\t\tawait freshVite.close();\n\t\t\t\t}\n\t\t\t\trouteFiles = buildRouteFiles();\n\t\t\t\treportRouteIssues(checkRoutes(site));\n\t\t\t\treportRouteIssues(checkApiCalls(site));\n\t\t\t\treportRouteIssues(checkLayoutSlots(site));\n\t\t\t\tinvalidateManifest(vite);\n\t\t\t\tvite.ws.send({ type: \"full-reload\", path: \"*\" });\n\t\t\t})\n\t\t\t.catch((e) => console.error(e));\n\t};\n\n\t// Route-file edits are `change` events and are handled by `recheck`/HMR\n\t// (the route path is derived from the filename, so an edit doesn't change\n\t// the route table); only file-set events and config-dependency edits need\n\t// a reload\n\tvite.watcher.on(\"change\", (file) => {\n\t\trecheck(file);\n\t\tif (configDeps.has(file)) reload();\n\t});\n\tvite.watcher.on(\"add\", (file) => {\n\t\trecheck(file);\n\t\tif (configDeps.has(file) || inRouteFolder(file)) reload();\n\t});\n\tconst onRemove = (file: string) => {\n\t\tif (configDeps.has(file) || inRouteFolder(file)) reload();\n\t};\n\tvite.watcher.on(\"unlink\", onRemove);\n\tvite.watcher.on(\"addDir\", onRemove);\n\tvite.watcher.on(\"unlinkDir\", onRemove);\n}\n\nfunction isInside(dir: string, file: string): boolean {\n\tconst rel = path.relative(dir, file);\n\treturn rel === \"\" || (!rel.startsWith(\"..\") && !path.isAbsolute(rel));\n}\n\n/**\n * Invalidates the generated `@torpor/build/manifest` module in every\n * environment, so the server entry re-runs with the rebuilt route table on the\n * next request and the client gets the new manifest on reload.\n */\nfunction invalidateManifest(vite: ViteDevServer): void {\n\tfor (const env of Object.values(vite.environments)) {\n\t\tconst mod = env.moduleGraph.getModuleById(MANIFEST_MODULE_ID);\n\t\tif (mod) env.moduleGraph.invalidateModule(mod);\n\t}\n}\n\nfunction normalizePlugins(plugins: Plugin | Plugin[] | void): Plugin[] {\n\tif (!plugins) return [];\n\treturn Array.isArray(plugins) ? plugins : [plugins];\n}\n\nfunction asAliasArray(alias: AliasOptions | undefined): AliasEntry[] {\n\t// Normalize an existing `resolve.alias` value (array | object | undefined)\n\t// into an array so we can concatenate our tsconfig-derived aliases.\n\tif (!alias) return [];\n\tif (Array.isArray(alias)) return alias;\n\treturn Object.entries(alias).map(([find, replacement]) => ({ find, replacement }));\n}\n\n/**\n * Teaches a dep optimizer how to compile `.torp` files. The optimizer is a\n * rolldown build, so it needs a rolldown-shaped plugin (the vite export) — an\n * esbuild-shaped one is silently ignored. Applied to the root optimizer and\n * to each SSR optimizer, which keeps its own settings.\n */\nfunction addTorpOptimizerSettings(optimizeDeps: NonNullable<UserConfig[\"optimizeDeps\"]>): void {\n\toptimizeDeps.extensions ??= [];\n\tif (!optimizeDeps.extensions.includes(\".torp\")) {\n\t\toptimizeDeps.extensions.push(\".torp\");\n\t}\n\toptimizeDeps.rolldownOptions ??= {};\n\toptimizeDeps.rolldownOptions.plugins ??= [torpor()];\n}\n","// From https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/MIME_types/Common_types\n\nexport default function contentType(extension: string): string {\n\treturn types[extension] || \"application/octet-stream\";\n}\n\nconst types: Record<string, string> = {\n\t\".aac\": \"audio/aac\",\n\t\".abw\": \"application/x-abiword\",\n\t\".apng\": \"image/apng\",\n\t\".arc\": \"application/x-freearc\",\n\t\".avif\": \"image/avif\",\n\t\".avi\": \"video/x-msvideo\",\n\t\".azw\": \"application/vnd.amazon.ebook\",\n\t\".bin\": \"application/octet-stream\",\n\t\".bmp\": \"image/bmp\",\n\t\".bz\": \"application/x-bzip\",\n\t\".bz2\": \"application/x-bzip2\",\n\t\".cda\": \"application/x-cdf\",\n\t\".csh\": \"application/x-csh\",\n\t\".css\": \"text/css\",\n\t\".csv\": \"text/csv\",\n\t\".doc\": \"application/msword\",\n\t\".docx\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n\t\".eot\": \"application/vnd.ms-fontobject\",\n\t\".epub\": \"application/epub+zip\",\n\t\".gz\": \"application/gzip\",\n\t\".gif\": \"image/gif\",\n\t\".htm\": \"text/html\",\n\t\".html\": \"text/html\",\n\t\".ico\": \"image/vnd.microsoft.icon\",\n\t\".ics\": \"text/calendar\",\n\t\".jar\": \"application/java-archive\",\n\t\".jpeg\": \"image/jpeg\",\n\t\".jpg\": \"image/jpeg\",\n\t\".js\": \"text/javascript\",\n\t\".json\": \"application/json\",\n\t\".jsonld\": \"application/ld+json\",\n\t\".mid\": \"audio/midi\",\n\t\".midi\": \"audio/midi\",\n\t\".mjs\": \"text/javascript\",\n\t\".mp3\": \"audio/mpeg\",\n\t\".mp4\": \"video/mp4\",\n\t\".mpeg\": \"video/mpeg\",\n\t\".mpkg\": \"application/vnd.apple.installer+xml\",\n\t\".odp\": \"application/vnd.oasis.opendocument.presentation\",\n\t\".ods\": \"application/vnd.oasis.opendocument.spreadsheet\",\n\t\".odt\": \"application/vnd.oasis.opendocument.text\",\n\t\".oga\": \"audio/ogg\",\n\t\".ogv\": \"video/ogg\",\n\t\".ogx\": \"application/ogg\",\n\t\".opus\": \"audio/ogg\",\n\t\".otf\": \"font/otf\",\n\t\".png\": \"image/png\",\n\t\".pdf\": \"application/pdf\",\n\t\".php\": \"application/x-httpd-php\",\n\t\".ppt\": \"application/vnd.ms-powerpoint\",\n\t\".pptx\": \"application/vnd.openxmlformats-officedocument.presentationml.presentation\",\n\t\".rar\": \"application/vnd.rar\",\n\t\".rtf\": \"application/rtf\",\n\t\".sh\": \"application/x-sh\",\n\t\".svg\": \"image/svg+xml\",\n\t\".tar\": \"application/x-tar\",\n\t\".tif\": \"image/tiff\",\n\t\".tiff\": \"image/tiff\",\n\t\".ts\": \"video/mp2t\",\n\t\".ttf\": \"font/ttf\",\n\t\".txt\": \"text/plain\",\n\t\".vsd\": \"application/vnd.visio\",\n\t\".wav\": \"audio/wav\",\n\t\".weba\": \"audio/webm\",\n\t\".webm\": \"video/webm\",\n\t\".webp\": \"image/webp\",\n\t\".woff\": \"font/woff\",\n\t\".woff2\": \"font/woff2\",\n\t\".xhtml\": \"application/xhtml+xml\",\n\t\".xls\": \"application/vnd.ms-excel\",\n\t\".xlsx\": \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n\t\".xml\": \"application/xml\",\n\t\".xul\": \"application/vnd.mozilla.xul+xml\",\n\t\".zip\": \"application/zip\",\n\t\".3gp\": \"video/3gpp\",\n\t\".3g2\": \"video/3gpp2\",\n\t\".7z\": \"application/x-7z-compressed\",\n};\n","import { configDotenv } from \"dotenv\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport contentType from \"../server/contentType.ts\";\nimport Site from \"../site/Site\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\nimport runBuild from \"./runBuild\";\n\nexport default async function runPreview(site: Site): Promise<void> {\n\t// Build the site\n\tawait runBuild(site);\n\n\tconst distFolder = site.outputFolder;\n\tconst clientFolder = path.join(distFolder, \"client\");\n\tconst serverFolder = path.join(distFolder, \"server\");\n\n\t// Read site.html if present, and find the client script file in /assets.\n\t// An endpoints-only site has no site.html, and no template is needed\n\tlet template: string | undefined;\n\tconst siteHtml = path.join(clientFolder, \"site.html\");\n\tif (existsSync(siteHtml)) {\n\t\tlet clientScript = (await fs.readdir(path.join(clientFolder, \"assets\"))).find((f) =>\n\t\t\tf.startsWith(\"clientEntry-\"),\n\t\t);\n\t\tif (!clientScript) {\n\t\t\tthrow new Error(\"clientEntry.js not found\");\n\t\t}\n\t\tclientScript = `/assets/${clientScript}`;\n\n\t\ttemplate = await fs.readFile(siteHtml, \"utf-8\");\n\n\t\t// Prepare site.html so that we can just splice components into it\n\t\ttemplate = prepareTemplate(template, clientScript);\n\t}\n\n\t// Configure the server\n\tconst server = new Server();\n\n\t// Serve dist/client/assets statically\n\tserver.add(\"/assets/*\", async (ev) => {\n\t\ttry {\n\t\t\tconst url = new URL(ev.request.url);\n\t\t\tconst file = path.join(clientFolder, url.pathname);\n\t\t\tif (existsSync(file)) {\n\t\t\t\tconst body = await fs.readFile(file);\n\t\t\t\treturn new Response(body, {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\theaders: {\n\t\t\t\t\t\t\"Content-Type\": contentType(path.extname(file)),\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (e: any) {\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tconst serverScript = path.resolve(serverFolder, \"serverEntry.js\");\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry\n\t\t\tconst { load } = await import(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Load environment variables from a `.env` file, with defaults if not set\n\tconfigDotenv();\n\n\tprocess.env.PROTOCOL ??= \"http:\";\n\tprocess.env.HOST ??= \"localhost\";\n\tprocess.env.PORT ??= \"7059\";\n\n\t// Serve the site\n\tawait site.adapter.serve(server, site);\n}\n","import runBuild from \"./runBuild\";\nimport runDev from \"./runDev\";\nimport { loadSite } from \"./loadSite\";\nimport runPreview from \"./runPreview\";\n\nexport { loadSite };\n\nexport default async function run(\n\tfolder: string,\n\tmode: \"dev\" | \"build\" | \"preview\",\n): Promise<void> {\n\tconst { site, vite } = await loadSite(folder);\n\ttry {\n\t\tswitch (mode) {\n\t\t\tcase \"dev\": {\n\t\t\t\t// The config Vite server is passed along so the dev server can\n\t\t\t\t// watch the config's import graph and re-load it when route\n\t\t\t\t// definitions (e.g. a routes.ts) change\n\t\t\t\tawait runDev(site, vite);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"build\": {\n\t\t\t\tawait runBuild(site);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"preview\": {\n\t\t\t\tawait runPreview(site);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\tconsole.log(\"No mode passed, running in dev\");\n\t\t\t\tawait runDev(site, vite);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tawait vite.close();\n\t}\n}\n","import { writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { ViteDevServer } from \"vite\";\nimport buildOpenApiDocument from \"../openapi/document\";\nimport { OPEN_API_STATE_KEY } from \"../openapi/plugin\";\nimport type { OpenApiEndPoint, OpenApiRouteEntry, ResolvedOpenApiOptions } from \"../openapi/types\";\nimport type Site from \"../site/Site\";\nimport { SERVER_ROUTE } from \"../types/RouteType\";\n\n/**\n * Writes an OpenAPI document for the site's +server endpoints to a file.\n * Route files are loaded through the supplied Vite server, so this must be\n * called while the server from `loadSite` is still open.\n */\nexport default async function runOpenApi(\n\tsite: Site,\n\tvite: ViteDevServer,\n\toutFile = \"openapi.json\",\n): Promise<void> {\n\tconst options = site.pluginState.get(OPEN_API_STATE_KEY) as ResolvedOpenApiOptions | undefined;\n\tif (!options) {\n\t\tthrow new Error(\n\t\t\t'No OpenAPI options found. Add the openApi() plugin to site.plugins to use \"tb --openapi\"',\n\t\t);\n\t}\n\n\tconst entries: OpenApiRouteEntry[] = [];\n\tfor (const route of site.routes) {\n\t\tif (route.type !== SERVER_ROUTE) {\n\t\t\tcontinue;\n\t\t}\n\t\t// Don't document the docs page itself\n\t\tif (options.docs && route.path === options.docs) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (route.endPoint && !route.file) {\n\t\t\t// Inline endpoint\n\t\t\tentries.push({ path: route.path, endPoint: route.endPoint as OpenApiEndPoint });\n\t\t} else if (route.file) {\n\t\t\tconst file = path.resolve(site.root, route.file);\n\t\t\tconst mod = await vite.ssrLoadModule(file);\n\t\t\tentries.push({ path: route.path, endPoint: mod.default });\n\t\t}\n\t}\n\n\tconst doc = buildOpenApiDocument(entries, options);\n\tawait writeFile(path.resolve(site.root, outFile), JSON.stringify(doc, null, 2) + \"\\n\");\n\n\tconsole.log(\n\t\t`OpenAPI document written to ${outFile} (${Object.keys(doc.paths ?? {}).length} paths)`,\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAwB,gBAAgB,MAA4B;CACnE,MAAM,OAAOA,MAAK,KAAK,MAAM,eAAe;CAC5C,IAAI;CACJ,IAAI;CACJ,IAAI;EAEH,MAAM,kBADW,KAAK,MAAM,WAAW,aAAa,MAAM,OAAO,CAAC,CACnC,CAAC,CAAC,mBAAmB,CAAC;EACrD,UAAU,gBAAgB,UAAUA,MAAK,QAAQ,MAAM,gBAAgB,OAAO,IAAI;EAClF,QAAQ,gBAAgB;CACzB,QAAQ;EACP,OAAO,CAAC;CACT;CACA,IAAI,CAAC,OAAO,OAAO,CAAC;CAEpB,MAAM,UAAwB,CAAC;CAC/B,KAAK,MAAM,CAAC,SAAS,YAAY,OAAO,QAAQ,KAAK,GAAG;EACvD,MAAM,SAAS,UAAU;EACzB,IAAI,CAAC,QAAQ;EACb,IAAI,QAAQ,SAAS,GAAG,GAAG;GAK1B,MAAM,OAAO,QAAQ,MAAM,GAAG,EAAE;GAChC,MAAM,YAAY,OAAO,MAAM,GAAG,EAAE;GACpC,QAAQ,KAAK;IACZ;IACA,aAAa,GAAGA,MAAK,QAAQ,SAAS,SAAS,EAAE;GAClD,CAAC;EACF,OACC,QAAQ,KAAK;GAAE,MAAM;GAAS,aAAaA,MAAK,QAAQ,SAAS,MAAM;EAAE,CAAC;CAE5E;CACA,OAAO;AACR;;;;;AAMA,SAAgB,WAAW,MAAsB;CAChD,IAAI,MAAM;CACV,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,SAAS;EACjC,MAAM,IAAI,KAAK;EACf,IAAI,MAAM,QAAO,MAAM,KAAK;G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