@torpor/build 1.7.0 → 1.7.1

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.
package/dist/bin/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #! /usr/bin/env node
2
- import { a as loadSite, n as run, t as runOpenApi } from "../runOpenApi-BAB9naJt.mjs";
2
+ import { a as loadSite, n as run, t as runOpenApi } from "../runOpenApi-Cz7_PXSt.mjs";
3
3
  //#region src/bin/index.ts
4
4
  const workingDir = process.cwd();
5
5
  if (process.argv.includes("--openapi")) {
@@ -1,7 +1,7 @@
1
1
  import { t as Router } from "./Router-C4ADUfhv.mjs";
2
2
  import { o as setBasePath } from "./basePath-DQnbHc7o.mjs";
3
3
  import { t as $page } from "./_page-CW6SLuT4.mjs";
4
- import { a as client, n as navigate, r as loadData } from "./load-d3Mr0HKQ.mjs";
4
+ import { a as client, n as navigate, r as loadData } from "./load-GG7Shn4q.mjs";
5
5
  import manifest from "@torpor/build/manifest";
6
6
  //#region src/site/clientEntry.ts
7
7
  setBasePath(manifest.base);
@@ -24,6 +24,8 @@ window.addEventListener("click", async (e) => {
24
24
  });
25
25
  window.addEventListener("mouseover", maybePrefetch);
26
26
  window.addEventListener("touchstart", maybePrefetch);
27
+ window.addEventListener("focusin", maybePrefetch);
28
+ window.addEventListener("pointerdown", maybePrefetch);
27
29
  async function maybePrefetch(e) {
28
30
  const link = getLink(e.target);
29
31
  if (link) {
@@ -31,14 +33,17 @@ async function maybePrefetch(e) {
31
33
  const href = link.href;
32
34
  const url = new URL(href);
33
35
  const path = url.pathname;
36
+ if (path === document.location.pathname) return;
34
37
  const query = url.searchParams;
35
38
  const route = router.match(path, query);
36
39
  if (route) {
37
40
  const handler = route.handler;
38
41
  const params = route.params || {};
39
- const clientEndPoint = handler.endPoint ? (await handler.endPoint())?.default : void 0;
40
- if (!clientEndPoint?.component) return;
41
- await loadData(handler, params, path, query, [], clientEndPoint, true);
42
+ try {
43
+ const clientEndPoint = handler.endPoint ? (await handler.endPoint())?.default : void 0;
44
+ if (!clientEndPoint?.component) return;
45
+ await loadData(handler, params, path, query, [], clientEndPoint, true);
46
+ } catch {}
42
47
  }
43
48
  }
44
49
  }
@@ -49,7 +54,8 @@ function getLink(target) {
49
54
  return link ?? void 0;
50
55
  }
51
56
  function ignoreAnchorMouseEvent(link, e) {
52
- return e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || e.shiftKey || link.target && link.target !== "_self" || link.rel === "external" || link.hasAttribute("download") || link.isContentEditable;
57
+ const mouse = e;
58
+ return e.defaultPrevented || mouse.altKey || mouse.ctrlKey || mouse.metaKey || mouse.shiftKey || link.target && link.target !== "_self" || link.rel === "external" || link.hasAttribute("download") || link.isContentEditable;
53
59
  }
54
60
  window.addEventListener("popstate", async () => {
55
61
  if (!await navigateToLocation(document.location)) {
@@ -1 +1 @@
1
- {"version":3,"file":"clientEntry.mjs","names":[],"sources":["../src/site/clientEntry.ts"],"sourcesContent":["import manifest from \"@torpor/build/manifest\";\nimport loadData from \"../nav/loadData.ts\";\nimport navigate from \"../nav/navigate.ts\";\nimport $page from \"../state/$page.ts\";\nimport client from \"../state/client\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport Router from \"./Router.ts\";\nimport { setBasePath } from \"./basePath.ts\";\n\nsetBasePath(manifest.base);\n\n// Build the router from the Site object created by the user\nconst router = new Router();\nrouter.addPages(manifest.routes);\n\n// Put it in client state so that it can be accessed from navigate. We can't\n// just import it to navigate because that gets built by tsdown, without Vite\n// and the manifest\nclient.router = router;\nclient.viewTransitions = manifest.viewTransitions ?? false;\n\n// Intercept clicks on links\nwindow.addEventListener(\"click\", async (e) => {\n\tconst link = getLink(e.target);\n\tif (link) {\n\t\tif (ignoreAnchorMouseEvent(link, e)) {\n\t\t\treturn;\n\t\t}\n\n\t\te.preventDefault();\n\n\t\tconst href = link.href;\n\t\tconst url = new URL(href);\n\n\t\tif (await navigate(url)) {\n\t\t\t// Save the scroll position of the outgoing page on the current\n\t\t\t// history entry, so that going (or coming) back can restore it\n\t\t\twindow.history.replaceState({ scroll: window.scrollY }, \"\", document.location.href);\n\t\t\twindow.history.pushState({ scroll: 0 }, \"\", url);\n\t\t} else {\n\t\t\twindow.location.href = href;\n\t\t}\n\t}\n});\n\n// Intercept mouseover/focus/touchstart on links for prefetching\n// TODO: settings e.g. <a href=\"\" data-tb-prefetch=\"eager\"/\"visible\"/\"hover\"/\"touch\">\nwindow.addEventListener(\"mouseover\", maybePrefetch);\nwindow.addEventListener(\"touchstart\", maybePrefetch);\n\nasync function maybePrefetch(e: MouseEvent | TouchEvent) {\n\tconst link = getLink(e.target);\n\tif (link) {\n\t\tif (ignoreAnchorMouseEvent(link, e)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst href = link.href;\n\t\tconst url = new URL(href);\n\n\t\tconst path = url.pathname;\n\t\tconst query = url.searchParams;\n\t\tconst route = router.match(path, query);\n\t\tif (route) {\n\t\t\tconst handler = route.handler;\n\t\t\tconst params = route.params || {};\n\n\t\t\t// A route with no client endpoint (a pure `+server` route) has\n\t\t\t// nothing to prefetch\n\t\t\tconst clientEndPoint: PageEndPoint | undefined = handler.endPoint\n\t\t\t\t? (await handler.endPoint())?.default\n\t\t\t\t: undefined;\n\t\t\tif (!clientEndPoint?.component) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Just dummy this up\n\t\t\tlet newStack: LayoutPath[] = [];\n\n\t\t\tawait loadData(handler, params, path, query, newStack, clientEndPoint, true);\n\t\t}\n\t}\n}\n\nfunction getLink(target: EventTarget | null): HTMLAnchorElement | undefined {\n\t// The target may be a child element of the link (e.g. an icon inside it),\n\t// so walk up to the nearest actual link. Fragment-only links (href=\"#...\")\n\t// are left to the browser's native jump-to-anchor behavior\n\tif (!(target instanceof Element)) return;\n\tconst link = target.closest(\"a[href]\");\n\tif (link?.getAttribute(\"href\")?.startsWith(\"#\")) return;\n\treturn (link as HTMLAnchorElement) ?? undefined;\n}\n\nfunction ignoreAnchorMouseEvent(link: HTMLAnchorElement, e: MouseEvent | TouchEvent) {\n\t// Ignore the event if it was already handled (e.g. a user handler calling\n\t// preventDefault), a modifier key is pressed, the target is not \"_self\"\n\t// (e.g. \"_blank\"), rel=\"external\", it's a download link, or it's in a\n\t// contenteditable region\n\treturn (\n\t\te.defaultPrevented ||\n\t\te.altKey ||\n\t\te.ctrlKey ||\n\t\te.metaKey ||\n\t\te.shiftKey ||\n\t\t(link.target && link.target !== \"_self\") ||\n\t\tlink.rel === \"external\" ||\n\t\tlink.hasAttribute(\"download\") ||\n\t\tlink.isContentEditable\n\t);\n}\n\n// Listen for changes to the URL that occur when the user navigates using the\n// back or forward buttons\nwindow.addEventListener(\"popstate\", async () => {\n\tconst navigated = await navigateToLocation(document.location);\n\tif (!navigated) {\n\t\twindow.location.reload();\n\t\treturn;\n\t}\n\t// Restore the scroll position that was saved on the history entry\n\trequestAnimationFrame(() => {\n\t\tconst state = window.history.state as { scroll?: number } | null;\n\t\twindow.scrollTo(0, state?.scroll ?? 0);\n\t});\n});\n\n// Do the initial navigation and hydration\nawait navigateToLocation(document.location, true);\n\nasync function navigateToLocation(location: Location, firstTime = false) {\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\treturn await navigate(new URL(location.toString()), firstTime);\n}\n"],"mappings":";;;;;;AAUA,YAAY,SAAS,IAAI;AAGzB,MAAM,SAAS,IAAI,OAAO;AAC1B,OAAO,SAAS,SAAS,MAAM;AAK/B,OAAO,SAAS;AAChB,OAAO,kBAAkB,SAAS,mBAAmB;AAGrD,OAAO,iBAAiB,SAAS,OAAO,MAAM;CAC7C,MAAM,OAAO,QAAQ,EAAE,MAAM;CAC7B,IAAI,MAAM;EACT,IAAI,uBAAuB,MAAM,CAAC,GACjC;EAGD,EAAE,eAAe;EAEjB,MAAM,OAAO,KAAK;EAClB,MAAM,MAAM,IAAI,IAAI,IAAI;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AAiB,YAAY,YAAY;CAE/C,IAAI,CAAC,MADmB,mBAAmB,SAAS,QAAQ,GAC5C;EACf,OAAO,SAAS,OAAO;EACvB;CACD;CAEA,4BAA4B;EAC3B,MAAM,QAAQ,OAAO,QAAQ;EAC7B,OAAO,SAAS,GAAG,OAAO,UAAU,CAAC;CACtC,CAAC;AACF,CAAC;AAGD,MAAM,mBAAmB,SAAS,UAAU,IAAI;AAEhD,eAAe,mBAAmB,UAAoB,YAAY,OAAO;CAGxE,MAAM,OAAO,KAAA;CAEb,OAAO,MAAM,SAAS,IAAI,IAAI,SAAS,SAAS,CAAC,GAAG,SAAS;AAC9D"}
1
+ {"version":3,"file":"clientEntry.mjs","names":[],"sources":["../src/site/clientEntry.ts"],"sourcesContent":["import manifest from \"@torpor/build/manifest\";\nimport loadData from \"../nav/loadData.ts\";\nimport navigate from \"../nav/navigate.ts\";\nimport $page from \"../state/$page.ts\";\nimport client from \"../state/client\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport Router from \"./Router.ts\";\nimport { setBasePath } from \"./basePath.ts\";\n\nsetBasePath(manifest.base);\n\n// Build the router from the Site object created by the user\nconst router = new Router();\nrouter.addPages(manifest.routes);\n\n// Put it in client state so that it can be accessed from navigate. We can't\n// just import it to navigate because that gets built by tsdown, without Vite\n// and the manifest\nclient.router = router;\nclient.viewTransitions = manifest.viewTransitions ?? false;\n\n// Intercept clicks on links\nwindow.addEventListener(\"click\", async (e) => {\n\tconst link = getLink(e.target);\n\tif (link) {\n\t\tif (ignoreAnchorMouseEvent(link, e)) {\n\t\t\treturn;\n\t\t}\n\n\t\te.preventDefault();\n\n\t\tconst href = link.href;\n\t\tconst url = new URL(href);\n\n\t\tif (await navigate(url)) {\n\t\t\t// Save the scroll position of the outgoing page on the current\n\t\t\t// history entry, so that going (or coming) back can restore it\n\t\t\twindow.history.replaceState({ scroll: window.scrollY }, \"\", document.location.href);\n\t\t\twindow.history.pushState({ scroll: 0 }, \"\", url);\n\t\t} else {\n\t\t\twindow.location.href = href;\n\t\t}\n\t}\n});\n\n// Intercept mouseover/focus/touchstart on links for prefetching\n// TODO: settings e.g. <a href=\"\" data-tb-prefetch=\"eager\"/\"visible\"/\"hover\"/\"touch\">\nwindow.addEventListener(\"mouseover\", maybePrefetch);\nwindow.addEventListener(\"touchstart\", maybePrefetch);\n// Keyboard focus, and the press-down that precedes a click (a fast click can\n// land before any hover), warm the target too, so the navigation can await the\n// same in-flight request rather than starting its own\nwindow.addEventListener(\"focusin\", maybePrefetch);\nwindow.addEventListener(\"pointerdown\", maybePrefetch);\n\nasync function maybePrefetch(e: Event) {\n\tconst link = getLink(e.target);\n\tif (link) {\n\t\tif (ignoreAnchorMouseEvent(link, e)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst href = link.href;\n\t\tconst url = new URL(href);\n\n\t\tconst path = url.pathname;\n\t\t// Nothing to warm for the page we're already on\n\t\tif (path === document.location.pathname) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst query = url.searchParams;\n\t\tconst route = router.match(path, query);\n\t\tif (route) {\n\t\t\tconst handler = route.handler;\n\t\t\tconst params = route.params || {};\n\n\t\t\ttry {\n\t\t\t\t// A route with no client endpoint (a pure `+server` route) has\n\t\t\t\t// nothing to prefetch\n\t\t\t\tconst clientEndPoint: PageEndPoint | undefined = handler.endPoint\n\t\t\t\t\t? (await handler.endPoint())?.default\n\t\t\t\t\t: undefined;\n\t\t\t\tif (!clientEndPoint?.component) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Just dummy this up\n\t\t\t\tlet newStack: LayoutPath[] = [];\n\n\t\t\t\tawait loadData(handler, params, path, query, newStack, clientEndPoint, true);\n\t\t\t} catch {\n\t\t\t\t// A prefetch is best-effort: the real navigation retries\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction getLink(target: EventTarget | null): HTMLAnchorElement | undefined {\n\t// The target may be a child element of the link (e.g. an icon inside it),\n\t// so walk up to the nearest actual link. Fragment-only links (href=\"#...\")\n\t// are left to the browser's native jump-to-anchor behavior\n\tif (!(target instanceof Element)) return;\n\tconst link = target.closest(\"a[href]\");\n\tif (link?.getAttribute(\"href\")?.startsWith(\"#\")) return;\n\treturn (link as HTMLAnchorElement) ?? undefined;\n}\n\nfunction ignoreAnchorMouseEvent(link: HTMLAnchorElement, e: Event) {\n\t// Ignore the event if it was already handled (e.g. a user handler calling\n\t// preventDefault), a modifier key is pressed, the target is not \"_self\"\n\t// (e.g. \"_blank\"), rel=\"external\", it's a download link, or it's in a\n\t// contenteditable region\n\tconst mouse = e as MouseEvent;\n\treturn (\n\t\te.defaultPrevented ||\n\t\tmouse.altKey ||\n\t\tmouse.ctrlKey ||\n\t\tmouse.metaKey ||\n\t\tmouse.shiftKey ||\n\t\t(link.target && link.target !== \"_self\") ||\n\t\tlink.rel === \"external\" ||\n\t\tlink.hasAttribute(\"download\") ||\n\t\tlink.isContentEditable\n\t);\n}\n\n// Listen for changes to the URL that occur when the user navigates using the\n// back or forward buttons\nwindow.addEventListener(\"popstate\", async () => {\n\tconst navigated = await navigateToLocation(document.location);\n\tif (!navigated) {\n\t\twindow.location.reload();\n\t\treturn;\n\t}\n\t// Restore the scroll position that was saved on the history entry\n\trequestAnimationFrame(() => {\n\t\tconst state = window.history.state as { scroll?: number } | null;\n\t\twindow.scrollTo(0, state?.scroll ?? 0);\n\t});\n});\n\n// Do the initial navigation and hydration\nawait navigateToLocation(document.location, true);\n\nasync function navigateToLocation(location: Location, firstTime = false) {\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\treturn await navigate(new URL(location.toString()), firstTime);\n}\n"],"mappings":";;;;;;AAUA,YAAY,SAAS,IAAI;AAGzB,MAAM,SAAS,IAAI,OAAO;AAC1B,OAAO,SAAS,SAAS,MAAM;AAK/B,OAAO,SAAS;AAChB,OAAO,kBAAkB,SAAS,mBAAmB;AAGrD,OAAO,iBAAiB,SAAS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AAO,OAAO,QAAQ,SAAS;CACrC,IAAI,MAAM,aAAa,MAAM,CAAC,EAAE,WAAW,GAAG,GAAG;CACjD,OAAQ,QAA8B,KAAA;AACvC;AAEA,SAAS,uBAAuB,MAAyB,GAAU;CAKlE,MAAM,QAAQ;CACd,OACC,EAAE,oBACF,MAAM,UACN,MAAM,WACN,MAAM,WACN,MAAM,YACL,KAAK,UAAU,KAAK,WAAW,WAChC,KAAK,QAAQ,cACb,KAAK,aAAa,UAAU,KAC5B,KAAK;AAEP;AAIA,OAAO,iBAAiB,YAAY,YAAY;CAE/C,IAAI,CAAC,MADmB,mBAAmB,SAAS,QAAQ,GAC5C;EACf,OAAO,SAAS,OAAO;EACvB;CACD;CAEA,4BAA4B;EAC3B,MAAM,QAAQ,OAAO,QAAQ;EAC7B,OAAO,SAAS,GAAG,OAAO,UAAU,CAAC;CACtC,CAAC;AACF,CAAC;AAGD,MAAM,mBAAmB,SAAS,UAAU,IAAI;AAEhD,eAAe,mBAAmB,UAAoB,YAAY,OAAO;CAGxE,MAAM,OAAO,KAAA;CAEb,OAAO,MAAM,SAAS,IAAI,IAAI,SAAS,SAAS,CAAC,GAAG,SAAS;AAC9D"}
package/dist/env.mjs CHANGED
@@ -1,2 +1 @@
1
- import { n as setEnvSchema, t as env } from "./env-C2SUAwAq.mjs";
2
- export { env as default, setEnvSchema };
1
+ export { t as default, n as setEnvSchema } from "./env-C2SUAwAq.mjs";
@@ -8,6 +8,7 @@ const client = globalThis[CLIENT_SYMBOL] ??= {
8
8
  router: null,
9
9
  layoutStack: [],
10
10
  prefetchedData: {},
11
+ prefetchedServerData: {},
11
12
  viewTransitions: false
12
13
  };
13
14
  //#endregion
@@ -84,7 +85,7 @@ async function loadData(handler, params, path, query, newLayoutStack, clientEndP
84
85
  reuse
85
86
  };
86
87
  });
87
- const server = await loadServerData(handler, path, query, layouts.filter((l) => l.reuse).map((l) => l.layoutPath));
88
+ const server = await loadServerData(handler, path, query, layouts.filter((l) => l.reuse).map((l) => l.layoutPath), prefetch);
88
89
  if (server === void 0) return;
89
90
  if ("error" in server) return {
90
91
  data,
@@ -129,13 +130,47 @@ async function loadData(handler, params, path, query, newLayoutStack, clientEndP
129
130
  return { data };
130
131
  }
131
132
  /**
132
- * Fetches the page's combined server data. Returns `undefined` when a load
133
- * redirected, or an `error` result when a load failed.
133
+ * Fetches the page's combined server data for a navigation, reusing a prefetch
134
+ * when there is one.
135
+ *
136
+ * A prefetch warms this request for the navigation that follows, and a
137
+ * navigation consumes it (once). So a hover costs one request, a click that
138
+ * lands while the prefetch is still in flight awaits the same promise instead
139
+ * of issuing a second one, and a prefetched response is never served to more
140
+ * than the one navigation it was loaded for (no stale data on later visits).
134
141
  */
135
- async function loadServerData(handler, path, query, reusedLayouts) {
142
+ async function loadServerData(handler, path, query, reusedLayouts, prefetch) {
136
143
  const embedded = takeEmbeddedServerData();
137
144
  if (embedded !== void 0) return embedded;
138
145
  if (!hasServerData(handler)) return {};
146
+ const key = serverDataKey(path, query);
147
+ if (prefetch) {
148
+ const cached = client.prefetchedServerData[key];
149
+ if (cached) return cached;
150
+ const pending = requestServerData(path, query, reusedLayouts);
151
+ client.prefetchedServerData[key] = pending;
152
+ pending.catch(() => {
153
+ if (client.prefetchedServerData[key] === pending) delete client.prefetchedServerData[key];
154
+ });
155
+ return pending;
156
+ }
157
+ const prefetched = client.prefetchedServerData[key];
158
+ if (prefetched) {
159
+ delete client.prefetchedServerData[key];
160
+ return prefetched;
161
+ }
162
+ return requestServerData(path, query, reusedLayouts);
163
+ }
164
+ /** The `/~server` request cache key: the page path and its query. */
165
+ function serverDataKey(path, query) {
166
+ return path + (query.size > 0 ? `?${query}` : "");
167
+ }
168
+ /**
169
+ * The posted data request: `GET <page url>/~server` carrying the data header,
170
+ * which the server answers with the page's and its layouts' server data as one
171
+ * JSON body.
172
+ */
173
+ async function requestServerData(path, query, reusedLayouts) {
139
174
  const url = new URL(document.location.origin + getBasePath() + path.replace(/\/$/, "") + "/~server");
140
175
  for (let [name, value] of query) url.searchParams.append(name, value);
141
176
  const headers = { [DATA_REQUEST_HEADER]: "1" };
@@ -228,7 +263,21 @@ async function errorOf(response) {
228
263
  }
229
264
  //#endregion
230
265
  //#region src/nav/navigate.ts
231
- async function navigate(rawUrl, withHydration = false) {
266
+ /**
267
+ * Navigations run one at a time. Each mutates shared client state
268
+ * (`client.layoutStack`) and the live DOM, so two in flight at once can have
269
+ * one clear a layout's slot region that the other is about to reuse (the
270
+ * `slotRegion.startNode!` in `render` then throws). Requests are chained, so a
271
+ * rapid second click -- or a popstate while a form submit reloads -- waits for
272
+ * the first to finish instead of interleaving.
273
+ */
274
+ let pendingNavigation = Promise.resolve();
275
+ function navigate(rawUrl, withHydration = false) {
276
+ const result = pendingNavigation.then(() => navigateNow(rawUrl, withHydration));
277
+ pendingNavigation = result.catch(() => {});
278
+ return result;
279
+ }
280
+ async function navigateNow(rawUrl, withHydration) {
232
281
  let parent = document.getElementById("app");
233
282
  if (!parent) {
234
283
  console.log("500");
@@ -363,4 +412,4 @@ async function load(path) {
363
412
  //#endregion
364
413
  export { client as a, reload as i, navigate as n, loadData as r, load as t };
365
414
 
366
- //# sourceMappingURL=load-d3Mr0HKQ.mjs.map
415
+ //# sourceMappingURL=load-GG7Shn4q.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load-GG7Shn4q.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.\n */\nexport default async function reload(): Promise<boolean> {\n\tconst url = new URL(document.location.href);\n\treturn await navigate(url);\n}\n","import $page from \"../state/$page\";\nimport load from \"./load\";\nimport reload from \"./reload\";\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\tconst response = await fetch(\n\t\taction,\n\t\t// @ts-ignore -- don't know what it's complaining about here\n\t\toptions,\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","import { DATA_REUSE_HEADER, DATA_REQUEST_HEADER } from \"../dataRequest.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 and UI\n\t// are reused), so the data request can skip loading them\n\tconst layoutStack = client.layoutStack;\n\tconst layouts = (handler.layouts ?? []).map((layout, index) => {\n\t\tlet layoutPath = layout.path;\n\t\tfor (let key in params) {\n\t\t\tlayoutPath = layoutPath.replace(`[${key}]`, params[key]);\n\t\t}\n\t\tconst previous = layoutStack.at(index);\n\t\tconst reuse = !prefetch && previous?.path === layoutPath;\n\t\treturn { layout, index, layoutPath, previous, reuse };\n\t});\n\n\t// One request for all the (non-reused) server data\n\tconst server = await loadServerData(\n\t\thandler,\n\t\tpath,\n\t\tquery,\n\t\tlayouts.filter((l) => l.reuse).map((l) => l.layoutPath),\n\t\tprefetch,\n\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, 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 (reuse && previous) {\n\t\t\t// The layout is already rendered: keep its data and slot region\n\t\t\tstackLayout.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 response = 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);\n\t\t\tif (response) {\n\t\t\t\tif (isRedirect(response)) return;\n\t\t\t\treturn { data, error: await errorOf(response) };\n\t\t\t}\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 response = await runClientLoad(clientEndPoint, clientLocation(path), query, params, data);\n\tif (response) {\n\t\tif (isRedirect(response)) return;\n\t\treturn { data, error: await errorOf(response) };\n\t}\n\tconst pageServerData = server.loads?.[handler.layouts?.length ?? 0];\n\tif (pageServerData) Object.assign(data, pageServerData);\n\n\treturn { data };\n}\n\ntype ServerData = {\n\tloads?: (Record<string, any> | null)[];\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 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\n\t\tvoid pending.catch(() => {\n\t\t\tif (client.prefetchedServerData[key] === pending) {\n\t\t\t\tdelete client.prefetchedServerData[key];\n\t\t\t}\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/**\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\tconst response = await fetch(url, {\n\t\tredirect: \"manual\",\n\t\theaders,\n\t});\n\tif (isRedirect(response)) {\n\t\treturn undefined;\n\t}\n\tif (!response.ok) {\n\t\treturn { error: await errorOf(response) };\n\t}\n\t// A site without a server (e.g. a static host) responds with the page's\n\t// html rather than json; there's nothing to merge\n\tif (!response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\treturn {};\n\t}\n\treturn (await response.json()) as ServerData;\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 * Runs a route's client-side load, merging its json data into `data`. Returns\n * a non-ok Response for the caller to turn into an error page.\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): Promise<Response | undefined> {\n\tif (!endPoint?.load) return;\n\n\tconst clientKey = location + (query.size > 0 ? `?${query}` : \"\");\n\tconst prefetchedData = client.prefetchedData;\n\tif (prefetchedData[clientKey]) {\n\t\tObject.assign(data, prefetchedData[clientKey]);\n\t\treturn;\n\t}\n\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\tconst clientResponse = await endPoint.load({ url: clientUrl, params, data });\n\tif (clientResponse) {\n\t\tif (clientResponse.ok) {\n\t\t\tif (clientResponse.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\tconst clientData = await clientResponse.json();\n\t\t\t\tObject.assign(data, clientData);\n\t\t\t\tprefetchedData[clientKey] = clientData;\n\t\t\t}\n\t\t} else {\n\t\t\treturn clientResponse;\n\t\t}\n\t}\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 from \"./loadData\";\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\n// @ts-ignore\nexport default function navigate(rawUrl: URL, withHydration = false): Promise<boolean> {\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<boolean> {\n\tlet parent = document.getElementById(\"app\");\n\tif (!parent) {\n\t\t// TODO: 500\n\t\tconsole.log(\"500\");\n\t\treturn false;\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 false;\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 return false and let the caller do a full page 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 false;\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, or (on a prerendered site with no server) the\n\t\t// ~server request couldn't be made. Leave the current page alone;\n\t\t// the caller (e.g. the client entry) falls back to a full page load,\n\t\t// which follows the redirect\n\t\treturn false;\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 false;\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 false;\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 false;\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.length = 0;\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 || errorResult.error) {\n\t\t\t// The error page's own load failed too -- fall back to a full\n\t\t\t// page load\n\t\t\treturn false;\n\t\t}\n\t\tdata = errorResult.data;\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\tlet reused = false;\n\t// The index of the innermost reused layout. Its slotRegion is the region\n\t// that must be cleared and refilled (it contains the next layout's or the\n\t// page's content). This is usually the last entry of the stack, but not\n\t// when an outer layout is reused while an inner one is new — e.g.\n\t// navigating between sections that share the root layout.\n\tlet 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 (layoutStack[i].reuse) {\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\treusedIndex = i;\n\t\t\t\t\treused = true;\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\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 true;\n}\n","import navigate from \"./navigate\";\n\n/**\n * Loads and renders the page at the supplied path.\n */\nexport default async function load(path: string): Promise<boolean> {\n\tconst url = new URL(path, document.location.href);\n\treturn await navigate(url);\n}\n"],"mappings":";;;;;AAEA,MAAM,gBAA+B,OAAO,IAAI,aAAa;AAE7D,MAAM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C,SAAS,oBAAoB,MAAM;MAEnC,OAAO;CAIR,OAAO,iBAAiB,CAAC;CAEzB,OAAO;AACR;;;;;;ACnSA,eAA8B,KAAK,MAAgC;CAElE,OAAO,MAAM,SAAS,IADN,IAAI,MAAM,SAAS,SAAS,IACtB,CAAG;AAC1B"}
package/dist/nav.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as getBasePath, t as addBaseToPath } from "./basePath-DQnbHc7o.mjs";
2
- import { i as reload, t as load } from "./load-d3Mr0HKQ.mjs";
2
+ import { i as reload, t as load } from "./load-GG7Shn4q.mjs";
3
3
  //#region src/nav/route.ts
4
4
  /**
5
5
  * Builds a route path in a type-safe manner, filling in dynamic segments, e.g.
package/dist/nodeDev.mjs CHANGED
@@ -1,2 +1 @@
1
- import { t as devPlugin } from "./devPlugin-V689J6l6.mjs";
2
- export { devPlugin as nodeDev };
1
+ export { t as nodeDev } from "./devPlugin-V689J6l6.mjs";
package/dist/openapi.mjs CHANGED
@@ -1,2 +1 @@
1
- import { i as buildOpenApiDocument, n as openApi, r as openApiDocsHtml, t as OPEN_API_STATE_KEY } from "./plugin-D8Www11B.mjs";
2
- export { OPEN_API_STATE_KEY, buildOpenApiDocument, openApi, openApiDocsHtml };
1
+ export { t as OPEN_API_STATE_KEY, i as buildOpenApiDocument, n as openApi, r as openApiDocsHtml } from "./plugin-D8Www11B.mjs";
package/dist/run.mjs CHANGED
@@ -1,2 +1 @@
1
- import { i as runDev, n as run, o as runBuild, r as runPreview, t as runOpenApi } from "./runOpenApi-BAB9naJt.mjs";
2
- export { run, runBuild, runDev, runOpenApi, runPreview };
1
+ export { n as run, o as runBuild, i as runDev, t as runOpenApi, r as runPreview } from "./runOpenApi-Cz7_PXSt.mjs";
@@ -1381,15 +1381,16 @@ function watchRoutes(site, vite, configVite) {
1381
1381
  }
1382
1382
  report(file, checkApiCallSource(source, file, apiCheck));
1383
1383
  };
1384
- let configDeps = configVite && site.configFile ? configDependencyFiles(configVite, site.root) : /* @__PURE__ */ new Set();
1384
+ const configFolder = site.configFile ? fpath.dirname(site.configFile) : site.root;
1385
+ let configDeps = configVite && site.configFile ? configDependencyFiles(configVite, configFolder) : /* @__PURE__ */ new Set();
1385
1386
  const inRouteFolder = (file) => site.routeFolders.some((f) => isInside(fpath.resolve(site.root, f.folder), file));
1386
1387
  let pending = Promise.resolve();
1387
1388
  const reload = () => {
1388
1389
  if (!site.configFile) return;
1389
1390
  pending = pending.then(async () => {
1390
- const { site: fresh, vite: freshVite } = await loadSite(site.root);
1391
+ const { site: fresh, vite: freshVite } = await loadSite(configFolder);
1391
1392
  try {
1392
- configDeps = configDependencyFiles(freshVite, site.root);
1393
+ configDeps = configDependencyFiles(freshVite, configFolder);
1393
1394
  if (!site.applyRouteState(fresh)) return;
1394
1395
  } finally {
1395
1396
  await freshVite.close();
@@ -1635,4 +1636,4 @@ async function runOpenApi(site, vite, outFile = "openapi.json") {
1635
1636
  //#endregion
1636
1637
  export { loadSite as a, runDev as i, run as n, runBuild as o, runPreview as r, runOpenApi as t };
1637
1638
 
1638
- //# sourceMappingURL=runOpenApi-BAB9naJt.mjs.map
1639
+ //# sourceMappingURL=runOpenApi-Cz7_PXSt.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"runOpenApi-BAB9naJt.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 sitePackageJson = path.resolve(siteRoot, \"package.json\");\n\tif (!existsSync(sitePackageJson)) return [];\n\n\tconst pkg: PackageJson = JSON.parse(readFileSync(sitePackageJson, \"utf8\"));\n\tconst packages = new Set<string>();\n\tconst visited = new Set<string>();\n\n\tconst rootRequire = createRequire(sitePackageJson);\n\tfor (const name of dependencyNames(pkg)) {\n\t\tcollectTorporPackage(name, rootRequire, packages, visited);\n\t}\n\treturn [...packages];\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 */\nexport function addTorporPackageConfig(siteRoot: string, config: UserConfig): void {\n\tconst packages = findTorporPackages(siteRoot);\n\tif (packages.length === 0) return;\n\n\tconfig.optimizeDeps ??= {};\n\tconfig.optimizeDeps.exclude = [...(config.optimizeDeps.exclude ?? []), ...packages];\n\n\tconfig.ssr ??= {};\n\tconst noExternal = config.ssr.noExternal;\n\tif (noExternal === undefined) {\n\t\tconfig.ssr.noExternal = packages;\n\t} else if (Array.isArray(noExternal)) {\n\t\tnoExternal.push(...packages);\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\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 collectTorporPackage(\n\tname: string,\n\trequire: NodeRequire,\n\tpackages: Set<string>,\n\tvisited: Set<string>,\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 || visited.has(packageJsonPath)) return;\n\tvisited.add(packageJsonPath);\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\tif (isTorporPackage(pkg)) {\n\t\tpackages.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\tconst depRequire = createRequire(packageJsonPath);\n\tfor (const depName of dependencyNames(pkg)) {\n\t\tcollectTorporPackage(depName, depRequire, packages, visited);\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 * Clears site/node_modules/.vite when workspace packages changed since the\n * last dev run. Returns true when the cache was removed.\n */\nexport function clearStaleDepCache(siteRoot: string, log?: (message: string) => void): boolean {\n\ttry {\n\t\tconst workspaceRoot = findWorkspaceRoot(siteRoot);\n\t\tif (!workspaceRoot) return false;\n\n\t\tconst cacheDir = path.join(siteRoot, \"node_modules\", \".vite\");\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 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 } 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// 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\tconfig.optimizeDeps ??= {};\n\tconfig.optimizeDeps.extensions ??= [];\n\tconfig.optimizeDeps.extensions.push(\".torp\");\n\tconfig.optimizeDeps.rolldownOptions ??= {};\n\tconfig.optimizeDeps.rolldownOptions.plugins ??= [torpor()];\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// Workspace packages may have been rebuilt since the last dev run; drop\n\t// Vite's dep cache so SSR never executes stale prebundled modules\n\tclearStaleDepCache(site.root, (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\tlet configDeps =\n\t\tconfigVite && site.configFile\n\t\t\t? configDependencyFiles(configVite, site.root)\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(site.root);\n\t\t\t\ttry {\n\t\t\t\t\tconfigDeps = configDependencyFiles(freshVite, site.root);\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","// 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;;;;;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AGD,MAAM,UAA+B,CAAC;CACtC,KAAK,MAAM,SAAS,KAAK,QAAQ;EAChC,IAAI,MAAM,SAAA,GACT;EAGD,IAAI,QAAQ,QAAQ,MAAM,SAAS,QAAQ,MAC1C;EAED,IAAI,MAAM,YAAY,CAAC,MAAM,MAE5B,QAAQ,KAAK;GAAE,MAAM,MAAM;GAAM,UAAU,MAAM;EAA4B,CAAC;OACxE,IAAI,MAAM,MAAM;GACtB,MAAM,OAAOE,MAAK,QAAQ,KAAK,MAAM,MAAM,IAAI;GAC/C,MAAM,MAAM,MAAM,KAAK,cAAc,IAAI;GACzC,QAAQ,KAAK;IAAE,MAAM,MAAM;IAAM,UAAU,IAAI;GAAQ,CAAC;EACzD;CACD;CAEA,MAAM,MAAM,qBAAqB,SAAS,OAAO;CACjD,MAAM,UAAUA,MAAK,QAAQ,KAAK,MAAM,OAAO,GAAG,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI,IAAI;CAErF,QAAQ,IACP,+BAA+B,QAAQ,IAAI,OAAO,KAAK,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC,OAAO,QAChF;AACD"}
1
+ {"version":3,"file":"runOpenApi-Cz7_PXSt.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 sitePackageJson = path.resolve(siteRoot, \"package.json\");\n\tif (!existsSync(sitePackageJson)) return [];\n\n\tconst pkg: PackageJson = JSON.parse(readFileSync(sitePackageJson, \"utf8\"));\n\tconst packages = new Set<string>();\n\tconst visited = new Set<string>();\n\n\tconst rootRequire = createRequire(sitePackageJson);\n\tfor (const name of dependencyNames(pkg)) {\n\t\tcollectTorporPackage(name, rootRequire, packages, visited);\n\t}\n\treturn [...packages];\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 */\nexport function addTorporPackageConfig(siteRoot: string, config: UserConfig): void {\n\tconst packages = findTorporPackages(siteRoot);\n\tif (packages.length === 0) return;\n\n\tconfig.optimizeDeps ??= {};\n\tconfig.optimizeDeps.exclude = [...(config.optimizeDeps.exclude ?? []), ...packages];\n\n\tconfig.ssr ??= {};\n\tconst noExternal = config.ssr.noExternal;\n\tif (noExternal === undefined) {\n\t\tconfig.ssr.noExternal = packages;\n\t} else if (Array.isArray(noExternal)) {\n\t\tnoExternal.push(...packages);\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\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 collectTorporPackage(\n\tname: string,\n\trequire: NodeRequire,\n\tpackages: Set<string>,\n\tvisited: Set<string>,\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 || visited.has(packageJsonPath)) return;\n\tvisited.add(packageJsonPath);\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\tif (isTorporPackage(pkg)) {\n\t\tpackages.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\tconst depRequire = createRequire(packageJsonPath);\n\tfor (const depName of dependencyNames(pkg)) {\n\t\tcollectTorporPackage(depName, depRequire, packages, visited);\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 * Clears site/node_modules/.vite when workspace packages changed since the\n * last dev run. Returns true when the cache was removed.\n */\nexport function clearStaleDepCache(siteRoot: string, log?: (message: string) => void): boolean {\n\ttry {\n\t\tconst workspaceRoot = findWorkspaceRoot(siteRoot);\n\t\tif (!workspaceRoot) return false;\n\n\t\tconst cacheDir = path.join(siteRoot, \"node_modules\", \".vite\");\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 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 } 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// 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\tconfig.optimizeDeps ??= {};\n\tconfig.optimizeDeps.extensions ??= [];\n\tconfig.optimizeDeps.extensions.push(\".torp\");\n\tconfig.optimizeDeps.rolldownOptions ??= {};\n\tconfig.optimizeDeps.rolldownOptions.plugins ??= [torpor()];\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// Workspace packages may have been rebuilt since the last dev run; drop\n\t// Vite's dep cache so SSR never executes stale prebundled modules\n\tclearStaleDepCache(site.root, (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","// 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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M,IAAI;EAGzB;CACD,UAAU;EACT,MAAM,KAAK,MAAM;CAClB;AACD;;;;;;;;ACxBA,eAA8B,WAC7B,MACA,MACA,UAAU,gBACM;CAChB,MAAM,UAAU,KAAK,YAAY,IAAI,kBAAkB;CACvD,IAAI,CAAC,SACJ,MAAM,IAAI,MACT,4FACD;CAGD,MAAM,UAA+B,CAAC;CACtC,KAAK,MAAM,SAAS,KAAK,QAAQ;EAChC,IAAI,MAAM,SAAA,GACT;EAGD,IAAI,QAAQ,QAAQ,MAAM,SAAS,QAAQ,MAC1C;EAED,IAAI,MAAM,YAAY,CAAC,MAAM,MAE5B,QAAQ,KAAK;GAAE,MAAM,MAAM;GAAM,UAAU,MAAM;EAA4B,CAAC;OACxE,IAAI,MAAM,MAAM;GACtB,MAAM,OAAOE,MAAK,QAAQ,KAAK,MAAM,MAAM,IAAI;GAC/C,MAAM,MAAM,MAAM,KAAK,cAAc,IAAI;GACzC,QAAQ,KAAK;IAAE,MAAM,MAAM;IAAM,UAAU,IAAI;GAAQ,CAAC;EACzD;CACD;CAEA,MAAM,MAAM,qBAAqB,SAAS,OAAO;CACjD,MAAM,UAAUA,MAAK,QAAQ,KAAK,MAAM,OAAO,GAAG,KAAK,UAAU,KAAK,MAAM,CAAC,IAAI,IAAI;CAErF,QAAQ,IACP,+BAA+B,QAAQ,IAAI,OAAO,KAAK,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC,OAAO,QAChF;AACD"}
package/dist/schema.mjs CHANGED
@@ -1,2 +1 @@
1
- import { n as ValidationError, t as validate } from "./validate-Ok4krlkX.mjs";
2
- export { ValidationError, validate };
1
+ export { n as ValidationError, t as validate } from "./validate-Ok4krlkX.mjs";
@@ -1,2 +1 @@
1
- import { t as Server } from "../Server-C0PGzSQO.mjs";
2
- export { Server as default };
1
+ export { t as default } from "../Server-C0PGzSQO.mjs";
@@ -1,2 +1 @@
1
- import { n as router, t as load } from "./serverEntry-BcB9YQLk.mjs";
2
- export { load, router };
1
+ export { t as load, n as router } from "./serverEntry-BcB9YQLk.mjs";
package/dist/state.mjs CHANGED
@@ -1,2 +1 @@
1
- import { t as $page } from "./_page-CW6SLuT4.mjs";
2
- export { $page };
1
+ export { t as $page } from "./_page-CW6SLuT4.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@torpor/build",
3
- "version": "1.7.0",
3
+ "version": "1.7.1",
4
4
  "description": "A framework for building sites and apps with Torpor",
5
5
  "type": "module",
6
6
  "exports": {
@@ -80,12 +80,12 @@
80
80
  "author": "",
81
81
  "license": "ISC",
82
82
  "dependencies": {
83
- "cookie": "^2.0.1",
84
- "dotenv": "^18.0.6",
85
- "vite": "npm:@voidzero-dev/vite-plus-core@1.1.0",
86
- "vite-plus": "1.1.0",
87
83
  "@torpor/unplugin": "^1.2.4",
88
- "@torpor/view": "^1.2.1"
84
+ "@torpor/view": "^1.2.1",
85
+ "cookie": "^2.0.1",
86
+ "dotenv": "^18.0.8",
87
+ "vite": "npm:@voidzero-dev/vite-plus-core@1.2.0",
88
+ "vite-plus": "1.2.0"
89
89
  },
90
90
  "devDependencies": {
91
91
  "@typescript/native-preview": "7.0.0-dev.20260707.2",
@@ -1 +0,0 @@
1
- {"version":3,"file":"load-d3Mr0HKQ.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\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.\n */\nexport default async function reload(): Promise<boolean> {\n\tconst url = new URL(document.location.href);\n\treturn await navigate(url);\n}\n","import $page from \"../state/$page\";\nimport load from \"./load\";\nimport reload from \"./reload\";\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\tconst response = await fetch(\n\t\taction,\n\t\t// @ts-ignore -- don't know what it's complaining about here\n\t\toptions,\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","import { DATA_REUSE_HEADER, DATA_REQUEST_HEADER } from \"../dataRequest.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 and UI\n\t// are reused), so the data request can skip loading them\n\tconst layoutStack = client.layoutStack;\n\tconst layouts = (handler.layouts ?? []).map((layout, index) => {\n\t\tlet layoutPath = layout.path;\n\t\tfor (let key in params) {\n\t\t\tlayoutPath = layoutPath.replace(`[${key}]`, params[key]);\n\t\t}\n\t\tconst previous = layoutStack.at(index);\n\t\tconst reuse = !prefetch && previous?.path === layoutPath;\n\t\treturn { layout, index, layoutPath, previous, reuse };\n\t});\n\n\t// One request for all the (non-reused) server data\n\tconst server = await loadServerData(\n\t\thandler,\n\t\tpath,\n\t\tquery,\n\t\tlayouts.filter((l) => l.reuse).map((l) => l.layoutPath),\n\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, 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 (reuse && previous) {\n\t\t\t// The layout is already rendered: keep its data and slot region\n\t\t\tstackLayout.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 response = 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);\n\t\t\tif (response) {\n\t\t\t\tif (isRedirect(response)) return;\n\t\t\t\treturn { data, error: await errorOf(response) };\n\t\t\t}\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 response = await runClientLoad(clientEndPoint, clientLocation(path), query, params, data);\n\tif (response) {\n\t\tif (isRedirect(response)) return;\n\t\treturn { data, error: await errorOf(response) };\n\t}\n\tconst pageServerData = server.loads?.[handler.layouts?.length ?? 0];\n\tif (pageServerData) Object.assign(data, pageServerData);\n\n\treturn { data };\n}\n\ntype ServerData = {\n\tloads?: (Record<string, any> | null)[];\n};\n\n/**\n * Fetches the page's combined server data. Returns `undefined` when a load\n * redirected, or an `error` result when a load failed.\n */\nasync function loadServerData(\n\thandler: RouteHandler,\n\tpath: string,\n\tquery: URLSearchParams,\n\treusedLayouts: string[],\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 embedded;\n\t}\n\n\tif (!hasServerData(handler)) {\n\t\treturn {};\n\t}\n\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\tconst response = await fetch(url, {\n\t\tredirect: \"manual\",\n\t\theaders,\n\t});\n\tif (isRedirect(response)) {\n\t\treturn undefined;\n\t}\n\tif (!response.ok) {\n\t\treturn { error: await errorOf(response) };\n\t}\n\t// A site without a server (e.g. a static host) responds with the page's\n\t// html rather than json; there's nothing to merge\n\tif (!response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\treturn {};\n\t}\n\treturn (await response.json()) as ServerData;\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 * Runs a route's client-side load, merging its json data into `data`. Returns\n * a non-ok Response for the caller to turn into an error page.\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): Promise<Response | undefined> {\n\tif (!endPoint?.load) return;\n\n\tconst clientKey = location + (query.size > 0 ? `?${query}` : \"\");\n\tconst prefetchedData = client.prefetchedData;\n\tif (prefetchedData[clientKey]) {\n\t\tObject.assign(data, prefetchedData[clientKey]);\n\t\treturn;\n\t}\n\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\tconst clientResponse = await endPoint.load({ url: clientUrl, params, data });\n\tif (clientResponse) {\n\t\tif (clientResponse.ok) {\n\t\t\tif (clientResponse.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\tconst clientData = await clientResponse.json();\n\t\t\t\tObject.assign(data, clientData);\n\t\t\t\tprefetchedData[clientKey] = clientData;\n\t\t\t}\n\t\t} else {\n\t\t\treturn clientResponse;\n\t\t}\n\t}\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 from \"./loadData\";\n\n// @ts-ignore\nexport default async function navigate(rawUrl: URL, withHydration = false): Promise<boolean> {\n\tlet parent = document.getElementById(\"app\");\n\tif (!parent) {\n\t\t// TODO: 500\n\t\tconsole.log(\"500\");\n\t\treturn false;\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 false;\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 return false and let the caller do a full page 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 false;\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, or (on a prerendered site with no server) the\n\t\t// ~server request couldn't be made. Leave the current page alone;\n\t\t// the caller (e.g. the client entry) falls back to a full page load,\n\t\t// which follows the redirect\n\t\treturn false;\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 false;\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 false;\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 false;\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.length = 0;\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 || errorResult.error) {\n\t\t\t// The error page's own load failed too -- fall back to a full\n\t\t\t// page load\n\t\t\treturn false;\n\t\t}\n\t\tdata = errorResult.data;\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\tlet reused = false;\n\t// The index of the innermost reused layout. Its slotRegion is the region\n\t// that must be cleared and refilled (it contains the next layout's or the\n\t// page's content). This is usually the last entry of the stack, but not\n\t// when an outer layout is reused while an inner one is new — e.g.\n\t// navigating between sections that share the root layout.\n\tlet 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 (layoutStack[i].reuse) {\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\treusedIndex = i;\n\t\t\t\t\treused = true;\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\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 true;\n}\n","import navigate from \"./navigate\";\n\n/**\n * Loads and renders the page at the supplied path.\n */\nexport default async function load(path: string): Promise<boolean> {\n\tconst url = new URL(path, document.location.href);\n\treturn await navigate(url);\n}\n"],"mappings":";;;;;AAEA,MAAM,gBAA+B,OAAO,IAAI,aAAa;AAE7D,MAAM,SAEJ,WAAW,mBAAmB;CAE9B,QAAQ;CACR,aAAa,CAAC;CAEd,gBAAgB,CAAC;CACjB,iBAAiB;AAClB;;;;;;ACRD,eAA8B,SAA2B;CAExD,OAAO,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