@torpor/build 1.8.7 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist/{MiddlewareFunction-BZilnEei.d.mts → MiddlewareFunction-7rIvFkjl.d.mts} +7 -1
  2. package/dist/MiddlewareFunction-7rIvFkjl.d.mts.map +1 -0
  3. package/dist/{Router-By9Nlg39.d.mts → Router-Bxm7K20d.d.mts} +4 -4
  4. package/dist/Router-Bxm7K20d.d.mts.map +1 -0
  5. package/dist/{Server-dcRbdPXf.mjs → Server-Djd9-NkU.mjs} +2 -2
  6. package/dist/{Server-dcRbdPXf.mjs.map → Server-Djd9-NkU.mjs.map} +1 -1
  7. package/dist/{Server-qn5Ws_d0.d.mts → Server-hwbZ7P2g.d.mts} +2 -2
  8. package/dist/{Server-qn5Ws_d0.d.mts.map → Server-hwbZ7P2g.d.mts.map} +1 -1
  9. package/dist/{ServerEvent-BY4f3RVF.mjs → ServerEvent-L0rT_mBJ.mjs} +10 -1
  10. package/dist/{ServerEvent-BY4f3RVF.mjs.map → ServerEvent-L0rT_mBJ.mjs.map} +1 -1
  11. package/dist/{ServerHook-W111nEhe.d.mts → ServerHook-CyVEr5OL.d.mts} +2 -2
  12. package/dist/{ServerHook-W111nEhe.d.mts.map → ServerHook-CyVEr5OL.d.mts.map} +1 -1
  13. package/dist/{ServerLoadEvent-BH6oG1o6.d.mts → ServerLoadEvent-F60w1TZt.d.mts} +14 -4
  14. package/dist/ServerLoadEvent-F60w1TZt.d.mts.map +1 -0
  15. package/dist/{Site-DGZJB7Do.d.mts → Site-CAeAqjkk.d.mts} +192 -7
  16. package/dist/Site-CAeAqjkk.d.mts.map +1 -0
  17. package/dist/bin/index.js +37 -2
  18. package/dist/bin/index.js.map +1 -1
  19. package/dist/clientEntry.mjs +45 -6
  20. package/dist/clientEntry.mjs.map +1 -1
  21. package/dist/dev.d.mts +2 -2
  22. package/dist/dev.mjs +2 -2
  23. package/dist/{devPlugin-lLzauETn.mjs → devPlugin-D9b5uhzm.mjs} +2 -2
  24. package/dist/{devPlugin-lLzauETn.mjs.map → devPlugin-D9b5uhzm.mjs.map} +1 -1
  25. package/dist/discovery.d.mts +1 -1
  26. package/dist/index.d.mts +5 -5
  27. package/dist/{load-G-4A435s.mjs → load-BODDzmH0.mjs} +162 -67
  28. package/dist/load-BODDzmH0.mjs.map +1 -0
  29. package/dist/nav.d.mts +65 -4
  30. package/dist/nav.d.mts.map +1 -1
  31. package/dist/nav.mjs +38 -10
  32. package/dist/nav.mjs.map +1 -1
  33. package/dist/nodeDev.d.mts +1 -1
  34. package/dist/nodeDev.mjs +1 -1
  35. package/dist/openapi.d.mts +24 -80
  36. package/dist/openapi.d.mts.map +1 -1
  37. package/dist/openapi.mjs +36 -1
  38. package/dist/openapi.mjs.map +1 -0
  39. package/dist/{plugin-D8Www11B.mjs → plugin-BQsMnkTj.mjs} +42 -3
  40. package/dist/plugin-BQsMnkTj.mjs.map +1 -0
  41. package/dist/run.d.mts +1 -1
  42. package/dist/run.mjs +1 -1
  43. package/dist/{runOpenApi-C5yMpQU1.mjs → runOpenApi-BZ314IiI.mjs} +44 -21
  44. package/dist/runOpenApi-BZ314IiI.mjs.map +1 -0
  45. package/dist/server/Server.d.mts +1 -1
  46. package/dist/server/Server.mjs +1 -1
  47. package/dist/server.d.mts +4 -4
  48. package/dist/server.mjs +2 -2
  49. package/dist/{serverEntry-D1hE-Jzt.mjs → serverEntry-8YnfpKTj.mjs} +2 -2
  50. package/dist/{serverEntry-D1hE-Jzt.mjs.map → serverEntry-8YnfpKTj.mjs.map} +1 -1
  51. package/dist/{serverEntry-BGii8bB6.d.mts → serverEntry-Da1PFlIU.d.mts} +3 -3
  52. package/dist/{serverEntry-BGii8bB6.d.mts.map → serverEntry-Da1PFlIU.d.mts.map} +1 -1
  53. package/dist/serverEntry.d.mts +1 -1
  54. package/dist/serverEntry.mjs +1 -1
  55. package/dist/{serverHandlers-CSBUEgJt.mjs → serverHandlers-Ba_35jpO.mjs} +38 -12
  56. package/dist/serverHandlers-Ba_35jpO.mjs.map +1 -0
  57. package/dist/{sitemap-xmE0zfme.d.mts → sitemap-CnIYTLhu.d.mts} +2 -2
  58. package/dist/{sitemap-xmE0zfme.d.mts.map → sitemap-CnIYTLhu.d.mts.map} +1 -1
  59. package/dist/test.d.mts +2 -2
  60. package/dist/test.mjs +2 -2
  61. package/package.json +10 -7
  62. package/dist/MiddlewareFunction-BZilnEei.d.mts.map +0 -1
  63. package/dist/Router-By9Nlg39.d.mts.map +0 -1
  64. package/dist/ServerLoadEvent-BH6oG1o6.d.mts.map +0 -1
  65. package/dist/Site-DGZJB7Do.d.mts.map +0 -1
  66. package/dist/load-G-4A435s.mjs.map +0 -1
  67. package/dist/plugin-D8Www11B.mjs.map +0 -1
  68. package/dist/runOpenApi-C5yMpQU1.mjs.map +0 -1
  69. package/dist/serverHandlers-CSBUEgJt.mjs.map +0 -1
@@ -1,8 +1,43 @@
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-G-4A435s.mjs";
4
+ import { a as client, n as navigate, r as loadData } from "./load-BODDzmH0.mjs";
5
5
  import manifest from "@torpor/build/manifest";
6
+ //#region src/nav/navigationFailure.ts
7
+ /**
8
+ * Decides what happens after a navigation rendered nothing.
9
+ *
10
+ * A failed navigation while offline can't be recovered by a document load
11
+ * either (unless a service worker has that url cached), so the current page is
12
+ * kept — often holding an unsaved form or an optimistic edit — and the app is
13
+ * told through the cancelable `torpor:navigation-failed` `CustomEvent` on
14
+ * `window`. Everything else takes the document fallback: by-design server
15
+ * navigations (`+server` routes, redirects), and online failures such as a
16
+ * stale chunk hash, which a reload fixes by picking up the new manifest.
17
+ *
18
+ * `navigator.onLine` only reports that the machine has a network interface,
19
+ * not that the server is reachable, so it is used here as a hint (it decides
20
+ * whether to keep the page, not whether the network works). The event carries
21
+ * the caught error so an app can tell the cases apart.
22
+ *
23
+ * Returns `"document"` when the caller should navigate the document, and
24
+ * `"kept"` when the page was left in place.
25
+ */
26
+ function handleNavigationFailure(href, result) {
27
+ if (result.type !== "failed" || navigator.onLine !== false) return "document";
28
+ const event = new CustomEvent("torpor:navigation-failed", {
29
+ cancelable: true,
30
+ detail: {
31
+ href,
32
+ reason: "offline",
33
+ error: result.error
34
+ }
35
+ });
36
+ if (!window.dispatchEvent(event)) return "document";
37
+ console.warn(`Navigation to ${href} failed while offline; staying on the current page. Listen for torpor:navigation-failed to show your own notice.`);
38
+ return "kept";
39
+ }
40
+ //#endregion
6
41
  //#region src/site/clientEntry.ts
7
42
  setBasePath(manifest.base);
8
43
  const router = new Router();
@@ -16,16 +51,20 @@ window.addEventListener("click", async (e) => {
16
51
  e.preventDefault();
17
52
  const href = link.href;
18
53
  const url = new URL(href);
19
- let navigated = false;
54
+ let result;
20
55
  try {
21
- navigated = await navigate(url);
56
+ result = await navigate(url);
22
57
  } catch (error) {
23
58
  console.error(error);
59
+ result = {
60
+ type: "failed",
61
+ error
62
+ };
24
63
  }
25
- if (navigated) {
64
+ if (result.type === "rendered") {
26
65
  window.history.replaceState({ scroll: window.scrollY }, "", document.location.href);
27
66
  window.history.pushState({ scroll: 0 }, "", url);
28
- } else window.location.href = href;
67
+ } else if (handleNavigationFailure(href, result) === "document") window.location.href = href;
29
68
  }
30
69
  });
31
70
  window.addEventListener("mouseover", maybePrefetch);
@@ -64,7 +103,7 @@ function ignoreAnchorMouseEvent(link, e) {
64
103
  return e.defaultPrevented || mouse.altKey || mouse.ctrlKey || mouse.metaKey || mouse.shiftKey || link.target && link.target !== "_self" || link.rel === "external" || link.hasAttribute("download") || link.isContentEditable;
65
104
  }
66
105
  window.addEventListener("popstate", async () => {
67
- if (!await navigateToLocation(document.location)) {
106
+ if ((await navigateToLocation(document.location)).type !== "rendered") {
68
107
  window.location.reload();
69
108
  return;
70
109
  }
@@ -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\tlet navigated = false;\n\t\ttry {\n\t\t\tnavigated = await navigate(url);\n\t\t} catch (error) {\n\t\t\t// `navigate` already catches its own failures, but never let an\n\t\t\t// unexpected throw swallow the full-page fallback\n\t\t\tconsole.error(error);\n\t\t}\n\t\tif (navigated) {\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,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;EAExB,IAAI,YAAY;EAChB,IAAI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,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"}
1
+ {"version":3,"file":"clientEntry.mjs","names":[],"sources":["../src/nav/navigationFailure.ts","../src/site/clientEntry.ts"],"sourcesContent":["import type { NavigationResult } from \"./navigate.ts\";\n\n/**\n * The detail of the `torpor:navigation-failed` window event.\n */\nexport type NavigationFailureDetail = {\n\t/** The url the navigation was headed to. */\n\thref: string;\n\t/** Why the page was kept: the network is unreachable. */\n\treason: \"offline\";\n\t/** The failure that would have triggered the document fallback. */\n\terror?: unknown;\n};\n\n/** What the caller should do after a navigation rendered nothing. */\nexport type NavigationFallback = \"document\" | \"kept\";\n\n/**\n * Decides what happens after a navigation rendered nothing.\n *\n * A failed navigation while offline can't be recovered by a document load\n * either (unless a service worker has that url cached), so the current page is\n * kept — often holding an unsaved form or an optimistic edit — and the app is\n * told through the cancelable `torpor:navigation-failed` `CustomEvent` on\n * `window`. Everything else takes the document fallback: by-design server\n * navigations (`+server` routes, redirects), and online failures such as a\n * stale chunk hash, which a reload fixes by picking up the new manifest.\n *\n * `navigator.onLine` only reports that the machine has a network interface,\n * not that the server is reachable, so it is used here as a hint (it decides\n * whether to keep the page, not whether the network works). The event carries\n * the caught error so an app can tell the cases apart.\n *\n * Returns `\"document\"` when the caller should navigate the document, and\n * `\"kept\"` when the page was left in place.\n */\nexport default function handleNavigationFailure(\n\thref: string,\n\tresult: NavigationResult,\n): NavigationFallback {\n\tif (result.type !== \"failed\" || navigator.onLine !== false) {\n\t\treturn \"document\";\n\t}\n\n\tconst event = new CustomEvent<NavigationFailureDetail>(\"torpor:navigation-failed\", {\n\t\tcancelable: true,\n\t\tdetail: { href, reason: \"offline\", error: result.error },\n\t});\n\t// An app that cancels the event (e.g. its service worker caches the target\n\t// shell) asks for the document navigation after all\n\tif (!window.dispatchEvent(event)) {\n\t\treturn \"document\";\n\t}\n\n\tconsole.warn(\n\t\t`Navigation to ${href} failed while offline; staying on the current page. ` +\n\t\t\t\"Listen for torpor:navigation-failed to show your own notice.\",\n\t);\n\treturn \"kept\";\n}\n","import manifest from \"@torpor/build/manifest\";\nimport loadData from \"../nav/loadData.ts\";\nimport navigate from \"../nav/navigate.ts\";\nimport type { NavigationResult } from \"../nav/navigate.ts\";\nimport handleNavigationFailure from \"../nav/navigationFailure.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\tlet result: NavigationResult;\n\t\ttry {\n\t\t\tresult = await navigate(url);\n\t\t} catch (error) {\n\t\t\t// `navigate` already catches its own failures, but never let an\n\t\t\t// unexpected throw swallow the fallback\n\t\t\tconsole.error(error);\n\t\t\tresult = { type: \"failed\", error };\n\t\t}\n\t\tif (result.type === \"rendered\") {\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 if (handleNavigationFailure(href, result) === \"document\") {\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 result = await navigateToLocation(document.location);\n\tif (result.type !== \"rendered\") {\n\t\t// TODO: keep the page and notify the app when offline, like a click\n\t\t// failure; the url has already moved here, so that needs a history fix\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(\n\tlocation: Location,\n\tfirstTime = false,\n): Promise<NavigationResult> {\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":";;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAwB,wBACvB,MACA,QACqB;CACrB,IAAI,OAAO,SAAS,YAAY,UAAU,WAAW,OACpD,OAAO;CAGR,MAAM,QAAQ,IAAI,YAAqC,4BAA4B;EAClF,YAAY;EACZ,QAAQ;GAAE;GAAM,QAAQ;GAAW,OAAO,OAAO;EAAM;CACxD,CAAC;CAGD,IAAI,CAAC,OAAO,cAAc,KAAK,GAC9B,OAAO;CAGR,QAAQ,KACP,iBAAiB,KAAK,iHAEvB;CACA,OAAO;AACR;;;AC/CA,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;EAExB,IAAI;EACJ,IAAI;GACH,SAAS,MAAM,SAAS,GAAG;EAC5B,SAAS,OAAO;GAGf,QAAQ,MAAM,KAAK;GACnB,SAAS;IAAE,MAAM;IAAU;GAAM;EAClC;EACA,IAAI,OAAO,SAAS,YAAY;GAG/B,OAAO,QAAQ,aAA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,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,KAAI,MADiB,mBAAmB,SAAS,QAAQ,EAAA,CAC9C,SAAS,YAAY;EAG/B,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,mBACd,UACA,YAAY,OACgB;CAG5B,MAAM,OAAO,KAAA;CAEb,OAAO,MAAM,SAAS,IAAI,IAAI,SAAS,SAAS,CAAC,GAAG,SAAS;AAC9D"}
package/dist/dev.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { t as Server } from "./Server-qn5Ws_d0.mjs";
2
- import { t as load } from "./serverEntry-BGii8bB6.mjs";
1
+ import { t as Server } from "./Server-hwbZ7P2g.mjs";
2
+ import { t as load } from "./serverEntry-Da1PFlIU.mjs";
3
3
  export { Server, load };
package/dist/dev.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { t as Server } from "./Server-dcRbdPXf.mjs";
2
- import { t as load } from "./serverEntry-D1hE-Jzt.mjs";
1
+ import { t as Server } from "./Server-Djd9-NkU.mjs";
2
+ import { t as load } from "./serverEntry-8YnfpKTj.mjs";
3
3
  export { Server, load };
@@ -1,5 +1,5 @@
1
1
  import { r as serverError } from "./response-C5EZsszY.mjs";
2
- import { t as Server } from "./Server-dcRbdPXf.mjs";
2
+ import { t as Server } from "./Server-Djd9-NkU.mjs";
3
3
  import { t as flattenHeaders } from "./flattenHeaders-DM5qsSqO.mjs";
4
4
  import { existsSync, promises, realpathSync } from "node:fs";
5
5
  import fpath from "node:path";
@@ -141,4 +141,4 @@ async function sendResponse(response, res) {
141
141
  //#endregion
142
142
  export { siteEntryPaths as i, prepareTemplate as n, detectSourceMode as r, devPlugin as t };
143
143
 
144
- //# sourceMappingURL=devPlugin-lLzauETn.mjs.map
144
+ //# sourceMappingURL=devPlugin-D9b5uhzm.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"devPlugin-lLzauETn.mjs","names":["path","path","fs"],"sources":["../src/utils/entryPaths.ts","../src/run/prepareTemplate.ts","../src/run/devPlugin.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Paths to the site entry files that `tb` loads from the installed\n * `@torpor/build` package, in either source (linked framework) or dist\n * (registry install) mode.\n */\nexport type SiteEntryPaths = {\n\tserverEntry: string;\n\tclientEntry: string;\n\tclientDevEntry: string;\n};\n\n/**\n * Whether tb should run the framework from its TypeScript source instead of\n * its compiled dist. This is a framework-development convenience: registry\n * installs always run dist. Source mode is enabled explicitly via the\n * TORPOR_SOURCE_DEV env var, or automatically when both `@torpor/build` and\n * `@torpor/view` are symlinked into the app from outside node_modules (as\n * workspace links and `link:` overrides do). Both packages must be linked,\n * because source mode resolves their `torpor:source` export conditions, which\n * point at src files that registry installs don't ship.\n */\nexport function detectSourceMode(siteRoot: string): boolean {\n\tif (process.env.TORPOR_SOURCE_DEV) return true;\n\tconst packages = [\"@torpor/build\", \"@torpor/view\"];\n\treturn packages.every((pkg) => {\n\t\ttry {\n\t\t\tconst dist = path.resolve(siteRoot, \"node_modules\", pkg, \"dist/index.mjs\");\n\t\t\tconst real = realpathSync(dist);\n\t\t\treturn !real.includes(\"node_modules\");\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\n/**\n * The site entry files for the given mode: raw TypeScript sources when the\n * framework is linked (Vite transforms them, and edits show up without a\n * rebuild), compiled `.mjs` bundles for registry installs.\n */\nexport function siteEntryPaths(siteRoot: string, sourceMode: boolean): SiteEntryPaths {\n\tconst folder = path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/site\" : \"dist\",\n\t);\n\tconst ext = sourceMode ? \".ts\" : \".mjs\";\n\treturn {\n\t\tserverEntry: path.join(folder, `serverEntry${ext}`),\n\t\tclientEntry: path.join(folder, `clientEntry${ext}`),\n\t\tclientDevEntry: path.join(folder, `clientEntryDev${ext}`),\n\t};\n}\n\n/**\n * The torpor `Server` class module that a Cloudflare `_worker.ts` imports,\n * for the given mode.\n */\nexport function serverClassPath(siteRoot: string, sourceMode: boolean): string {\n\treturn path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/server/Server.ts\" : \"dist/server/Server.mjs\",\n\t);\n}\n","export default function prepareTemplate(\n\ttemplate: string,\n\tclientScript: string,\n\tclientDevScript?: string,\n): string {\n\tlet result = template;\n\n\t// Put %COMPONENT_HEAD% before </head>\n\t// This is where styles will go\n\tlet headStart = result.indexOf(\"</head>\");\n\tif (headStart === -1) {\n\t\tthrow new Error(`Couldn't find <head> end tag`);\n\t}\n\tresult = result.substring(0, headStart) + \"%COMPONENT_HEAD%\" + result.substring(headStart);\n\n\t// Put %COMPONENT_BODY% inside <div id=\"app\"></div>\n\t// This is where the component's HTML will go\n\tlet divMatchStart = regexIndexOf(result, /<div\\s+id=(\"app\"|'app'|app)[\\s>]/);\n\tif (divMatchStart === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tlet bodyStart = result.indexOf(\">\", divMatchStart) + 1;\n\tlet bodyEnd = result.indexOf(\"</div>\", bodyStart);\n\tif (bodyEnd === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tresult = result.substring(0, bodyStart) + \"%COMPONENT_BODY%\" + result.substring(bodyEnd);\n\n\t// Add the clientEntry script at the very end, for hydrating and navigating\n\tif (clientDevScript) {\n\t\tresult += `<script type=\"module\" src=\"${clientDevScript}\"></script>`;\n\t}\n\tresult += `<script type=\"module\" src=\"${clientScript}\"></script>`;\n\n\treturn result;\n}\n\n// From https://stackoverflow.com/a/274094\nfunction regexIndexOf(string: string, regex: RegExp, position?: number) {\n\tvar indexOf = string.substring(position || 0).search(regex);\n\treturn indexOf >= 0 ? indexOf + (position || 0) : indexOf;\n}\n","import { type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { type Plugin, type ViteDevServer } from \"vite\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport flattenHeaders from \"../server/connect/flattenHeaders.ts\";\nimport type Site from \"../site/Site.ts\";\nimport { siteEntryPaths } from \"../utils/entryPaths\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\n\ntype ReqHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\n/**\n * The default Node-runtime dev plugin. Reads `src/site.html`, sets up a torpor\n * `Server` whose catch-all route renders via `vite.ssrLoadModule`, and registers\n * a Connect middleware (after Vite's own middlewares) that bridges Node\n * req/res to the torpor Server's fetch handler.\n *\n * Adapters that need a different runtime (e.g. workerd) provide their own\n * `dev()` plugin instead.\n */\nexport default function devPlugin(site: Site, sourceMode = false): Plugin {\n\treturn {\n\t\tname: \"torpor-dev\",\n\t\tconfigureServer(vite) {\n\t\t\t// Kick off async setup immediately; the middleware awaits it so we\n\t\t\t// don't depend on whether Vite awaits configureServer itself.\n\t\t\tconst handlerPromise = createDevHandler(vite, site, sourceMode);\n\t\t\t// Return a post-hook so our middleware runs AFTER Vite's internal\n\t\t\t// middlewares (static serving, transforms, HMR), acting as the SSR\n\t\t\t// fallback.\n\t\t\treturn () => {\n\t\t\t\tvite.middlewares.use(async (req, res, next) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst handler = await handlerPromise;\n\t\t\t\t\t\tawait handler(req, res);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tnext(e as Error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t};\n}\n\nasync function createDevHandler(\n\tvite: ViteDevServer,\n\tsite: Site,\n\tsourceMode: boolean,\n): Promise<ReqHandler> {\n\tconst entries = siteEntryPaths(site.root, sourceMode);\n\tconst serverScript = entries.serverEntry;\n\n\t// Read site.html if present\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc). An endpoints-only\n\t// site has no site.html, and no template is needed\n\tlet template: string | undefined;\n\tconst templateFile = path.resolve(site.root, \"src/site.html\");\n\tif (existsSync(templateFile)) {\n\t\ttemplate = await fs.readFile(templateFile, \"utf-8\");\n\n\t\t// Apply Vite HTML transforms. This injects the Vite HMR client, and also\n\t\t// applies HTML transforms from Vite plugins. Note that we only support a\n\t\t// universal transform, not individual transforms for each route\n\t\ttemplate = await vite.transformIndexHtml(\"\", template);\n\n\t\t// Prepare site.html so that we can just splice components into it\n\t\ttemplate = prepareTemplate(template, entries.clientEntry, entries.clientDevEntry);\n\t}\n\n\tconst server = new Server();\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry. ssrLoadModule automatically transforms ESM\n\t\t\t// source code to be usable in Node.js. No bundling is required, and\n\t\t\t// it provides efficient invalidation similar to HMR\n\t\t\tconst { load } = await vite.ssrLoadModule(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\t// If an error is caught, let Vite fix the stack trace so it maps\n\t\t\t// back to your actual source code\n\t\t\tvite.ssrFixStacktrace(e);\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Put adapter-specific functionality in the `adapter` property of\n\t// globalThis for now\n\t// @ts-ignore\n\tglobalThis.adapter = { env: process.env };\n\n\treturn async (req, res) => {\n\t\tconst request = await nodeReqToRequest(req);\n\t\tconst response = await server.fetch(request);\n\t\tawait sendResponse(response, res);\n\t};\n}\n\nasync function nodeReqToRequest(req: IncomingMessage): Promise<Request> {\n\tconst url = req.url ?? \"/\";\n\tconst host = req.headers.host ?? \"localhost\";\n\tconst protocol = \"encrypted\" in req.socket && req.socket.encrypted ? \"https\" : \"http\";\n\tconst init: RequestInit = {\n\t\tmethod: req.method,\n\t\theaders: flattenHeaders(req.headers),\n\t};\n\tif (req.method !== \"GET\" && req.method !== \"HEAD\") {\n\t\tinit.body = Readable.toWeb(req) as ReadableStream;\n\t\t// @ts-ignore duplex is required when streaming a body\n\t\tinit.duplex = \"half\";\n\t}\n\treturn new Request(`${protocol}://${host}${url}`, init);\n}\n\nasync function sendResponse(response: Response, res: ServerResponse): Promise<void> {\n\tres.statusCode = response.status;\n\tresponse.headers.forEach((value, key) => res.setHeader(key, value));\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\tReadable.fromWeb(response.body as unknown as import(\"node:stream/web\").ReadableStream).pipe(res);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAiB,UAA2B;CAC3D,IAAI,QAAQ,IAAI,mBAAmB,OAAO;CAE1C,OAAO,CADW,iBAAiB,cACrB,CAAC,CAAC,OAAO,QAAQ;EAC9B,IAAI;GACH,MAAM,OAAOA,MAAK,QAAQ,UAAU,gBAAgB,KAAK,gBAAgB;GAEzE,OAAO,CADM,aAAa,IACf,CAAC,CAAC,SAAS,cAAc;EACrC,QAAQ;GACP,OAAO;EACR;CACD,CAAC;AACF;;;;;;AAOA,SAAgB,eAAe,UAAkB,YAAqC;CACrF,MAAM,SAASA,MAAK,QACnB,UACA,8BACA,aAAa,aAAa,MAC3B;CACA,MAAM,MAAM,aAAa,QAAQ;CACjC,OAAO;EACN,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,gBAAgBA,MAAK,KAAK,QAAQ,iBAAiB,KAAK;CACzD;AACD;;;ACvDA,SAAwB,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AAS,IAA2D,CAAC,CAAC,KAAK,GAAG;AAChG"}
1
+ {"version":3,"file":"devPlugin-D9b5uhzm.mjs","names":["path","path","fs"],"sources":["../src/utils/entryPaths.ts","../src/run/prepareTemplate.ts","../src/run/devPlugin.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Paths to the site entry files that `tb` loads from the installed\n * `@torpor/build` package, in either source (linked framework) or dist\n * (registry install) mode.\n */\nexport type SiteEntryPaths = {\n\tserverEntry: string;\n\tclientEntry: string;\n\tclientDevEntry: string;\n};\n\n/**\n * Whether tb should run the framework from its TypeScript source instead of\n * its compiled dist. This is a framework-development convenience: registry\n * installs always run dist. Source mode is enabled explicitly via the\n * TORPOR_SOURCE_DEV env var, or automatically when both `@torpor/build` and\n * `@torpor/view` are symlinked into the app from outside node_modules (as\n * workspace links and `link:` overrides do). Both packages must be linked,\n * because source mode resolves their `torpor:source` export conditions, which\n * point at src files that registry installs don't ship.\n */\nexport function detectSourceMode(siteRoot: string): boolean {\n\tif (process.env.TORPOR_SOURCE_DEV) return true;\n\tconst packages = [\"@torpor/build\", \"@torpor/view\"];\n\treturn packages.every((pkg) => {\n\t\ttry {\n\t\t\tconst dist = path.resolve(siteRoot, \"node_modules\", pkg, \"dist/index.mjs\");\n\t\t\tconst real = realpathSync(dist);\n\t\t\treturn !real.includes(\"node_modules\");\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\n/**\n * The site entry files for the given mode: raw TypeScript sources when the\n * framework is linked (Vite transforms them, and edits show up without a\n * rebuild), compiled `.mjs` bundles for registry installs.\n */\nexport function siteEntryPaths(siteRoot: string, sourceMode: boolean): SiteEntryPaths {\n\tconst folder = path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/site\" : \"dist\",\n\t);\n\tconst ext = sourceMode ? \".ts\" : \".mjs\";\n\treturn {\n\t\tserverEntry: path.join(folder, `serverEntry${ext}`),\n\t\tclientEntry: path.join(folder, `clientEntry${ext}`),\n\t\tclientDevEntry: path.join(folder, `clientEntryDev${ext}`),\n\t};\n}\n\n/**\n * The torpor `Server` class module that a Cloudflare `_worker.ts` imports,\n * for the given mode.\n */\nexport function serverClassPath(siteRoot: string, sourceMode: boolean): string {\n\treturn path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/server/Server.ts\" : \"dist/server/Server.mjs\",\n\t);\n}\n","export default function prepareTemplate(\n\ttemplate: string,\n\tclientScript: string,\n\tclientDevScript?: string,\n): string {\n\tlet result = template;\n\n\t// Put %COMPONENT_HEAD% before </head>\n\t// This is where styles will go\n\tlet headStart = result.indexOf(\"</head>\");\n\tif (headStart === -1) {\n\t\tthrow new Error(`Couldn't find <head> end tag`);\n\t}\n\tresult = result.substring(0, headStart) + \"%COMPONENT_HEAD%\" + result.substring(headStart);\n\n\t// Put %COMPONENT_BODY% inside <div id=\"app\"></div>\n\t// This is where the component's HTML will go\n\tlet divMatchStart = regexIndexOf(result, /<div\\s+id=(\"app\"|'app'|app)[\\s>]/);\n\tif (divMatchStart === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tlet bodyStart = result.indexOf(\">\", divMatchStart) + 1;\n\tlet bodyEnd = result.indexOf(\"</div>\", bodyStart);\n\tif (bodyEnd === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tresult = result.substring(0, bodyStart) + \"%COMPONENT_BODY%\" + result.substring(bodyEnd);\n\n\t// Add the clientEntry script at the very end, for hydrating and navigating\n\tif (clientDevScript) {\n\t\tresult += `<script type=\"module\" src=\"${clientDevScript}\"></script>`;\n\t}\n\tresult += `<script type=\"module\" src=\"${clientScript}\"></script>`;\n\n\treturn result;\n}\n\n// From https://stackoverflow.com/a/274094\nfunction regexIndexOf(string: string, regex: RegExp, position?: number) {\n\tvar indexOf = string.substring(position || 0).search(regex);\n\treturn indexOf >= 0 ? indexOf + (position || 0) : indexOf;\n}\n","import { type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { type Plugin, type ViteDevServer } from \"vite\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport flattenHeaders from \"../server/connect/flattenHeaders.ts\";\nimport type Site from \"../site/Site.ts\";\nimport { siteEntryPaths } from \"../utils/entryPaths\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\n\ntype ReqHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\n/**\n * The default Node-runtime dev plugin. Reads `src/site.html`, sets up a torpor\n * `Server` whose catch-all route renders via `vite.ssrLoadModule`, and registers\n * a Connect middleware (after Vite's own middlewares) that bridges Node\n * req/res to the torpor Server's fetch handler.\n *\n * Adapters that need a different runtime (e.g. workerd) provide their own\n * `dev()` plugin instead.\n */\nexport default function devPlugin(site: Site, sourceMode = false): Plugin {\n\treturn {\n\t\tname: \"torpor-dev\",\n\t\tconfigureServer(vite) {\n\t\t\t// Kick off async setup immediately; the middleware awaits it so we\n\t\t\t// don't depend on whether Vite awaits configureServer itself.\n\t\t\tconst handlerPromise = createDevHandler(vite, site, sourceMode);\n\t\t\t// Return a post-hook so our middleware runs AFTER Vite's internal\n\t\t\t// middlewares (static serving, transforms, HMR), acting as the SSR\n\t\t\t// fallback.\n\t\t\treturn () => {\n\t\t\t\tvite.middlewares.use(async (req, res, next) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst handler = await handlerPromise;\n\t\t\t\t\t\tawait handler(req, res);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tnext(e as Error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t};\n}\n\nasync function createDevHandler(\n\tvite: ViteDevServer,\n\tsite: Site,\n\tsourceMode: boolean,\n): Promise<ReqHandler> {\n\tconst entries = siteEntryPaths(site.root, sourceMode);\n\tconst serverScript = entries.serverEntry;\n\n\t// Read site.html if present\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc). An endpoints-only\n\t// site has no site.html, and no template is needed\n\tlet template: string | undefined;\n\tconst templateFile = path.resolve(site.root, \"src/site.html\");\n\tif (existsSync(templateFile)) {\n\t\ttemplate = await fs.readFile(templateFile, \"utf-8\");\n\n\t\t// Apply Vite HTML transforms. This injects the Vite HMR client, and also\n\t\t// applies HTML transforms from Vite plugins. Note that we only support a\n\t\t// universal transform, not individual transforms for each route\n\t\ttemplate = await vite.transformIndexHtml(\"\", template);\n\n\t\t// Prepare site.html so that we can just splice components into it\n\t\ttemplate = prepareTemplate(template, entries.clientEntry, entries.clientDevEntry);\n\t}\n\n\tconst server = new Server();\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry. ssrLoadModule automatically transforms ESM\n\t\t\t// source code to be usable in Node.js. No bundling is required, and\n\t\t\t// it provides efficient invalidation similar to HMR\n\t\t\tconst { load } = await vite.ssrLoadModule(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\t// If an error is caught, let Vite fix the stack trace so it maps\n\t\t\t// back to your actual source code\n\t\t\tvite.ssrFixStacktrace(e);\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Put adapter-specific functionality in the `adapter` property of\n\t// globalThis for now\n\t// @ts-ignore\n\tglobalThis.adapter = { env: process.env };\n\n\treturn async (req, res) => {\n\t\tconst request = await nodeReqToRequest(req);\n\t\tconst response = await server.fetch(request);\n\t\tawait sendResponse(response, res);\n\t};\n}\n\nasync function nodeReqToRequest(req: IncomingMessage): Promise<Request> {\n\tconst url = req.url ?? \"/\";\n\tconst host = req.headers.host ?? \"localhost\";\n\tconst protocol = \"encrypted\" in req.socket && req.socket.encrypted ? \"https\" : \"http\";\n\tconst init: RequestInit = {\n\t\tmethod: req.method,\n\t\theaders: flattenHeaders(req.headers),\n\t};\n\tif (req.method !== \"GET\" && req.method !== \"HEAD\") {\n\t\tinit.body = Readable.toWeb(req) as ReadableStream;\n\t\t// @ts-ignore duplex is required when streaming a body\n\t\tinit.duplex = \"half\";\n\t}\n\treturn new Request(`${protocol}://${host}${url}`, init);\n}\n\nasync function sendResponse(response: Response, res: ServerResponse): Promise<void> {\n\tres.statusCode = response.status;\n\tresponse.headers.forEach((value, key) => res.setHeader(key, value));\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\tReadable.fromWeb(response.body as unknown as import(\"node:stream/web\").ReadableStream).pipe(res);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAiB,UAA2B;CAC3D,IAAI,QAAQ,IAAI,mBAAmB,OAAO;CAE1C,OAAO,CADW,iBAAiB,cACrB,CAAC,CAAC,OAAO,QAAQ;EAC9B,IAAI;GACH,MAAM,OAAOA,MAAK,QAAQ,UAAU,gBAAgB,KAAK,gBAAgB;GAEzE,OAAO,CADM,aAAa,IACf,CAAC,CAAC,SAAS,cAAc;EACrC,QAAQ;GACP,OAAO;EACR;CACD,CAAC;AACF;;;;;;AAOA,SAAgB,eAAe,UAAkB,YAAqC;CACrF,MAAM,SAASA,MAAK,QACnB,UACA,8BACA,aAAa,aAAa,MAC3B;CACA,MAAM,MAAM,aAAa,QAAQ;CACjC,OAAO;EACN,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,gBAAgBA,MAAK,KAAK,QAAQ,iBAAiB,KAAK;CACzD;AACD;;;ACvDA,SAAwB,gBACvB,UACA,cACA,iBACS;CACT,IAAI,SAAS;CAIb,IAAI,YAAY,OAAO,QAAQ,SAAS;CACxC,IAAI,cAAc,IACjB,MAAM,IAAI,MAAM,8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me.mjs";
1
+ import { n as sitemapResponse, r as HeadElement, t as SitemapOptions } from "./sitemap-CnIYTLhu.mjs";
2
2
  //#region src/discovery/seo.d.ts
3
3
  /**
4
4
  * The elements to build head markup from: a page title, a description and
package/dist/index.d.mts CHANGED
@@ -1,11 +1,11 @@
1
- import { t as Router } from "./Router-By9Nlg39.mjs";
1
+ import { t as Router } from "./Router-Bxm7K20d.mjs";
2
2
  import { a as RouteParamsOf, i as RouteArgsOf, n as ParseRouteParams, r as RouteArgs } from "./ParseRouteParams-BtC0eH3z.mjs";
3
- import { n as QueryRecord, r as ServerLoadEvent, t as FormDataRecord } from "./ServerLoadEvent-BH6oG1o6.mjs";
4
- import { t as ServerHook } from "./ServerHook-W111nEhe.mjs";
5
- import { a as PageLoadReturn, i as PageEndPoint, o as PageLoadEvent } from "./sitemap-xmE0zfme.mjs";
3
+ import { n as QueryRecord, r as ServerLoadEvent, t as FormDataRecord } from "./ServerLoadEvent-F60w1TZt.mjs";
4
+ import { t as ServerHook } from "./ServerHook-CyVEr5OL.mjs";
5
+ import { a as PageLoadReturn, i as PageEndPoint, o as PageLoadEvent } from "./sitemap-CnIYTLhu.mjs";
6
6
  import { n as UntypedResponse, t as TypedResponse } from "./TypedResponse-6lznqN4U.mjs";
7
7
  import { t as StandardSchemaV1 } from "./StandardSchema-D28L8_zZ.mjs";
8
- import { a as ServerEndPoint, c as ActionBody, d as PageServerActionSchemas, f as PageServerEndPoint, g as Adapter, h as SitePlugin, i as SchemaQuery, l as LoadParams, m as PageServerAction, n as ParamsOf, o as ServerEndPointSchemas, p as PageServerLoad, r as SchemaBody, s as ServerRequest, t as Site, u as LoadQuery } from "./Site-DGZJB7Do.mjs";
8
+ import { C as PageServerEndPoint, D as Adapter, E as SitePlugin, S as PageServerActionSchemas, T as PageServerAction, a as ServerEndPoint, b as LoadParams, i as SchemaQuery, n as ParamsOf, o as ServerEndPointSchemas, r as SchemaBody, s as ServerRequest, t as Site, w as PageServerLoad, x as LoadQuery, y as ActionBody } from "./Site-CAeAqjkk.mjs";
9
9
  import { t as Jsonify } from "./Jsonify-hFz5OjtZ.mjs";
10
10
  //#region src/types/PageData.d.ts
11
11
  /**
@@ -15,10 +15,11 @@ const client = globalThis[CLIENT_SYMBOL] ??= {
15
15
  //#endregion
16
16
  //#region src/nav/reload.ts
17
17
  /**
18
- * Reloads data for the currently loaded page and rerenders it.
18
+ * Reloads data for the currently loaded page and rerenders it. Returns whether
19
+ * the page was rendered in place (see `load`).
19
20
  */
20
21
  async function reload() {
21
- return await navigate(new URL(document.location.href));
22
+ return (await navigate(new URL(document.location.href))).type === "rendered";
22
23
  }
23
24
  //#endregion
24
25
  //#region src/nav/formSubmit.ts
@@ -36,7 +37,14 @@ async function formSubmit(e) {
36
37
  credentials: "same-origin",
37
38
  headers: { "X-Torpor-Form-Submit": "" }
38
39
  };
39
- const response = await fetch(action, options);
40
+ let response;
41
+ try {
42
+ response = await fetch(action, options);
43
+ } catch (error) {
44
+ console.error("The form submit failed", error);
45
+ handleSubmitFailure(form, action, error);
46
+ return;
47
+ }
40
48
  if (response.status === 200 && response.headers.has("Content-Disposition") && /attachment;\s*filename="(.+?)"/.test(response.headers.get("Content-Disposition"))) {
41
49
  const downloadFileName = response.headers.get("Content-Disposition")?.match(/attachment;\s*filename="(.+?)"/)[1] ?? "file";
42
50
  const downloadLink = document.createElement("a");
@@ -59,6 +67,30 @@ async function formSubmit(e) {
59
67
  } else window.location.reload();
60
68
  }
61
69
  }
70
+ /**
71
+ * Tells the app that a client form submission failed (offline, or the server
72
+ * couldn't be reached), so it can show its own notice. The form keeps the
73
+ * values the user typed, ready for the app to retry.
74
+ *
75
+ * Dispatched on `window` as a cancelable `torpor:submit-failed` `CustomEvent`.
76
+ * An app that cancels it asks for a native form submission after all, e.g. a
77
+ * service worker serves the POST, or the browser's own offline handling is
78
+ * preferred.
79
+ */
80
+ function handleSubmitFailure(form, action, error) {
81
+ const event = new CustomEvent("torpor:submit-failed", {
82
+ cancelable: true,
83
+ detail: {
84
+ action,
85
+ error
86
+ }
87
+ });
88
+ if (!window.dispatchEvent(event)) {
89
+ HTMLFormElement.prototype.submit.call(form);
90
+ return;
91
+ }
92
+ console.warn(`The form submission to ${action} failed; staying on the current page. Listen for torpor:submit-failed to show your own notice.`);
93
+ }
62
94
  //#endregion
63
95
  //#region src/nav/loadData.ts
64
96
  /**
@@ -74,8 +106,7 @@ async function loadData(handler, params, path, query, newLayoutStack, clientEndP
74
106
  let data = {};
75
107
  const layoutStack = client.layoutStack;
76
108
  const layouts = (handler.layouts ?? []).map((layout, index) => {
77
- let layoutPath = layout.path;
78
- for (let key in params) layoutPath = layoutPath.replace(`[${key}]`, params[key]);
109
+ const layoutPath = resolveLayoutPath(layout.path, params);
79
110
  const previous = layoutStack.at(index);
80
111
  const rendered = previous?.path === layoutPath;
81
112
  return {
@@ -105,32 +136,55 @@ async function loadData(handler, params, path, query, newLayoutStack, clientEndP
105
136
  Object.assign(stackLayout.data, previous.data);
106
137
  } else {
107
138
  const layoutEndPoint = (await layout.endPoint())?.default;
108
- const response = await runClientLoad(layoutEndPoint, clientLocation(layoutPath), query, params, stackLayout.data, prefetch);
109
- if (response) {
110
- if (isRedirect(response)) return;
111
- return {
112
- data,
113
- error: await errorOf(response)
114
- };
115
- }
139
+ const loaded = await runClientLoad(layoutEndPoint, clientLocation(layoutPath), query, params, stackLayout.data, prefetch);
140
+ if (loaded?.redirect) return;
141
+ if (loaded?.error) return {
142
+ data,
143
+ error: loaded.error
144
+ };
116
145
  const serverData = server.loads?.[index];
117
146
  if (serverData) Object.assign(stackLayout.data, serverData);
118
147
  }
119
148
  Object.assign(data, stackLayout.data);
120
149
  newLayoutStack.push(stackLayout);
121
150
  }
122
- const response = await runClientLoad(clientEndPoint, clientLocation(path), query, params, data, prefetch);
123
- if (response) {
124
- if (isRedirect(response)) return;
125
- return {
126
- data,
127
- error: await errorOf(response)
128
- };
129
- }
151
+ const loaded = await runClientLoad(clientEndPoint, clientLocation(path), query, params, data, prefetch);
152
+ if (loaded?.redirect) return;
153
+ if (loaded?.error) return {
154
+ data,
155
+ error: loaded.error
156
+ };
130
157
  const pageServerData = server.loads?.[handler.layouts?.length ?? 0];
131
158
  if (pageServerData) Object.assign(data, pageServerData);
132
159
  return { data };
133
160
  }
161
+ /** The path of a layout with its `[param]` segments substituted. */
162
+ function resolveLayoutPath(path, params) {
163
+ for (let key in params) path = path.replace(`[${key}]`, params[key]);
164
+ return path;
165
+ }
166
+ /**
167
+ * Builds the layout stack for an error page whose own loads can't run (offline,
168
+ * or the server is down): layouts already on screen keep their data and slot
169
+ * regions, so the error renders over the shell instead of the shell being
170
+ * replaced by a document load that would fail too. Layouts that aren't on
171
+ * screen render with no data.
172
+ */
173
+ function errorLayoutStack(handler, params) {
174
+ const stack = [];
175
+ (handler.layouts ?? []).forEach((layout, index) => {
176
+ const path = resolveLayoutPath(layout.path, params);
177
+ const previous = client.layoutStack.at(index);
178
+ const rendered = previous?.path === path;
179
+ stack.push({
180
+ path,
181
+ data: rendered && previous ? { ...previous.data } : {},
182
+ reuse: rendered,
183
+ slotRegion: rendered && previous ? previous.slotRegion : null
184
+ });
185
+ });
186
+ return stack;
187
+ }
134
188
  /**
135
189
  * A request-local registry of deferred promises. Values arrive after the first
136
190
  * frame (client navigation) or in inline scripts (initial hydration), and
@@ -202,9 +256,9 @@ async function loadServerData(handler, path, query, reusedLayouts, prefetch) {
202
256
  if (cached) return cached;
203
257
  const pending = requestServerData(path, query, reusedLayouts);
204
258
  client.prefetchedServerData[key] = pending;
205
- pending.catch(() => {
206
- if (client.prefetchedServerData[key] === pending) delete client.prefetchedServerData[key];
207
- });
259
+ pending.then((result) => {
260
+ if (isLoadError(result)) dropPrefetch(client.prefetchedServerData, key, pending);
261
+ }, () => dropPrefetch(client.prefetchedServerData, key, pending));
208
262
  return pending;
209
263
  }
210
264
  const prefetched = client.prefetchedServerData[key];
@@ -218,6 +272,14 @@ async function loadServerData(handler, path, query, reusedLayouts, prefetch) {
218
272
  function serverDataKey(path, query) {
219
273
  return path + (query.size > 0 ? `?${query}` : "");
220
274
  }
275
+ /** Whether a load resolved to an error result (as opposed to data/nothing). */
276
+ function isLoadError(value) {
277
+ return typeof value === "object" && value !== null && "error" in value;
278
+ }
279
+ /** Removes a failed prefetch, unless the navigation has already consumed it. */
280
+ function dropPrefetch(prefetches, key, pending) {
281
+ if (prefetches[key] === pending) delete prefetches[key];
282
+ }
221
283
  /**
222
284
  * The posted data request: `GET <page url>/~server` carrying the data header,
223
285
  * which the server answers with the page's and its layouts' server data as one
@@ -228,16 +290,28 @@ async function requestServerData(path, query, reusedLayouts) {
228
290
  for (let [name, value] of query) url.searchParams.append(name, value);
229
291
  const headers = { [DATA_REQUEST_HEADER]: "1" };
230
292
  if (reusedLayouts.length > 0) headers[DATA_REUSE_HEADER] = JSON.stringify(reusedLayouts);
231
- const response = await fetch(url, {
232
- redirect: "manual",
233
- headers
234
- });
235
- if (isRedirect(response)) return;
236
- if (!response.ok) return { error: await errorOf(response) };
237
- const type = response.headers.get("Content-Type");
238
- if (type?.includes("application/x-ndjson")) return await readServerDataStream(response);
239
- if (!type?.includes("application/json")) return {};
240
- return await response.json();
293
+ try {
294
+ const response = await fetch(url, {
295
+ redirect: "manual",
296
+ headers
297
+ });
298
+ if (isRedirect(response)) return;
299
+ if (!response.ok) return { error: await errorOf(response) };
300
+ const type = response.headers.get("Content-Type");
301
+ if (type?.includes("application/x-ndjson")) return await readServerDataStream(response);
302
+ if (!type?.includes("application/json")) return {};
303
+ return await response.json();
304
+ } catch (error) {
305
+ console.error("The server data request failed", error);
306
+ return { error: unreachableError() };
307
+ }
308
+ }
309
+ /** The error rendered when the server can't be reached at all. */
310
+ function unreachableError() {
311
+ return {
312
+ status: 503,
313
+ message: navigator.onLine === false ? "You're offline." : "Could not reach the server."
314
+ };
241
315
  }
242
316
  /**
243
317
  * Reads a streamed data response: the first frame carries the critical loads
@@ -325,13 +399,13 @@ function hasServerData(handler) {
325
399
  return (handler.layouts ?? []).some((layout) => !!layout.serverEndPoint);
326
400
  }
327
401
  /**
328
- * Runs a route's client-side load, merging its json data into `data`. Returns
329
- * a non-ok Response for the caller to turn into an error page.
402
+ * Runs a route's client-side load, merging its json data into `data` and
403
+ * returning the redirect or error for the caller to handle.
330
404
  *
331
405
  * A prefetch caches the in-flight promise, not its resolved value, so a
332
406
  * navigation that lands while the load is still running continues the same
333
407
  * request instead of running it a second time. The navigation that follows
334
- * consumes (and clears) the entry; a failed promise is dropped so the
408
+ * consumes (and clears) the entry; a failed prefetch is dropped so the
335
409
  * navigation retries.
336
410
  */
337
411
  async function runClientLoad(endPoint, location, query, params, data, prefetch) {
@@ -344,28 +418,37 @@ async function runClientLoad(endPoint, location, query, params, data, prefetch)
344
418
  const promise = loadClientResponse(endPoint.load, query, params, data);
345
419
  prefetchedData[clientKey] = promise;
346
420
  pending = promise;
347
- promise.catch(() => {
348
- if (prefetchedData[clientKey] === promise) delete prefetchedData[clientKey];
349
- });
421
+ promise.then((result) => {
422
+ if (result.error) dropPrefetch(prefetchedData, clientKey, promise);
423
+ }, () => dropPrefetch(prefetchedData, clientKey, promise));
350
424
  } else if (!prefetch) delete prefetchedData[clientKey];
351
425
  return mergeClientLoad(await pending, data);
352
426
  }
353
427
  async function loadClientResponse(load, query, params, data) {
354
428
  const clientUrl = new URL(document.location.href);
355
429
  for (let [name, value] of query) clientUrl.searchParams.append(name, value);
356
- const response = await load({
357
- url: clientUrl,
358
- params,
359
- data
360
- });
361
- if (!response) return {};
362
- if (!response.ok) return { response };
363
- const body = await readResponseBody(response);
364
- return body ? { data: body } : {};
430
+ try {
431
+ const response = await load({
432
+ url: clientUrl,
433
+ params,
434
+ data
435
+ });
436
+ if (!response) return {};
437
+ if (isRedirect(response)) return { redirect: true };
438
+ if (!response.ok) return { error: await errorOf(response) };
439
+ const body = await readResponseBody(response);
440
+ return body ? { data: body } : {};
441
+ } catch (error) {
442
+ console.error("The client load failed", error);
443
+ return { error: {
444
+ status: 500,
445
+ message: "Internal error"
446
+ } };
447
+ }
365
448
  }
366
449
  function mergeClientLoad(result, data) {
367
450
  if (result.data) Object.assign(data, result.data);
368
- return result.response;
451
+ return result;
369
452
  }
370
453
  function clientLocation(path) {
371
454
  return document.location.origin + getBasePath() + path;
@@ -411,21 +494,28 @@ async function navigateNow(rawUrl, withHydration) {
411
494
  const previousUrl = $page.url;
412
495
  const previousStatus = $page.status;
413
496
  const previousError = $page.error;
497
+ let result;
414
498
  try {
415
- return await renderNavigation(rawUrl, withHydration);
499
+ result = await renderNavigation(rawUrl, withHydration);
416
500
  } catch (error) {
501
+ console.error(error);
502
+ result = {
503
+ type: "failed",
504
+ error
505
+ };
506
+ }
507
+ if (result.type === "failed" && !withHydration) {
417
508
  $page.url = previousUrl;
418
509
  $page.status = previousStatus;
419
510
  $page.error = previousError;
420
- console.error(error);
421
- return false;
422
511
  }
512
+ return result;
423
513
  }
424
514
  async function renderNavigation(rawUrl, withHydration) {
425
515
  let parent = document.getElementById("app");
426
516
  if (!parent) {
427
517
  console.log("500");
428
- return false;
518
+ return { type: "failed" };
429
519
  }
430
520
  const url = stripBaseFromUrl(rawUrl, getBasePath()) ?? rawUrl;
431
521
  const path = url.pathname;
@@ -444,7 +534,7 @@ async function renderNavigation(rawUrl, withHydration) {
444
534
  } else {
445
535
  const errorPath = findErrorRoute(client.router, path);
446
536
  const errorRoute = errorPath && client.router.match(errorPath, query);
447
- if (!errorRoute) return false;
537
+ if (!errorRoute) return { type: "failed" };
448
538
  route = errorRoute;
449
539
  $page.status = 404;
450
540
  $page.error = { message: "Not found" };
@@ -452,27 +542,30 @@ async function renderNavigation(rawUrl, withHydration) {
452
542
  let handler = route.handler;
453
543
  let params = route.params || {};
454
544
  let clientEndPoint = handler.endPoint ? (await handler.endPoint())?.default : void 0;
455
- if (!clientEndPoint?.component) return false;
545
+ if (!clientEndPoint?.component) return { type: "server-only" };
456
546
  let newLayoutStack = [];
457
547
  const result = await loadData(handler, params, path, query, newLayoutStack, clientEndPoint);
458
- if (result === void 0) return false;
548
+ if (result === void 0) return { type: "redirect" };
459
549
  let data = result.data;
460
550
  if (result.error) {
461
- if (withHydration) return false;
551
+ if (withHydration) return { type: "failed" };
462
552
  const errorPath = findErrorRoute(client.router, path);
463
553
  const errorRoute = errorPath && client.router.match(errorPath, query);
464
- if (!errorRoute) return false;
554
+ if (!errorRoute) return { type: "failed" };
465
555
  route = errorRoute;
466
556
  handler = errorRoute.handler;
467
557
  params = errorRoute.params || {};
468
558
  clientEndPoint = handler.endPoint ? (await handler.endPoint())?.default : void 0;
469
- if (!clientEndPoint?.component) return false;
559
+ if (!clientEndPoint?.component) return { type: "failed" };
470
560
  $page.status = result.error.status;
471
561
  $page.error = { message: result.error.message };
472
- newLayoutStack.length = 0;
562
+ newLayoutStack = [];
473
563
  const errorResult = await loadData(handler, params, path, query, newLayoutStack, clientEndPoint);
474
- if (errorResult === void 0 || errorResult.error) return false;
475
- data = errorResult.data;
564
+ if (errorResult === void 0) return { type: "redirect" };
565
+ if (errorResult.error) {
566
+ newLayoutStack = errorLayoutStack(handler, params);
567
+ data = {};
568
+ } else data = errorResult.data;
476
569
  }
477
570
  let formInput = document.getElementById("t-form-data");
478
571
  let form;
@@ -553,17 +646,19 @@ async function renderNavigation(rawUrl, withHydration) {
553
646
  if (!withHydration && client.viewTransitions && typeof document.startViewTransition === "function") document.startViewTransition(render);
554
647
  else render();
555
648
  client.prefetchedData = {};
556
- return true;
649
+ return { type: "rendered" };
557
650
  }
558
651
  //#endregion
559
652
  //#region src/nav/load.ts
560
653
  /**
561
- * Loads and renders the page at the supplied path.
654
+ * Loads and renders the page at the supplied path. Returns whether the page
655
+ * was rendered in place: `false` when the document has to take over (a
656
+ * `+server` route, a redirect, or a failed navigation).
562
657
  */
563
658
  async function load(path) {
564
- return await navigate(new URL(path, document.location.href));
659
+ return (await navigate(new URL(path, document.location.href))).type === "rendered";
565
660
  }
566
661
  //#endregion
567
662
  export { client as a, reload as i, navigate as n, loadData as r, load as t };
568
663
 
569
- //# sourceMappingURL=load-G-4A435s.mjs.map
664
+ //# sourceMappingURL=load-BODDzmH0.mjs.map