@rshono/core 1.0.0-rc.14 → 1.0.0-rc.16

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.
@@ -32,7 +32,12 @@ export interface DeployRuntime {
32
32
  /**
33
33
  * Hands the app to the platform and returns whatever the entry module should `export default` there:
34
34
  * nothing where rshono owns the process (this binds the port), otherwise the export the platform looks
35
- * for — `{ fetch }` on Workers, a handler function on Vercel and Lambda.
35
+ * for — `{ fetch }` on Workers, a streaming handler on Lambda, and on Vercel a Node
36
+ * `(IncomingMessage, ServerResponse)` listener, which is what its `Nodejs` launcher calls.
37
+ *
38
+ * Note that a web `Request` is not the common currency here: two of the three targets are handed one by
39
+ * their platform, and Vercel is not, so converting is part of the handoff rather than something the
40
+ * request-handling code below can assume has already happened.
36
41
  */
37
42
  serveApp(app: Hono): unknown;
38
43
  /** Mounts the hashed client bundle at `/_static`, ahead of the app's routes. A no-op where a CDN serves it. */
@@ -1 +1 @@
1
- {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../src/deploy/contract.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAElF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,YAAY,GAAG,QAAQ,GAAG,YAAY,CAAC;AAE3E;;;;;;GAMG;AACH,MAAM,WAAW,aAAa;IAC5B;;;;OAIG;IACH,QAAQ,CAAC,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC;IAC7B,+GAA+G;IAC/G,iBAAiB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IACnC,sGAAsG;IACtG,mBAAmB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IACrC;;;;;;;OAOG;IACH,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAAC;IACxF,yFAAyF;IACzF,OAAO,IAAI,IAAI,CAAC;CACjB"}
1
+ {"version":3,"file":"contract.d.ts","sourceRoot":"","sources":["../../src/deploy/contract.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAElF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,YAAY,GAAG,QAAQ,GAAG,YAAY,CAAC;AAE3E;;;;;;GAMG;AACH,MAAM,WAAW,aAAa;IAC5B;;;;;;;;;OASG;IACH,QAAQ,CAAC,GAAG,EAAE,IAAI,GAAG,OAAO,CAAC;IAC7B,+GAA+G;IAC/G,iBAAiB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IACnC,sGAAsG;IACtG,mBAAmB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAAC;IACrC;;;;;;;OAOG;IACH,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAAC;IACxF,yFAAyF;IACzF,OAAO,IAAI,IAAI,CAAC;CACjB"}
@@ -1 +1 @@
1
- {"version":3,"file":"contract.js","sourceRoot":"","sources":["../../src/deploy/contract.ts"],"names":[],"mappings":"","sourcesContent":["import type { Context, Hono } from 'hono';\nimport type { PrerenderVariant, PrerenderedPage } from '../server/prerendered.js';\n\n/**\n * A hosting platform `rshono build` targets. Selected with `deploy` in `rshono.config.ts`, the\n * `--deploy` flag or the `RSHONO_DEPLOY` env var.\n *\n * - `'node'` (the default) — rshono binds the port and you run the build with `rshono start`. Covers a\n * VPS, a container, a PaaS, and — through `node:` compatibility — Bun and Deno.\n * - `'cloudflare'` — a Worker; the entry exports `{ fetch }`.\n * - `'vercel'` — a Vercel function, plus the on-disk layout and config streaming needs there.\n * - `'aws-lambda'` — a streaming Lambda handler.\n *\n * There is one target per *handoff* — who opens the socket, and what shape a request arrives in — since\n * that is the part an app cannot arrange for itself. `rshono dev` always runs the `node` server.\n *\n * @example\n * ```ts\n * export default defineConfig({ deploy: 'cloudflare' });\n * ```\n *\n * @see {@link https://www.rshono.com/docs/deployment#the-targets | Docs — the targets}\n */\nexport type DeployTarget = 'node' | 'cloudflare' | 'vercel' | 'aws-lambda';\n\n/**\n * Everything the app server needs from the platform it runs on — the whole of what \"which platform is\n * this\" means at request time, since `runtime/entry.rsc.tsx` is written against this and nothing else.\n *\n * One preset implements it per target, and the build-time `@rshono/deploy` alias resolves to exactly\n * that module, so only the selected platform's code is ever in the bundle.\n */\nexport interface DeployRuntime {\n /**\n * Hands the app to the platform and returns whatever the entry module should `export default` there:\n * nothing where rshono owns the process (this binds the port), otherwise the export the platform looks\n * for — `{ fetch }` on Workers, a handler function on Vercel and Lambda.\n */\n serveApp(app: Hono): unknown;\n /** Mounts the hashed client bundle at `/_static`, ahead of the app's routes. A no-op where a CDN serves it. */\n mountStaticAssets(app: Hono): void;\n /** Mounts `public/` at the web root, after every route, so it only answers paths no route claimed. */\n mountPublicFallback(app: Hono): void;\n /**\n * Reads the page prerendered for `c.req.path`, or `null` when there is none — in which case the route\n * renders per request.\n *\n * Takes the whole {@link Context} because without a filesystem the store *is* a request-scoped\n * binding (`c.env.ASSETS` on Workers). The path is untrusted either way, so an implementation treats\n * traversal as a miss — see `prerenderedRelPath`.\n */\n readPrerendered(c: Context, variant: PrerenderVariant): Promise<PrerenderedPage | null>;\n /** Loads `.env` files where the platform has a filesystem. Env is bindings elsewhere. */\n loadEnv(): void;\n}\n"]}
1
+ {"version":3,"file":"contract.js","sourceRoot":"","sources":["../../src/deploy/contract.ts"],"names":[],"mappings":"","sourcesContent":["import type { Context, Hono } from 'hono';\nimport type { PrerenderVariant, PrerenderedPage } from '../server/prerendered.js';\n\n/**\n * A hosting platform `rshono build` targets. Selected with `deploy` in `rshono.config.ts`, the\n * `--deploy` flag or the `RSHONO_DEPLOY` env var.\n *\n * - `'node'` (the default) — rshono binds the port and you run the build with `rshono start`. Covers a\n * VPS, a container, a PaaS, and — through `node:` compatibility — Bun and Deno.\n * - `'cloudflare'` — a Worker; the entry exports `{ fetch }`.\n * - `'vercel'` — a Vercel function, plus the on-disk layout and config streaming needs there.\n * - `'aws-lambda'` — a streaming Lambda handler.\n *\n * There is one target per *handoff* — who opens the socket, and what shape a request arrives in — since\n * that is the part an app cannot arrange for itself. `rshono dev` always runs the `node` server.\n *\n * @example\n * ```ts\n * export default defineConfig({ deploy: 'cloudflare' });\n * ```\n *\n * @see {@link https://www.rshono.com/docs/deployment#the-targets | Docs — the targets}\n */\nexport type DeployTarget = 'node' | 'cloudflare' | 'vercel' | 'aws-lambda';\n\n/**\n * Everything the app server needs from the platform it runs on — the whole of what \"which platform is\n * this\" means at request time, since `runtime/entry.rsc.tsx` is written against this and nothing else.\n *\n * One preset implements it per target, and the build-time `@rshono/deploy` alias resolves to exactly\n * that module, so only the selected platform's code is ever in the bundle.\n */\nexport interface DeployRuntime {\n /**\n * Hands the app to the platform and returns whatever the entry module should `export default` there:\n * nothing where rshono owns the process (this binds the port), otherwise the export the platform looks\n * for — `{ fetch }` on Workers, a streaming handler on Lambda, and on Vercel a Node\n * `(IncomingMessage, ServerResponse)` listener, which is what its `Nodejs` launcher calls.\n *\n * Note that a web `Request` is not the common currency here: two of the three targets are handed one by\n * their platform, and Vercel is not, so converting is part of the handoff rather than something the\n * request-handling code below can assume has already happened.\n */\n serveApp(app: Hono): unknown;\n /** Mounts the hashed client bundle at `/_static`, ahead of the app's routes. A no-op where a CDN serves it. */\n mountStaticAssets(app: Hono): void;\n /** Mounts `public/` at the web root, after every route, so it only answers paths no route claimed. */\n mountPublicFallback(app: Hono): void;\n /**\n * Reads the page prerendered for `c.req.path`, or `null` when there is none — in which case the route\n * renders per request.\n *\n * Takes the whole {@link Context} because without a filesystem the store *is* a request-scoped\n * binding (`c.env.ASSETS` on Workers). The path is untrusted either way, so an implementation treats\n * traversal as a miss — see `prerenderedRelPath`.\n */\n readPrerendered(c: Context, variant: PrerenderVariant): Promise<PrerenderedPage | null>;\n /** Loads `.env` files where the platform has a filesystem. Env is bindings elsewhere. */\n loadEnv(): void;\n}\n"]}
@@ -2,6 +2,13 @@ import type { DeployRuntime } from '../contract.js';
2
2
  /**
3
3
  * Vercel, as a single Node function fed by the platform's own router.
4
4
  *
5
+ * The function is invoked the way `launcherType: 'Nodejs'` invokes one — with `(IncomingMessage,
6
+ * ServerResponse)`, not a web `Request`. That is the whole of the Build Output API's Node contract; the
7
+ * `Request`/`Response` handler shape the platform documents elsewhere belongs to the `@vercel/node` builder,
8
+ * which compiles and wraps a source file, and a `--prebuilt` upload never runs it. So the handoff converts,
9
+ * and `hono/vercel`'s `handle` — a pass-through that forwards its first argument straight to `app.fetch` —
10
+ * cannot be what does it.
11
+ *
5
12
  * `/_static` and `public/` are in the static output, and `config.json` puts the filesystem handler ahead of the
6
13
  * function, so mounting them here would be dead weight. Prerendered pages are *not* static output — one URL
7
14
  * answers with a document or a flight payload on the `RSC` request header, and a path-keyed CDN cannot choose — so
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../src/deploy/vercel/runtime.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAGpD;;;;;;;GAOG;AACH,eAAO,MAAM,OAAO,EAAE,aAoBrB,CAAC"}
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../src/deploy/vercel/runtime.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAoBpD;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,OAAO,EAAE,aA+BrB,CAAC"}
@@ -1,8 +1,31 @@
1
- import { handle } from 'hono/vercel';
1
+ import { getRequestListener } from '@hono/node-server';
2
2
  import { fileSystemRuntime } from '../filesystem.js';
3
+ /**
4
+ * The scheme the browser used, which the socket cannot answer for: Vercel terminates TLS at the edge and
5
+ * reaches the function over plain HTTP, so an `https://` request arrives on an unencrypted socket and every
6
+ * absolute URL the app derived from it would carry the wrong scheme — a redirect back to `http://`, an
7
+ * origin check comparing against one.
8
+ *
9
+ * Read without `trustProxy`, unlike `publicUrl`, because on this target the header is not
10
+ * client-supplied: the function is reachable only through Vercel's edge, which sets it on every request. The
11
+ * config field stays what it is — the answer for a proxy *you* put in front, which the framework cannot vouch
12
+ * for. Falls back to `https`, the only scheme a deployment is served on.
13
+ */
14
+ function browserScheme(incoming) {
15
+ const header = incoming.headers['x-forwarded-proto'];
16
+ const value = (Array.isArray(header) ? header[0] : header)?.split(',')[0]?.trim();
17
+ return value === 'http' ? 'http' : 'https';
18
+ }
3
19
  /**
4
20
  * Vercel, as a single Node function fed by the platform's own router.
5
21
  *
22
+ * The function is invoked the way `launcherType: 'Nodejs'` invokes one — with `(IncomingMessage,
23
+ * ServerResponse)`, not a web `Request`. That is the whole of the Build Output API's Node contract; the
24
+ * `Request`/`Response` handler shape the platform documents elsewhere belongs to the `@vercel/node` builder,
25
+ * which compiles and wraps a source file, and a `--prebuilt` upload never runs it. So the handoff converts,
26
+ * and `hono/vercel`'s `handle` — a pass-through that forwards its first argument straight to `app.fetch` —
27
+ * cannot be what does it.
28
+ *
6
29
  * `/_static` and `public/` are in the static output, and `config.json` puts the filesystem handler ahead of the
7
30
  * function, so mounting them here would be dead weight. Prerendered pages are *not* static output — one URL
8
31
  * answers with a document or a flight payload on the `RSC` request header, and a path-keyed CDN cannot choose — so
@@ -23,7 +46,18 @@ export const runtime = {
23
46
  // handler does that; `serveStatic`, which the filesystem targets use, is no longer in the path.
24
47
  },
25
48
  serveApp(app) {
26
- return handle(app);
49
+ // The same conversion `rshono start` runs on, so a request is built here exactly as it is on the `node`
50
+ // target — including a streamed response body, which `supportsResponseStreaming` in `.vc-config.json`
51
+ // then keeps unbuffered on the way out.
52
+ const listener = getRequestListener(app.fetch);
53
+ return (incoming, outgoing) => {
54
+ const host = incoming.headers.host;
55
+ // Left alone when there is no `Host`, so the listener answers with its own 400 rather than this
56
+ // building `https://undefined/…` and the app rejecting a URL it should never have been handed.
57
+ if (host)
58
+ incoming.url = `${browserScheme(incoming)}://${host}${incoming.url ?? '/'}`;
59
+ return listener(incoming, outgoing);
60
+ };
27
61
  },
28
62
  };
29
63
  //# sourceMappingURL=runtime.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/deploy/vercel/runtime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,OAAO,GAAkB;IACpC,GAAG,iBAAiB;IAEpB,iBAAiB;QACf,gEAAgE;IAClE,CAAC;IAED,mBAAmB;QACjB,sGAAsG;QACtG,wGAAwG;QACxG,yGAAyG;QACzG,qDAAqD;QACrD,EAAE;QACF,uGAAuG;QACvG,gGAAgG;IAClG,CAAC;IAED,QAAQ,CAAC,GAAS;QAChB,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC;CACF,CAAC","sourcesContent":["import type { Hono } from 'hono';\nimport { handle } from 'hono/vercel';\nimport type { DeployRuntime } from '../contract.js';\nimport { fileSystemRuntime } from '../filesystem.js';\n\n/**\n * Vercel, as a single Node function fed by the platform's own router.\n *\n * `/_static` and `public/` are in the static output, and `config.json` puts the filesystem handler ahead of the\n * function, so mounting them here would be dead weight. Prerendered pages are *not* static output — one URL\n * answers with a document or a flight payload on the `RSC` request header, and a path-keyed CDN cannot choose — so\n * they ship inside the function and are read from its read-only disk, exactly as on a server.\n */\nexport const runtime: DeployRuntime = {\n ...fileSystemRuntime,\n\n mountStaticAssets(): void {\n // Served from `.vercel/output/static` before the function runs.\n },\n\n mountPublicFallback(): void {\n // As above: `public/` is in the static output and `{ handle: 'filesystem' }` is matched ahead of this\n // function, so nothing here could ever answer for one of those paths. Stated as an override rather than\n // left to fall out of `dist/public` not being uploaded, because that would make the behaviour incidental\n // to a `cpSync` in `build.ts` instead of a decision.\n //\n // The one thing this hands to the platform: resolving a directory to its `index.html`. Vercel's static\n // handler does that; `serveStatic`, which the filesystem targets use, is no longer in the path.\n },\n\n serveApp(app: Hono): unknown {\n return handle(app);\n },\n};\n"]}
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/deploy/vercel/runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAIvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD;;;;;;;;;;GAUG;AACH,SAAS,aAAa,CAAC,QAAyB;IAC9C,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,mBAAmB,CAAC,CAAC;IACrD,MAAM,KAAK,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC;IAClF,OAAO,KAAK,KAAK,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC;AAC7C,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,OAAO,GAAkB;IACpC,GAAG,iBAAiB;IAEpB,iBAAiB;QACf,gEAAgE;IAClE,CAAC;IAED,mBAAmB;QACjB,sGAAsG;QACtG,wGAAwG;QACxG,yGAAyG;QACzG,qDAAqD;QACrD,EAAE;QACF,uGAAuG;QACvG,gGAAgG;IAClG,CAAC;IAED,QAAQ,CAAC,GAAS;QAChB,wGAAwG;QACxG,sGAAsG;QACtG,wCAAwC;QACxC,MAAM,QAAQ,GAAG,kBAAkB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAE/C,OAAO,CAAC,QAAyB,EAAE,QAAwB,EAAiB,EAAE;YAC5E,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC;YACnC,gGAAgG;YAChG,+FAA+F;YAC/F,IAAI,IAAI;gBAAE,QAAQ,CAAC,GAAG,GAAG,GAAG,aAAa,CAAC,QAAQ,CAAC,MAAM,IAAI,GAAG,QAAQ,CAAC,GAAG,IAAI,GAAG,EAAE,CAAC;YACtF,OAAO,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC;QACtC,CAAC,CAAC;IACJ,CAAC;CACF,CAAC","sourcesContent":["import { getRequestListener } from '@hono/node-server';\nimport type { Hono } from 'hono';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { DeployRuntime } from '../contract.js';\nimport { fileSystemRuntime } from '../filesystem.js';\n\n/**\n * The scheme the browser used, which the socket cannot answer for: Vercel terminates TLS at the edge and\n * reaches the function over plain HTTP, so an `https://` request arrives on an unencrypted socket and every\n * absolute URL the app derived from it would carry the wrong scheme — a redirect back to `http://`, an\n * origin check comparing against one.\n *\n * Read without `trustProxy`, unlike `publicUrl`, because on this target the header is not\n * client-supplied: the function is reachable only through Vercel's edge, which sets it on every request. The\n * config field stays what it is — the answer for a proxy *you* put in front, which the framework cannot vouch\n * for. Falls back to `https`, the only scheme a deployment is served on.\n */\nfunction browserScheme(incoming: IncomingMessage): string {\n const header = incoming.headers['x-forwarded-proto'];\n const value = (Array.isArray(header) ? header[0] : header)?.split(',')[0]?.trim();\n return value === 'http' ? 'http' : 'https';\n}\n\n/**\n * Vercel, as a single Node function fed by the platform's own router.\n *\n * The function is invoked the way `launcherType: 'Nodejs'` invokes one — with `(IncomingMessage,\n * ServerResponse)`, not a web `Request`. That is the whole of the Build Output API's Node contract; the\n * `Request`/`Response` handler shape the platform documents elsewhere belongs to the `@vercel/node` builder,\n * which compiles and wraps a source file, and a `--prebuilt` upload never runs it. So the handoff converts,\n * and `hono/vercel`'s `handle` — a pass-through that forwards its first argument straight to `app.fetch` —\n * cannot be what does it.\n *\n * `/_static` and `public/` are in the static output, and `config.json` puts the filesystem handler ahead of the\n * function, so mounting them here would be dead weight. Prerendered pages are *not* static output — one URL\n * answers with a document or a flight payload on the `RSC` request header, and a path-keyed CDN cannot choose — so\n * they ship inside the function and are read from its read-only disk, exactly as on a server.\n */\nexport const runtime: DeployRuntime = {\n ...fileSystemRuntime,\n\n mountStaticAssets(): void {\n // Served from `.vercel/output/static` before the function runs.\n },\n\n mountPublicFallback(): void {\n // As above: `public/` is in the static output and `{ handle: 'filesystem' }` is matched ahead of this\n // function, so nothing here could ever answer for one of those paths. Stated as an override rather than\n // left to fall out of `dist/public` not being uploaded, because that would make the behaviour incidental\n // to a `cpSync` in `build.ts` instead of a decision.\n //\n // The one thing this hands to the platform: resolving a directory to its `index.html`. Vercel's static\n // handler does that; `serveStatic`, which the filesystem targets use, is no longer in the path.\n },\n\n serveApp(app: Hono): unknown {\n // The same conversion `rshono start` runs on, so a request is built here exactly as it is on the `node`\n // target — including a streamed response body, which `supportsResponseStreaming` in `.vc-config.json`\n // then keeps unbuffered on the way out.\n const listener = getRequestListener(app.fetch);\n\n return (incoming: IncomingMessage, outgoing: ServerResponse): Promise<void> => {\n const host = incoming.headers.host;\n // Left alone when there is no `Host`, so the listener answers with its own 400 rather than this\n // building `https://undefined/…` and the app rejecting a URL it should never have been handed.\n if (host) incoming.url = `${browserScheme(incoming)}://${host}${incoming.url ?? '/'}`;\n return listener(incoming, outgoing);\n };\n },\n};\n"]}
@@ -134,6 +134,11 @@ async function main() {
134
134
  }
135
135
  window.history.replaceState(null, '', target.href);
136
136
  }
137
+ // A traversal is the browser's to perform: it moves the entry itself and fires `popstate`, which is where
138
+ // `listenNavigation` picks the new document up — so these need no more than to ask, and inherit the same
139
+ // fetch, scroll restoration and `pending` flag a back-button press already got.
140
+ const back = () => window.history.back();
141
+ const forward = () => window.history.forward();
137
142
  // A refresh keeps the URL, so it can't ride the history patch like push/replace and drives the re-fetch itself.
138
143
  const refresh = () => startNav(async () => {
139
144
  try {
@@ -246,7 +251,7 @@ async function main() {
246
251
  stopNavigating();
247
252
  };
248
253
  }, []);
249
- const router = React.useMemo(() => ({ push, replace, refresh, pending }), [pending]);
254
+ const router = React.useMemo(() => ({ push, replace, back, forward, refresh, pending }), [pending]);
250
255
  return _jsx(RouterContext.Provider, { value: router, children: payload.root });
251
256
  }
252
257
  setServerCallback(async (id, args) => {
@@ -1 +1 @@
1
- {"version":3,"file":"entry.client.js","sourceRoot":"","sources":["../../src/runtime/entry.client.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EACL,eAAe,EACf,wBAAwB,EACxB,2BAA2B,EAC3B,WAAW,EACX,iBAAiB,GAClB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAGpE,sGAAsG;AACtG,6CAA6C;AAC7C,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,aAAa,EAAyB,MAAM,iBAAiB,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEhD,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,aAAa,CAAC;AAOrD,0GAA0G;AAC1G,SAAS,iBAAiB;IACxB,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,wFAAwF;IACxF,IAAI,UAAwD,CAAC;IAC7D,MAAM,MAAM,GAAG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QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;gBAC9D,MAAM;QACV,CAAC;IACH,CAAC;IAED,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,cAAc,CAAC,CAAC;IAC/C,yGAAyG;IACzG,0GAA0G;IAC1G,qEAAqE;IACrE,IAAI,KAAK,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;IAC7C,MAAM,CAAC,SAAS,GAAG,CAAC,KAA2B,EAAE,EAAE;QACjD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAe,CAAC;QACrD,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,uBAAuB,EAAE,KAAK,CAAC,CAAC,CAAC;IACrG,CAAC,CAAC;AACJ,CAAC;AAED,mGAAmG;AACnG,kFAAkF;AAClF,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,8CAA8C,EAAE,KAAK,CAAC,CAAC;IACrE,SAAS,CAAC,KAAK,CAAC,CAAC;AACnB,CAAC,CAAC,CAAC","sourcesContent":["import React from 'react';\nimport { hydrateRoot } from 'react-dom/client';\nimport {\n createFromFetch,\n createFromReadableStream,\n createTemporaryReferenceSet,\n encodeReply,\n setServerCallback,\n} from 'react-server-dom-rspack/client.browser';\nimport { isControlDigest, parseRedirectDigest } from './control.js';\nimport type { DevMessage } from './dev-protocol.js';\nimport type { RscPayload } from './entry.rsc.js';\n// Dev-only: its one caller sits behind `import.meta.webpackHot`, which a production build compiles to\n// `false` — so this module is dropped there.\nimport { walkHotUpdates } from './hot-update.js';\nimport { RouterContext, type NavigationRouter } from './navigation.js';\nimport { createRscRequest } from './request.js';\n\nconst isDev = process.env.NODE_ENV === 'development';\n\ndeclare global {\n /** The array the payload `<script>` tags `flight-inject.ts` emits push their chunks into. */\n var __FLIGHT_DATA: Array<string | Uint8Array> | undefined;\n}\n\n/** The flight payload the document carried, read back out of `__FLIGHT_DATA` — see `flight-inject.ts`. */\nfunction readFlightPayload(): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n // Assigned synchronously by `start`, which `new ReadableStream` runs before it returns.\n let controller!: ReadableStreamDefaultController<Uint8Array>;\n const stream = new ReadableStream<Uint8Array>({\n start: (c) => void (controller = c),\n });\n const enqueue = (chunk: string | Uint8Array) => controller.enqueue(typeof chunk === 'string' ? encoder.encode(chunk) : chunk);\n\n // Payload scripts interleave with the document: the ones that already ran are in the array, the rest\n // arrive through `push`.\n const data = (self.__FLIGHT_DATA ??= []);\n for (const chunk of data) enqueue(chunk);\n data.push = enqueue as typeof data.push;\n\n // The last payload script lands before parsing finishes, so that is what closes the stream.\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => controller.close(), { once: true });\n } else {\n controller.close();\n }\n return stream;\n}\n\n/** Created at module evaluation, not inside `main()`, so no chunk can be pushed before it is watching. */\nconst flightStream = readFlightPayload();\n\n/**\n * The part of the location a payload is rendered for — the document, without the fragment, which the server\n * never sees. Two URLs that differ only by `#hash` describe the same payload.\n */\nconst documentUrl = (): string => location.pathname + location.search;\n\n/** Guarantees somewhere to attach the fatal overlay: the root container is `document`, so a teardown can take `<body>` with it. */\nfunction overlayHost(): HTMLElement {\n if (!document.documentElement) document.appendChild(document.createElement('html'));\n if (!document.body) document.documentElement.appendChild(document.createElement('body'));\n return document.body;\n}\n\n/**\n * Paints the reason for an uncaught render error over the blank page it leaves behind — the full stack in\n * dev, a generic notice and a reload button in production.\n *\n * DOM calls rather than React (the renderer is what just failed), and `textContent` rather than\n * `innerHTML` (an error message is untrusted input).\n */\nfunction showFatal(error: unknown, componentStack?: string | null): void {\n // Queued: React's teardown runs after this callback returns and would remove a node appended inline.\n setTimeout(() => {\n const host = overlayHost();\n host.querySelector('[data-rshono-fatal]')?.remove();\n\n const box = document.createElement('div');\n box.setAttribute('data-rshono-fatal', '');\n box.setAttribute('role', 'alert');\n box.style.cssText =\n 'position:fixed;inset:0;z-index:2147483647;overflow:auto;padding:1.5rem;background:#18181b;color:#f4f4f5;' +\n 'font:14px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;text-align:left';\n\n const title = document.createElement('div');\n title.textContent = isDev ? 'Unhandled error' : 'Something went wrong';\n title.style.cssText = 'font-size:1.0625rem;font-weight:700;color:#f87171;margin:0 0 0.75rem';\n box.appendChild(title);\n\n if (isDev) {\n const detail = document.createElement('pre');\n detail.style.cssText = 'margin:0;white-space:pre-wrap;word-break:break-word';\n detail.textContent =\n (error instanceof Error ? (error.stack ?? `${error.name}: ${error.message}`) : String(error)) +\n (componentStack ? `\\n\\nComponent stack:${componentStack}` : '');\n box.appendChild(detail);\n } else {\n const message = document.createElement('p');\n message.textContent = 'This page hit an unexpected error and can’t continue.';\n message.style.cssText = 'margin:0 0 1rem;color:#d4d4d8';\n box.appendChild(message);\n }\n\n const reload = document.createElement('button');\n reload.textContent = 'Reload page';\n reload.style.cssText =\n 'margin-top:1.25rem;padding:0.5rem 1rem;font:inherit;color:#18181b;background:#f4f4f5;border:0;border-radius:4px;cursor:pointer';\n reload.addEventListener('click', () => window.location.reload());\n box.appendChild(reload);\n\n host.appendChild(box);\n }, 0);\n}\n\n/**\n * Asks a URL for its flight payload. Deliberately uncached — a payload can never be staler than the click\n * that wanted it, and the browser's own HTTP cache is what makes a repeat visit cheap.\n */\nfunction requestPayload(href: string, signal: AbortSignal): Promise<RscPayload> {\n return createFromFetch<RscPayload>(fetch(createRscRequest(new URL(href, location.href).href, undefined, signal)));\n}\n\nasync function main() {\n // The assertion is load-bearing under the compiler that builds this: TypeScript 7 declares `nonce` on\n // HTMLElement, 6 declares it on Element. ESLint runs the older lib — where the narrowing is redundant —\n // so it reports an assertion that `tsc` requires. Believe `typecheck`, not the rule.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n const cspMeta = document.querySelector('meta[property=\"csp-nonce\"]') as HTMLMetaElement | null;\n if (cspMeta?.nonce) __webpack_nonce__ = cspMeta.nonce;\n\n // Both are replaced by BrowserRoot's own on mount. The defaults cover the window before hydration, where\n // `setServerCallback` is already registered but there is no root to update — a reload is the honest answer.\n let setPayload: (v: RscPayload) => void = () => {\n window.location.reload();\n };\n // Runs work inside the nav transition so useNavigation().pending stays true across the round-trip.\n let startNav: (run: () => void | Promise<void>) => void = (run) => {\n void run();\n };\n\n const initialPayload = await createFromReadableStream<RscPayload>(flightStream);\n\n function push(href: string) {\n const target = new URL(href, window.location.href);\n if (target.origin !== window.location.origin) {\n window.location.assign(target.href);\n return;\n }\n window.history.pushState(null, '', target.href);\n }\n\n function replace(href: string) {\n const target = new URL(href, window.location.href);\n if (target.origin !== window.location.origin) {\n window.location.replace(target.href);\n return;\n }\n window.history.replaceState(null, '', target.href);\n }\n\n // A refresh keeps the URL, so it can't ride the history patch like push/replace and drives the re-fetch itself.\n const refresh = () =>\n startNav(async () => {\n try {\n await fetchRscPayload();\n } catch {\n window.location.reload();\n }\n });\n\n /**\n * Turns a control-signal digest — how `redirect()` / `notFound()` reach the browser — into a real\n * navigation. Returns false for anything else, so callers fall through to their own handling.\n *\n * `hard` forces a full document load, for signals that surfaced *through React*: it unmounts the root on\n * an uncaught error, leaving no live tree to soft-navigate with.\n */\n function handleControlDigest(error: unknown, { hard = false }: { hard?: boolean } = {}): boolean {\n const digest = (error as { digest?: unknown } | null)?.digest;\n if (!isControlDigest(digest)) return false;\n const redirect = parseRedirectDigest(digest);\n if (!redirect) {\n window.location.reload();\n } else if (hard) {\n window.location.assign(new URL(redirect.location, window.location.href).href);\n } else {\n push(redirect.location);\n }\n return true;\n }\n\n /**\n * The navigation whose payload the screen is allowed to show. React runs async transitions concurrently, so\n * two overlapping navigations are two live fetches with no ordering between them — without this, a slow\n * first response landing after a fast second one renders the page the user already left while the address\n * bar shows the one they asked for.\n */\n let currentNavigation = 0;\n /** The in-flight navigation's fetch, so a newer one can stop paying for it. */\n let navigationFetch: AbortController | null = null;\n\n /**\n * Fetches the payload for the current URL and applies it, unless a newer navigation started meanwhile.\n *\n * @returns `true` when this navigation is the one that settled the screen, `false` when it was superseded.\n * The distinction is what keeps a stale response from scrolling a page it is no longer rendering — and\n * why being superseded resolves rather than throws: both callers answer a rejection with a full reload,\n * so surfacing the abort would turn every fast second click into one.\n */\n async function fetchRscPayload(): Promise<boolean> {\n const navigation = ++currentNavigation;\n navigationFetch?.abort();\n const controller = (navigationFetch = new AbortController());\n const superseded = () => navigation !== currentNavigation;\n\n let payload: RscPayload;\n try {\n payload = await requestPayload(window.location.href, controller.signal);\n } catch (error) {\n // Checked before the error is read: an abort is this navigation being replaced, and the one that\n // replaced it owns the outcome.\n if (superseded()) return false;\n if (handleControlDigest(error)) return true;\n throw error;\n }\n if (superseded()) return false;\n if (payload.redirect) {\n push(payload.redirect);\n return true;\n }\n setPayload(payload);\n return true;\n }\n\n function BrowserRoot() {\n const [payload, setPayloadState] = React.useState(initialPayload);\n const [pending, startTransition] = React.useTransition();\n // The scroll a fetched navigation still owes, held until its payload is on screen.\n const pendingScroll = React.useRef<(() => void) | null>(null);\n\n React.useEffect(() => {\n setPayload = (v) => setPayloadState(v);\n startNav = (run) => startTransition(run);\n }, [startTransition]);\n\n /**\n * Scrolls where the navigation asked, once React has put its payload in the DOM — a `#hash` target does\n * not exist until the new tree does. A layout effect, so the pre-scroll position is never painted.\n */\n React.useLayoutEffect(() => {\n const scroll = pendingScroll.current;\n pendingScroll.current = null;\n scroll?.();\n }, [payload]);\n\n React.useEffect(() => {\n const stopNavigating = listenNavigation((afterRender) =>\n startNav(async () => {\n try {\n // Only the navigation that settled the screen owes a scroll — a superseded one would move the\n // page the navigation that replaced it is about to render.\n if (await fetchRscPayload()) pendingScroll.current = afterRender;\n } catch {\n window.location.reload();\n }\n }),\n );\n const stopUpgradingLinks = listenLinks();\n return () => {\n stopUpgradingLinks();\n stopNavigating();\n };\n }, []);\n\n const router = React.useMemo<NavigationRouter>(() => ({ push, replace, refresh, pending }), [pending]);\n\n return <RouterContext.Provider value={router}>{payload.root}</RouterContext.Provider>;\n }\n\n setServerCallback(async (id, args) => {\n const temporaryReferences = createTemporaryReferenceSet();\n // The document the action is being called from. Every action response carries a fresh payload for that\n // page, so if a navigation has moved on by the time it arrives the payload describes a page the user has\n // left — the return value is still theirs, but painting it is not. Compared without the fragment, which\n // the server never saw.\n const calledFrom = documentUrl();\n const request = createRscRequest(window.location.href, {\n id,\n body: await encodeReply(args, { temporaryReferences }),\n });\n let payload: RscPayload;\n try {\n payload = await createFromFetch<RscPayload>(fetch(request), { temporaryReferences });\n } catch (error) {\n if (handleControlDigest(error)) return undefined;\n throw error;\n }\n if (payload.redirect) {\n push(payload.redirect);\n return undefined;\n }\n if (documentUrl() === calledFrom) React.startTransition(() => setPayload(payload));\n if (payload.notFound) return undefined;\n const result = payload.returnValue!;\n if (!result.ok) throw result.error;\n return result.value;\n });\n\n // A `redirect()` / `notFound()` from a component below the page root reaches us through React: it rides the\n // flight payload as an error, and boundaries re-throw it so it lands here rather than in a fallback.\n //\n // Installing these hooks opts out of React's own defaults, so everything that isn't a control signal has to\n // be put back by hand — `reportError` rather than a bare log, so error-reporting tools still see it.\n hydrateRoot(document, <BrowserRoot />, {\n formState: initialPayload.formState,\n onCaughtError: (error, errorInfo) => {\n if (handleControlDigest(error, { hard: true })) return;\n // A boundary handled it and the tree is intact, so no overlay over the app's own fallback.\n console.error(error, errorInfo.componentStack ?? '');\n },\n onUncaughtError: (error, errorInfo) => {\n if (handleControlDigest(error, { hard: true })) return;\n // Nothing caught it, so React tears the root down — and the root is `document`.\n globalThis.reportError(error);\n showFatal(error, errorInfo.componentStack);\n },\n });\n\n if (import.meta.webpackHot) {\n initDevRefresh(fetchRscPayload);\n }\n}\n\ntype NavigationType = 'push' | 'replace' | 'pop';\n\n/** Runs teardown in reverse and empties the list, so a second call is a no-op. */\nfunction disposeAll(undo: Array<() => void>): void {\n for (const dispose of undo.splice(0).reverse()) dispose();\n}\n\n// An `<a>` we intercept for soft navigation: same-origin, same tab, not a download,\n// and not explicitly opted out with `data-native` (which forces a full browser navigation).\nfunction isRouterLink(link: HTMLAnchorElement): boolean {\n return (\n !!link.href &&\n (!link.target || link.target === '_self') &&\n link.origin === location.origin &&\n !link.hasAttribute('download') &&\n !link.hasAttribute('data-native')\n );\n}\n\n/**\n * Upgrades the app's anchors: a plain left-click becomes a soft navigation. It shares no state with\n * `listenNavigation` — a click only calls `history.pushState`, which is where that picks the navigation up.\n */\nfunction listenLinks(): () => void {\n const undo: Array<() => void> = [];\n\n function onClick(e: MouseEvent) {\n const link = (e.target as Element).closest('a');\n if (\n link &&\n link instanceof HTMLAnchorElement &&\n isRouterLink(link) &&\n e.button === 0 &&\n !e.metaKey &&\n !e.ctrlKey &&\n !e.altKey &&\n !e.shiftKey &&\n !e.defaultPrevented\n ) {\n if (link.hash && link.pathname === location.pathname && link.search === location.search) return;\n e.preventDefault();\n history.pushState(null, '', link.href);\n }\n }\n document.addEventListener('click', onClick);\n undo.push(() => document.removeEventListener('click', onClick));\n\n return () => disposeAll(undo);\n}\n\n/**\n * The element the current `#fragment` names, if it is on the page. A fragment is percent-encoded and an `id`\n * is not, so it is decoded first — and taken literally when a hand-written `%` makes that throw.\n */\nfunction fragmentTarget(): HTMLElement | null {\n const fragment = location.hash.slice(1);\n if (!fragment) return null;\n let id = fragment;\n try {\n id = decodeURIComponent(fragment);\n } catch {\n // Malformed escape — the literal fragment is the better guess at the id than nothing.\n }\n return document.getElementById(id);\n}\n\nfunction listenNavigation(onNavigation: (afterRender: () => void) => void): () => void {\n const undo: Array<() => void> = [];\n\n // Set explicitly as a statement of intent: the browser remembers a traversal's offset, and nothing here\n // tracks one.\n const prevRestoration = window.history.scrollRestoration;\n try {\n window.history.scrollRestoration = 'auto';\n } catch {\n // Not settable in every browser, and only a preference — the navigation still works without it.\n }\n undo.push(() => {\n try {\n window.history.scrollRestoration = prevRestoration;\n } catch {\n // As above: if it could not be set, it cannot be put back either.\n }\n });\n\n /**\n * A push is not a real navigation to the browser, so nothing resets the scroll offset. A `#hash` names\n * where to land instead; `replace` keeps its position, and a traversal is the browser's to restore.\n *\n * `scrollIntoView` is the algorithm a browser's own fragment jump uses, so `scroll-padding-top` still\n * applies. Neither call passes a `behavior`, leaving `scroll-behavior: smooth` the app's to ask for.\n */\n const afterRenderFor = (type: NavigationType) => () => {\n if (type !== 'push') return;\n const target = fragmentTarget();\n if (target) target.scrollIntoView();\n else window.scrollTo(0, 0);\n };\n\n // What the payload on screen was rendered for. See {@link documentUrl}.\n let renderedUrl = documentUrl();\n\n /**\n * A navigation that moves only the fragment leaves the document unchanged, so the payload on screen is\n * already the right one — fetching another would re-render the page out from under the jump.\n * `router.refresh()` is unaffected, and remains the way to ask for fresh data at an unchanged URL.\n */\n const notify = (type: NavigationType) => {\n const afterRender = afterRenderFor(type);\n if (documentUrl() === renderedUrl) {\n afterRender();\n return;\n }\n renderedUrl = documentUrl();\n onNavigation(afterRender);\n };\n\n const onPopState = () => notify('pop');\n window.addEventListener('popstate', onPopState);\n undo.push(() => window.removeEventListener('popstate', onPopState));\n\n // Saved unbound on purpose, and called back with `.call(this, …)` below — patching `history` is the only\n // way to see a navigation the app makes itself, and the receiver is restored at every call site.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const oldPushState = window.history.pushState;\n window.history.pushState = function (state, unused, url) {\n const res = oldPushState.call(this, state, unused, url as string);\n notify('push');\n return res;\n };\n undo.push(() => {\n window.history.pushState = oldPushState;\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method -- as with `pushState` above.\n const oldReplaceState = window.history.replaceState;\n window.history.replaceState = function (state, unused, url) {\n const res = oldReplaceState.call(this, state, unused, url as string);\n notify('replace');\n return res;\n };\n undo.push(() => {\n window.history.replaceState = oldReplaceState;\n });\n\n return () => disposeAll(undo);\n}\n\n/**\n * Dev-only refresh client, listening to the CLI's SSE endpoint:\n *\n * client-built → hot-apply the waiting updates; anything the page can't be patched up to reloads.\n * rsc-update → server component code changed: re-fetch the flight payload, state preserved.\n * hello → sent on (re)connect with the latest build hash; a mismatch means a missed event.\n */\n// `Promise<unknown>`: the payload fetch reports whether its navigation was superseded, which matters to a\n// click and not to a rebuild — here only settling or rejecting does.\nfunction initDevRefresh(fetchRscPayload: () => Promise<unknown>) {\n const hot = import.meta.webpackHot!;\n let connectedOnce = false;\n /** The newest build the dev server has announced — what {@link applyClientUpdate} walks towards. */\n let targetHash: string | undefined;\n\n function reload(reason: string, error?: unknown): void {\n console.warn(`[rshono] ${reason} — reloading`, ...(error === undefined ? [] : [error]));\n window.location.reload();\n }\n\n async function applyClientUpdate(): Promise<void> {\n const giveUp = await walkHotUpdates(\n hot,\n () => __webpack_hash__,\n () => targetHash,\n );\n if (giveUp) reload(giveUp.reason, giveUp.error);\n }\n\n async function handle(message: DevMessage): Promise<void> {\n switch (message.type) {\n case 'hello':\n targetHash = message.hash ?? targetHash;\n if (connectedOnce) {\n await applyClientUpdate();\n await fetchRscPayload().catch(() => window.location.reload());\n }\n connectedOnce = true;\n break;\n case 'client-built':\n targetHash = message.hash;\n await applyClientUpdate();\n break;\n case 'rsc-update':\n console.log('[rshono] server components updated');\n await fetchRscPayload().catch(() => window.location.reload());\n break;\n }\n }\n\n const source = new EventSource('/_rshono/hmr');\n // Chained rather than handled as they arrive: `hot.check` may only run from `idle`, and a burst of saves\n // puts several frames on the wire inside the time one takes. Queueing drops nothing, because `targetHash`\n // is shared — whichever handler runs next walks to the newest build.\n let queue: Promise<void> = Promise.resolve();\n source.onmessage = (event: MessageEvent<string>) => {\n const message = JSON.parse(event.data) as DevMessage;\n queue = queue.then(() => handle(message)).catch((error) => reload('the dev client failed', error));\n };\n}\n\n// A bootstrap failure — a truncated initial payload, most likely — would otherwise be an unhandled\n// rejection: nothing hydrates, nothing is reported, and the page just sits there.\nmain().catch((error) => {\n console.error('[rshono] the client runtime failed to start:', error);\n showFat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,MAAM,CAAC,SAAS,GAAG,CAAC,KAA2B,EAAE,EAAE;QACjD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAe,CAAC;QACrD,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,MAAM,CAAC,uBAAuB,EAAE,KAAK,CAAC,CAAC,CAAC;IACrG,CAAC,CAAC;AACJ,CAAC;AAED,mGAAmG;AACnG,kFAAkF;AAClF,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,8CAA8C,EAAE,KAAK,CAAC,CAAC;IACrE,SAAS,CAAC,KAAK,CAAC,CAAC;AACnB,CAAC,CAAC,CAAC","sourcesContent":["import React from 'react';\nimport { hydrateRoot } from 'react-dom/client';\nimport {\n createFromFetch,\n createFromReadableStream,\n createTemporaryReferenceSet,\n encodeReply,\n setServerCallback,\n} from 'react-server-dom-rspack/client.browser';\nimport { isControlDigest, parseRedirectDigest } from './control.js';\nimport type { DevMessage } from './dev-protocol.js';\nimport type { RscPayload } from './entry.rsc.js';\n// Dev-only: its one caller sits behind `import.meta.webpackHot`, which a production build compiles to\n// `false` — so this module is dropped there.\nimport { walkHotUpdates } from './hot-update.js';\nimport { RouterContext, type NavigationRouter } from './navigation.js';\nimport { createRscRequest } from './request.js';\n\nconst isDev = process.env.NODE_ENV === 'development';\n\ndeclare global {\n /** The array the payload `<script>` tags `flight-inject.ts` emits push their chunks into. */\n var __FLIGHT_DATA: Array<string | Uint8Array> | undefined;\n}\n\n/** The flight payload the document carried, read back out of `__FLIGHT_DATA` — see `flight-inject.ts`. */\nfunction readFlightPayload(): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n // Assigned synchronously by `start`, which `new ReadableStream` runs before it returns.\n let controller!: ReadableStreamDefaultController<Uint8Array>;\n const stream = new ReadableStream<Uint8Array>({\n start: (c) => void (controller = c),\n });\n const enqueue = (chunk: string | Uint8Array) => controller.enqueue(typeof chunk === 'string' ? encoder.encode(chunk) : chunk);\n\n // Payload scripts interleave with the document: the ones that already ran are in the array, the rest\n // arrive through `push`.\n const data = (self.__FLIGHT_DATA ??= []);\n for (const chunk of data) enqueue(chunk);\n data.push = enqueue as typeof data.push;\n\n // The last payload script lands before parsing finishes, so that is what closes the stream.\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => controller.close(), { once: true });\n } else {\n controller.close();\n }\n return stream;\n}\n\n/** Created at module evaluation, not inside `main()`, so no chunk can be pushed before it is watching. */\nconst flightStream = readFlightPayload();\n\n/**\n * The part of the location a payload is rendered for — the document, without the fragment, which the server\n * never sees. Two URLs that differ only by `#hash` describe the same payload.\n */\nconst documentUrl = (): string => location.pathname + location.search;\n\n/** Guarantees somewhere to attach the fatal overlay: the root container is `document`, so a teardown can take `<body>` with it. */\nfunction overlayHost(): HTMLElement {\n if (!document.documentElement) document.appendChild(document.createElement('html'));\n if (!document.body) document.documentElement.appendChild(document.createElement('body'));\n return document.body;\n}\n\n/**\n * Paints the reason for an uncaught render error over the blank page it leaves behind — the full stack in\n * dev, a generic notice and a reload button in production.\n *\n * DOM calls rather than React (the renderer is what just failed), and `textContent` rather than\n * `innerHTML` (an error message is untrusted input).\n */\nfunction showFatal(error: unknown, componentStack?: string | null): void {\n // Queued: React's teardown runs after this callback returns and would remove a node appended inline.\n setTimeout(() => {\n const host = overlayHost();\n host.querySelector('[data-rshono-fatal]')?.remove();\n\n const box = document.createElement('div');\n box.setAttribute('data-rshono-fatal', '');\n box.setAttribute('role', 'alert');\n box.style.cssText =\n 'position:fixed;inset:0;z-index:2147483647;overflow:auto;padding:1.5rem;background:#18181b;color:#f4f4f5;' +\n 'font:14px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;text-align:left';\n\n const title = document.createElement('div');\n title.textContent = isDev ? 'Unhandled error' : 'Something went wrong';\n title.style.cssText = 'font-size:1.0625rem;font-weight:700;color:#f87171;margin:0 0 0.75rem';\n box.appendChild(title);\n\n if (isDev) {\n const detail = document.createElement('pre');\n detail.style.cssText = 'margin:0;white-space:pre-wrap;word-break:break-word';\n detail.textContent =\n (error instanceof Error ? (error.stack ?? `${error.name}: ${error.message}`) : String(error)) +\n (componentStack ? `\\n\\nComponent stack:${componentStack}` : '');\n box.appendChild(detail);\n } else {\n const message = document.createElement('p');\n message.textContent = 'This page hit an unexpected error and can’t continue.';\n message.style.cssText = 'margin:0 0 1rem;color:#d4d4d8';\n box.appendChild(message);\n }\n\n const reload = document.createElement('button');\n reload.textContent = 'Reload page';\n reload.style.cssText =\n 'margin-top:1.25rem;padding:0.5rem 1rem;font:inherit;color:#18181b;background:#f4f4f5;border:0;border-radius:4px;cursor:pointer';\n reload.addEventListener('click', () => window.location.reload());\n box.appendChild(reload);\n\n host.appendChild(box);\n }, 0);\n}\n\n/**\n * Asks a URL for its flight payload. Deliberately uncached — a payload can never be staler than the click\n * that wanted it, and the browser's own HTTP cache is what makes a repeat visit cheap.\n */\nfunction requestPayload(href: string, signal: AbortSignal): Promise<RscPayload> {\n return createFromFetch<RscPayload>(fetch(createRscRequest(new URL(href, location.href).href, undefined, signal)));\n}\n\nasync function main() {\n // The assertion is load-bearing under the compiler that builds this: TypeScript 7 declares `nonce` on\n // HTMLElement, 6 declares it on Element. ESLint runs the older lib — where the narrowing is redundant —\n // so it reports an assertion that `tsc` requires. Believe `typecheck`, not the rule.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n const cspMeta = document.querySelector('meta[property=\"csp-nonce\"]') as HTMLMetaElement | null;\n if (cspMeta?.nonce) __webpack_nonce__ = cspMeta.nonce;\n\n // Both are replaced by BrowserRoot's own on mount. The defaults cover the window before hydration, where\n // `setServerCallback` is already registered but there is no root to update — a reload is the honest answer.\n let setPayload: (v: RscPayload) => void = () => {\n window.location.reload();\n };\n // Runs work inside the nav transition so useNavigation().pending stays true across the round-trip.\n let startNav: (run: () => void | Promise<void>) => void = (run) => {\n void run();\n };\n\n const initialPayload = await createFromReadableStream<RscPayload>(flightStream);\n\n function push(href: string) {\n const target = new URL(href, window.location.href);\n if (target.origin !== window.location.origin) {\n window.location.assign(target.href);\n return;\n }\n window.history.pushState(null, '', target.href);\n }\n\n function replace(href: string) {\n const target = new URL(href, window.location.href);\n if (target.origin !== window.location.origin) {\n window.location.replace(target.href);\n return;\n }\n window.history.replaceState(null, '', target.href);\n }\n\n // A traversal is the browser's to perform: it moves the entry itself and fires `popstate`, which is where\n // `listenNavigation` picks the new document up — so these need no more than to ask, and inherit the same\n // fetch, scroll restoration and `pending` flag a back-button press already got.\n const back = () => window.history.back();\n const forward = () => window.history.forward();\n\n // A refresh keeps the URL, so it can't ride the history patch like push/replace and drives the re-fetch itself.\n const refresh = () =>\n startNav(async () => {\n try {\n await fetchRscPayload();\n } catch {\n window.location.reload();\n }\n });\n\n /**\n * Turns a control-signal digest — how `redirect()` / `notFound()` reach the browser — into a real\n * navigation. Returns false for anything else, so callers fall through to their own handling.\n *\n * `hard` forces a full document load, for signals that surfaced *through React*: it unmounts the root on\n * an uncaught error, leaving no live tree to soft-navigate with.\n */\n function handleControlDigest(error: unknown, { hard = false }: { hard?: boolean } = {}): boolean {\n const digest = (error as { digest?: unknown } | null)?.digest;\n if (!isControlDigest(digest)) return false;\n const redirect = parseRedirectDigest(digest);\n if (!redirect) {\n window.location.reload();\n } else if (hard) {\n window.location.assign(new URL(redirect.location, window.location.href).href);\n } else {\n push(redirect.location);\n }\n return true;\n }\n\n /**\n * The navigation whose payload the screen is allowed to show. React runs async transitions concurrently, so\n * two overlapping navigations are two live fetches with no ordering between them — without this, a slow\n * first response landing after a fast second one renders the page the user already left while the address\n * bar shows the one they asked for.\n */\n let currentNavigation = 0;\n /** The in-flight navigation's fetch, so a newer one can stop paying for it. */\n let navigationFetch: AbortController | null = null;\n\n /**\n * Fetches the payload for the current URL and applies it, unless a newer navigation started meanwhile.\n *\n * @returns `true` when this navigation is the one that settled the screen, `false` when it was superseded.\n * The distinction is what keeps a stale response from scrolling a page it is no longer rendering — and\n * why being superseded resolves rather than throws: both callers answer a rejection with a full reload,\n * so surfacing the abort would turn every fast second click into one.\n */\n async function fetchRscPayload(): Promise<boolean> {\n const navigation = ++currentNavigation;\n navigationFetch?.abort();\n const controller = (navigationFetch = new AbortController());\n const superseded = () => navigation !== currentNavigation;\n\n let payload: RscPayload;\n try {\n payload = await requestPayload(window.location.href, controller.signal);\n } catch (error) {\n // Checked before the error is read: an abort is this navigation being replaced, and the one that\n // replaced it owns the outcome.\n if (superseded()) return false;\n if (handleControlDigest(error)) return true;\n throw error;\n }\n if (superseded()) return false;\n if (payload.redirect) {\n push(payload.redirect);\n return true;\n }\n setPayload(payload);\n return true;\n }\n\n function BrowserRoot() {\n const [payload, setPayloadState] = React.useState(initialPayload);\n const [pending, startTransition] = React.useTransition();\n // The scroll a fetched navigation still owes, held until its payload is on screen.\n const pendingScroll = React.useRef<(() => void) | null>(null);\n\n React.useEffect(() => {\n setPayload = (v) => setPayloadState(v);\n startNav = (run) => startTransition(run);\n }, [startTransition]);\n\n /**\n * Scrolls where the navigation asked, once React has put its payload in the DOM — a `#hash` target does\n * not exist until the new tree does. A layout effect, so the pre-scroll position is never painted.\n */\n React.useLayoutEffect(() => {\n const scroll = pendingScroll.current;\n pendingScroll.current = null;\n scroll?.();\n }, [payload]);\n\n React.useEffect(() => {\n const stopNavigating = listenNavigation((afterRender) =>\n startNav(async () => {\n try {\n // Only the navigation that settled the screen owes a scroll — a superseded one would move the\n // page the navigation that replaced it is about to render.\n if (await fetchRscPayload()) pendingScroll.current = afterRender;\n } catch {\n window.location.reload();\n }\n }),\n );\n const stopUpgradingLinks = listenLinks();\n return () => {\n stopUpgradingLinks();\n stopNavigating();\n };\n }, []);\n\n const router = React.useMemo<NavigationRouter>(() => ({ push, replace, back, forward, refresh, pending }), [pending]);\n\n return <RouterContext.Provider value={router}>{payload.root}</RouterContext.Provider>;\n }\n\n setServerCallback(async (id, args) => {\n const temporaryReferences = createTemporaryReferenceSet();\n // The document the action is being called from. Every action response carries a fresh payload for that\n // page, so if a navigation has moved on by the time it arrives the payload describes a page the user has\n // left — the return value is still theirs, but painting it is not. Compared without the fragment, which\n // the server never saw.\n const calledFrom = documentUrl();\n const request = createRscRequest(window.location.href, {\n id,\n body: await encodeReply(args, { temporaryReferences }),\n });\n let payload: RscPayload;\n try {\n payload = await createFromFetch<RscPayload>(fetch(request), { temporaryReferences });\n } catch (error) {\n if (handleControlDigest(error)) return undefined;\n throw error;\n }\n if (payload.redirect) {\n push(payload.redirect);\n return undefined;\n }\n if (documentUrl() === calledFrom) React.startTransition(() => setPayload(payload));\n if (payload.notFound) return undefined;\n const result = payload.returnValue!;\n if (!result.ok) throw result.error;\n return result.value;\n });\n\n // A `redirect()` / `notFound()` from a component below the page root reaches us through React: it rides the\n // flight payload as an error, and boundaries re-throw it so it lands here rather than in a fallback.\n //\n // Installing these hooks opts out of React's own defaults, so everything that isn't a control signal has to\n // be put back by hand — `reportError` rather than a bare log, so error-reporting tools still see it.\n hydrateRoot(document, <BrowserRoot />, {\n formState: initialPayload.formState,\n onCaughtError: (error, errorInfo) => {\n if (handleControlDigest(error, { hard: true })) return;\n // A boundary handled it and the tree is intact, so no overlay over the app's own fallback.\n console.error(error, errorInfo.componentStack ?? '');\n },\n onUncaughtError: (error, errorInfo) => {\n if (handleControlDigest(error, { hard: true })) return;\n // Nothing caught it, so React tears the root down — and the root is `document`.\n globalThis.reportError(error);\n showFatal(error, errorInfo.componentStack);\n },\n });\n\n if (import.meta.webpackHot) {\n initDevRefresh(fetchRscPayload);\n }\n}\n\ntype NavigationType = 'push' | 'replace' | 'pop';\n\n/** Runs teardown in reverse and empties the list, so a second call is a no-op. */\nfunction disposeAll(undo: Array<() => void>): void {\n for (const dispose of undo.splice(0).reverse()) dispose();\n}\n\n// An `<a>` we intercept for soft navigation: same-origin, same tab, not a download,\n// and not explicitly opted out with `data-native` (which forces a full browser navigation).\nfunction isRouterLink(link: HTMLAnchorElement): boolean {\n return (\n !!link.href &&\n (!link.target || link.target === '_self') &&\n link.origin === location.origin &&\n !link.hasAttribute('download') &&\n !link.hasAttribute('data-native')\n );\n}\n\n/**\n * Upgrades the app's anchors: a plain left-click becomes a soft navigation. It shares no state with\n * `listenNavigation` — a click only calls `history.pushState`, which is where that picks the navigation up.\n */\nfunction listenLinks(): () => void {\n const undo: Array<() => void> = [];\n\n function onClick(e: MouseEvent) {\n const link = (e.target as Element).closest('a');\n if (\n link &&\n link instanceof HTMLAnchorElement &&\n isRouterLink(link) &&\n e.button === 0 &&\n !e.metaKey &&\n !e.ctrlKey &&\n !e.altKey &&\n !e.shiftKey &&\n !e.defaultPrevented\n ) {\n if (link.hash && link.pathname === location.pathname && link.search === location.search) return;\n e.preventDefault();\n history.pushState(null, '', link.href);\n }\n }\n document.addEventListener('click', onClick);\n undo.push(() => document.removeEventListener('click', onClick));\n\n return () => disposeAll(undo);\n}\n\n/**\n * The element the current `#fragment` names, if it is on the page. A fragment is percent-encoded and an `id`\n * is not, so it is decoded first — and taken literally when a hand-written `%` makes that throw.\n */\nfunction fragmentTarget(): HTMLElement | null {\n const fragment = location.hash.slice(1);\n if (!fragment) return null;\n let id = fragment;\n try {\n id = decodeURIComponent(fragment);\n } catch {\n // Malformed escape — the literal fragment is the better guess at the id than nothing.\n }\n return document.getElementById(id);\n}\n\nfunction listenNavigation(onNavigation: (afterRender: () => void) => void): () => void {\n const undo: Array<() => void> = [];\n\n // Set explicitly as a statement of intent: the browser remembers a traversal's offset, and nothing here\n // tracks one.\n const prevRestoration = window.history.scrollRestoration;\n try {\n window.history.scrollRestoration = 'auto';\n } catch {\n // Not settable in every browser, and only a preference — the navigation still works without it.\n }\n undo.push(() => {\n try {\n window.history.scrollRestoration = prevRestoration;\n } catch {\n // As above: if it could not be set, it cannot be put back either.\n }\n });\n\n /**\n * A push is not a real navigation to the browser, so nothing resets the scroll offset. A `#hash` names\n * where to land instead; `replace` keeps its position, and a traversal is the browser's to restore.\n *\n * `scrollIntoView` is the algorithm a browser's own fragment jump uses, so `scroll-padding-top` still\n * applies. Neither call passes a `behavior`, leaving `scroll-behavior: smooth` the app's to ask for.\n */\n const afterRenderFor = (type: NavigationType) => () => {\n if (type !== 'push') return;\n const target = fragmentTarget();\n if (target) target.scrollIntoView();\n else window.scrollTo(0, 0);\n };\n\n // What the payload on screen was rendered for. See {@link documentUrl}.\n let renderedUrl = documentUrl();\n\n /**\n * A navigation that moves only the fragment leaves the document unchanged, so the payload on screen is\n * already the right one — fetching another would re-render the page out from under the jump.\n * `router.refresh()` is unaffected, and remains the way to ask for fresh data at an unchanged URL.\n */\n const notify = (type: NavigationType) => {\n const afterRender = afterRenderFor(type);\n if (documentUrl() === renderedUrl) {\n afterRender();\n return;\n }\n renderedUrl = documentUrl();\n onNavigation(afterRender);\n };\n\n const onPopState = () => notify('pop');\n window.addEventListener('popstate', onPopState);\n undo.push(() => window.removeEventListener('popstate', onPopState));\n\n // Saved unbound on purpose, and called back with `.call(this, …)` below — patching `history` is the only\n // way to see a navigation the app makes itself, and the receiver is restored at every call site.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const oldPushState = window.history.pushState;\n window.history.pushState = function (state, unused, url) {\n const res = oldPushState.call(this, state, unused, url as string);\n notify('push');\n return res;\n };\n undo.push(() => {\n window.history.pushState = oldPushState;\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method -- as with `pushState` above.\n const oldReplaceState = window.history.replaceState;\n window.history.replaceState = function (state, unused, url) {\n const res = oldReplaceState.call(this, state, unused, url as string);\n notify('replace');\n return res;\n };\n undo.push(() => {\n window.history.replaceState = oldReplaceState;\n });\n\n return () => disposeAll(undo);\n}\n\n/**\n * Dev-only refresh client, listening to the CLI's SSE endpoint:\n *\n * client-built → hot-apply the waiting updates; anything the page can't be patched up to reloads.\n * rsc-update → server component code changed: re-fetch the flight payload, state preserved.\n * hello → sent on (re)connect with the latest build hash; a mismatch means a missed event.\n */\n// `Promise<unknown>`: the payload fetch reports whether its navigation was superseded, which matters to a\n// click and not to a rebuild — here only settling or rejecting does.\nfunction initDevRefresh(fetchRscPayload: () => Promise<unknown>) {\n const hot = import.meta.webpackHot!;\n let connectedOnce = false;\n /** The newest build the dev server has announced — what {@link applyClientUpdate} walks towards. */\n let targetHash: string | undefined;\n\n function reload(reason: string, error?: unknown): void {\n console.warn(`[rshono] ${reason} — reloading`, ...(error === undefined ? [] : [error]));\n window.location.reload();\n }\n\n async function applyClientUpdate(): Promise<void> {\n const giveUp = await walkHotUpdates(\n hot,\n () => __webpack_hash__,\n () => targetHash,\n );\n if (giveUp) reload(giveUp.reason, giveUp.error);\n }\n\n async function handle(message: DevMessage): Promise<void> {\n switch (message.type) {\n case 'hello':\n targetHash = message.hash ?? targetHash;\n if (connectedOnce) {\n await applyClientUpdate();\n await fetchRscPayload().catch(() => window.location.reload());\n }\n connectedOnce = true;\n break;\n case 'client-built':\n targetHash = message.hash;\n await applyClientUpdate();\n break;\n case 'rsc-update':\n console.log('[rshono] server components updated');\n await fetchRscPayload().catch(() => window.location.reload());\n break;\n }\n }\n\n const source = new EventSource('/_rshono/hmr');\n // Chained rather than handled as they arrive: `hot.check` may only run from `idle`, and a burst of saves\n // puts several frames on the wire inside the time one takes. Queueing drops nothing, because `targetHash`\n // is shared — whichever handler runs next walks to the newest build.\n let queue: Promise<void> = Promise.resolve();\n source.onmessage = (event: MessageEvent<string>) => {\n const message = JSON.parse(event.data) as DevMessage;\n queue = queue.then(() => handle(message)).catch((error) => reload('the dev client failed', error));\n };\n}\n\n// A bootstrap failure — a truncated initial payload, most likely — would otherwise be an unhandled\n// rejection: nothing hydrates, nothing is reported, and the page just sits there.\nmain().catch((error) => {\n console.error('[rshono] the client runtime failed to start:', error);\n showFatal(error);\n});\n"]}
@@ -2,15 +2,17 @@ import { type ReactNode } from 'react';
2
2
  /**
3
3
  * Imperative navigation actions, reached as `useNavigation().router`.
4
4
  *
5
- * `push` / `replace` / `refresh` are **soft** navigations: the new page's flight payload is fetched and
6
- * applied in place, so client component state outside the changed subtree survives. Off-site hrefs fall
7
- * back to a full load.
5
+ * Every action is a **soft** navigation: the page's flight payload is fetched and applied in place, so
6
+ * client component state outside the changed subtree survives. Off-site hrefs — and a traversal that leaves
7
+ * the app — fall back to a full load.
8
8
  *
9
9
  * @example
10
10
  * ```tsx
11
11
  * const { router } = useNavigation();
12
12
  * router.push('/dashboard'); // navigate, new history entry
13
13
  * router.replace('/login'); // navigate, no new entry
14
+ * router.back(); // one entry back, as the browser's button does
15
+ * router.forward(); // one entry forward
14
16
  * router.refresh(); // re-run this route's server components
15
17
  * ```
16
18
  */
@@ -19,6 +21,10 @@ export interface NavigationRouter {
19
21
  push(href: string): void;
20
22
  /** Navigates to `href`, replacing the current history entry instead of adding one. */
21
23
  replace(href: string): void;
24
+ /** Steps one entry back in the browser's session history. Nothing to go back to is a no-op. */
25
+ back(): void;
26
+ /** Steps one entry forward in the browser's session history. A no-op on the newest entry. */
27
+ forward(): void;
22
28
  /** Re-fetches the current route from the server, re-running its server components. */
23
29
  refresh(): void;
24
30
  /** `true` while a soft navigation is in flight — use it to disable controls or show a spinner. */
@@ -80,7 +86,7 @@ export declare function RouterProvider({ href, params, children }: {
80
86
  * ```
81
87
  *
82
88
  * @returns The current {@link NavigationState}: `url` and `params`, plus `router`
83
- * ({@link NavigationRouter}) with `push` / `replace` / `refresh` / `pending`.
89
+ * ({@link NavigationRouter}) with `push` / `replace` / `back` / `forward` / `refresh` / `pending`.
84
90
  * @throws If called outside a page's React tree, where there is no navigation
85
91
  * context to read.
86
92
  *
@@ -1 +1 @@
1
- {"version":3,"file":"navigation.d.ts","sourceRoot":"","sources":["../../src/runtime/navigation.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAsC,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AAE3E;;;;;;;;;;;;;;GAcG;AACH,MAAM,WAAW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AO,IAAI,IAAI,CAAC;IAChB,sFAAsF;IACtF,OAAO,IAAI,IAAI,CAAC;IAChB,kGAAkG;IAClG,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,oGAAoG;AACpG,MAAM,WAAW,eAAe;IAC9B;;;OAGG;IACH,GAAG,EAAE,GAAG,CAAC;IACT,yFAAyF;IACzF,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,4DAA4D;IAC5D,MAAM,EAAE,gBAAgB,CAAC;CAC1B;AAMD;;;;GAIG;AACH,eAAO,MAAM,aAAa,2CAAiD,CAAC;AAI5E;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,QAAQ,EAAE,SAAS,CAAA;CAAE,+BAK/H;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAgB,aAAa,IAAI,eAAe,CAQ/C"}
@@ -2,7 +2,7 @@
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { createContext, useContext, useMemo } from 'react';
4
4
  const noop = () => { };
5
- const defaultRouter = { push: noop, replace: noop, refresh: noop, pending: false };
5
+ const defaultRouter = { push: noop, replace: noop, back: noop, forward: noop, refresh: noop, pending: false };
6
6
  /**
7
7
  * Carries the live {@link NavigationRouter} from the hydration runtime down to {@link RouterProvider}.
8
8
  *
@@ -48,7 +48,7 @@ export function RouterProvider({ href, params, children }) {
48
48
  * ```
49
49
  *
50
50
  * @returns The current {@link NavigationState}: `url` and `params`, plus `router`
51
- * ({@link NavigationRouter}) with `push` / `replace` / `refresh` / `pending`.
51
+ * ({@link NavigationRouter}) with `push` / `replace` / `back` / `forward` / `refresh` / `pending`.
52
52
  * @throws If called outside a page's React tree, where there is no navigation
53
53
  * context to read.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f,CAAC","sourcesContent":["'use client';\n\nimport { createContext, useContext, useMemo, type ReactNode } from 'react';\n\n/**\n * Imperative navigation actions, reached as `useNavigation().router`.\n *\n * `push` / `replace` / `refresh` are **soft** navigations: the new page's flight payload is fetched and\n * applied in place, so client component state outside the changed subtree survives. Off-site hrefs fall\n * back to a full load.\n *\n * @example\n * ```tsx\n * const { router } = useNavigation();\n * router.push('/dashboard'); // navigate, new history entry\n * router.replace('/login'); // navigate, no new entry\n * router.refresh(); // re-run this route's server components\n * ```\n */\nexport interface NavigationRouter {\n /** Navigates to `href` and pushes a new history entry. */\n push(href: string): void;\n /** Navigates to `href`, replacing the current history entry instead of adding one. */\n replace(href: string): void;\n /** Re-fetches the current route from the server, re-running its server components. */\n refresh(): void;\n /** `true` while a soft navigation is in flight — use it to disable controls or show a spinner. */\n pending: boolean;\n}\n\n// No `back()` / `forward()`: `history.back()` needs no framework, and the runtime's `popstate` listener\n// picks the traversal up either way.\n\n/** The current location plus the {@link NavigationRouter}, as returned by {@link useNavigation}. */\nexport interface NavigationState {\n /**\n * The full current {@link URL}. A fresh instance per navigation, so mutating it affects nothing else\n * — it is not written back to the address bar.\n */\n url: URL;\n /** Matched route params for the current page, e.g. `{ id: '42' }` for `/profile/:id`. */\n params: Record<string, string>;\n /** Imperative navigation actions and the `pending` flag. */\n router: NavigationRouter;\n}\n\nconst noop = () => {};\n\nconst defaultRouter: NavigationRouter = { push: noop, replace: noop, refresh: noop, pending: false };\n\n/**\n * Carries the live {@link NavigationRouter} from the hydration runtime down to {@link RouterProvider}.\n *\n * @internal\n */\nexport const RouterContext = createContext<NavigationRouter>(defaultRouter);\n\nconst NavigationContext = createContext<NavigationState | null>(null);\n\n/**\n * Publishes the per-render location and params for {@link useNavigation} to read. The RSC entry wraps\n * every page in one.\n *\n * @internal\n */\nexport function RouterProvider({ href, params, children }: { href: string; params: Record<string, string>; children: ReactNode }) {\n const router = useContext(RouterContext);\n const value = useMemo<NavigationState>(() => ({ url: new URL(href), params, router }), [href, params, router]);\n\n return <NavigationContext.Provider value={value}>{children}</NavigationContext.Provider>;\n}\n\n/**\n * Reactive access to the current URL and programmatic navigation, in one hook. Call it from a\n * `'use client'` component.\n *\n * `url` and `params` are computed on the server and travel in the flight payload, so they are correct\n * during SSR — no hydration flicker — and update on every navigation. `router` holds the imperative\n * actions plus a `pending` flag, `true` while a soft navigation is in flight.\n *\n * Hooks can't run in a server component; read the same data there from `getRequestContext()`.\n *\n * @example\n * ```tsx\n * 'use client';\n * import { useNavigation } from '@rshono/core/client';\n *\n * export function NextPage() {\n * const { url, router } = useNavigation();\n * const page = Number(url.searchParams.get('page') ?? '1');\n * return (\n * <button disabled={router.pending} onClick={() => router.push(`${url.pathname}?page=${page + 1}`)}>\n * Next {router.pending ? '…' : ''}\n * </button>\n * );\n * }\n * ```\n *\n * @returns The current {@link NavigationState}: `url` and `params`, plus `router`\n * ({@link NavigationRouter}) with `push` / `replace` / `refresh` / `pending`.\n * @throws If called outside a page's React tree, where there is no navigation\n * context to read.\n *\n * @see {@link https://www.rshono.com/docs/api#rshonocoreclient | Docs — `@rshono/core/client`}\n * @see {@link https://www.rshono.com/docs/pages#client-components | Docs — client components}\n */\nexport function useNavigation(): NavigationState {\n const value = useContext(NavigationContext);\n if (!value) {\n throw new Error(\n \"[rshono] useNavigation() must be called inside a 'use client' component rendered by a page. In a server component, read the URL from getRequestContext() instead.\",\n );\n }\n return value;\n}\n"]}
1
+ {"version":3,"file":"navigation.js","sourceRoot":"","sources":["../../src/runtime/navigation.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,aAAa,EAAE,UAAU,EAAE,OAAO,EAAkB,MAAM,OAAO,CAAC;AA+C3E,MAAM,IAAI,GAAG,GAAG,EAAE,GAAE,CAAC,CAAC;AAEtB,MAAM,aAAa,GAAqB,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAEhI;;;;GAIG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,aAAa,CAAmB,aAAa,CAAC,CAAC;AAE5E,MAAM,iBAAiB,GAAG,aAAa,CAAyB,IAAI,CAAC,CAAC;AAEtE;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAyE;IAC9H,MAAM,MAAM,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;IACzC,MAAM,KAAK,GAAG,OAAO,CAAkB,GAAG,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,IAAI,GAAG,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAE/G,OAAO,KAAC,iBAAiB,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAA8B,CAAC;AAC3F,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,UAAU,aAAa;IAC3B,MAAM,KAAK,GAAG,UAAU,CAAC,iBAAiB,CAAC,CAAC;IAC5C,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CACb,mKAAmK,CACpK,CAAC;IACJ,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["'use client';\n\nimport { createContext, useContext, useMemo, type ReactNode } from 'react';\n\n/**\n * Imperative navigation actions, reached as `useNavigation().router`.\n *\n * Every action is a **soft** navigation: the page's flight payload is fetched and applied in place, so\n * client component state outside the changed subtree survives. Off-site hrefs — and a traversal that leaves\n * the app — fall back to a full load.\n *\n * @example\n * ```tsx\n * const { router } = useNavigation();\n * router.push('/dashboard'); // navigate, new history entry\n * router.replace('/login'); // navigate, no new entry\n * router.back(); // one entry back, as the browser's button does\n * router.forward(); // one entry forward\n * router.refresh(); // re-run this route's server components\n * ```\n */\nexport interface NavigationRouter {\n /** Navigates to `href` and pushes a new history entry. */\n push(href: string): void;\n /** Navigates to `href`, replacing the current history entry instead of adding one. */\n replace(href: string): void;\n /** Steps one entry back in the browser's session history. Nothing to go back to is a no-op. */\n back(): void;\n /** Steps one entry forward in the browser's session history. A no-op on the newest entry. */\n forward(): void;\n /** Re-fetches the current route from the server, re-running its server components. */\n refresh(): void;\n /** `true` while a soft navigation is in flight — use it to disable controls or show a spinner. */\n pending: boolean;\n}\n\n/** The current location plus the {@link NavigationRouter}, as returned by {@link useNavigation}. */\nexport interface NavigationState {\n /**\n * The full current {@link URL}. A fresh instance per navigation, so mutating it affects nothing else\n * — it is not written back to the address bar.\n */\n url: URL;\n /** Matched route params for the current page, e.g. `{ id: '42' }` for `/profile/:id`. */\n params: Record<string, string>;\n /** Imperative navigation actions and the `pending` flag. */\n router: NavigationRouter;\n}\n\nconst noop = () => {};\n\nconst defaultRouter: NavigationRouter = { push: noop, replace: noop, back: noop, forward: noop, refresh: noop, pending: false };\n\n/**\n * Carries the live {@link NavigationRouter} from the hydration runtime down to {@link RouterProvider}.\n *\n * @internal\n */\nexport const RouterContext = createContext<NavigationRouter>(defaultRouter);\n\nconst NavigationContext = createContext<NavigationState | null>(null);\n\n/**\n * Publishes the per-render location and params for {@link useNavigation} to read. The RSC entry wraps\n * every page in one.\n *\n * @internal\n */\nexport function RouterProvider({ href, params, children }: { href: string; params: Record<string, string>; children: ReactNode }) {\n const router = useContext(RouterContext);\n const value = useMemo<NavigationState>(() => ({ url: new URL(href), params, router }), [href, params, router]);\n\n return <NavigationContext.Provider value={value}>{children}</NavigationContext.Provider>;\n}\n\n/**\n * Reactive access to the current URL and programmatic navigation, in one hook. Call it from a\n * `'use client'` component.\n *\n * `url` and `params` are computed on the server and travel in the flight payload, so they are correct\n * during SSR — no hydration flicker — and update on every navigation. `router` holds the imperative\n * actions plus a `pending` flag, `true` while a soft navigation is in flight.\n *\n * Hooks can't run in a server component; read the same data there from `getRequestContext()`.\n *\n * @example\n * ```tsx\n * 'use client';\n * import { useNavigation } from '@rshono/core/client';\n *\n * export function NextPage() {\n * const { url, router } = useNavigation();\n * const page = Number(url.searchParams.get('page') ?? '1');\n * return (\n * <button disabled={router.pending} onClick={() => router.push(`${url.pathname}?page=${page + 1}`)}>\n * Next {router.pending ? '…' : ''}\n * </button>\n * );\n * }\n * ```\n *\n * @returns The current {@link NavigationState}: `url` and `params`, plus `router`\n * ({@link NavigationRouter}) with `push` / `replace` / `back` / `forward` / `refresh` / `pending`.\n * @throws If called outside a page's React tree, where there is no navigation\n * context to read.\n *\n * @see {@link https://www.rshono.com/docs/api#rshonocoreclient | Docs — `@rshono/core/client`}\n * @see {@link https://www.rshono.com/docs/pages#client-components | Docs — client components}\n */\nexport function useNavigation(): NavigationState {\n const value = useContext(NavigationContext);\n if (!value) {\n throw new Error(\n \"[rshono] useNavigation() must be called inside a 'use client' component rendered by a page. In a server component, read the URL from getRequestContext() instead.\",\n );\n }\n return value;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rshono/core",
3
- "version": "1.0.0-rc.14",
3
+ "version": "1.0.0-rc.16",
4
4
  "description": "Minimalist web framework — Hono + Rspack + React Server Components",
5
5
  "author": "Lasse <lasse@lassetange.com> (https://www.lassetange.com)",
6
6
  "license": "MIT",
@@ -51,18 +51,18 @@
51
51
  "access": "public"
52
52
  },
53
53
  "dependencies": {
54
- "@hono/node-server": "^2.0.11",
54
+ "@hono/node-server": "^2.1.1",
55
55
  "@rspack/core": "2.1.7",
56
56
  "@rspack/plugin-react-refresh": "2.0.2",
57
57
  "react-refresh": "0.18.0",
58
58
  "react-server-dom-rspack": "0.0.3"
59
59
  },
60
60
  "devDependencies": {
61
- "@playwright/test": "^1.58.0",
62
- "@types/node": "^26.1.1",
63
- "@types/react": "^19.2.17",
64
- "@types/react-dom": "^19.2.3",
65
- "hono": "^4.12.31",
61
+ "@playwright/test": "^1.62.1",
62
+ "@types/node": "^26.2.0",
63
+ "@types/react": "^19.2.18",
64
+ "@types/react-dom": "^19.2.4",
65
+ "hono": "^4.13.1",
66
66
  "react": "19.2.8",
67
67
  "react-dom": "19.2.8",
68
68
  "typescript": "^7.0.2"