@opentf/afw 0.0.0-stage → 0.32.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 (72) hide show
  1. package/README.md +66 -2
  2. package/components/Link.d.ts +12 -0
  3. package/components/Link.jsx +54 -0
  4. package/core/context.d.ts +7 -0
  5. package/core/context.js +60 -0
  6. package/core/dev.js +27 -0
  7. package/core/errors.d.ts +14 -0
  8. package/core/errors.js +48 -0
  9. package/core/html.js +10 -0
  10. package/core/metadata.js +184 -0
  11. package/core/reactive.d.ts +5 -0
  12. package/core/reactive.js +190 -0
  13. package/core/render-context.js +11 -0
  14. package/core/signals.d.ts +8 -0
  15. package/core/signals.js +264 -0
  16. package/index.d.ts +5 -0
  17. package/index.js +13 -0
  18. package/jsx-runtime.d.ts +37 -0
  19. package/package.json +60 -4
  20. package/runtime/clipboard.d.ts +7 -0
  21. package/runtime/clipboard.js +47 -0
  22. package/runtime/code-block.d.ts +14 -0
  23. package/runtime/code-block.js +76 -0
  24. package/runtime/context.browser.js +163 -0
  25. package/runtime/context.d.ts +13 -0
  26. package/runtime/context.js +44 -0
  27. package/runtime/dom.browser.js +423 -0
  28. package/runtime/dom.d.ts +142 -0
  29. package/runtime/dom.js +670 -0
  30. package/runtime/error-boundary.browser.js +140 -0
  31. package/runtime/error-boundary.d.ts +19 -0
  32. package/runtime/error-boundary.js +123 -0
  33. package/runtime/events.browser.js +29 -0
  34. package/runtime/events.d.ts +1 -0
  35. package/runtime/events.js +17 -0
  36. package/runtime/head.js +29 -0
  37. package/runtime/hmr.js +170 -0
  38. package/runtime/hydrate.browser.js +144 -0
  39. package/runtime/hydrate.d.ts +173 -0
  40. package/runtime/hydrate.js +536 -0
  41. package/runtime/index.d.ts +14 -0
  42. package/runtime/index.js +24 -0
  43. package/runtime/lifecycle.d.ts +6 -0
  44. package/runtime/lifecycle.js +14 -0
  45. package/runtime/mount.d.ts +20 -0
  46. package/runtime/mount.js +85 -0
  47. package/runtime/portal.browser.js +85 -0
  48. package/runtime/portal.d.ts +12 -0
  49. package/runtime/portal.js +74 -0
  50. package/runtime/raw-html.d.ts +11 -0
  51. package/runtime/raw-html.js +55 -0
  52. package/runtime/resource.d.ts +9 -0
  53. package/runtime/resource.js +139 -0
  54. package/runtime/route-data.d.ts +15 -0
  55. package/runtime/route-data.js +64 -0
  56. package/runtime/router.d.ts +146 -0
  57. package/runtime/router.js +765 -0
  58. package/server/adapters/node.d.ts +28 -0
  59. package/server/adapters/node.js +74 -0
  60. package/server/api.d.ts +175 -0
  61. package/server/api.js +233 -0
  62. package/server/builtins.js +42 -0
  63. package/server/cookies.d.ts +44 -0
  64. package/server/cookies.js +122 -0
  65. package/server/head.js +9 -0
  66. package/server/index.d.ts +151 -0
  67. package/server/index.js +31 -0
  68. package/server/loader.js +201 -0
  69. package/server/middleware.js +119 -0
  70. package/server/render-context.js +30 -0
  71. package/server/render.js +172 -0
  72. package/server/ssg-runtime.js +239 -0
@@ -0,0 +1,85 @@
1
+ // Mounting a factory-style view (pages/layouts compile to factory functions;
2
+ // SPEC §2.2). Components compile to Custom Elements and mount via the DOM.
3
+
4
+ import { reportError } from "../core/errors.js";
5
+ import { scope } from "../core/signals.js";
6
+
7
+ // Keep partial builds owned too: scope() only returns a disposer when its
8
+ // callback finishes, so capture an error until we can dispose and rethrow it.
9
+ function ownedScope(fn) {
10
+ let failed = false, failure;
11
+ const owned = scope(() => {
12
+ try { return fn(); }
13
+ catch (error) { failed = true; failure = error; }
14
+ });
15
+ if (failed) {
16
+ try { owned.dispose(); } catch (error) { console.error(error); }
17
+ throw failure;
18
+ }
19
+ return owned;
20
+ }
21
+
22
+ /** Build a factory view and attach its reactive scope to the node's teardown. */
23
+ export function buildScopedView(view) {
24
+ const owned = ownedScope(view);
25
+ const node = owned.result;
26
+ try {
27
+ const lc = (node.__lifecycle ??= { mounts: [], cleanups: [] });
28
+ lc.cleanups.push(owned.dispose);
29
+ return node;
30
+ } catch (error) {
31
+ try { owned.dispose(); } catch (cleanupError) { console.error(cleanupError); }
32
+ throw error;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Mount a view into `target`. `view` is either a factory function returning a
38
+ * DOM node or an already-built node. Returns the mounted node.
39
+ *
40
+ * Page/layout factories may attach a `__lifecycle` record (`{ mounts, cleanups }`)
41
+ * built from `onMount`/`onCleanup`. After insertion we run the `onMount` callbacks,
42
+ * collecting any returned disposer into `cleanups` so a caller (e.g. the router)
43
+ * can tear the page down on navigation.
44
+ *
45
+ * A factory build runs inside a reactive `scope`, and the scope's disposer joins
46
+ * the cleanups: teardown (router navigation) stops every binding effect the page
47
+ * created, so a replaced page's subscriptions don't outlive it.
48
+ */
49
+ export function mount(view, target) {
50
+ const node = typeof view === "function" ? buildScopedView(view) : view;
51
+ target.appendChild(node);
52
+ runMount(node);
53
+ return node;
54
+ }
55
+
56
+ /** Run a node's `onMount` callbacks, collecting returned disposers as cleanups. */
57
+ export function runMount(node) {
58
+ const lc = node && node.__lifecycle;
59
+ if (!lc) return;
60
+ for (const cb of lc.mounts) {
61
+ try {
62
+ const owned = ownedScope(cb);
63
+ lc.cleanups.push(owned.dispose);
64
+ const disposer = owned.result;
65
+ if (typeof disposer === "function") lc.cleanups.push(disposer);
66
+ } catch (e) {
67
+ reportError(e, { phase: "mount" });
68
+ }
69
+ }
70
+ lc.mounts = [];
71
+ }
72
+
73
+ /** Run a node's collected `onCleanup`/disposer teardown (idempotent). */
74
+ export function runCleanup(node) {
75
+ const lc = node && node.__lifecycle;
76
+ if (!lc) return;
77
+ for (const cb of lc.cleanups) {
78
+ try {
79
+ cb();
80
+ } catch (e) {
81
+ console.error(e);
82
+ }
83
+ }
84
+ lc.cleanups = [];
85
+ }
@@ -0,0 +1,85 @@
1
+ import { describe, expect, test } from "../../afw-test/browser-runner.js";
2
+
3
+ import { createContext, enterHost, exitHost, readContext } from "./context.js";
4
+ import "./portal.js";
5
+
6
+ // A <afw-internal-portal> wrapping `child`, with an optional target selector.
7
+ function portal(child, to) {
8
+ const p = document.createElement("afw-internal-portal");
9
+ if (to !== undefined) p.to = to;
10
+ p.appendChild(child);
11
+ return p;
12
+ }
13
+
14
+ describe("portal", () => {
15
+ test("moves children to the default target (body) and removes them on teardown", () => {
16
+ const host = document.createElement("div");
17
+ document.body.appendChild(host);
18
+
19
+ const modal = document.createElement("section");
20
+ modal.id = "modal";
21
+ const p = portal(modal);
22
+ host.appendChild(p); // connect fires → relocate
23
+
24
+ // The modal moved to body; the portal element itself stays as the anchor.
25
+ expect(modal.parentNode).toBe(document.body);
26
+ expect(p.contains(modal)).toBe(false);
27
+
28
+ p.remove(); // disconnect → relocated content removed
29
+ expect(modal.parentNode).toBe(null);
30
+ host.remove();
31
+ });
32
+
33
+ test("honors a selector target", () => {
34
+ const root = document.createElement("div");
35
+ root.id = "toast-root";
36
+ document.body.appendChild(root);
37
+
38
+ const toast = document.createElement("div");
39
+ const p = portal(toast, "#toast-root");
40
+ document.body.appendChild(p);
41
+
42
+ expect(toast.parentNode).toBe(root);
43
+ p.remove();
44
+ root.remove();
45
+ });
46
+
47
+ test("preserves context across the portal boundary", () => {
48
+ const Theme = createContext("dark");
49
+
50
+ // A consumer custom element that resolves context at connect time.
51
+ let resolved;
52
+ customElements.define(
53
+ "afw-portal-consumer",
54
+ class extends HTMLElement {
55
+ connectedCallback() {
56
+ enterHost(this);
57
+ try {
58
+ resolved = readContext(Theme);
59
+ } finally {
60
+ exitHost();
61
+ }
62
+ }
63
+ },
64
+ );
65
+
66
+ // <provider value="light"> <afw-internal-portal> <consumer/> </afw-internal-portal> </provider>
67
+ const provider = document.createElement("afw-internal-context-provider");
68
+ provider.context = Theme;
69
+ provider.value = "light";
70
+ const consumer = document.createElement("afw-portal-consumer");
71
+ const p = portal(consumer);
72
+ provider.appendChild(p);
73
+ document.body.appendChild(provider); // connect: provider → portal moves consumer to body
74
+
75
+ // The consumer physically lives in body now, but still resolves the provider
76
+ // above the <Portal> in the logical tree.
77
+ expect(consumer.parentNode).toBe(document.body);
78
+ expect(resolved.value).toBe("light");
79
+
80
+ provider.value = "solar"; // still wired to the provider signal
81
+ expect(resolved.value).toBe("solar");
82
+ p.remove();
83
+ provider.remove();
84
+ });
85
+ });
@@ -0,0 +1,12 @@
1
+ export class PortalElement extends HTMLElement {
2
+ set to(v: any);
3
+ get to(): any;
4
+ _to: any;
5
+ connectedCallback(): void;
6
+ _mounted: boolean | undefined;
7
+ _relocate(): void;
8
+ _moved: ChildNode[] | null | undefined;
9
+ disconnectedCallback(): void;
10
+ }
11
+ /** JSX props consumed by the compiler-generated custom-element host. */
12
+ export const Portal: { new(props: { to: string | Element; children?: unknown }): PortalElement; prototype: PortalElement };
@@ -0,0 +1,74 @@
1
+ //! Portal — render a subtree into a different DOM location (a modal/tooltip/toast
2
+ //! escaping an ancestor's overflow/z-index/transform).
3
+ //
4
+ // <Portal to="#toast-root"> … </Portal> // selector, element, or default body
5
+ //
6
+ // `<Portal>` compiles to this built-in `afw-internal-portal` element (capitalized name →
7
+ // tag, like <ContextProvider>) — no compiler changes. At connect it moves its
8
+ // light-DOM children to the target; on disconnect it removes them so their
9
+ // custom-element disconnect + effect cleanups run (the part userland leaks).
10
+ //
11
+ // Context is preserved across the boundary: each relocated root is marked
12
+ // `data-afw-portal` with a `__portalHost` back-pointer to this element, and
13
+ // `readContext` (context.js) hops across it. Note that for modals/dialogs the
14
+ // native top layer (`<dialog>.showModal()`, the popover API) is usually a better
15
+ // fit than a portal — Portal is the general escape hatch for everything else.
16
+
17
+ import { afterHydration } from "./hydrate.js";
18
+
19
+ function resolveTarget(to) {
20
+ if (to && to.nodeType === 1) return to; // an element
21
+ if (typeof to === "string" && to) return document.querySelector(to) || document.body;
22
+ return document.body;
23
+ }
24
+
25
+ export class PortalElement extends HTMLElement {
26
+ set to(v) {
27
+ this._to = v;
28
+ }
29
+ get to() {
30
+ return this._to;
31
+ }
32
+
33
+ connectedCallback() {
34
+ if (this._mounted) return;
35
+ this._mounted = true;
36
+ // During first-paint hydration the portal upgrades *before* the owning component adopts
37
+ // its slotted children (the portal is defined eagerly by the runtime; the parent is a
38
+ // route-chunk component). Relocating now would move the children out of the portal host
39
+ // before the parent's `hydrateSlot` walk can wire them, leaving the portaled content
40
+ // unhydrated. So defer the move until hydration finishes; on a CSR build (not hydrating)
41
+ // `afterHydration` runs it synchronously, exactly as before.
42
+ afterHydration(() => this._relocate());
43
+ }
44
+
45
+ _relocate() {
46
+ if (!this._mounted || this._moved) return; // disconnected before flush, or already moved
47
+ const target = resolveTarget(this._to);
48
+ // Snapshot children, mark each element root for the context hop, then move
49
+ // them — markers must be set before the move connects them at the target.
50
+ this._moved = Array.from(this.childNodes);
51
+ for (const n of this._moved) {
52
+ if (n.nodeType === 1) {
53
+ n.__portalHost = this;
54
+ n.setAttribute("data-afw-portal", "");
55
+ }
56
+ }
57
+ for (const n of this._moved) target.appendChild(n);
58
+ }
59
+
60
+ disconnectedCallback() {
61
+ for (const n of this._moved || []) n.remove(); // triggers descendants' cleanup
62
+ // Reset to null, not []: `_relocate` treats a non-null `_moved` as "already relocated"
63
+ // (so a stale queued callback can't move twice), and a re-mount must be free to relocate.
64
+ this._moved = null;
65
+ this._mounted = false;
66
+ }
67
+ }
68
+
69
+ // Exported so `import { Portal } from "@opentf/afw"` resolves; the import side
70
+ // effect registers the element (JSX uses the `afw-internal-portal` tag).
71
+ export const Portal = PortalElement;
72
+ if (typeof customElements !== "undefined" && !customElements.get("afw-internal-portal")) {
73
+ customElements.define("afw-internal-portal", PortalElement);
74
+ }
@@ -0,0 +1,11 @@
1
+ export class RawHtmlElement extends HTMLElement {
2
+ set html(v: any);
3
+ get html(): any;
4
+ _html: any;
5
+ _adopted: boolean | undefined;
6
+ _value: any;
7
+ connectedCallback(): void;
8
+ _applied: boolean | undefined;
9
+ }
10
+ /** JSX props consumed by the compiler-generated custom-element host. */
11
+ export const RawHtml: { new(props: { html: string }): RawHtmlElement; prototype: RawHtmlElement };
@@ -0,0 +1,55 @@
1
+ //! RawHtml — render a trusted HTML string as light-DOM content.
2
+ //
3
+ // <RawHtml html={"<pre>…</pre>"} /> // compiles to the built-in `afw-internal-raw-html`
4
+ //
5
+ // Used by the MDX front-end for build-time syntax-highlighted code blocks: the
6
+ // highlighted markup is static (no reactivity), so the element just assigns its
7
+ // `html` property to `innerHTML`. The string is treated as trusted — it comes from
8
+ // the compiler, not user input. SSG renders the string inline (server/builtins.js).
9
+
10
+ import { isHydrating } from "./hydrate.js";
11
+
12
+ export class RawHtmlElement extends HTMLElement {
13
+ set html(v) {
14
+ this._html = v;
15
+ if (!this.isConnected) return;
16
+ // The server already rendered this exact string inline and we adopted it; the adopt
17
+ // walk re-applies the prop right after claiming the host, and re-assigning innerHTML
18
+ // there would tear out the DOM we just adopted (see code-block.js for the same case).
19
+ if (this._adopted) {
20
+ this._adopted = false;
21
+ this._value = v;
22
+ return;
23
+ }
24
+ if (v !== this._value) {
25
+ this.innerHTML = v == null ? "" : String(v);
26
+ this._value = v;
27
+ }
28
+ }
29
+ get html() {
30
+ return this._html;
31
+ }
32
+
33
+ connectedCallback() {
34
+ // Server-rendered inline (server/builtins.js) and adopted on first paint — keep it.
35
+ if (isHydrating() && this.firstChild) {
36
+ this._adopted = true;
37
+ this._applied = true;
38
+ this._value = this._html;
39
+ return;
40
+ }
41
+ // Apply once on connect (the property is set before append during CSR build).
42
+ if (this._html != null && !this._applied) {
43
+ this.innerHTML = String(this._html);
44
+ this._value = this._html;
45
+ this._applied = true;
46
+ }
47
+ }
48
+ }
49
+
50
+ // Exported so `import { RawHtml } from "@opentf/afw"` resolves; the import side
51
+ // effect registers the element (JSX uses the `afw-internal-raw-html` tag).
52
+ export const RawHtml = RawHtmlElement;
53
+ if (typeof customElements !== "undefined" && !customElements.get("afw-internal-raw-html")) {
54
+ customElements.define("afw-internal-raw-html", RawHtmlElement);
55
+ }
@@ -0,0 +1,9 @@
1
+ export interface Resource<T> {
2
+ readonly data: T | undefined;
3
+ readonly loading: boolean;
4
+ readonly error: unknown;
5
+ refetch(): Promise<T | undefined> | undefined;
6
+ }
7
+ export function resource<T>(fetcher: (value: true, context: { signal: AbortSignal | undefined }) => T | Promise<T>, options?: { initial?: T }): Resource<T>;
8
+ export function resource<S, T>(source: () => S, fetcher: (value: NonNullable<Exclude<S, false>>, context: { signal: AbortSignal | undefined }) => T | Promise<T>, options?: { initial?: T }): Resource<T>;
9
+ export function __setResourceServer(value: boolean | null): void;
@@ -0,0 +1,139 @@
1
+ // `resource()` — the client-side async-data primitive (SPEC §7.4, docs/DATA.md).
2
+ // Components are strictly synchronous (SPEC §5.5), so async data lives *next to*
3
+ // the view: a resource wraps a fetcher in signals and the view renders its
4
+ // reactive `loading` / `error` / `data` states:
5
+ //
6
+ // const users = resource(() => fetch("/api/users").then((r) => r.json()));
7
+ // // in JSX: {users.loading ? <Spinner /> : users.data.map(...)}
8
+ //
9
+ // With a reactive source, the fetch re-runs whenever the source changes, and a
10
+ // `null`/`false` source pauses it (conditional fetching):
11
+ //
12
+ // const user = resource(() => router.params.id, (id, { signal }) =>
13
+ // fetch(`/api/users/${id}`, { signal }).then((r) => r.json()));
14
+ //
15
+ // Staleness: each run bumps a token and aborts the previous run's AbortController
16
+ // (passed to the fetcher as `{ signal }`), so an out-of-order resolution can never
17
+ // overwrite newer data — even for fetchers that ignore the signal.
18
+ //
19
+ // Server (SSG/SSR): no effect is created and nothing is fetched — `loading` stays
20
+ // `true`, so the prerendered HTML shows the loading branch. That is exactly what
21
+ // the client's first paint renders before its own fetch resolves, keeping
22
+ // hydration adoption aligned.
23
+
24
+ import { batch, effect, signal, untracked } from "../core/signals.js";
25
+
26
+ // Test override: the DOM suites run in esdev's `--dom` realm (a `document`
27
+ // always exists), so server behavior is opted into explicitly.
28
+ let serverOverride = null;
29
+
30
+ /** Force server (true) / client (false) behavior for new resources — tests only. */
31
+ export function __setResourceServer(v) {
32
+ serverOverride = v;
33
+ }
34
+
35
+ const isServer = () => serverOverride ?? typeof document === "undefined";
36
+
37
+ /**
38
+ * Create a resource. Two call shapes:
39
+ *
40
+ * resource(fetcher, options?) — fetch once (and on refetch())
41
+ * resource(source, fetcher, options?) — re-fetch when the reactive `source`
42
+ * changes; `null`/`false` pauses
43
+ *
44
+ * @param {Function} source reactive source read inside the tracking effect; its
45
+ * value is passed to the fetcher.
46
+ * @param {Function} fetcher `(sourceValue, { signal }) => data | Promise<data>`.
47
+ * @param {{ initial?: unknown }} [options] `initial` seeds `data` before the
48
+ * first resolution.
49
+ * @returns {{ data: unknown, loading: boolean, error: unknown,
50
+ * refetch: () => Promise<unknown> | undefined }} reactive getters —
51
+ * read them inside bindings/effects to subscribe.
52
+ */
53
+ export function resource(source, fetcher, options = {}) {
54
+ if (typeof fetcher !== "function") {
55
+ options = fetcher ?? {};
56
+ fetcher = source;
57
+ source = null;
58
+ }
59
+ const src = typeof source === "function" ? source : () => true;
60
+ const data = signal(options.initial);
61
+ const error = signal(undefined);
62
+ const loading = signal(true); // a fetch is intended; the server leaves it true
63
+ let token = 0;
64
+ let controller = null;
65
+
66
+ function run(value) {
67
+ controller?.abort();
68
+ // Captured per-run: by the time a superseded run's promise settles, the
69
+ // module-level `controller` already belongs to a newer run.
70
+ const c = (controller = typeof AbortController !== "undefined" ? new AbortController() : null);
71
+ const t = ++token;
72
+ batch(() => {
73
+ loading.value = true;
74
+ error.value = undefined;
75
+ });
76
+ // The async IIFE starts the fetcher *synchronously* (no wasted microtask)
77
+ // while converting a synchronous throw into a rejection.
78
+ return (async () => fetcher(value, { signal: c?.signal }))()
79
+ .then(
80
+ (v) => {
81
+ if (t !== token) return; // superseded — a newer run owns the signals
82
+ batch(() => {
83
+ data.value = v;
84
+ loading.value = false;
85
+ });
86
+ return v;
87
+ },
88
+ (e) => {
89
+ if (t !== token) return;
90
+ // Keep the last good `data` (stale-while-error); only `error` flips.
91
+ batch(() => {
92
+ error.value = e;
93
+ loading.value = false;
94
+ });
95
+ },
96
+ );
97
+ }
98
+
99
+ if (!isServer()) {
100
+ effect(() => {
101
+ const value = src(); // the effect's ONLY tracked read
102
+ if (value == null || value === false) {
103
+ // Paused: cancel anything in flight and settle as "not loading".
104
+ untracked(() => {
105
+ token++;
106
+ controller?.abort();
107
+ controller = null;
108
+ loading.value = false;
109
+ });
110
+ return;
111
+ }
112
+ untracked(() => run(value));
113
+ // Before a re-run (source changed) and on scope dispose: invalidate + abort,
114
+ // so a torn-down region's fetch can neither land nor leak a connection.
115
+ return () => {
116
+ token++;
117
+ controller?.abort();
118
+ };
119
+ });
120
+ }
121
+
122
+ return {
123
+ get data() {
124
+ return data.value;
125
+ },
126
+ get loading() {
127
+ return loading.value;
128
+ },
129
+ get error() {
130
+ return error.value;
131
+ },
132
+ /** Re-run the fetcher with the current source value (no-op while paused). */
133
+ refetch() {
134
+ const value = untracked(src);
135
+ if (value == null || value === false) return undefined;
136
+ return run(value);
137
+ },
138
+ };
139
+ }
@@ -0,0 +1,15 @@
1
+ /** The data-endpoint URL for a page path: `"/"` → `/__data.json`,
2
+ * `"/todos"` → `/todos/__data.json`, preserving the query string. */
3
+ export function dataUrlFor(pathname: any, search?: string): string;
4
+ /**
5
+ * Fetch a route's loader data. 200 → the parsed JSON; 404 → `undefined` (no
6
+ * loader / `notFound()`); anything else throws (the router reports it and
7
+ * commits the navigation with no data).
8
+ */
9
+ export function fetchRouteData(pathname: any, search?: string): Promise<any>;
10
+ /** The loader data inlined by the server for the current document, or `undefined`. */
11
+ export function readInlineRouteData(): any;
12
+ /** Reset the cached inline payload (tests only — a fresh document between cases). */
13
+ export function __resetInlineRouteData(): void;
14
+ /** The reserved per-route data filename/URL suffix (`/todos` → `/todos/__data.json`). */
15
+ export const DATA_FILE: "__data.json";
@@ -0,0 +1,64 @@
1
+ // Route-loader data on the client (docs/DATA.md). A page with a sibling
2
+ // `loader.{js,ts}` gets its data three ways, all converging on `router.data`:
3
+ //
4
+ // • first paint over server HTML — the payload is inlined as
5
+ // `<script type="application/json" id="__afw_data">` and read here;
6
+ // • SPA navigation — fetched from `<path>/__data.json` (the same URL a static
7
+ // host serves as a literal file written at SSG time, and the serve/dev
8
+ // servers answer dynamically);
9
+ // • dev/CSR first load — the same fetch, since there is no server markup.
10
+ //
11
+ // The endpoint returns the raw loader JSON (no envelope): 404 means "no data for
12
+ // this route" (no loader, or the loader called `notFound()`) and maps to
13
+ // `undefined` so the page renders its empty state.
14
+
15
+ /** The reserved per-route data filename/URL suffix (`/todos` → `/todos/__data.json`). */
16
+ export const DATA_FILE = "__data.json";
17
+
18
+ // Match the router's path normalization (a trailing slash must hit the same URL).
19
+ const normalize = (p) => (p || "/").replace(/(.)\/+$/, "$1");
20
+
21
+ /** The data-endpoint URL for a page path: `"/"` → `/__data.json`,
22
+ * `"/todos"` → `/todos/__data.json`, preserving the query string. */
23
+ export function dataUrlFor(pathname, search = "") {
24
+ const path = normalize(pathname);
25
+ return (path === "/" ? `/${DATA_FILE}` : `${path}/${DATA_FILE}`) + (search || "");
26
+ }
27
+
28
+ /**
29
+ * Fetch a route's loader data. 200 → the parsed JSON; 404 → `undefined` (no
30
+ * loader / `notFound()`); anything else throws (the router reports it and
31
+ * commits the navigation with no data).
32
+ */
33
+ export async function fetchRouteData(pathname, search = "") {
34
+ const res = await fetch(dataUrlFor(pathname, search));
35
+ if (res.status === 404) return undefined;
36
+ if (!res.ok) throw new Error(`route data request for ${pathname} failed (${res.status})`);
37
+ return res.json();
38
+ }
39
+
40
+ // The inline first-paint payload, read once and cached (mirrors the island-props
41
+ // payload reader in hydrate.js). `undefined` data serializes to *no script at all*
42
+ // (the toolchain skips injection), so a missing element simply reads as undefined.
43
+ let _read = false;
44
+ let _value;
45
+
46
+ /** The loader data inlined by the server for the current document, or `undefined`. */
47
+ export function readInlineRouteData() {
48
+ if (!_read) {
49
+ _read = true;
50
+ const el = typeof document !== "undefined" ? document.getElementById("__afw_data") : null;
51
+ try {
52
+ _value = el ? JSON.parse(el.textContent || "null") : undefined;
53
+ } catch {
54
+ _value = undefined;
55
+ }
56
+ }
57
+ return _value;
58
+ }
59
+
60
+ /** Reset the cached inline payload (tests only — a fresh document between cases). */
61
+ export function __resetInlineRouteData() {
62
+ _read = false;
63
+ _value = undefined;
64
+ }