@rshono/core 1.0.0-rc.13 → 1.0.0-rc.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +29 -8
- package/dist/builder/env-shadow-loader.cjs +20 -1
- package/dist/builder/react-versions.d.ts +13 -0
- package/dist/builder/react-versions.d.ts.map +1 -0
- package/dist/builder/react-versions.js +74 -0
- package/dist/builder/react-versions.js.map +1 -0
- package/dist/builder/rspack-config.d.ts.map +1 -1
- package/dist/builder/rspack-config.js +45 -5
- package/dist/builder/rspack-config.js.map +1 -1
- package/dist/cli/build.d.ts.map +1 -1
- package/dist/cli/build.js +4 -0
- package/dist/cli/build.js.map +1 -1
- package/dist/cli/index.js +2 -1
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/start.d.ts.map +1 -1
- package/dist/cli/start.js +10 -13
- package/dist/cli/start.js.map +1 -1
- package/dist/deploy/cloudflare/runtime.js +1 -1
- package/dist/deploy/cloudflare/runtime.js.map +1 -1
- package/dist/deploy/filesystem.d.ts.map +1 -1
- package/dist/deploy/filesystem.js +8 -0
- package/dist/deploy/filesystem.js.map +1 -1
- package/dist/deploy/presets.d.ts.map +1 -1
- package/dist/deploy/presets.js +24 -0
- package/dist/deploy/presets.js.map +1 -1
- package/dist/deploy/vercel/build.d.ts.map +1 -1
- package/dist/deploy/vercel/build.js +10 -4
- package/dist/deploy/vercel/build.js.map +1 -1
- package/dist/deploy/vercel/runtime.d.ts +1 -1
- package/dist/deploy/vercel/runtime.d.ts.map +1 -1
- package/dist/deploy/vercel/runtime.js +10 -1
- package/dist/deploy/vercel/runtime.js.map +1 -1
- package/dist/runtime/context.d.ts.map +1 -1
- package/dist/runtime/context.js +15 -0
- package/dist/runtime/context.js.map +1 -1
- package/dist/runtime/entry.client.js +55 -11
- package/dist/runtime/entry.client.js.map +1 -1
- package/dist/runtime/entry.rsc.d.ts.map +1 -1
- package/dist/runtime/entry.rsc.js +74 -8
- package/dist/runtime/entry.rsc.js.map +1 -1
- package/dist/runtime/flight-inject.d.ts.map +1 -1
- package/dist/runtime/flight-inject.js +31 -4
- package/dist/runtime/flight-inject.js.map +1 -1
- package/dist/runtime/request.d.ts +12 -4
- package/dist/runtime/request.d.ts.map +1 -1
- package/dist/runtime/request.js +28 -7
- package/dist/runtime/request.js.map +1 -1
- package/dist/server/prerendered.d.ts +11 -3
- package/dist/server/prerendered.d.ts.map +1 -1
- package/dist/server/prerendered.js +31 -5
- package/dist/server/prerendered.js.map +1 -1
- package/dist/server/shutdown.d.ts +4 -1
- package/dist/server/shutdown.d.ts.map +1 -1
- package/dist/server/shutdown.js +4 -1
- package/dist/server/shutdown.js.map +1 -1
- package/dist/server/ssg.js +1 -1
- package/dist/server/ssg.js.map +1 -1
- package/package.json +2 -2
package/dist/cli/start.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start.js","sourceRoot":"","sources":["../../src/cli/start.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"start.js","sourceRoot":"","sources":["../../src/cli/start.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAQrD,MAAM,CAAC,KAAK,UAAU,YAAY,CAAC,OAAqB;IACtD,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;IACxC,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;IACtC,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC;IACrD,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC1B,OAAO,CAAC,KAAK,CAAC,+DAA+D,CAAC,CAAC;QAC/E,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IAED,4GAA4G;IAC5G,yCAAyC;IACzC,MAAM,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;IACxC,IAAI,MAAM,KAAK,IAAI,IAAI,MAAM,KAAK,MAAM,EAAE,CAAC;QACzC,MAAM,IAAI,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;QACnC,OAAO,CAAC,KAAK,CAAC,8BAA8B,MAAM,sCAAsC,IAAI,CAAC,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;QACrH,OAAO,CAAC,KAAK,CAAC,0EAA0E,CAAC,CAAC;QAC1F,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IAED,mGAAmG;IACnG,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,CAAC,GAAG,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IACxD,IAAI,IAAI,KAAK,SAAS;QAAE,OAAO,CAAC,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC;IAEhD,mGAAmG;IACnG,wGAAwG;IACxG,2GAA2G;IAC3G,2GAA2G;IAC3G,mGAAmG;IACnG,MAAM,MAAM,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { readBuildMarker } from '../deploy/build-marker.js';\nimport { deployHintFor } from '../deploy/presets.js';\n\ninterface StartOptions {\n rootDir: string;\n port?: number;\n host?: string;\n}\n\nexport async function startCommand(options: StartOptions): Promise<void> {\n const { rootDir, port, host } = options;\n const distDir = join(rootDir, 'dist');\n const mainPath = join(distDir, 'server', 'main.mjs');\n if (!existsSync(mainPath)) {\n console.error('rshono: no production build found — run `rshono build` first.');\n process.exit(1);\n }\n\n // A bundle built for a hosting platform has no listener in it, so starting one here would exit silently the\n // moment the module finished evaluating.\n const target = readBuildMarker(distDir);\n if (target !== null && target !== 'node') {\n const hint = deployHintFor(target);\n console.error(`rshono: this build targets ${target}, which \\`rshono start\\` cannot run${hint ? ` — ${hint}` : '.'}`);\n console.error(' Rebuild for a server with `rshono build --deploy node` to run it here.');\n process.exit(1);\n }\n\n // Read by the bundle as it evaluates, which is what binds the port — so they have to be set first.\n if (port !== undefined) process.env.PORT = String(port);\n if (host !== undefined) process.env.HOST = host;\n\n // Imported into this process rather than spawned into a child. The child only ever existed to pass\n // `--enable-source-maps`, and `bin/rshono.mjs` already enables the same thing in-process before the CLI\n // loads — so a supervisor bought a second PID and its own heap in every container, an extra frame in every\n // stack, and signal forwarding for signals the bundle already handles itself through `onShutdown`. `start`\n // deliberately imports no Rspack, so the process this leaves behind is the server and little else.\n await import(pathToFileURL(mainPath).href);\n}\n"]}
|
|
@@ -3,7 +3,7 @@ import { createPageCache, prerenderedRelPath, toPrerenderedPage } from '../../se
|
|
|
3
3
|
* Where `finalize` puts the prerendered pages inside the assets directory.
|
|
4
4
|
*
|
|
5
5
|
* A prefix of its own, rather than the pages' real URLs, is what keeps every page URL reaching the worker: one
|
|
6
|
-
* URL answers with a document or a flight payload
|
|
6
|
+
* URL answers with a document or a flight payload on the `RSC` request header, and a path-keyed CDN cannot make that
|
|
7
7
|
* choice. The tree is reachable here too, so `finalize` marks it `noindex` rather than leaving a crawler to
|
|
8
8
|
* find the same page twice.
|
|
9
9
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/deploy/cloudflare/runtime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,iBAAiB,EAAwB,MAAM,6BAA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QAClC,IAAI,MAAM;YAAE,OAAO,MAAM,CAAC;QAE1B,MAAM,KAAK,GAAG,MAAM,aAAa,CAAC,CAAC,EAAE,GAAG,UAAU,IAAI,OAAO,EAAE,CAAC,CAAC;QACjE,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,MAAM,KAAK,GAAG;YAAE,OAAO,IAAI,CAAC;QAEhD,uFAAuF;QACvF,MAAM,IAAI,GAAG,MAAM,iBAAiB,CAAC,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,WAAW,EAAE,CAAC,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;QAC3G,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,uGAAuG;QACvG,kBAAkB;IACpB,CAAC;CACF,CAAC","sourcesContent":["import type { Context, Hono } from 'hono';\nimport { createPageCache, prerenderedRelPath, toPrerenderedPage, type PrerenderedPage } from '../../server/prerendered.js';\nimport type { DeployRuntime } from '../contract.js';\n\n/**\n * Where `finalize` puts the prerendered pages inside the assets directory.\n *\n * A prefix of its own, rather than the pages' real URLs, is what keeps every page URL reaching the worker: one\n * URL answers with a document or a flight payload
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../src/deploy/cloudflare/runtime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,kBAAkB,EAAE,iBAAiB,EAAwB,MAAM,6BAA6B,CAAC;AAG3H;;;;;;;GAOG;AACH,MAAM,UAAU,GAAG,QAAQ,CAAC;AAO5B,SAAS,aAAa,CAAC,CAAU;IAC/B,MAAM,OAAO,GAAI,CAAC,CAAC,GAA8C,EAAE,MAAM,CAAC;IAC1E,OAAO,OAAO,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,UAAU,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;AACzE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AC,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,WAAW,EAAE,CAAC,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;QAC3G,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO;QACL,uGAAuG;QACvG,kBAAkB;IACpB,CAAC;CACF,CAAC","sourcesContent":["import type { Context, Hono } from 'hono';\nimport { createPageCache, prerenderedRelPath, toPrerenderedPage, type PrerenderedPage } from '../../server/prerendered.js';\nimport type { DeployRuntime } from '../contract.js';\n\n/**\n * Where `finalize` puts the prerendered pages inside the assets directory.\n *\n * A prefix of its own, rather than the pages' real URLs, is what keeps every page URL reaching the worker: one\n * URL answers with a document or a flight payload on the `RSC` request header, and a path-keyed CDN cannot make that\n * choice. The tree is reachable here too, so `finalize` marks it `noindex` rather than leaving a crawler to\n * find the same page twice.\n */\nconst SSG_PREFIX = '/__ssg';\n\n/** The Workers Assets binding, as much of it as this file uses. */\ninterface AssetsBinding {\n fetch(request: Request): Promise<Response>;\n}\n\nfunction assetsBinding(c: Context): AssetsBinding | null {\n const binding = (c.env as { ASSETS?: AssetsBinding } | undefined)?.ASSETS;\n return binding && typeof binding.fetch === 'function' ? binding : null;\n}\n\n/**\n * Asks the assets binding for one path, or `null` when there is no binding — which is how a caller tells \"this\n * deployment serves its assets some other way\" from \"that file is not there\".\n *\n * `headers` is forwarded only where the *client's* conditional and range requests should be answered by the\n * store: an `If-None-Match` on a page being fetched to serve would come back 304 with no body.\n */\nasync function assetResponse(c: Context, path: string, headers?: Headers): Promise<Response | null> {\n const binding = assetsBinding(c);\n if (!binding) return null;\n // Resolved against the request so the lookup carries this deployment's own origin; only the path is used.\n const url = new URL(path, c.req.url);\n return binding.fetch(new Request(url, { method: 'GET', headers }));\n}\n\n/**\n * Hands an asset response back as the app's own. Rebuilt rather than returned as-is, because a `Response` from\n * `fetch` has immutable headers and the framework's outermost middleware writes to them on the way out.\n */\nfunction serveAsset(asset: Response): Response {\n return new Response(asset.body, asset);\n}\n\n/** Prerendered pages, keyed by the path that produced them. Per isolate rather than per process. */\nconst pageCache = createPageCache();\n\n/**\n * Cloudflare Workers: the host owns the process, so there is nothing to listen on, and there is no filesystem,\n * so `.env` files are out. What is left is the assets binding, which every read here goes through.\n */\nexport const runtime: DeployRuntime = {\n serveApp(app: Hono): unknown {\n // `app.fetch` already takes `(request, env, ctx)`, which is why bindings arrive as `c.env`.\n return { fetch: app.fetch };\n },\n\n mountStaticAssets(app: Hono): void {\n // Normally dead — the CDN answers `/_static/*` before the worker is invoked — but keeps the deployment\n // correct, if slower, under an assets configuration that routes everything to the worker first.\n app.on(['GET', 'HEAD'], '/_static/*', async (c, next) => {\n const asset = await assetResponse(c, c.req.path, c.req.raw.headers);\n return asset && asset.status !== 404 ? serveAsset(asset) : next();\n });\n },\n\n mountPublicFallback(app: Hono): void {\n app.on(['GET', 'HEAD'], '/*', async (c, next) => {\n // The prerender tree lives in the same store, but the app only serves it through `readPrerendered`.\n if (c.req.path.startsWith(`${SSG_PREFIX}/`)) return next();\n const asset = await assetResponse(c, c.req.path, c.req.raw.headers);\n return asset && asset.status !== 404 ? serveAsset(asset) : next();\n });\n },\n\n async readPrerendered(c: Context, variant): Promise<PrerenderedPage | null> {\n const relPath = prerenderedRelPath(c.req.path, variant);\n if (relPath === null) return null;\n\n const key = `${variant}\\0${relPath}`;\n const cached = pageCache.get(key);\n if (cached) return cached;\n\n const asset = await assetResponse(c, `${SSG_PREFIX}/${relPath}`);\n if (!asset || asset.status !== 200) return null;\n\n // The store's own validator where it has one — it already describes these exact bytes.\n const page = await toPrerenderedPage(new Uint8Array(await asset.arrayBuffer()), asset.headers.get('etag'));\n pageCache.set(key, page);\n return page;\n },\n\n loadEnv(): void {\n // Nothing to load: secrets and bindings arrive per request as `c.env`, which `getRequestContext().env`\n // already merges.\n },\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"filesystem.d.ts","sourceRoot":"","sources":["../../src/deploy/filesystem.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"filesystem.d.ts","sourceRoot":"","sources":["../../src/deploy/filesystem.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AA4BnD;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,EAAE,IAAI,CAAC,aAAa,EAAE,UAAU,CAiB7D,CAAC"}
|
|
@@ -4,6 +4,14 @@ import { loadEnvFiles } from '../server/load-env.js';
|
|
|
4
4
|
import { readPrerendered } from '../server/ssg.js';
|
|
5
5
|
import { createPublicFallback, createStaticAssetsApp } from '../server/static.js';
|
|
6
6
|
const { isDev, outDir } = __RSHONO_CONFIG__;
|
|
7
|
+
// The server bundle is minified and ships a source map, so this is what makes a production stack trace point
|
|
8
|
+
// at the original TypeScript. Done here rather than left to `--enable-source-maps` because a serverless host
|
|
9
|
+
// starts the process itself and passes no flags of ours: Vercel and Lambda would otherwise report minified
|
|
10
|
+
// frames to whatever `onServerError` forwards them to. Guarded because the same `DeployRuntime` shape is
|
|
11
|
+
// implemented for runtimes with no `process`.
|
|
12
|
+
if (typeof process !== 'undefined' && typeof process.setSourceMapsEnabled === 'function') {
|
|
13
|
+
process.setSourceMapsEnabled(true);
|
|
14
|
+
}
|
|
7
15
|
/**
|
|
8
16
|
* The project root, derived from where the bundle ended up: this module is compiled into
|
|
9
17
|
* `<root>/<outDir>/server/main.mjs`, which is why every output directory sits one level under the root.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"filesystem.js","sourceRoot":"","sources":["../../src/deploy/filesystem.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;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C,IAAI,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;IAED,OAAO;QACL,YAAY,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;CACF,CAAC","sourcesContent":["import type { Hono } from 'hono';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { loadEnvFiles } from '../server/load-env.js';\nimport { readPrerendered } from '../server/ssg.js';\nimport { createPublicFallback, createStaticAssetsApp } from '../server/static.js';\nimport type { DeployRuntime } from './contract.js';\n\nconst { isDev, outDir } = __RSHONO_CONFIG__;\n\n/**\n * The project root, derived from where the bundle ended up: this module is compiled into\n * `<root>/<outDir>/server/main.mjs`, which is why every output directory sits one level under the root.\n *\n * Derived rather than baked in, because an absolute build-time path would tie the output to the machine that\n * produced it — building in CI to run elsewhere is the normal case. A preset that relocates the bundle keeps\n * `dist/server/main.mjs` intact inside its own layout for this reason.\n */\nconst rootDir = join(import.meta.dirname, '..', '..');\n\nconst staticDir = join(rootDir, outDir, 'static');\nconst ssgDir = join(rootDir, outDir, 'ssg');\n/** `public/` is copied into the build output, so a deployed build is self-contained; dev reads the source. */\nconst publicDir = isDev ? join(rootDir, 'public') : join(rootDir, outDir, 'public');\n\n/**\n * Everything a deploy target with a real filesystem does the same way. Node and the serverless runtimes that\n * unpack onto a read-only disk (Vercel, AWS Lambda) differ only in how the app is handed over, so each of\n * those presets is this object plus its own {@link DeployRuntime.serveApp}.\n */\nexport const fileSystemRuntime: Omit<DeployRuntime, 'serveApp'> = {\n mountStaticAssets(app: Hono): void {\n app.route('/_static', createStaticAssetsApp({ root: staticDir, isDev }));\n },\n\n mountPublicFallback(app: Hono): void {\n if (!existsSync(publicDir)) return;\n app.on(['GET', 'HEAD'], '/*', createPublicFallback({ root: publicDir, isDev }));\n },\n\n readPrerendered(c, variant) {\n return readPrerendered(ssgDir, c.req.path, variant);\n },\n\n loadEnv(): void {\n loadEnvFiles(rootDir);\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"filesystem.js","sourceRoot":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AC,CAAC,CAAC;IAC3E,CAAC;IAED,mBAAmB,CAAC,GAAS;QAC3B,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC;YAAE,OAAO;QACnC,GAAG,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,IAAI,EAAE,oBAAoB,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;IAClF,CAAC;IAED,eAAe,CAAC,CAAC,EAAE,OAAO;QACxB,OAAO,eAAe,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACtD,CAAC;IAED,OAAO;QACL,YAAY,CAAC,OAAO,CAAC,CAAC;IACxB,CAAC;CACF,CAAC","sourcesContent":["import type { Hono } from 'hono';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { loadEnvFiles } from '../server/load-env.js';\nimport { readPrerendered } from '../server/ssg.js';\nimport { createPublicFallback, createStaticAssetsApp } from '../server/static.js';\nimport type { DeployRuntime } from './contract.js';\n\nconst { isDev, outDir } = __RSHONO_CONFIG__;\n\n// The server bundle is minified and ships a source map, so this is what makes a production stack trace point\n// at the original TypeScript. Done here rather than left to `--enable-source-maps` because a serverless host\n// starts the process itself and passes no flags of ours: Vercel and Lambda would otherwise report minified\n// frames to whatever `onServerError` forwards them to. Guarded because the same `DeployRuntime` shape is\n// implemented for runtimes with no `process`.\nif (typeof process !== 'undefined' && typeof process.setSourceMapsEnabled === 'function') {\n process.setSourceMapsEnabled(true);\n}\n\n/**\n * The project root, derived from where the bundle ended up: this module is compiled into\n * `<root>/<outDir>/server/main.mjs`, which is why every output directory sits one level under the root.\n *\n * Derived rather than baked in, because an absolute build-time path would tie the output to the machine that\n * produced it — building in CI to run elsewhere is the normal case. A preset that relocates the bundle keeps\n * `dist/server/main.mjs` intact inside its own layout for this reason.\n */\nconst rootDir = join(import.meta.dirname, '..', '..');\n\nconst staticDir = join(rootDir, outDir, 'static');\nconst ssgDir = join(rootDir, outDir, 'ssg');\n/** `public/` is copied into the build output, so a deployed build is self-contained; dev reads the source. */\nconst publicDir = isDev ? join(rootDir, 'public') : join(rootDir, outDir, 'public');\n\n/**\n * Everything a deploy target with a real filesystem does the same way. Node and the serverless runtimes that\n * unpack onto a read-only disk (Vercel, AWS Lambda) differ only in how the app is handed over, so each of\n * those presets is this object plus its own {@link DeployRuntime.serveApp}.\n */\nexport const fileSystemRuntime: Omit<DeployRuntime, 'serveApp'> = {\n mountStaticAssets(app: Hono): void {\n app.route('/_static', createStaticAssetsApp({ root: staticDir, isDev }));\n },\n\n mountPublicFallback(app: Hono): void {\n if (!existsSync(publicDir)) return;\n app.on(['GET', 'HEAD'], '/*', createPublicFallback({ root: publicDir, isDev }));\n },\n\n readPrerendered(c, variant) {\n return readPrerendered(ssgDir, c.req.path, variant);\n },\n\n loadEnv(): void {\n loadEnvFiles(rootDir);\n },\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"presets.d.ts","sourceRoot":"","sources":["../../src/deploy/presets.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAElD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAGlD,6FAA6F;AAC7F,MAAM,WAAW,kBAAkB;IACjC,uGAAuG;IACvG,OAAO,EAAE,MAAM,CAAC;IAChB,qBAAqB;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,6EAA6E;IAC7E,SAAS,EAAE,MAAM,CAAC;IAClB,2FAA2F;IAC3F,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,kGAAkG;IAClG,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;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qF;IACrF,QAAQ,CAAC,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3C;;;OAGG;IACH,eAAe,CAAC,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI,CAAC;IAC9C;;;OAGG;IACH,QAAQ,CAAC,CAAC,GAAG,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;CAC1D;AAED;;;GAGG;AACH,eAAO,MAAM,WAAW,EAAE,YAIzB,CAAC;AAiFF,kEAAkE;AAClE,eAAO,MAAM,cAAc,EAA2B,YAAY,EAAE,CAAC;AAErE;;;GAGG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAE3D;AAED,+DAA+D;AAC/D,MAAM,WAAW,aAAa;IAC5B,2BAA2B;IAC3B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,mGAAmG;IACnG,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,gDAAgD;IAChD,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,aAAkB,GAAG,YAAY,CAS7E"}
|
package/dist/deploy/presets.js
CHANGED
|
@@ -31,27 +31,51 @@ const CLOUDFLARE_PRESET = {
|
|
|
31
31
|
},
|
|
32
32
|
finalize: finalizeCloudflareBuild,
|
|
33
33
|
};
|
|
34
|
+
/**
|
|
35
|
+
* Bundles the app's dependencies into the server output instead of importing them from `node_modules`.
|
|
36
|
+
*
|
|
37
|
+
* The generated config externalizes them, which is right where the bundle runs *inside* the project — but a
|
|
38
|
+
* serverless function is uploaded as a directory rather than installed into one, so nothing resolves
|
|
39
|
+
* `node_modules` at request time and an externalized `import 'some-package'` is a cold start that dies on
|
|
40
|
+
* `ERR_MODULE_NOT_FOUND`. Node's own builtins stay external either way, through the `node` externals preset
|
|
41
|
+
* that `target: 'node'` already enables.
|
|
42
|
+
*
|
|
43
|
+
* The cost is a dependency that cannot be bundled — a native addon, or one that reads its own files off disk
|
|
44
|
+
* relative to `__dirname`. Those now fail the build rather than the deploy, which is the same constraint
|
|
45
|
+
* `cloudflare` has always had; the `rspack` hook in `rshono.config.ts` is the way out.
|
|
46
|
+
*/
|
|
47
|
+
function bundleDependencies(config) {
|
|
48
|
+
config.externals = [];
|
|
49
|
+
}
|
|
34
50
|
/**
|
|
35
51
|
* Vercel: one Node function behind the platform's CDN, which serves the assets and reaches the function only
|
|
36
52
|
* for a page. `finalize` assembles the Build Output API layout the platform uploads — including the
|
|
37
53
|
* `supportsResponseStreaming` flag, without which Vercel buffers the whole response and silently undoes
|
|
38
54
|
* streamed SSR.
|
|
55
|
+
*
|
|
56
|
+
* Only `dist/server` is uploaded with the function, which is why dependencies are bundled: see
|
|
57
|
+
* {@link bundleDependencies}.
|
|
39
58
|
*/
|
|
40
59
|
const VERCEL_PRESET = {
|
|
41
60
|
name: 'vercel',
|
|
42
61
|
runtimeModule: 'deploy/vercel/runtime.js',
|
|
43
62
|
deployHint: 'deploy with `vercel deploy --prebuilt`',
|
|
63
|
+
configureServer: bundleDependencies,
|
|
44
64
|
finalize: finalizeVercelBuild,
|
|
45
65
|
};
|
|
46
66
|
/**
|
|
47
67
|
* AWS Lambda behind a Function URL in `RESPONSE_STREAM` mode — the AWS shape that keeps streaming. The
|
|
48
68
|
* runtime wraps the app in `awslambda.streamifyResponse`; the buffered alternative would deploy fine and then
|
|
49
69
|
* hold every page until its last byte rendered.
|
|
70
|
+
*
|
|
71
|
+
* The deployment package is `dist/` and nothing else, which is why dependencies are bundled: see
|
|
72
|
+
* {@link bundleDependencies}.
|
|
50
73
|
*/
|
|
51
74
|
const AWS_LAMBDA_PRESET = {
|
|
52
75
|
name: 'aws-lambda',
|
|
53
76
|
runtimeModule: 'deploy/aws-lambda/runtime.js',
|
|
54
77
|
deployHint: 'zip dist/ with the handler at dist/server/main.mjs',
|
|
78
|
+
configureServer: bundleDependencies,
|
|
55
79
|
};
|
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,IAAI,EAAE,WAAW;IACjB,UAAU,EAAE,iBAAiB;IAC7B,MAAM,EAAE,aAAa;IACrB,YAAY,EAAE,iBAAiB;CAChC,CAAC;AAEF,kEAAkE;AAClE,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAmB,CAAC;AAErE;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,MAAc;IAC1C,OAAQ,OAAoD,CAAC,MAAM,CAAC,EAAE,UAAU,IAAI,IAAI,CAAC;AAC3F,CAAC;AAYD;;;;GAIG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAO,GAAkB,EAAE;IAC7D,MAAM,MAAM,GAAG,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,OAAO,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,OAAO,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC;IACrF,IAAI,CAAC,MAAM;QAAE,OAAO,WAAW,CAAC;IAEhC,MAAM,MAAM,GAAI,OAAoD,CAAC,MAAM,CAAC,CAAC;IAC7E,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,kCAAkC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,uBAAuB,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC/H,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { RspackOptions } from '@rspack/core';\nimport { finalizeCloudflareBuild } from './cloudflare/build.js';\nimport type { DeployTarget } from './contract.js';\nimport { finalizeVercelBuild } from './vercel/build.js';\n\n/** What a preset's {@link DeployPreset.finalize} is told about the build it is arranging. */\nexport interface DeployBuildContext {\n /** The project root — where `rshono build` ran, and what a platform config file is written next to. */\n rootDir: string;\n /** `<root>/dist`. */\n distDir: string;\n /** The hashed client bundle, `<root>/dist/static` — served at `/_static`. */\n staticDir: string;\n /** The copy of the app's `public/`, or `null` when it has none. Served at the web root. */\n publicDir: string | null;\n /** Prerendered pages, `<root>/dist/ssg` — empty when the app has no `render: 'static'` routes. */\n ssgDir: string;\n}\n\n/**\n * The build-time half of a deploy target: which runtime module the bundle gets, how the server compiler has\n * to change to produce something the platform can run, and how the output is arranged once it exists.\n *\n * The runtime half is `DeployRuntime`, in its own file because it is compiled *into* the app bundle — this\n * side only ever runs in the CLI.\n */\nexport interface DeployPreset {\n readonly name: DeployTarget;\n /**\n * The module `@rshono/deploy` resolves to, as a path relative to the framework's own `dist/`.\n * Slash-separated and split on use, so it stays a valid path on Windows too.\n */\n readonly runtimeModule: string;\n /** How to run what was just built, completing the \"build complete —\" line. */\n readonly deployHint: string;\n /**\n * Extra resolve conditions for the server bundle, most specific first — what picks the right build of React\n * and the RSC runtime, both of which ship one per runtime. Omit to accept whatever the Rspack target\n * implies, which is correct for Node.\n */\n readonly resolveConditions?: readonly string[];\n /** browserslist-style targets for the server bundle's swc pass. Defaults to Node. */\n readonly syntaxTargets?: readonly string[];\n /**\n * Adjusts the generated server Rspack config for this platform — target, externals policy, output shape.\n * Mutates in place, and runs before the user's `rspack` hook so that hook keeps the last word.\n */\n configureServer?(config: RspackOptions): void;\n /**\n * Arranges the finished build for the platform: assembles the directory layout it expects, emits its config\n * file, and prints how to deploy. Runs last, so everything it needs to move is already on disk.\n */\n finalize?(ctx: DeployBuildContext): Promise<void> | void;\n}\n\n/**\n * Node: a long-lived server process. The generated config is already this shape — `target: 'node'`, the\n * externals policy and ESM chunk output are all defaults — so the preset has nothing to contribute.\n */\nexport const NODE_PRESET: DeployPreset = {\n name: 'node',\n runtimeModule: 'deploy/node/runtime.js',\n deployHint: 'run `rshono start`',\n};\n\n/**\n * Cloudflare Workers: the host owns the process, the CDN owns the assets, and there is no filesystem.\n *\n * Every setting here follows from `workerd` not being Node. Dependencies are bundled because nothing resolves\n * `node_modules` at runtime; `node:` and `cloudflare:` imports stay external because the runtime provides\n * them under `nodejs_compat`; and async chunks are inlined because Wrangler's bundler cannot follow the\n * computed specifier Rspack's ESM chunk loader emits — a split bundle deploys and then fails on first render.\n */\nconst CLOUDFLARE_PRESET: DeployPreset = {\n name: 'cloudflare',\n runtimeModule: 'deploy/cloudflare/runtime.js',\n deployHint: 'deploy with `wrangler deploy`',\n resolveConditions: ['workerd'],\n syntaxTargets: ['chrome 120'],\n configureServer(config) {\n config.target = 'webworker';\n config.externalsType = 'module-import';\n config.externals = [/^(?:node|cloudflare):/];\n config.output = { ...config.output, asyncChunks: false };\n },\n finalize: finalizeCloudflareBuild,\n};\n\n/**\n * Vercel: one Node function behind the platform's CDN, which serves the assets and reaches the function only\n * for a page. `finalize` assembles the Build Output API layout the platform uploads — including the\n * `supportsResponseStreaming` flag, without which Vercel buffers the whole response and silently undoes\n * streamed SSR.\n */\nconst VERCEL_PRESET: DeployPreset = {\n name: 'vercel',\n runtimeModule: 'deploy/vercel/runtime.js',\n deployHint: 'deploy with `vercel deploy --prebuilt`',\n finalize: finalizeVercelBuild,\n};\n\n/**\n * AWS Lambda behind a Function URL in `RESPONSE_STREAM` mode — the AWS shape that keeps streaming. The\n * runtime wraps the app in `awslambda.streamifyResponse`; the buffered alternative would deploy fine and then\n * hold every page until its last byte rendered.\n */\nconst AWS_LAMBDA_PRESET: DeployPreset = {\n name: 'aws-lambda',\n runtimeModule: 'deploy/aws-lambda/runtime.js',\n deployHint: 'zip dist/ with the handler at dist/server/main.mjs',\n};\n\nconst PRESETS: Record<DeployTarget, DeployPreset> = {\n node: NODE_PRESET,\n cloudflare: CLOUDFLARE_PRESET,\n vercel: VERCEL_PRESET,\n 'aws-lambda': AWS_LAMBDA_PRESET,\n};\n\n/** Every target `deploy` accepts, for error messages and docs. */\nexport const DEPLOY_TARGETS = Object.keys(PRESETS) as DeployTarget[];\n\n/**\n * How to deploy what a given target built, or `null` for a name this rshono does not know — which a `dist/`\n * from a newer version can legitimately carry.\n */\nexport function deployHintFor(target: string): string | null {\n return (PRESETS as Record<string, DeployPreset | undefined>)[target]?.deployHint ?? null;\n}\n\n/** Where a deploy target can be named, in precedence order. */\nexport interface DeploySources {\n /** The `--deploy` flag. */\n flag?: string;\n /** The `RSHONO_DEPLOY` env var — for a CI job that deploys the same app to more than one place. */\n env?: string;\n /** The `deploy` field in `rshono.config.ts`. */\n config?: string;\n}\n\n/**\n * Resolves the preset to build with: the flag wins over the environment, which wins over the config file,\n * which wins over the `node` default. Blank values are ignored at every level, so an unset-but-present\n * `RSHONO_DEPLOY=` in CI falls through rather than failing the build.\n */\nexport function resolveDeployPreset(sources: DeploySources = {}): DeployPreset {\n const target = sources.flag?.trim() || sources.env?.trim() || sources.config?.trim();\n if (!target) return NODE_PRESET;\n\n const preset = (PRESETS as Record<string, DeployPreset | undefined>)[target];\n if (!preset) {\n throw new Error(`[rshono] unknown deploy target ${JSON.stringify(target)} — expected one of: ${DEPLOY_TARGETS.join(', ')}.`);\n }\n return preset;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"presets.js","sourceRoot":"","sources":["../../src/deploy/presets.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAEhE,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAoDxD;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAiB;IACvC,IAAI,EAAE,MAAM;IACZ,aAAa,EAAE,wBAAwB;IACvC,UAAU,EAAE,oBAAoB;CACjC,CAAC;AAEF;;;;;;;GAOG;AACH,MAAM,iBAAiB,GAAiB;IACtC,IAAI,EAAE,YAAY;IAClB,aAAa,EAAE,8BAA8B;IAC7C,UAAU,EAAE,+BAA+B;IAC3C,iBAAiB,EAAE,CAAC,SAAS,CAAC;IAC9B,aAAa,EAAE,CAAC,YAAY,CAAC;IAC7B,eAAe,CAAC,MAAM;QACpB,MAAM,CAAC,MAAM,GAAG,WAAW,CAAC;QAC5B,MAAM,CAAC,aAAa,GAAG,eAAe,CAAC;QACvC,MAAM,CAAC,SAAS,GAAG,CAAC,uBAAu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M;QAAE,OAAO,WAAW,CAAC;IAEhC,MAAM,MAAM,GAAI,OAAoD,CAAC,MAAM,CAAC,CAAC;IAC7E,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,IAAI,KAAK,CAAC,kCAAkC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,uBAAuB,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC/H,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type { RspackOptions } from '@rspack/core';\nimport { finalizeCloudflareBuild } from './cloudflare/build.js';\nimport type { DeployTarget } from './contract.js';\nimport { finalizeVercelBuild } from './vercel/build.js';\n\n/** What a preset's {@link DeployPreset.finalize} is told about the build it is arranging. */\nexport interface DeployBuildContext {\n /** The project root — where `rshono build` ran, and what a platform config file is written next to. */\n rootDir: string;\n /** `<root>/dist`. */\n distDir: string;\n /** The hashed client bundle, `<root>/dist/static` — served at `/_static`. */\n staticDir: string;\n /** The copy of the app's `public/`, or `null` when it has none. Served at the web root. */\n publicDir: string | null;\n /** Prerendered pages, `<root>/dist/ssg` — empty when the app has no `render: 'static'` routes. */\n ssgDir: string;\n}\n\n/**\n * The build-time half of a deploy target: which runtime module the bundle gets, how the server compiler has\n * to change to produce something the platform can run, and how the output is arranged once it exists.\n *\n * The runtime half is `DeployRuntime`, in its own file because it is compiled *into* the app bundle — this\n * side only ever runs in the CLI.\n */\nexport interface DeployPreset {\n readonly name: DeployTarget;\n /**\n * The module `@rshono/deploy` resolves to, as a path relative to the framework's own `dist/`.\n * Slash-separated and split on use, so it stays a valid path on Windows too.\n */\n readonly runtimeModule: string;\n /** How to run what was just built, completing the \"build complete —\" line. */\n readonly deployHint: string;\n /**\n * Extra resolve conditions for the server bundle, most specific first — what picks the right build of React\n * and the RSC runtime, both of which ship one per runtime. Omit to accept whatever the Rspack target\n * implies, which is correct for Node.\n */\n readonly resolveConditions?: readonly string[];\n /** browserslist-style targets for the server bundle's swc pass. Defaults to Node. */\n readonly syntaxTargets?: readonly string[];\n /**\n * Adjusts the generated server Rspack config for this platform — target, externals policy, output shape.\n * Mutates in place, and runs before the user's `rspack` hook so that hook keeps the last word.\n */\n configureServer?(config: RspackOptions): void;\n /**\n * Arranges the finished build for the platform: assembles the directory layout it expects, emits its config\n * file, and prints how to deploy. Runs last, so everything it needs to move is already on disk.\n */\n finalize?(ctx: DeployBuildContext): Promise<void> | void;\n}\n\n/**\n * Node: a long-lived server process. The generated config is already this shape — `target: 'node'`, the\n * externals policy and ESM chunk output are all defaults — so the preset has nothing to contribute.\n */\nexport const NODE_PRESET: DeployPreset = {\n name: 'node',\n runtimeModule: 'deploy/node/runtime.js',\n deployHint: 'run `rshono start`',\n};\n\n/**\n * Cloudflare Workers: the host owns the process, the CDN owns the assets, and there is no filesystem.\n *\n * Every setting here follows from `workerd` not being Node. Dependencies are bundled because nothing resolves\n * `node_modules` at runtime; `node:` and `cloudflare:` imports stay external because the runtime provides\n * them under `nodejs_compat`; and async chunks are inlined because Wrangler's bundler cannot follow the\n * computed specifier Rspack's ESM chunk loader emits — a split bundle deploys and then fails on first render.\n */\nconst CLOUDFLARE_PRESET: DeployPreset = {\n name: 'cloudflare',\n runtimeModule: 'deploy/cloudflare/runtime.js',\n deployHint: 'deploy with `wrangler deploy`',\n resolveConditions: ['workerd'],\n syntaxTargets: ['chrome 120'],\n configureServer(config) {\n config.target = 'webworker';\n config.externalsType = 'module-import';\n config.externals = [/^(?:node|cloudflare):/];\n config.output = { ...config.output, asyncChunks: false };\n },\n finalize: finalizeCloudflareBuild,\n};\n\n/**\n * Bundles the app's dependencies into the server output instead of importing them from `node_modules`.\n *\n * The generated config externalizes them, which is right where the bundle runs *inside* the project — but a\n * serverless function is uploaded as a directory rather than installed into one, so nothing resolves\n * `node_modules` at request time and an externalized `import 'some-package'` is a cold start that dies on\n * `ERR_MODULE_NOT_FOUND`. Node's own builtins stay external either way, through the `node` externals preset\n * that `target: 'node'` already enables.\n *\n * The cost is a dependency that cannot be bundled — a native addon, or one that reads its own files off disk\n * relative to `__dirname`. Those now fail the build rather than the deploy, which is the same constraint\n * `cloudflare` has always had; the `rspack` hook in `rshono.config.ts` is the way out.\n */\nfunction bundleDependencies(config: RspackOptions): void {\n config.externals = [];\n}\n\n/**\n * Vercel: one Node function behind the platform's CDN, which serves the assets and reaches the function only\n * for a page. `finalize` assembles the Build Output API layout the platform uploads — including the\n * `supportsResponseStreaming` flag, without which Vercel buffers the whole response and silently undoes\n * streamed SSR.\n *\n * Only `dist/server` is uploaded with the function, which is why dependencies are bundled: see\n * {@link bundleDependencies}.\n */\nconst VERCEL_PRESET: DeployPreset = {\n name: 'vercel',\n runtimeModule: 'deploy/vercel/runtime.js',\n deployHint: 'deploy with `vercel deploy --prebuilt`',\n configureServer: bundleDependencies,\n finalize: finalizeVercelBuild,\n};\n\n/**\n * AWS Lambda behind a Function URL in `RESPONSE_STREAM` mode — the AWS shape that keeps streaming. The\n * runtime wraps the app in `awslambda.streamifyResponse`; the buffered alternative would deploy fine and then\n * hold every page until its last byte rendered.\n *\n * The deployment package is `dist/` and nothing else, which is why dependencies are bundled: see\n * {@link bundleDependencies}.\n */\nconst AWS_LAMBDA_PRESET: DeployPreset = {\n name: 'aws-lambda',\n runtimeModule: 'deploy/aws-lambda/runtime.js',\n deployHint: 'zip dist/ with the handler at dist/server/main.mjs',\n configureServer: bundleDependencies,\n};\n\nconst PRESETS: Record<DeployTarget, DeployPreset> = {\n node: NODE_PRESET,\n cloudflare: CLOUDFLARE_PRESET,\n vercel: VERCEL_PRESET,\n 'aws-lambda': AWS_LAMBDA_PRESET,\n};\n\n/** Every target `deploy` accepts, for error messages and docs. */\nexport const DEPLOY_TARGETS = Object.keys(PRESETS) as DeployTarget[];\n\n/**\n * How to deploy what a given target built, or `null` for a name this rshono does not know — which a `dist/`\n * from a newer version can legitimately carry.\n */\nexport function deployHintFor(target: string): string | null {\n return (PRESETS as Record<string, DeployPreset | undefined>)[target]?.deployHint ?? null;\n}\n\n/** Where a deploy target can be named, in precedence order. */\nexport interface DeploySources {\n /** The `--deploy` flag. */\n flag?: string;\n /** The `RSHONO_DEPLOY` env var — for a CI job that deploys the same app to more than one place. */\n env?: string;\n /** The `deploy` field in `rshono.config.ts`. */\n config?: string;\n}\n\n/**\n * Resolves the preset to build with: the flag wins over the environment, which wins over the config file,\n * which wins over the `node` default. Blank values are ignored at every level, so an unset-but-present\n * `RSHONO_DEPLOY=` in CI falls through rather than failing the build.\n */\nexport function resolveDeployPreset(sources: DeploySources = {}): DeployPreset {\n const target = sources.flag?.trim() || sources.env?.trim() || sources.config?.trim();\n if (!target) return NODE_PRESET;\n\n const preset = (PRESETS as Record<string, DeployPreset | undefined>)[target];\n if (!preset) {\n throw new Error(`[rshono] unknown deploy target ${JSON.stringify(target)} — expected one of: ${DEPLOY_TARGETS.join(', ')}.`);\n }\n return preset;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../../src/deploy/vercel/build.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AA0BxD,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../../src/deploy/vercel/build.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AA0BxD,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CA4ChF"}
|
|
@@ -34,14 +34,20 @@ export async function finalizeVercelBuild(ctx) {
|
|
|
34
34
|
cpSync(ctx.staticDir, join(staticOut, '_static'), { recursive: true });
|
|
35
35
|
if (ctx.publicDir)
|
|
36
36
|
cpSync(ctx.publicDir, staticOut, { recursive: true });
|
|
37
|
-
// Shipped inside the function: the bundle,
|
|
37
|
+
// Shipped inside the function: the bundle, and the one thing it reads from disk at request time.
|
|
38
|
+
//
|
|
39
|
+
// `public/` is deliberately *not* among them, though it is on the filesystem targets. It went into the
|
|
40
|
+
// static output above, and `{ handle: 'filesystem' }` sits ahead of the catch-all route, so the platform
|
|
41
|
+
// answers those paths before the function is invoked — a copy here is bytes uploaded and unpacked on every
|
|
42
|
+
// cold start that nothing can ever read. `vercel/runtime.ts` turns the matching mount off to say so.
|
|
38
43
|
cpSync(join(ctx.distDir, 'server'), join(functionDir, 'dist', 'server'), { recursive: true });
|
|
39
44
|
if (existsSync(ctx.ssgDir))
|
|
40
45
|
cpSync(ctx.ssgDir, join(functionDir, 'dist', 'ssg'), { recursive: true });
|
|
41
|
-
if (ctx.publicDir)
|
|
42
|
-
cpSync(ctx.publicDir, join(functionDir, 'dist', 'public'), { recursive: true });
|
|
43
46
|
writeFileSync(join(functionDir, '.vc-config.json'), `${JSON.stringify({
|
|
44
|
-
runtime
|
|
47
|
+
// The Node the build ran on, so the function runs the runtime the app was tested against — and so
|
|
48
|
+
// this does not become a hard-coded version the platform retires on a date the framework does not
|
|
49
|
+
// control. A major Vercel does not offer is an explicit error from the deploy rather than a mismatch.
|
|
50
|
+
runtime: `nodejs${process.versions.node.split('.')[0]}.x`,
|
|
45
51
|
handler: HANDLER,
|
|
46
52
|
launcherType: 'Nodejs',
|
|
47
53
|
// Without this the platform buffers the whole response, undoing streamed SSR.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","sourceRoot":"","sources":["../../../src/deploy/vercel/build.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACvE,OAAO,EAAE,EAAE,EAAE,MAAM,kBAAkB,CAAC;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC;;;GAGG;AACH,MAAM,UAAU,GAAG,IAAI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EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;IAE9G,OAAO,CAAC,GAAG,CAAC,iBAAiB,UAAU,wBAAwB,CAAC,CAAC;AACnE,CAAC","sourcesContent":["import { cpSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { DeployBuildContext } from '../presets.js';\n\n/**\n * The Build Output API v3 layout, which `vercel deploy --prebuilt` uploads verbatim — producing it directly\n * means Vercel runs no build of its own.\n */\nconst OUTPUT_DIR = join('.vercel', 'output');\nconst FUNCTION_DIR = join('functions', 'index.func');\n\n/**\n * The bundle keeps this exact path inside the function because the runtime derives the project root from where\n * it sits (see `deploy/filesystem.ts`), so `dist/ssg` and `dist/public` land where it already looks — and no\n * runtime code needs to know it is on Vercel.\n */\nconst HANDLER = 'dist/server/main.mjs';\n\n/**\n * Routes, in the order Vercel evaluates them: hashed assets get the immutable header the CDN cannot infer,\n * then anything in the static output is served from it, and whatever is left is the app's to render.\n */\nconst ROUTES = [\n { src: '^/_static/(.*)$', headers: { 'cache-control': 'public, max-age=31536000, immutable' }, continue: true },\n { handle: 'filesystem' },\n { src: '/(.*)', dest: '/index' },\n];\n\nexport async function finalizeVercelBuild(ctx: DeployBuildContext): Promise<void> {\n const outputDir = join(ctx.rootDir, OUTPUT_DIR);\n const staticOut = join(outputDir, 'static');\n const functionDir = join(outputDir, FUNCTION_DIR);\n\n // From scratch, so a deleted page or asset cannot survive in the uploaded output.\n await rm(outputDir, { recursive: true, force: true });\n mkdirSync(staticOut, { recursive: true });\n mkdirSync(functionDir, { recursive: true });\n\n // Served by the CDN: the hashed bundle under its public path, and `public/` at the web root.\n cpSync(ctx.staticDir, join(staticOut, '_static'), { recursive: true });\n if (ctx.publicDir) cpSync(ctx.publicDir, staticOut, { recursive: true });\n\n // Shipped inside the function: the bundle, and the one thing it reads from disk at request time.\n //\n // `public/` is deliberately *not* among them, though it is on the filesystem targets. It went into the\n // static output above, and `{ handle: 'filesystem' }` sits ahead of the catch-all route, so the platform\n // answers those paths before the function is invoked — a copy here is bytes uploaded and unpacked on every\n // cold start that nothing can ever read. `vercel/runtime.ts` turns the matching mount off to say so.\n cpSync(join(ctx.distDir, 'server'), join(functionDir, 'dist', 'server'), { recursive: true });\n if (existsSync(ctx.ssgDir)) cpSync(ctx.ssgDir, join(functionDir, 'dist', 'ssg'), { recursive: true });\n\n writeFileSync(\n join(functionDir, '.vc-config.json'),\n `${JSON.stringify(\n {\n // The Node the build ran on, so the function runs the runtime the app was tested against — and so\n // this does not become a hard-coded version the platform retires on a date the framework does not\n // control. A major Vercel does not offer is an explicit error from the deploy rather than a mismatch.\n runtime: `nodejs${process.versions.node.split('.')[0]}.x`,\n handler: HANDLER,\n launcherType: 'Nodejs',\n // Without this the platform buffers the whole response, undoing streamed SSR.\n supportsResponseStreaming: true,\n },\n null,\n 2,\n )}\\n`,\n );\n\n writeFileSync(join(outputDir, 'config.json'), `${JSON.stringify({ version: 3, routes: ROUTES }, null, 2)}\\n`);\n\n console.log(` • assembled ${OUTPUT_DIR} (Build Output API v3)`);\n}\n"]}
|
|
@@ -4,7 +4,7 @@ import type { DeployRuntime } from '../contract.js';
|
|
|
4
4
|
*
|
|
5
5
|
* `/_static` and `public/` are in the static output, and `config.json` puts the filesystem handler ahead of the
|
|
6
6
|
* function, so mounting them here would be dead weight. Prerendered pages are *not* static output — one URL
|
|
7
|
-
* answers with a document or a flight payload
|
|
7
|
+
* answers with a document or a flight payload on the `RSC` request header, and a path-keyed CDN cannot choose — so
|
|
8
8
|
* they ship inside the function and are read from its read-only disk, exactly as on a server.
|
|
9
9
|
*/
|
|
10
10
|
export declare const runtime: DeployRuntime;
|
|
@@ -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,
|
|
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"}
|
|
@@ -5,7 +5,7 @@ import { fileSystemRuntime } from '../filesystem.js';
|
|
|
5
5
|
*
|
|
6
6
|
* `/_static` and `public/` are in the static output, and `config.json` puts the filesystem handler ahead of the
|
|
7
7
|
* function, so mounting them here would be dead weight. Prerendered pages are *not* static output — one URL
|
|
8
|
-
* answers with a document or a flight payload
|
|
8
|
+
* answers with a document or a flight payload on the `RSC` request header, and a path-keyed CDN cannot choose — so
|
|
9
9
|
* they ship inside the function and are read from its read-only disk, exactly as on a server.
|
|
10
10
|
*/
|
|
11
11
|
export const runtime = {
|
|
@@ -13,6 +13,15 @@ export const runtime = {
|
|
|
13
13
|
mountStaticAssets() {
|
|
14
14
|
// Served from `.vercel/output/static` before the function runs.
|
|
15
15
|
},
|
|
16
|
+
mountPublicFallback() {
|
|
17
|
+
// As above: `public/` is in the static output and `{ handle: 'filesystem' }` is matched ahead of this
|
|
18
|
+
// function, so nothing here could ever answer for one of those paths. Stated as an override rather than
|
|
19
|
+
// left to fall out of `dist/public` not being uploaded, because that would make the behaviour incidental
|
|
20
|
+
// to a `cpSync` in `build.ts` instead of a decision.
|
|
21
|
+
//
|
|
22
|
+
// The one thing this hands to the platform: resolving a directory to its `index.html`. Vercel's static
|
|
23
|
+
// handler does that; `serveStatic`, which the filesystem targets use, is no longer in the path.
|
|
24
|
+
},
|
|
16
25
|
serveApp(app) {
|
|
17
26
|
return handle(app);
|
|
18
27
|
},
|
|
@@ -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,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
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/runtime/context.ts"],"names":[],"mappings":"AAIA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,MAAM,CAAC;AAEzC,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAIvD;;;;;;;;;GASG;AACH,MAAM,MAAM,cAAc,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;AAWzD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,GAAG,IAAI,CAEhD;AAkCD;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAE5D;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC,MA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AAO,EAAE,OAAO,EAAE,kBAAkB,KAAK,IAAI,CAAC;AAavF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAE/D;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,kBAAkB,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CActG"}
|
package/dist/runtime/context.js
CHANGED
|
@@ -462,6 +462,14 @@ export function notFound() {
|
|
|
462
462
|
throw new NotFoundSignal();
|
|
463
463
|
}
|
|
464
464
|
let errorHandler;
|
|
465
|
+
/**
|
|
466
|
+
* Errors already forwarded, so one fault is reported once however many stages it crosses.
|
|
467
|
+
*
|
|
468
|
+
* A thrown server action is reported where it is known to be an action and then re-thrown, which lands it in
|
|
469
|
+
* the top-level handler as well — and a funnel that counts the same error twice, under two different
|
|
470
|
+
* `source`s, is worse than one that only ever names the outer stage.
|
|
471
|
+
*/
|
|
472
|
+
const alreadyReported = new WeakSet();
|
|
465
473
|
/**
|
|
466
474
|
* Registers a handler for every error the framework catches, so they can reach an error tracker
|
|
467
475
|
* (Sentry, Datadog, a log pipeline) instead of only `stderr`.
|
|
@@ -493,6 +501,13 @@ export function onServerError(handler) {
|
|
|
493
501
|
* @internal
|
|
494
502
|
*/
|
|
495
503
|
export function reportServerError(error, info) {
|
|
504
|
+
// The first stage to recognise it wins, since that is the one that knows what it was. A primitive throw
|
|
505
|
+
// cannot be tracked and is reported wherever it is caught.
|
|
506
|
+
if (typeof error === 'object' && error !== null) {
|
|
507
|
+
if (alreadyReported.has(error))
|
|
508
|
+
return;
|
|
509
|
+
alreadyReported.add(error);
|
|
510
|
+
}
|
|
496
511
|
console.error(info.message, error);
|
|
497
512
|
if (!errorHandler)
|
|
498
513
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","sourceRoot":"","sources":["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,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;IACtE,CAAC;IAAC,OAAO,YAAY,EAAE,CAAC;QACtB,OAAO,CAAC,KAAK,CAAC,2CAA2C,EAAE,YAAY,CAAC,CAAC;IAC3E,CAAC;AACH,CAAC","sourcesContent":["// `__RSHONO_CONFIG__` is a global const, and an `import` cannot bring one into scope — a path reference is\n// the only way to reach it, which is the whole reason that file is separate. See its header.\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"../types/rshono-config.d.ts\" />\n/**\n * The request context: {@link getRequestContext} and the {@link RequestContext} it returns, the\n * {@link redirect} / {@link notFound} control-flow helpers, and the {@link onServerError} reporting\n * funnel — plus the `@internal` plumbing that binds a request to the async context.\n *\n * The public half is re-exported by `runtime/server.ts`, which is what `@rshono/core/server` resolves\n * to; an app imports that.\n */\n\nimport type { Context, Env } from 'hono';\nimport { deleteCookie, getCookie, setCookie } from 'hono/cookie';\nimport type { CookieOptions } from 'hono/utils/cookie';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { NotFoundSignal, RedirectSignal } from './control.js';\n\n/**\n * HTTP status codes accepted by {@link redirect}.\n *\n * - `301` Moved Permanently, `308` Permanent Redirect — cacheable, permanent.\n * - `302` Found, `307` Temporary Redirect — temporary.\n * - `303` See Other — the default; forces a `GET` on the target, which is what you almost always want\n * after a form action (post/redirect/get).\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status#redirection_messages | MDN — redirection status codes}\n */\nexport type RedirectStatus = 301 | 302 | 303 | 307 | 308;\n\nconst contextStorage = new AsyncLocalStorage<Context>();\n\n/** One {@link RequestContext} per Hono {@link Context}, so repeated `getRequestContext()` calls share its lazy getters. */\nconst wrappers = new WeakMap<Context, RequestContext>();\n\n// Keyed on the Hono context rather than held as a field, so marking a request never forces the lazily\n// built `RequestContext` wrapper into existence.\nconst rendering = new WeakSet<Context>();\n\n/**\n * Marks the request as having entered its page render, which is what makes\n * {@link RequestContext.setHeader} and `ctx.cookies.set()` start throwing.\n *\n * @internal\n */\nexport function beginPageRender(c: Context): void {\n rendering.add(c);\n}\n\n/** The shared refusal for a response write that arrived too late — the message names where it belongs instead. */\nfunction tooLateToWrite(call: string): never {\n throw new Error(\n `[rshono] ${call} was called while rendering a page, which is too late to affect the response. ` +\n 'A page streams, so its response head is already committed by the time the component runs — the ' +\n 'write would land on a full page load and be silently dropped on a soft navigation. Do it from a ' +\n \"'use server' action instead; or, in middleware and { type: 'endpoint' } routes — which are handed \" +\n \"Hono's `c` directly and run outside the request context — with `c.header(…)` / `setCookie(c, …)`.\",\n );\n}\n\n/** The shared refusal for a Hono `Context` member a page has no way to use. See the stubs on {@link RequestContext}. */\nfunction notOnContext(call: string, instead: string): never {\n throw new Error(\n `[rshono] ctx.${call} does not exist. A page returns JSX and the framework builds the response from it, ` +\n `so Hono's response builders have nothing to return to. ${instead}`,\n );\n}\n\n// Snapshotted rather than spread per request: enumerating `process.env` crosses into the host\n// environment (~20µs). Lazily, because `loadEnvFiles()` runs after this module is imported — so a\n// mutation after the first `ctx.env` read is not picked up.\nlet envSnapshot: Record<string, string | undefined> | undefined;\n\nfunction processEnv(): Record<string, string | undefined> {\n return (envSnapshot ??= typeof process !== 'undefined' && process.env ? { ...process.env } : {});\n}\n\n// Set by `build.ts` before it imports the app bundle, which inlines its own copy of this module — so\n// `process.env` is what crosses that boundary rather than a module-level flag.\nconst prerendering = typeof process !== 'undefined' && !!process.env?.RSHONO_PRERENDER;\n\n/**\n * Runs `fn` with `c` bound as the ambient request context, so {@link getRequestContext} resolves to it\n * anywhere in the call tree.\n *\n * @internal\n */\nexport function runWithContext<T>(c: Context, fn: () => T): T {\n return contextStorage.run(c, fn);\n}\n\n/**\n * The matched route params, or an empty object when there is no active match.\n *\n * @internal\n */\nexport function readParams(c: Context): Record<string, string> {\n try {\n return c.req.param();\n } catch {\n return {};\n }\n}\n\n/** A proxy chain appends to these headers, so the client-facing value is the first entry. */\nfunction firstForwardedValue(header: string | undefined): string | undefined {\n const first = header?.split(',')[0]?.trim();\n return first || undefined;\n}\n\n// Read through `typeof`: DefinePlugin inlines this into the server bundle, but the module is also the\n// public `@rshono/core/server` entry, which tooling can load without one. Absent means don't trust.\nconst trustProxy = typeof __RSHONO_CONFIG__ !== 'undefined' && __RSHONO_CONFIG__.trustProxy;\n\n/**\n * The browser-facing {@link URL} for a request, resolved from Hono's {@link Context} — a fresh\n * instance per call.\n *\n * `c.req.url` is the internal address the server was reached on, which is wrong behind a proxy;\n * `X-Forwarded-Host` / `-Proto` correct it, but only when `trustProxy` is enabled in\n * `rshono.config.ts` — they are client-supplied, so trusting them unconditionally would let anyone\n * dictate the origin of every absolute URL the app builds.\n *\n * This is the form for **middleware**, which is handed `c` and runs outside the request context — and\n * so the way to give Hono's own middleware the origin the browser actually used. In a server component\n * or action, prefer {@link RequestContext.url}, the same value cached per request.\n *\n * @param c - The Hono {@link Context} for the request.\n * @returns The browser-facing URL — proxy-corrected under `trustProxy`, `c.req.url` otherwise.\n *\n * @example\n * ```ts\n * // src/server.ts — a CSRF check that still works behind a proxy that rewrites Host\n * import { publicUrl } from '@rshono/core/server';\n * import { csrf } from 'hono/csrf';\n *\n * server.use(csrf({ origin: (origin, c) => origin === publicUrl(c).origin }));\n * ```\n *\n * @see {@link https://www.rshono.com/docs/configuration#proxy-headers | Docs — proxy headers}\n */\nexport function publicUrl(c: Context): URL {\n const url = new URL(c.req.url);\n if (!trustProxy) return url;\n\n const forwardedHost = firstForwardedValue(c.req.header('x-forwarded-host'));\n // Parsed, not assigned to `url.host`: that setter keeps the existing port when the new value has none.\n const forwarded = forwardedHost ? URL.parse(`http://${forwardedHost}`) : null;\n if (forwarded) {\n url.hostname = forwarded.hostname;\n url.port = forwarded.port;\n }\n\n // Only the two schemes a browser could have requested; anything else leaves the scheme alone.\n const forwardedProto = firstForwardedValue(c.req.header('x-forwarded-proto'));\n if (forwardedProto === 'http' || forwardedProto === 'https') url.protocol = forwardedProto;\n\n return url;\n}\n\n/**\n * The environment available to a request: Workers `Bindings` merged with process env vars. Values not\n * declared in `Bindings` are typed as `string | undefined`. See {@link RequestContext.env}.\n *\n * @see {@link https://hono.dev/docs/getting-started/cloudflare-workers#bindings | Hono — bindings}\n */\nexport type EnvVars<E extends Env> = E['Bindings'] & Record<string, string | undefined>;\n\n/**\n * Read-mostly wrapper around Hono's {@link Context}, for server components and server actions.\n *\n * Obtain one with {@link getRequestContext}, or take it off a page's `ctx` prop — the same object.\n * Never construct it yourself. One instance is reused for the whole request, so its lazy getters\n * ({@link RequestContext.url}, {@link RequestContext.env}) are computed at most once.\n *\n * @typeParam E - The Hono {@link Env} describing this app's `Bindings` and `Variables`, so\n * {@link RequestContext.var} and {@link RequestContext.env} stay typed.\n *\n * @example\n * ```tsx\n * import { getRequestContext } from '@rshono/core/server';\n *\n * export default async function Whoami() {\n * const ctx = getRequestContext();\n * const session = ctx.cookies.get('session');\n * return <p>{ctx.url.pathname} — {session ?? 'anonymous'}</p>;\n * }\n * ```\n *\n * @see {@link https://www.rshono.com/docs/api#rshonocoreserver | Docs — `@rshono/core/server`}\n * @see {@link https://hono.dev/docs/api/context | Hono — Context}, reachable in full via {@link RequestContext.hono}\n */\nexport class RequestContext<E extends Env = Env> {\n #raw: Context<E>;\n #url?: URL;\n #env?: EnvVars<E>;\n #params?: Record<string, string>;\n\n /**\n * One instance is created per request and handed out by {@link getRequestContext} or the `ctx` page\n * prop. Application code never calls this.\n *\n * @internal\n */\n constructor(c: Context<E>) {\n this.#raw = c;\n }\n\n /**\n * The underlying Hono {@link Context} — the escape hatch for what this wrapper does not expose, such\n * as `executionCtx.waitUntil()` on Workers.\n *\n * Its response builders (`redirect`, `json`, `body`, `status`, …) still do nothing from inside a\n * page: reaching them through here bypasses the errors the stubs on this class throw, it does not\n * make them work.\n *\n * @example\n * ```ts\n * getRequestContext().hono.executionCtx.waitUntil(logAsync()); // Workers\n * ```\n *\n * @see {@link https://hono.dev/docs/api/context | Hono — Context}\n */\n // Every member here is a getter or method so that none is *own enumerable*: React's \"you cannot pass\n // this to a client component\" diagnostic walks `Object.keys` recursively with no cycle guard, and the\n // Hono context graph reaches the socket through `req.raw`. `cookies` is the one own property, and it\n // is a shallow object of four functions.\n get hono(): Context<E> {\n return this.#raw;\n }\n\n /**\n * The parsed request — method, headers, path params, query and the body readers. Hono's\n * {@link Context.req}, unwrapped, so `ctx.req.header('authorization')` rather than\n * `ctx.hono.req.header(…)`.\n *\n * Reads only; setting a *response* header is {@link RequestContext.setHeader}, deliberately spelled\n * differently.\n *\n * @example\n * ```ts\n * const ctx = getRequestContext();\n * ctx.req.method; // 'GET'\n * ctx.req.header('authorization'); // string | undefined\n * ctx.req.query('tab'); // string | undefined\n * ```\n *\n * @see {@link https://hono.dev/docs/api/request | Hono — HonoRequest}\n */\n get req(): Context<E>['req'] {\n return this.#raw.req;\n }\n\n /**\n * Matched route params for this request, e.g. `{ id: '42' }` for `/profile/:id`. Empty when no route\n * matched.\n *\n * A page is handed the same record as its `params` prop, typed key-by-key from its route path, and\n * that is the better read where it exists. This is for everywhere else — a nested server component,\n * or a `'use server'` action.\n */\n get params(): Record<string, string> {\n return (this.#params ??= readParams(this.#raw as Context));\n }\n\n /**\n * The browser-facing request URL. Parsed once and cached, so every read within a request returns the\n * same instance — treat it as read-only.\n *\n * `X-Forwarded-Host` / `-Proto` are honoured only when `trustProxy` is enabled in\n * `rshono.config.ts`, since any client can send them.\n *\n * @example `const tab = getRequestContext().url.searchParams.get('tab');`\n *\n * @see {@link https://www.rshono.com/docs/configuration#proxy-headers | Docs — proxy headers}\n */\n get url(): URL {\n return (this.#url ??= publicUrl(this.#raw as Context));\n }\n\n /**\n * Typed variables set by middleware via `c.set('user', …)`, read here as `ctx.var.user`. Type them by\n * parameterising this class's {@link Env}.\n *\n * @example\n * ```ts\n * type AppEnv = { Variables: { user: { id: string } } };\n * const { user } = getRequestContext<AppEnv>().var; // typed, set by your middleware\n * ```\n *\n * @see {@link https://hono.dev/docs/api/context#var | Hono — c.var}\n * @see {@link https://www.rshono.com/docs/hono#typing-the-context | Docs — typing the context}\n */\n get var(): Readonly<E['Variables']> {\n return this.#raw.var;\n }\n\n /**\n * Environment for the request: process env vars merged with runtime bindings, which win on conflict.\n * Computed once and cached.\n *\n * @example `const key = getRequestContext().env.STRIPE_SECRET_KEY;`\n *\n * @see {@link https://hono.dev/docs/api/context#env | Hono — c.env}\n * @see {@link https://www.rshono.com/docs/configuration#environment-and-secrets | Docs — environment and secrets}\n */\n get env(): EnvVars<E> {\n if (this.#env) return this.#env;\n const bindings = this.#raw.env as Record<string, unknown> | undefined;\n return (this.#env = (bindings ? { ...processEnv(), ...bindings } : processEnv()) as EnvVars<E>);\n }\n\n /**\n * Read and write request/response cookies.\n *\n * @example\n * ```ts\n * const ctx = getRequestContext();\n * ctx.cookies.get('session'); // string | undefined\n * ctx.cookies.set('session', id, { httpOnly: true, sameSite: 'Lax', path: '/' });\n * ctx.cookies.delete('session', { path: '/' });\n * ```\n *\n * @see {@link https://hono.dev/docs/helpers/cookie | Hono — cookie helper}, which this wraps\n */\n cookies = {\n /** Reads a single cookie by name, or `undefined` if absent. Safe anywhere, a page included. */\n get: (name: string): string | undefined => getCookie(this.#raw, name),\n /** Reads every cookie as a `{ name: value }` record. Safe anywhere, a page included. */\n all: (): Record<string, string> => getCookie(this.#raw),\n /**\n * Sets a cookie on the response. See Hono's {@link CookieOptions} for `path`, `httpOnly`, `maxAge`\n * and the rest.\n *\n * **Throws inside a page render** — a `Set-Cookie` is a special case of\n * {@link RequestContext.setHeader}. Set cookies from a `'use server'` action, or with Hono's\n * `setCookie(c, …)` in middleware and endpoint routes.\n *\n * @throws If called while a page is rendering, where it could not reach the browser reliably.\n *\n * @see {@link https://hono.dev/docs/helpers/cookie#options | Hono — cookie options}\n */\n set: (name: string, value: string, options?: CookieOptions): void => {\n this.#assertWritable('ctx.cookies.set()');\n setCookie(this.#raw, name, value, options);\n },\n /**\n * Clears a cookie. Pass the same `path`/`domain` it was set with so the browser matches it.\n * Throws inside a page render, exactly as `set` does.\n *\n * @throws If called while a page is rendering.\n */\n delete: (name: string, options?: CookieOptions): void => {\n this.#assertWritable('ctx.cookies.delete()');\n deleteCookie(this.#raw, name, options);\n },\n };\n\n #assertWritable(call: string): void {\n if (rendering.has(this.#raw as Context)) tooLateToWrite(call);\n }\n\n /**\n * Sets a header on the response — from a `'use server'` action, which is the one place a request\n * context exists *and* the response is still open.\n *\n * From inside a page it throws: a page streams, so its response head is already committed by then,\n * and the write would land on a full page load but vanish on a soft navigation.\n *\n * Middleware and `{ type: 'endpoint' }` routes are handed Hono's `c` directly and use `c.header(…)`.\n * That is also where a header belonging to the *page* goes — `Cache-Control`, `X-Robots-Tag` — since\n * middleware runs before the render.\n *\n * @param name - Header name, case-insensitive.\n * @param value - Header value.\n * @param options - `{ append: true }` to add another value rather than replace.\n * @throws If called while a page is rendering, where it could not reach the browser reliably.\n *\n * @example\n * ```ts\n * 'use server';\n * export async function logout() {\n * const ctx = getRequestContext();\n * ctx.cookies.delete('session', { path: '/' });\n * ctx.setHeader('clear-site-data', '\"cache\", \"storage\"');\n * redirect('/');\n * }\n * ```\n */\n setHeader(name: string, value: string, options?: { append?: boolean }): void {\n this.#assertWritable('ctx.setHeader()');\n this.#raw.header(name, value, options);\n }\n\n // Hono's response builders, restated as errors naming what to use instead — through `ctx.hono` every\n // one of them is a silent no-op from a page. `@deprecated` strikes them through in autocomplete; the\n // unread `..._args` is so `ctx.redirect('/x')` reaches the thrown message rather than an arity error.\n\n /** @deprecated Not available on a page's context — use `redirect()` from `@rshono/core/server`. */\n redirect(..._args: unknown[]): never {\n return notOnContext(\n 'redirect(location, status?)',\n \"Use `redirect()` from '@rshono/core/server', which throws a signal the framework turns into a real redirect.\",\n );\n }\n\n /** @deprecated Not available on a page's context — use `notFound()` from `@rshono/core/server`. */\n notFound(..._args: unknown[]): never {\n return notOnContext('notFound()', \"Use `notFound()` from '@rshono/core/server', which aborts the render and shows the app's not-found page.\");\n }\n\n /** @deprecated A page renders JSX. For a JSON response, use an `{ type: 'endpoint' }` route. */\n json(..._args: unknown[]): never {\n return notOnContext('json(object)', \"For a JSON response use an { type: 'endpoint' } route; to read the request body use `ctx.req.json()`.\");\n }\n\n /** @deprecated A page renders JSX. For a text response, use an `{ type: 'endpoint' }` route. */\n text(..._args: unknown[]): never {\n return notOnContext('text(string)', \"For a text response use an { type: 'endpoint' } route; to read the request body use `ctx.req.text()`.\");\n }\n\n /** @deprecated A page renders JSX, which the framework turns into HTML for you. */\n html(..._args: unknown[]): never {\n return notOnContext('html(string)', \"A page's JSX is already its HTML; for a hand-built HTML response use an { type: 'endpoint' } route.\");\n }\n\n /** @deprecated Not available on a page's context. To read the request body, use `ctx.req`. */\n body(..._args: unknown[]): never {\n return notOnContext(\n 'body(data, …)',\n \"To read the *request* body use `ctx.req.json()` / `ctx.req.text()` / `ctx.req.formData()`; to build a response, use an { type: 'endpoint' } route.\",\n );\n }\n\n /** @deprecated A page's status is set by the framework — use `notFound()`, or an endpoint route. */\n status(..._args: unknown[]): never {\n return notOnContext(\n 'status(code)',\n \"A page's status is the framework's: 200, 404 via `notFound()`, 500 when it throws. For any other code use an { type: 'endpoint' } route.\",\n );\n }\n\n /** @deprecated Renamed — use `ctx.setHeader(name, value)`, which is valid from a `'use server'` action. */\n header(..._args: unknown[]): never {\n return notOnContext(\n 'header(name, value)',\n \"Use `ctx.setHeader(name, value)` from a 'use server' action, or `c.header(…)` in middleware — a page renders too late to set one.\",\n );\n }\n}\n\n/**\n * The {@link RequestContext} for the current request — URL, cookies, params, env and middleware\n * variables — read from a server component or a server action. Memoised per request, so repeated calls\n * return the same instance.\n *\n * A page is handed that same object as its `ctx` prop, so this import is for everywhere else: a nested\n * server component, or a `'use server'` action module.\n *\n * @typeParam E - The app's Hono {@link Env}, to type {@link RequestContext.var} and {@link RequestContext.env}.\n * @throws If called at module load, where there is no ambient context to resolve.\n * @throws If called while prerendering a `render: 'static'` route, which has no\n * per-request context at build time — mark the route `render: 'dynamic'` instead.\n *\n * @example\n * ```ts\n * 'use server';\n * import { getRequestContext, redirect } from '@rshono/core/server';\n *\n * export async function login(form: FormData) {\n * getRequestContext().cookies.set('session', String(form.get('email')), { httpOnly: true });\n * redirect('/dashboard');\n * }\n * ```\n *\n * @see {@link https://www.rshono.com/docs/api#rshonocoreserver | Docs — `@rshono/core/server`}\n */\nexport function getRequestContext<E extends Env = Env>(): RequestContext<E> {\n if (prerendering) {\n throw new Error(\n \"[rshono] getRequestContext() was called while prerendering a `render: 'static'` route. A static page \" +\n 'is rendered once at build time, so it has no per-request context to read (URL, cookies, ' +\n \"headers, env). Change this route to `render: 'dynamic'` so it renders per request, or remove \" +\n 'the getRequestContext() call.',\n );\n }\n const c = contextStorage.getStore();\n if (!c) {\n throw new Error(\n '[rshono] getRequestContext() was called outside a request. It only works inside a server component or a server action, not at module load.',\n );\n }\n let ctx = wrappers.get(c);\n if (!ctx) {\n ctx = new RequestContext(c);\n wrappers.set(c, ctx);\n }\n return ctx as unknown as RequestContext<E>;\n}\n\n/**\n * Redirects the request to `location`, by throwing a control signal the framework turns into an HTTP\n * redirect.\n *\n * Because it throws it never returns, so TypeScript narrows away everything after the call and there\n * is nothing to `return`. Don't wrap it in a `try/catch` that swallows the signal.\n *\n * @param location - Absolute path or URL to redirect to, e.g. `/dashboard`.\n * @param status - Redirect {@link RedirectStatus}; defaults to `303` (See Other), which is what makes\n * the browser follow up with a `GET` after a form action.\n *\n * @example\n * ```ts\n * const session = getRequestContext().cookies.get('session');\n * if (!session) redirect('/login');\n * // session is defined below this line\n * ```\n */\nexport function redirect(location: string, status: RedirectStatus = 303): never {\n throw new RedirectSignal(location, status);\n}\n\n/**\n * Aborts the current render with a 404, rendering the app's `notFound` page.\n *\n * Like {@link redirect} it throws a control signal and never returns, so TypeScript narrows away\n * everything after the call. Don't catch-and-swallow it.\n *\n * @example\n * ```tsx\n * export default async function Page({ params }: PageProps<'/users/:id'>) {\n * const user = await db.user.find(params.id);\n * if (!user) notFound();\n * return <Profile user={user} />; // user is non-null here\n * }\n * ```\n */\nexport function notFound(): never {\n throw new NotFoundSignal();\n}\n\n/**\n * Which stage of a request produced an error handed to a {@link ServerErrorHandler}.\n *\n * - `action` — a `'use server'` function threw. React sends the client an opaque marker with no\n * message in production, so this is the only place the real error is visible.\n * - `render` — a server component threw while the flight payload was being produced.\n * - `ssr` — SSR failed before the HTML shell could be sent, so the `error` page was unreachable too.\n * - `request` — anything else that reached the top-level handler, a thrown endpoint route included.\n */\nexport type ServerErrorSource = 'action' | 'render' | 'ssr' | 'request';\n\n/** What an {@link ServerErrorHandler} is told about an error, beyond the error itself. */\nexport interface ServerErrorContext {\n /** The stage that produced it — see {@link ServerErrorSource}. */\n source: ServerErrorSource;\n /** The request being served, for the URL, method and headers. */\n request: Request;\n}\n\n/** Handler registered with {@link onServerError}. Called for the side effect; its return value is ignored. */\nexport type ServerErrorHandler = (error: unknown, context: ServerErrorContext) => void;\n\nlet errorHandler: ServerErrorHandler | undefined;\n\n/**\n * Registers a handler for every error the framework catches, so they can reach an error tracker\n * (Sentry, Datadog, a log pipeline) instead of only `stderr`.\n *\n * Call it once, at the top level of `src/server.ts`, which is imported as the server starts.\n * Registering again replaces the previous handler. Errors still go to `stderr` either way, and a\n * handler that throws is caught and logged — reporting can never fail a request.\n *\n * @example\n * ```ts\n * // src/server.ts\n * import * as Sentry from '@sentry/node';\n * import { onServerError } from '@rshono/core/server';\n *\n * onServerError((error, { source, request }) => {\n * Sentry.captureException(error, { tags: { source }, extra: { url: request.url } });\n * });\n * ```\n *\n * @see {@link https://www.rshono.com/docs/hono#error-reporting | Docs — error reporting}\n */\nexport function onServerError(handler: ServerErrorHandler): void {\n errorHandler = handler;\n}\n\n/**\n * Logs an error and forwards it to the registered {@link ServerErrorHandler} — the single funnel every\n * caught server-side error goes through.\n *\n * @internal\n */\nexport function reportServerError(error: unknown, info: ServerErrorContext & { message: string }): void {\n console.error(info.message, error);\n if (!errorHandler) return;\n try {\n errorHandler(error, { source: info.source, request: info.request });\n } catch (handlerError) {\n console.error('[rshono] the onServerError handler threw:', handlerError);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/runtime/context.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,6FAA6F;AAC7F,qEAAqE;AACrE,oDAAoD;AACpD;;;;;;;GAOG;AAGH,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAEjE,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAc9D,MAAM,cAAc,GAAG,IAAI,iBAAiB,EAAW,CAAC;AAExD,2HAA2H;AAC3H,MAAM,QAAQ,GAAG,IAAI,OAAO,EAA2B,CAAC;AAExD,sGAAsG;AACtG,iDAAiD;AACjD,MAAM,SAAS,GAAG,IAAI,OAAO,EAAW,CAAC;AAEzC;;;;;GAKG;AACH,MAAM,UAAU,eAAe,CAAC,CAAU;IACxC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AACnB,CAAC;AAED,kHAAkH;AAClH,SAAS,cAAc,CAAC,IAAY;IAClC,MAAM,IAAI,KAAK,CACb,YAAY,IAAI,gFAAgF;QAC9F,iGAAiG;QACjG,kGAAkG;QAClG,oGAAoG;QACpG,mGAAmG,CACtG,CAAC;AACJ,CAAC;AAED,wHAAwH;AACxH,SAAS,YAAY,CAAC,IAAY,EAAE,OAAe;IACjD,MAAM,IAAI,KAAK,CACb,gBAAgB,IAAI,qFAAqF;QACvG,0DAA0D,OAAO,EAAE,CACtE,CAAC;AACJ,CAAC;AAED,8FAA8F;AAC9F,kGAAkG;AAClG,4DAA4D;AAC5D,IAAI,WAA2D,CAAC;AAEhE,SAAS,UAAU;IACjB,OAAO,CAAC,WAAW,KAAK,OAAO,OAAO,KAAK,WAAW,IAAI,OAA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c,EAAE,IAA8C;IAC9F,wGAAwG;IACxG,2DAA2D;IAC3D,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QAChD,IAAI,eAAe,CAAC,GAAG,CAAC,KAAK,CAAC;YAAE,OAAO;QACvC,eAAe,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC7B,CAAC;IACD,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACnC,IAAI,CAAC,YAAY;QAAE,OAAO;IAC1B,IAAI,CAAC;QACH,YAAY,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC;IACtE,CAAC;IAAC,OAAO,YAAY,EAAE,CAAC;QACtB,OAAO,CAAC,KAAK,CAAC,2CAA2C,EAAE,YAAY,CAAC,CAAC;IAC3E,CAAC;AACH,CAAC","sourcesContent":["// `__RSHONO_CONFIG__` is a global const, and an `import` cannot bring one into scope — a path reference is\n// the only way to reach it, which is the whole reason that file is separate. See its header.\n// eslint-disable-next-line @typescript-eslint/triple-slash-reference\n/// <reference path=\"../types/rshono-config.d.ts\" />\n/**\n * The request context: {@link getRequestContext} and the {@link RequestContext} it returns, the\n * {@link redirect} / {@link notFound} control-flow helpers, and the {@link onServerError} reporting\n * funnel — plus the `@internal` plumbing that binds a request to the async context.\n *\n * The public half is re-exported by `runtime/server.ts`, which is what `@rshono/core/server` resolves\n * to; an app imports that.\n */\n\nimport type { Context, Env } from 'hono';\nimport { deleteCookie, getCookie, setCookie } from 'hono/cookie';\nimport type { CookieOptions } from 'hono/utils/cookie';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { NotFoundSignal, RedirectSignal } from './control.js';\n\n/**\n * HTTP status codes accepted by {@link redirect}.\n *\n * - `301` Moved Permanently, `308` Permanent Redirect — cacheable, permanent.\n * - `302` Found, `307` Temporary Redirect — temporary.\n * - `303` See Other — the default; forces a `GET` on the target, which is what you almost always want\n * after a form action (post/redirect/get).\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status#redirection_messages | MDN — redirection status codes}\n */\nexport type RedirectStatus = 301 | 302 | 303 | 307 | 308;\n\nconst contextStorage = new AsyncLocalStorage<Context>();\n\n/** One {@link RequestContext} per Hono {@link Context}, so repeated `getRequestContext()` calls share its lazy getters. */\nconst wrappers = new WeakMap<Context, RequestContext>();\n\n// Keyed on the Hono context rather than held as a field, so marking a request never forces the lazily\n// built `RequestContext` wrapper into existence.\nconst rendering = new WeakSet<Context>();\n\n/**\n * Marks the request as having entered its page render, which is what makes\n * {@link RequestContext.setHeader} and `ctx.cookies.set()` start throwing.\n *\n * @internal\n */\nexport function beginPageRender(c: Context): void {\n rendering.add(c);\n}\n\n/** The shared refusal for a response write that arrived too late — the message names where it belongs instead. */\nfunction tooLateToWrite(call: string): never {\n throw new Error(\n `[rshono] ${call} was called while rendering a page, which is too late to affect the response. ` +\n 'A page streams, so its response head is already committed by the time the component runs — the ' +\n 'write would land on a full page load and be silently dropped on a soft navigation. Do it from a ' +\n \"'use server' action instead; or, in middleware and { type: 'endpoint' } routes — which are handed \" +\n \"Hono's `c` directly and run outside the request context — with `c.header(…)` / `setCookie(c, …)`.\",\n );\n}\n\n/** The shared refusal for a Hono `Context` member a page has no way to use. See the stubs on {@link RequestContext}. */\nfunction notOnContext(call: string, instead: string): never {\n throw new Error(\n `[rshono] ctx.${call} does not exist. A page returns JSX and the framework builds the response from it, ` +\n `so Hono's response builders have nothing to return to. ${instead}`,\n );\n}\n\n// Snapshotted rather than spread per request: enumerating `process.env` crosses into the host\n// environment (~20µs). Lazily, because `loadEnvFiles()` runs after this module is imported — so a\n// mutation after the first `ctx.env` read is not picked up.\nlet envSnapshot: Record<string, string | undefined> | undefined;\n\nfunction processEnv(): Record<string, string | undefined> {\n return (envSnapshot ??= typeof process !== 'undefined' && process.env ? { ...process.env } : {});\n}\n\n// Set by `build.ts` before it imports the app bundle, which inlines its own copy of this module — so\n// `process.env` is what crosses that boundary rather than a module-level flag.\nconst prerendering = typeof process !== 'undefined' && !!process.env?.RSHONO_PRERENDER;\n\n/**\n * Runs `fn` with `c` bound as the ambient request context, so {@link getRequestContext} resolves to it\n * anywhere in the call tree.\n *\n * @internal\n */\nexport function runWithContext<T>(c: Context, fn: () => T): T {\n return contextStorage.run(c, fn);\n}\n\n/**\n * The matched route params, or an empty object when there is no active match.\n *\n * @internal\n */\nexport function readParams(c: Context): Record<string, string> {\n try {\n return c.req.param();\n } catch {\n return {};\n }\n}\n\n/** A proxy chain appends to these headers, so the client-facing value is the first entry. */\nfunction firstForwardedValue(header: string | undefined): string | undefined {\n const first = header?.split(',')[0]?.trim();\n return first || undefined;\n}\n\n// Read through `typeof`: DefinePlugin inlines this into the server bundle, but the module is also the\n// public `@rshono/core/server` entry, which tooling can load without one. Absent means don't trust.\nconst trustProxy = typeof __RSHONO_CONFIG__ !== 'undefined' && __RSHONO_CONFIG__.trustProxy;\n\n/**\n * The browser-facing {@link URL} for a request, resolved from Hono's {@link Context} — a fresh\n * instance per call.\n *\n * `c.req.url` is the internal address the server was reached on, which is wrong behind a proxy;\n * `X-Forwarded-Host` / `-Proto` correct it, but only when `trustProxy` is enabled in\n * `rshono.config.ts` — they are client-supplied, so trusting them unconditionally would let anyone\n * dictate the origin of every absolute URL the app builds.\n *\n * This is the form for **middleware**, which is handed `c` and runs outside the request context — and\n * so the way to give Hono's own middleware the origin the browser actually used. In a server component\n * or action, prefer {@link RequestContext.url}, the same value cached per request.\n *\n * @param c - The Hono {@link Context} for the request.\n * @returns The browser-facing URL — proxy-corrected under `trustProxy`, `c.req.url` otherwise.\n *\n * @example\n * ```ts\n * // src/server.ts — a CSRF check that still works behind a proxy that rewrites Host\n * import { publicUrl } from '@rshono/core/server';\n * import { csrf } from 'hono/csrf';\n *\n * server.use(csrf({ origin: (origin, c) => origin === publicUrl(c).origin }));\n * ```\n *\n * @see {@link https://www.rshono.com/docs/configuration#proxy-headers | Docs — proxy headers}\n */\nexport function publicUrl(c: Context): URL {\n const url = new URL(c.req.url);\n if (!trustProxy) return url;\n\n const forwardedHost = firstForwardedValue(c.req.header('x-forwarded-host'));\n // Parsed, not assigned to `url.host`: that setter keeps the existing port when the new value has none.\n const forwarded = forwardedHost ? URL.parse(`http://${forwardedHost}`) : null;\n if (forwarded) {\n url.hostname = forwarded.hostname;\n url.port = forwarded.port;\n }\n\n // Only the two schemes a browser could have requested; anything else leaves the scheme alone.\n const forwardedProto = firstForwardedValue(c.req.header('x-forwarded-proto'));\n if (forwardedProto === 'http' || forwardedProto === 'https') url.protocol = forwardedProto;\n\n return url;\n}\n\n/**\n * The environment available to a request: Workers `Bindings` merged with process env vars. Values not\n * declared in `Bindings` are typed as `string | undefined`. See {@link RequestContext.env}.\n *\n * @see {@link https://hono.dev/docs/getting-started/cloudflare-workers#bindings | Hono — bindings}\n */\nexport type EnvVars<E extends Env> = E['Bindings'] & Record<string, string | undefined>;\n\n/**\n * Read-mostly wrapper around Hono's {@link Context}, for server components and server actions.\n *\n * Obtain one with {@link getRequestContext}, or take it off a page's `ctx` prop — the same object.\n * Never construct it yourself. One instance is reused for the whole request, so its lazy getters\n * ({@link RequestContext.url}, {@link RequestContext.env}) are computed at most once.\n *\n * @typeParam E - The Hono {@link Env} describing this app's `Bindings` and `Variables`, so\n * {@link RequestContext.var} and {@link RequestContext.env} stay typed.\n *\n * @example\n * ```tsx\n * import { getRequestContext } from '@rshono/core/server';\n *\n * export default async function Whoami() {\n * const ctx = getRequestContext();\n * const session = ctx.cookies.get('session');\n * return <p>{ctx.url.pathname} — {session ?? 'anonymous'}</p>;\n * }\n * ```\n *\n * @see {@link https://www.rshono.com/docs/api#rshonocoreserver | Docs — `@rshono/core/server`}\n * @see {@link https://hono.dev/docs/api/context | Hono — Context}, reachable in full via {@link RequestContext.hono}\n */\nexport class RequestContext<E extends Env = Env> {\n #raw: Context<E>;\n #url?: URL;\n #env?: EnvVars<E>;\n #params?: Record<string, string>;\n\n /**\n * One instance is created per request and handed out by {@link getRequestContext} or the `ctx` page\n * prop. Application code never calls this.\n *\n * @internal\n */\n constructor(c: Context<E>) {\n this.#raw = c;\n }\n\n /**\n * The underlying Hono {@link Context} — the escape hatch for what this wrapper does not expose, such\n * as `executionCtx.waitUntil()` on Workers.\n *\n * Its response builders (`redirect`, `json`, `body`, `status`, …) still do nothing from inside a\n * page: reaching them through here bypasses the errors the stubs on this class throw, it does not\n * make them work.\n *\n * @example\n * ```ts\n * getRequestContext().hono.executionCtx.waitUntil(logAsync()); // Workers\n * ```\n *\n * @see {@link https://hono.dev/docs/api/context | Hono — Context}\n */\n // Every member here is a getter or method so that none is *own enumerable*: React's \"you cannot pass\n // this to a client component\" diagnostic walks `Object.keys` recursively with no cycle guard, and the\n // Hono context graph reaches the socket through `req.raw`. `cookies` is the one own property, and it\n // is a shallow object of four functions.\n get hono(): Context<E> {\n return this.#raw;\n }\n\n /**\n * The parsed request — method, headers, path params, query and the body readers. Hono's\n * {@link Context.req}, unwrapped, so `ctx.req.header('authorization')` rather than\n * `ctx.hono.req.header(…)`.\n *\n * Reads only; setting a *response* header is {@link RequestContext.setHeader}, deliberately spelled\n * differently.\n *\n * @example\n * ```ts\n * const ctx = getRequestContext();\n * ctx.req.method; // 'GET'\n * ctx.req.header('authorization'); // string | undefined\n * ctx.req.query('tab'); // string | undefined\n * ```\n *\n * @see {@link https://hono.dev/docs/api/request | Hono — HonoRequest}\n */\n get req(): Context<E>['req'] {\n return this.#raw.req;\n }\n\n /**\n * Matched route params for this request, e.g. `{ id: '42' }` for `/profile/:id`. Empty when no route\n * matched.\n *\n * A page is handed the same record as its `params` prop, typed key-by-key from its route path, and\n * that is the better read where it exists. This is for everywhere else — a nested server component,\n * or a `'use server'` action.\n */\n get params(): Record<string, string> {\n return (this.#params ??= readParams(this.#raw as Context));\n }\n\n /**\n * The browser-facing request URL. Parsed once and cached, so every read within a request returns the\n * same instance — treat it as read-only.\n *\n * `X-Forwarded-Host` / `-Proto` are honoured only when `trustProxy` is enabled in\n * `rshono.config.ts`, since any client can send them.\n *\n * @example `const tab = getRequestContext().url.searchParams.get('tab');`\n *\n * @see {@link https://www.rshono.com/docs/configuration#proxy-headers | Docs — proxy headers}\n */\n get url(): URL {\n return (this.#url ??= publicUrl(this.#raw as Context));\n }\n\n /**\n * Typed variables set by middleware via `c.set('user', …)`, read here as `ctx.var.user`. Type them by\n * parameterising this class's {@link Env}.\n *\n * @example\n * ```ts\n * type AppEnv = { Variables: { user: { id: string } } };\n * const { user } = getRequestContext<AppEnv>().var; // typed, set by your middleware\n * ```\n *\n * @see {@link https://hono.dev/docs/api/context#var | Hono — c.var}\n * @see {@link https://www.rshono.com/docs/hono#typing-the-context | Docs — typing the context}\n */\n get var(): Readonly<E['Variables']> {\n return this.#raw.var;\n }\n\n /**\n * Environment for the request: process env vars merged with runtime bindings, which win on conflict.\n * Computed once and cached.\n *\n * @example `const key = getRequestContext().env.STRIPE_SECRET_KEY;`\n *\n * @see {@link https://hono.dev/docs/api/context#env | Hono — c.env}\n * @see {@link https://www.rshono.com/docs/configuration#environment-and-secrets | Docs — environment and secrets}\n */\n get env(): EnvVars<E> {\n if (this.#env) return this.#env;\n const bindings = this.#raw.env as Record<string, unknown> | undefined;\n return (this.#env = (bindings ? { ...processEnv(), ...bindings } : processEnv()) as EnvVars<E>);\n }\n\n /**\n * Read and write request/response cookies.\n *\n * @example\n * ```ts\n * const ctx = getRequestContext();\n * ctx.cookies.get('session'); // string | undefined\n * ctx.cookies.set('session', id, { httpOnly: true, sameSite: 'Lax', path: '/' });\n * ctx.cookies.delete('session', { path: '/' });\n * ```\n *\n * @see {@link https://hono.dev/docs/helpers/cookie | Hono — cookie helper}, which this wraps\n */\n cookies = {\n /** Reads a single cookie by name, or `undefined` if absent. Safe anywhere, a page included. */\n get: (name: string): string | undefined => getCookie(this.#raw, name),\n /** Reads every cookie as a `{ name: value }` record. Safe anywhere, a page included. */\n all: (): Record<string, string> => getCookie(this.#raw),\n /**\n * Sets a cookie on the response. See Hono's {@link CookieOptions} for `path`, `httpOnly`, `maxAge`\n * and the rest.\n *\n * **Throws inside a page render** — a `Set-Cookie` is a special case of\n * {@link RequestContext.setHeader}. Set cookies from a `'use server'` action, or with Hono's\n * `setCookie(c, …)` in middleware and endpoint routes.\n *\n * @throws If called while a page is rendering, where it could not reach the browser reliably.\n *\n * @see {@link https://hono.dev/docs/helpers/cookie#options | Hono — cookie options}\n */\n set: (name: string, value: string, options?: CookieOptions): void => {\n this.#assertWritable('ctx.cookies.set()');\n setCookie(this.#raw, name, value, options);\n },\n /**\n * Clears a cookie. Pass the same `path`/`domain` it was set with so the browser matches it.\n * Throws inside a page render, exactly as `set` does.\n *\n * @throws If called while a page is rendering.\n */\n delete: (name: string, options?: CookieOptions): void => {\n this.#assertWritable('ctx.cookies.delete()');\n deleteCookie(this.#raw, name, options);\n },\n };\n\n #assertWritable(call: string): void {\n if (rendering.has(this.#raw as Context)) tooLateToWrite(call);\n }\n\n /**\n * Sets a header on the response — from a `'use server'` action, which is the one place a request\n * context exists *and* the response is still open.\n *\n * From inside a page it throws: a page streams, so its response head is already committed by then,\n * and the write would land on a full page load but vanish on a soft navigation.\n *\n * Middleware and `{ type: 'endpoint' }` routes are handed Hono's `c` directly and use `c.header(…)`.\n * That is also where a header belonging to the *page* goes — `Cache-Control`, `X-Robots-Tag` — since\n * middleware runs before the render.\n *\n * @param name - Header name, case-insensitive.\n * @param value - Header value.\n * @param options - `{ append: true }` to add another value rather than replace.\n * @throws If called while a page is rendering, where it could not reach the browser reliably.\n *\n * @example\n * ```ts\n * 'use server';\n * export async function logout() {\n * const ctx = getRequestContext();\n * ctx.cookies.delete('session', { path: '/' });\n * ctx.setHeader('clear-site-data', '\"cache\", \"storage\"');\n * redirect('/');\n * }\n * ```\n */\n setHeader(name: string, value: string, options?: { append?: boolean }): void {\n this.#assertWritable('ctx.setHeader()');\n this.#raw.header(name, value, options);\n }\n\n // Hono's response builders, restated as errors naming what to use instead — through `ctx.hono` every\n // one of them is a silent no-op from a page. `@deprecated` strikes them through in autocomplete; the\n // unread `..._args` is so `ctx.redirect('/x')` reaches the thrown message rather than an arity error.\n\n /** @deprecated Not available on a page's context — use `redirect()` from `@rshono/core/server`. */\n redirect(..._args: unknown[]): never {\n return notOnContext(\n 'redirect(location, status?)',\n \"Use `redirect()` from '@rshono/core/server', which throws a signal the framework turns into a real redirect.\",\n );\n }\n\n /** @deprecated Not available on a page's context — use `notFound()` from `@rshono/core/server`. */\n notFound(..._args: unknown[]): never {\n return notOnContext('notFound()', \"Use `notFound()` from '@rshono/core/server', which aborts the render and shows the app's not-found page.\");\n }\n\n /** @deprecated A page renders JSX. For a JSON response, use an `{ type: 'endpoint' }` route. */\n json(..._args: unknown[]): never {\n return notOnContext('json(object)', \"For a JSON response use an { type: 'endpoint' } route; to read the request body use `ctx.req.json()`.\");\n }\n\n /** @deprecated A page renders JSX. For a text response, use an `{ type: 'endpoint' }` route. */\n text(..._args: unknown[]): never {\n return notOnContext('text(string)', \"For a text response use an { type: 'endpoint' } route; to read the request body use `ctx.req.text()`.\");\n }\n\n /** @deprecated A page renders JSX, which the framework turns into HTML for you. */\n html(..._args: unknown[]): never {\n return notOnContext('html(string)', \"A page's JSX is already its HTML; for a hand-built HTML response use an { type: 'endpoint' } route.\");\n }\n\n /** @deprecated Not available on a page's context. To read the request body, use `ctx.req`. */\n body(..._args: unknown[]): never {\n return notOnContext(\n 'body(data, …)',\n \"To read the *request* body use `ctx.req.json()` / `ctx.req.text()` / `ctx.req.formData()`; to build a response, use an { type: 'endpoint' } route.\",\n );\n }\n\n /** @deprecated A page's status is set by the framework — use `notFound()`, or an endpoint route. */\n status(..._args: unknown[]): never {\n return notOnContext(\n 'status(code)',\n \"A page's status is the framework's: 200, 404 via `notFound()`, 500 when it throws. For any other code use an { type: 'endpoint' } route.\",\n );\n }\n\n /** @deprecated Renamed — use `ctx.setHeader(name, value)`, which is valid from a `'use server'` action. */\n header(..._args: unknown[]): never {\n return notOnContext(\n 'header(name, value)',\n \"Use `ctx.setHeader(name, value)` from a 'use server' action, or `c.header(…)` in middleware — a page renders too late to set one.\",\n );\n }\n}\n\n/**\n * The {@link RequestContext} for the current request — URL, cookies, params, env and middleware\n * variables — read from a server component or a server action. Memoised per request, so repeated calls\n * return the same instance.\n *\n * A page is handed that same object as its `ctx` prop, so this import is for everywhere else: a nested\n * server component, or a `'use server'` action module.\n *\n * @typeParam E - The app's Hono {@link Env}, to type {@link RequestContext.var} and {@link RequestContext.env}.\n * @throws If called at module load, where there is no ambient context to resolve.\n * @throws If called while prerendering a `render: 'static'` route, which has no\n * per-request context at build time — mark the route `render: 'dynamic'` instead.\n *\n * @example\n * ```ts\n * 'use server';\n * import { getRequestContext, redirect } from '@rshono/core/server';\n *\n * export async function login(form: FormData) {\n * getRequestContext().cookies.set('session', String(form.get('email')), { httpOnly: true });\n * redirect('/dashboard');\n * }\n * ```\n *\n * @see {@link https://www.rshono.com/docs/api#rshonocoreserver | Docs — `@rshono/core/server`}\n */\nexport function getRequestContext<E extends Env = Env>(): RequestContext<E> {\n if (prerendering) {\n throw new Error(\n \"[rshono] getRequestContext() was called while prerendering a `render: 'static'` route. A static page \" +\n 'is rendered once at build time, so it has no per-request context to read (URL, cookies, ' +\n \"headers, env). Change this route to `render: 'dynamic'` so it renders per request, or remove \" +\n 'the getRequestContext() call.',\n );\n }\n const c = contextStorage.getStore();\n if (!c) {\n throw new Error(\n '[rshono] getRequestContext() was called outside a request. It only works inside a server component or a server action, not at module load.',\n );\n }\n let ctx = wrappers.get(c);\n if (!ctx) {\n ctx = new RequestContext(c);\n wrappers.set(c, ctx);\n }\n return ctx as unknown as RequestContext<E>;\n}\n\n/**\n * Redirects the request to `location`, by throwing a control signal the framework turns into an HTTP\n * redirect.\n *\n * Because it throws it never returns, so TypeScript narrows away everything after the call and there\n * is nothing to `return`. Don't wrap it in a `try/catch` that swallows the signal.\n *\n * @param location - Absolute path or URL to redirect to, e.g. `/dashboard`.\n * @param status - Redirect {@link RedirectStatus}; defaults to `303` (See Other), which is what makes\n * the browser follow up with a `GET` after a form action.\n *\n * @example\n * ```ts\n * const session = getRequestContext().cookies.get('session');\n * if (!session) redirect('/login');\n * // session is defined below this line\n * ```\n */\nexport function redirect(location: string, status: RedirectStatus = 303): never {\n throw new RedirectSignal(location, status);\n}\n\n/**\n * Aborts the current render with a 404, rendering the app's `notFound` page.\n *\n * Like {@link redirect} it throws a control signal and never returns, so TypeScript narrows away\n * everything after the call. Don't catch-and-swallow it.\n *\n * @example\n * ```tsx\n * export default async function Page({ params }: PageProps<'/users/:id'>) {\n * const user = await db.user.find(params.id);\n * if (!user) notFound();\n * return <Profile user={user} />; // user is non-null here\n * }\n * ```\n */\nexport function notFound(): never {\n throw new NotFoundSignal();\n}\n\n/**\n * Which stage of a request produced an error handed to a {@link ServerErrorHandler}.\n *\n * - `action` — a `'use server'` function threw. React sends the client an opaque marker with no\n * message in production, so this is the only place the real error is visible.\n * - `render` — a server component threw while the flight payload was being produced.\n * - `ssr` — SSR failed before the HTML shell could be sent, so the `error` page was unreachable too.\n * - `request` — anything else that reached the top-level handler, a thrown endpoint route included.\n */\nexport type ServerErrorSource = 'action' | 'render' | 'ssr' | 'request';\n\n/** What an {@link ServerErrorHandler} is told about an error, beyond the error itself. */\nexport interface ServerErrorContext {\n /** The stage that produced it — see {@link ServerErrorSource}. */\n source: ServerErrorSource;\n /** The request being served, for the URL, method and headers. */\n request: Request;\n}\n\n/** Handler registered with {@link onServerError}. Called for the side effect; its return value is ignored. */\nexport type ServerErrorHandler = (error: unknown, context: ServerErrorContext) => void;\n\nlet errorHandler: ServerErrorHandler | undefined;\n\n/**\n * Errors already forwarded, so one fault is reported once however many stages it crosses.\n *\n * A thrown server action is reported where it is known to be an action and then re-thrown, which lands it in\n * the top-level handler as well — and a funnel that counts the same error twice, under two different\n * `source`s, is worse than one that only ever names the outer stage.\n */\nconst alreadyReported = new WeakSet<object>();\n\n/**\n * Registers a handler for every error the framework catches, so they can reach an error tracker\n * (Sentry, Datadog, a log pipeline) instead of only `stderr`.\n *\n * Call it once, at the top level of `src/server.ts`, which is imported as the server starts.\n * Registering again replaces the previous handler. Errors still go to `stderr` either way, and a\n * handler that throws is caught and logged — reporting can never fail a request.\n *\n * @example\n * ```ts\n * // src/server.ts\n * import * as Sentry from '@sentry/node';\n * import { onServerError } from '@rshono/core/server';\n *\n * onServerError((error, { source, request }) => {\n * Sentry.captureException(error, { tags: { source }, extra: { url: request.url } });\n * });\n * ```\n *\n * @see {@link https://www.rshono.com/docs/hono#error-reporting | Docs — error reporting}\n */\nexport function onServerError(handler: ServerErrorHandler): void {\n errorHandler = handler;\n}\n\n/**\n * Logs an error and forwards it to the registered {@link ServerErrorHandler} — the single funnel every\n * caught server-side error goes through.\n *\n * @internal\n */\nexport function reportServerError(error: unknown, info: ServerErrorContext & { message: string }): void {\n // The first stage to recognise it wins, since that is the one that knows what it was. A primitive throw\n // cannot be tracked and is reported wherever it is caught.\n if (typeof error === 'object' && error !== null) {\n if (alreadyReported.has(error)) return;\n alreadyReported.add(error);\n }\n console.error(info.message, error);\n if (!errorHandler) return;\n try {\n errorHandler(error, { source: info.source, request: info.request });\n } catch (handlerError) {\n console.error('[rshono] the onServerError handler threw:', handlerError);\n }\n}\n"]}
|