@rshono/core 1.0.0-rc.7 → 1.0.0-rc.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +37 -11
  2. package/dist/builder/page-files.d.ts.map +1 -1
  3. package/dist/builder/page-files.js +7 -3
  4. package/dist/builder/page-files.js.map +1 -1
  5. package/dist/builder/public-env.d.ts +6 -0
  6. package/dist/builder/public-env.d.ts.map +1 -1
  7. package/dist/builder/public-env.js +6 -0
  8. package/dist/builder/public-env.js.map +1 -1
  9. package/dist/builder/rspack-config.d.ts.map +1 -1
  10. package/dist/builder/rspack-config.js +16 -19
  11. package/dist/builder/rspack-config.js.map +1 -1
  12. package/dist/cli/dev.d.ts.map +1 -1
  13. package/dist/cli/dev.js +63 -35
  14. package/dist/cli/dev.js.map +1 -1
  15. package/dist/cli/index.js +3 -4
  16. package/dist/cli/index.js.map +1 -1
  17. package/dist/config.d.ts +22 -65
  18. package/dist/config.d.ts.map +1 -1
  19. package/dist/config.js.map +1 -1
  20. package/dist/deploy/contract.d.ts +5 -5
  21. package/dist/deploy/contract.js.map +1 -1
  22. package/dist/deploy/filesystem.d.ts.map +1 -1
  23. package/dist/deploy/filesystem.js +6 -7
  24. package/dist/deploy/filesystem.js.map +1 -1
  25. package/dist/deploy/node/runtime.d.ts +5 -5
  26. package/dist/deploy/node/runtime.d.ts.map +1 -1
  27. package/dist/deploy/node/runtime.js +7 -11
  28. package/dist/deploy/node/runtime.js.map +1 -1
  29. package/dist/deploy/presets.d.ts +2 -6
  30. package/dist/deploy/presets.d.ts.map +1 -1
  31. package/dist/deploy/presets.js +2 -6
  32. package/dist/deploy/presets.js.map +1 -1
  33. package/dist/index.js +3 -3
  34. package/dist/index.js.map +1 -1
  35. package/dist/router.d.ts +15 -20
  36. package/dist/router.d.ts.map +1 -1
  37. package/dist/router.js +2 -3
  38. package/dist/router.js.map +1 -1
  39. package/dist/runtime/context.d.ts +53 -45
  40. package/dist/runtime/context.d.ts.map +1 -1
  41. package/dist/runtime/context.js +80 -82
  42. package/dist/runtime/context.js.map +1 -1
  43. package/dist/runtime/control.d.ts.map +1 -1
  44. package/dist/runtime/control.js +7 -0
  45. package/dist/runtime/control.js.map +1 -1
  46. package/dist/runtime/entry.client.js +29 -47
  47. package/dist/runtime/entry.client.js.map +1 -1
  48. package/dist/runtime/entry.rsc.d.ts.map +1 -1
  49. package/dist/runtime/entry.rsc.js +102 -138
  50. package/dist/runtime/entry.rsc.js.map +1 -1
  51. package/dist/runtime/flight-inject.d.ts +4 -4
  52. package/dist/runtime/flight-inject.js +2 -2
  53. package/dist/runtime/flight-inject.js.map +1 -1
  54. package/dist/runtime/navigation.js.map +1 -1
  55. package/dist/runtime/request.d.ts +3 -3
  56. package/dist/runtime/request.js +3 -3
  57. package/dist/runtime/request.js.map +1 -1
  58. package/dist/runtime/server.d.ts +3 -2
  59. package/dist/runtime/server.d.ts.map +1 -1
  60. package/dist/runtime/server.js +11 -8
  61. package/dist/runtime/server.js.map +1 -1
  62. package/dist/server/prerendered.d.ts +20 -35
  63. package/dist/server/prerendered.d.ts.map +1 -1
  64. package/dist/server/prerendered.js +8 -18
  65. package/dist/server/prerendered.js.map +1 -1
  66. package/dist/server/server-config.d.ts +10 -29
  67. package/dist/server/server-config.d.ts.map +1 -1
  68. package/dist/server/server-config.js +4 -70
  69. package/dist/server/server-config.js.map +1 -1
  70. package/dist/server/ssg.d.ts.map +1 -1
  71. package/dist/server/ssg.js +10 -11
  72. package/dist/server/ssg.js.map +1 -1
  73. package/package.json +1 -1
@@ -1,72 +1,14 @@
1
1
  /**
2
- * The single source of truth for the framework's built-in defaults.
2
+ * The framework's built-in defaults.
3
3
  *
4
- * `maxBodyBytes` is resolved here, into the bundle. `port` and `host` are not
5
- * settings at all: they are read from `PORT` / `HOST` (or `--port`) wherever the address is resolved
6
- * — `deploy/node/runtime.ts` for a server bundle, `cli/dev.ts` for the dev server — and this is the
7
- * default both fall back to. A config field for them would have been a fourth precedence level for
8
- * one number, overridden by the environment on every host that matters.
4
+ * `port` and `host` are not config fields at all — they come from `PORT` / `HOST` (or `--port`)
5
+ * wherever the address is resolved, `deploy/node/runtime.ts` for a server bundle and `cli/dev.ts`
6
+ * for the dev server, and this is what both fall back to.
9
7
  */
10
8
  export const SERVER_DEFAULTS = {
11
- maxBodyBytes: 1024 * 1024, // 1 MiB, matching Next.js's server-action body-size limit.
12
9
  port: 3000,
13
10
  host: '0.0.0.0',
14
11
  };
15
- /**
16
- * The built-in {@link RshonoConfig.csp} policy, keyed by directive so
17
- * {@link RshonoConfig.cspDirectives} can override entries individually.
18
- *
19
- * `script-src` carries the per-request nonce, appended at request time (see `entry.rsc.tsx`).
20
- * `style-src` needs `'unsafe-inline'` because React writes inline styles.
21
- */
22
- export const CSP_DEFAULTS = {
23
- 'default-src': "'self'",
24
- 'script-src': "'self'",
25
- 'style-src': "'self' 'unsafe-inline'",
26
- 'img-src': "'self' data:",
27
- 'connect-src': "'self'",
28
- // Not covered by default-src, and each closes an injection route of its own: a stray <base>
29
- // retargeting every relative URL, plugin content, framing (clickjacking), off-site form posts.
30
- 'base-uri': "'self'",
31
- 'object-src': "'none'",
32
- 'frame-ancestors': "'none'",
33
- 'form-action': "'self'",
34
- };
35
- const UNITS = { b: 1, kb: 1024, mb: 1024 ** 2, gb: 1024 ** 3 };
36
- /** Parse a {@link RshonoConfig.bodySizeLimit} value into a byte count (`false`/`0` → `0`, disabling the cap). */
37
- export function parseByteSize(value) {
38
- if (value === undefined)
39
- return undefined;
40
- if (value === false)
41
- return 0;
42
- if (typeof value === 'number')
43
- return value;
44
- const match = /^\s*(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?\s*$/i.exec(value);
45
- if (!match) {
46
- throw new Error(`[rshono] invalid bodySizeLimit ${JSON.stringify(value)} — use e.g. '1mb', 1048576, or false.`);
47
- }
48
- return Math.floor(Number(match[1]) * UNITS[(match[2] ?? 'b').toLowerCase()]);
49
- }
50
- /**
51
- * Normalize a config `allowedOrigins` entry (full origin or bare host) to a lowercase `URL.host`,
52
- * ready for a direct comparison against a parsed `Origin` header's host.
53
- *
54
- * A bare `host:port` has to be retried against a base, because on its own `'localhost:4000'`
55
- * parses as the *scheme* `localhost:` with path `4000` — leaving an empty host that would
56
- * silently never match anything. Throws rather than passing a junk entry through, so a typo
57
- * fails the build instead of quietly disabling the allowlist entry it was meant to add.
58
- */
59
- function normalizeOrigin(entry) {
60
- const host = URL.parse(entry)?.host || URL.parse(`http://${entry}`)?.host;
61
- if (!host) {
62
- throw new Error(`[rshono] invalid allowedOrigins entry ${JSON.stringify(entry)} — use a full origin ('https://admin.example.com') or a bare host ('localhost:4000').`);
63
- }
64
- return host.toLowerCase();
65
- }
66
- /** Drop directives the user blanked out, so `cspDirectives: { 'frame-ancestors': '' }` removes one. */
67
- function resolveCspDirectives(overrides) {
68
- return Object.fromEntries(Object.entries({ ...CSP_DEFAULTS, ...overrides }).filter(([, value]) => value.trim() !== ''));
69
- }
70
12
  /**
71
13
  * Resolve the user's {@link RshonoConfig} into the {@link ServerConfig} baked into the bundle.
72
14
  *
@@ -78,14 +20,6 @@ export function resolveServerConfig(config, { isDev }) {
78
20
  return {
79
21
  isDev,
80
22
  trustProxy: isDev || (config.trustProxy ?? false),
81
- cspEnabled: config.csp ?? false,
82
- cspDirectives: resolveCspDirectives(config.cspDirectives),
83
- checkOrigin: config.checkOrigin ?? true,
84
- allowedOrigins: (config.allowedOrigins ?? [])
85
- .map((entry) => entry.trim())
86
- .filter(Boolean)
87
- .map(normalizeOrigin),
88
- maxBodyBytes: parseByteSize(config.bodySizeLimit) ?? SERVER_DEFAULTS.maxBodyBytes,
89
23
  };
90
24
  }
91
25
  //# sourceMappingURL=server-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server-config.js","sourceRoot":"","sources":["../../src/server/server-config.ts"],"names":[],"mappings":"AAgCA;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B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AC,aAAa,CAAC,IAAI,eAAe,CAAC,YAAY;KAClF,CAAC;AACJ,CAAC","sourcesContent":["import type { RshonoConfig } from '../config.js';\n\n/**\n * The framework settings the server bundle needs at request time, fully resolved\n * (defaults applied, `bodySizeLimit` parsed to bytes, origins normalized to hosts).\n *\n * The value is produced once by {@link resolveServerConfig} from `rshono.config.ts`\n * and compiled into the server bundle as the `__RSHONO_CONFIG__` literal (see\n * `builder/rspack-config.ts`) — there is no runtime env-var interface for these.\n */\nexport interface ServerConfig {\n /**\n * `true` when the bundle came from `rshono dev`.\n *\n * Baked in rather than read from `process.env.NODE_ENV` at runtime: it is decided by which command\n * produced the bundle, and a deploy target need not have a `process` to read it from.\n */\n isDev: boolean;\n /** Honour `X-Forwarded-Host` / `-Proto` when resolving the browser-facing URL. Forced on in dev. */\n trustProxy: boolean;\n /** Send a strict per-request-nonce Content-Security-Policy with every HTML document. */\n cspEnabled: boolean;\n /** The resolved CSP directives (built-in defaults with the user's merged over them), minus the nonce. */\n cspDirectives: Record<string, string>;\n /** CSRF origin check on server-action POSTs. */\n checkOrigin: boolean;\n /** Extra origins allowed to post server actions, normalized to lowercase `URL.host` values. */\n allowedOrigins: string[];\n /** Max request body in bytes before a 413; `0` disables the cap. */\n maxBodyBytes: number;\n}\n\n/**\n * The single source of truth for the framework's built-in defaults.\n *\n * `maxBodyBytes` is resolved here, into the bundle. `port` and `host` are not\n * settings at all: they are read from `PORT` / `HOST` (or `--port`) wherever the address is resolved\n * — `deploy/node/runtime.ts` for a server bundle, `cli/dev.ts` for the dev server — and this is the\n * default both fall back to. A config field for them would have been a fourth precedence level for\n * one number, overridden by the environment on every host that matters.\n */\nexport const SERVER_DEFAULTS = {\n maxBodyBytes: 1024 * 1024, // 1 MiB, matching Next.js's server-action body-size limit.\n port: 3000,\n host: '0.0.0.0',\n} as const;\n\n/**\n * The built-in {@link RshonoConfig.csp} policy, keyed by directive so\n * {@link RshonoConfig.cspDirectives} can override entries individually.\n *\n * `script-src` carries the per-request nonce, appended at request time (see `entry.rsc.tsx`).\n * `style-src` needs `'unsafe-inline'` because React writes inline styles.\n */\nexport const CSP_DEFAULTS: Record<string, string> = {\n 'default-src': \"'self'\",\n 'script-src': \"'self'\",\n 'style-src': \"'self' 'unsafe-inline'\",\n 'img-src': \"'self' data:\",\n 'connect-src': \"'self'\",\n // Not covered by default-src, and each closes an injection route of its own: a stray <base>\n // retargeting every relative URL, plugin content, framing (clickjacking), off-site form posts.\n 'base-uri': \"'self'\",\n 'object-src': \"'none'\",\n 'frame-ancestors': \"'none'\",\n 'form-action': \"'self'\",\n};\n\nconst UNITS: Record<string, number> = { b: 1, kb: 1024, mb: 1024 ** 2, gb: 1024 ** 3 };\n\n/** Parse a {@link RshonoConfig.bodySizeLimit} value into a byte count (`false`/`0` → `0`, disabling the cap). */\nexport function parseByteSize(value: string | number | false | undefined): number | undefined {\n if (value === undefined) return undefined;\n if (value === false) return 0;\n if (typeof value === 'number') return value;\n const match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb)?\\s*$/i.exec(value);\n if (!match) {\n throw new Error(`[rshono] invalid bodySizeLimit ${JSON.stringify(value)} — use e.g. '1mb', 1048576, or false.`);\n }\n return Math.floor(Number(match[1]) * UNITS[(match[2] ?? 'b').toLowerCase()]);\n}\n\n/**\n * Normalize a config `allowedOrigins` entry (full origin or bare host) to a lowercase `URL.host`,\n * ready for a direct comparison against a parsed `Origin` header's host.\n *\n * A bare `host:port` has to be retried against a base, because on its own `'localhost:4000'`\n * parses as the *scheme* `localhost:` with path `4000` — leaving an empty host that would\n * silently never match anything. Throws rather than passing a junk entry through, so a typo\n * fails the build instead of quietly disabling the allowlist entry it was meant to add.\n */\nfunction normalizeOrigin(entry: string): string {\n const host = URL.parse(entry)?.host || URL.parse(`http://${entry}`)?.host;\n if (!host) {\n throw new Error(\n `[rshono] invalid allowedOrigins entry ${JSON.stringify(entry)} — use a full origin ('https://admin.example.com') or a bare host ('localhost:4000').`,\n );\n }\n return host.toLowerCase();\n}\n\n/** Drop directives the user blanked out, so `cspDirectives: { 'frame-ancestors': '' }` removes one. */\nfunction resolveCspDirectives(overrides: Record<string, string> | undefined): Record<string, string> {\n return Object.fromEntries(Object.entries({ ...CSP_DEFAULTS, ...overrides }).filter(([, value]) => value.trim() !== ''));\n}\n\n/**\n * Resolve the user's {@link RshonoConfig} into the {@link ServerConfig} baked into the bundle.\n *\n * `isDev` is a build-time input rather than a config field because it decides one thing the user\n * shouldn't have to: `trustProxy` is forced on under `rshono dev`, where the framework's own proxy\n * is the only way in (it sets the forwarded headers itself and binds to localhost).\n */\nexport function resolveServerConfig(config: RshonoConfig, { isDev }: { isDev: boolean }): ServerConfig {\n return {\n isDev,\n trustProxy: isDev || (config.trustProxy ?? false),\n cspEnabled: config.csp ?? false,\n cspDirectives: resolveCspDirectives(config.cspDirectives),\n checkOrigin: config.checkOrigin ?? true,\n allowedOrigins: (config.allowedOrigins ?? [])\n .map((entry) => entry.trim())\n .filter(Boolean)\n .map(normalizeOrigin),\n maxBodyBytes: parseByteSize(config.bodySizeLimit) ?? SERVER_DEFAULTS.maxBodyBytes,\n };\n}\n"]}
1
+ {"version":3,"file":"server-config.js","sourceRoot":"","sources":["../../src/server/server-config.ts"],"names":[],"mappings":"AA0BA;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,IAAI,EAAE,IAAI;IACV,IAAI,EAAE,SAAS;CACP,CAAC;AAEX;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,MAAoB,EAAE,EAAE,KAAK,EAAsB;IACrF,OAAO;QACL,KAAK;QACL,UAAU,EAAE,KAAK,IAAI,CAAC,MAAM,CAAC,UAAU,IAAI,KAAK,CAAC;KAClD,CAAC;AACJ,CAAC","sourcesContent":["import type { RshonoConfig } from '../config.js';\n\n/**\n * The framework settings the server bundle needs at request time, fully resolved.\n *\n * The value is produced once by {@link resolveServerConfig} from `rshono.config.ts`\n * and compiled into the server bundle as the `__RSHONO_CONFIG__` literal (see\n * `builder/rspack-config.ts`) — there is no runtime env-var interface for these.\n *\n * Only two fields, because only two things here are decided by the *build*. The per-request\n * security controls that used to live alongside them — the CSRF check, the CSP, the body cap — are\n * Hono middleware an app registers in `src/server.ts`, where they can be configured per route and\n * per environment instead of once per bundle.\n */\nexport interface ServerConfig {\n /**\n * `true` when the bundle came from `rshono dev`.\n *\n * Baked in rather than read from `process.env.NODE_ENV` at runtime: it is decided by which command\n * produced the bundle, and a deploy target need not have a `process` to read it from.\n */\n isDev: boolean;\n /** Honour `X-Forwarded-Host` / `-Proto` when resolving the browser-facing URL. Forced on in dev. */\n trustProxy: boolean;\n}\n\n/**\n * The framework's built-in defaults.\n *\n * `port` and `host` are not config fields at all — they come from `PORT` / `HOST` (or `--port`)\n * wherever the address is resolved, `deploy/node/runtime.ts` for a server bundle and `cli/dev.ts`\n * for the dev server, and this is what both fall back to.\n */\nexport const SERVER_DEFAULTS = {\n port: 3000,\n host: '0.0.0.0',\n} as const;\n\n/**\n * Resolve the user's {@link RshonoConfig} into the {@link ServerConfig} baked into the bundle.\n *\n * `isDev` is a build-time input rather than a config field because it decides one thing the user\n * shouldn't have to: `trustProxy` is forced on under `rshono dev`, where the framework's own proxy\n * is the only way in (it sets the forwarded headers itself and binds to localhost).\n */\nexport function resolveServerConfig(config: RshonoConfig, { isDev }: { isDev: boolean }): ServerConfig {\n return {\n isDev,\n trustProxy: isDev || (config.trustProxy ?? false),\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"ssg.d.ts","sourceRoot":"","sources":["../../src/server/ssg.ts"],"names":[],"mappings":"AAGA,OAAO,EAA+B,KAAK,KAAK,EAAE,MAAM,cAAc,CAAC;AACvE,OAAO,EAML,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACtB,MAAM,kBAAkB,CAAC;AAS1B;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAUrE;AA4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AAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAoBD,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,eAAe,CAAC,CA0D/F"}
@@ -84,14 +84,14 @@ export async function readPrerendered(ssgDir, requestPath, variant = 'html') {
84
84
  pageCache.set(key, page);
85
85
  return page;
86
86
  }
87
- /** Renders one representation of a path, or `null` if the app didn't answer with it. */
88
87
  async function renderVariant(fetch, url, variant) {
89
88
  const response = await fetch(new Request(url, { headers: { Accept: VARIANTS[variant].accept } }));
90
89
  if (response.status !== 200)
91
- return { status: response.status };
92
- if (!(response.headers.get('Content-Type') ?? '').includes(VARIANTS[variant].contentType))
93
- return null;
94
- return { body: await response.text() };
90
+ return { ok: false, reason: `${response.status}` };
91
+ if (!(response.headers.get('Content-Type') ?? '').includes(VARIANTS[variant].contentType)) {
92
+ return { ok: false, reason: `a non-${VARIANTS[variant].contentType} response` };
93
+ }
94
+ return { ok: true, body: await response.text() };
95
95
  }
96
96
  export async function prerenderStaticRoutes(options) {
97
97
  const { routes, fetch, ssgDir } = options;
@@ -118,9 +118,8 @@ export async function prerenderStaticRoutes(options) {
118
118
  }
119
119
  for (const path of paths) {
120
120
  const document = await renderVariant(fetch, origin + path, 'html');
121
- if (document === null || !('body' in document)) {
122
- const rendered = document === null ? 'a non-HTML response' : `${document.status}`;
123
- console.warn(` ⚠ "${path}" rendered ${rendered} at build time — skipping, will SSR per request.`);
121
+ if (!document.ok) {
122
+ console.warn(` ⚠ "${path}" rendered ${document.reason} at build time — skipping, will SSR per request.`);
124
123
  skipped.push(path);
125
124
  continue;
126
125
  }
@@ -131,10 +130,10 @@ export async function prerenderStaticRoutes(options) {
131
130
  };
132
131
  write('html', document.body);
133
132
  // The soft-navigation representation of the same page. Best-effort: if it doesn't come back
134
- // cleanly the document is still valid on its own, and serving falls back to rendering flight
135
- // per request — the behaviour before this was written at all.
133
+ // cleanly the document is still valid on its own, and serving falls back to rendering the
134
+ // flight payload per request.
136
135
  const flight = await renderVariant(fetch, origin + path, 'flight');
137
- if (flight !== null && 'body' in flight) {
136
+ if (flight.ok) {
138
137
  write('flight', flight.body);
139
138
  }
140
139
  else {
@@ -1 +1 @@
1
- {"version":3,"file":"ssg.js","sourceRoot":"","sources":["../../src/server/ssg.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACxD,OAAO,EAAE,WAAW,EAA8B,MAAM,cAAc,CAAC;AACvE,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,WAAW,EACX,iBAAiB,EACjB,QAAQ,GAGT,MAAM,kBAAkB,CAAC;AAE1B;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,kBAAkB,CAAC;AAE9C;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAA2B;IAC3D,IAAI,CAAC,OAAO;QAAE,OAAO,kBAAkB,CAAC;IACxC,MAAM,MAAM,GAAG,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAClC,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,QAAQ,KAAK,OAAO,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ,CAAC,EAAE,CAAC;QAC7E,MAAM,IAAI,KAAK,CAAC,4BAA4B,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,mDAAmD,CAAC,CAAC;IAC1H,CAAC;IACD,IAAI,MAAM,CAAC,QAAQ,KAAK,GAAG,IAAI,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;QAC5D,MAAM,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A8D;YAC9D,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,QAAQ,CAAC,CAAC;YACnE,IAAI,MAAM,KAAK,IAAI,IAAI,MAAM,IAAI,MAAM,EAAE,CAAC;gBACxC,KAAK,CAAC,QAAQ,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;YAC/B,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,IAAI,CAAC,QAAQ,IAAI,gFAAgF,CAAC,CAAC;YAC7G,CAAC;YAED,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACrB,CAAC;IACH,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, join, resolve, sep } from 'node:path';\nimport { isPageRoute, type PageRoute, type Route } from '../router.js';\nimport {\n createPageCache,\n prerenderedRelPath,\n ssgFilePath,\n toPrerenderedPage,\n VARIANTS,\n type PrerenderedPage,\n type PrerenderVariant,\n} from './prerendered.js';\n\n/**\n * Stand-in origin for a build that didn't declare {@link RshonoConfig.siteUrl}. Deliberately\n * obviously-wrong rather than a guess: a page that bakes this into a canonical tag should be easy\n * to spot, and the build warns when static routes are prerendered without a real origin.\n */\nconst DEFAULT_SSG_ORIGIN = 'http://localhost';\n\n/**\n * Resolve {@link RshonoConfig.siteUrl} to the origin prerendering should render against.\n *\n * A path is rejected rather than dropped: `'https://example.com/docs'` almost certainly means the\n * author expects a base path, and silently serving from the root would be a confusing way to find\n * out that isn't supported.\n */\nexport function resolveSiteOrigin(siteUrl: string | undefined): string {\n if (!siteUrl) return DEFAULT_SSG_ORIGIN;\n const parsed = URL.parse(siteUrl);\n if (!parsed || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) {\n throw new Error(`[rshono] invalid siteUrl ${JSON.stringify(siteUrl)} — use a full origin, e.g. 'https://example.com'.`);\n }\n if (parsed.pathname !== '/' || parsed.search || parsed.hash) {\n throw new Error(`[rshono] siteUrl ${JSON.stringify(siteUrl)} must be a bare origin — a base path is not supported.`);\n }\n return parsed.origin;\n}\n\nfunction interpolatePath(pattern: string, params: Record<string, string>): string {\n return pattern\n .split('/')\n .map((segment) => {\n if (!segment.startsWith(':')) {\n if (segment.includes('*')) {\n throw new Error(`Cannot prerender \"${pattern}\": wildcard segments are not supported by staticPaths.`);\n }\n return segment;\n }\n const name = segment.slice(1);\n if (!/^\\w+$/.test(name)) {\n throw new Error(`Cannot prerender \"${pattern}\": optional/regex params are not supported by staticPaths.`);\n }\n const value = params[name];\n if (value === undefined) {\n throw new Error(`staticPaths for \"${pattern}\" returned a param set without \"${name}\".`);\n }\n return encodeURIComponent(value);\n })\n .join('/');\n}\n\n/** Prerendered pages, keyed by the request that produced them (see {@link readPrerendered}). */\nconst pageCache = createPageCache();\n\nexport async function readPrerendered(ssgDir: string, requestPath: string, variant: PrerenderVariant = 'html'): Promise<PrerenderedPage | null> {\n // Keyed by what the request carried, not by the resolved filename, so a hit costs one Map lookup\n // instead of re-deriving the path every time. Safe because only *hits* are cached: an entry\n // exists only if this exact key already passed the checks below.\n const key = `${ssgDir}\\0${variant}\\0${requestPath}`;\n const cached = pageCache.get(key);\n if (cached) return cached;\n\n const relPath = prerenderedRelPath(requestPath, variant);\n if (relPath === null) return null;\n // Belt and braces: the shared guard already refused a traversal, and this proves the resolved file\n // is under the root whatever else the path contained.\n const root = resolve(ssgDir);\n const file = resolve(root, relPath);\n if (!file.startsWith(root + sep)) return null;\n\n // No encoding argument: the bytes are what gets served, and decoding them to a string here would\n // only mean re-encoding them on every request that hits the cache. Copied out of the Buffer rather\n // than kept as one, because `readFile` can hand back a view into Node's shared allocation pool and\n // this is retained for the life of the process.\n let body: Uint8Array<ArrayBuffer>;\n try {\n body = new Uint8Array(await readFile(file));\n } catch {\n return null;\n }\n\n const page = await toPrerenderedPage(body);\n pageCache.set(key, page);\n return page;\n}\n\ninterface PrerenderOptions {\n routes: readonly Route[];\n fetch: (request: Request) => Response | Promise<Response>;\n ssgDir: string;\n /** {@link RshonoConfig.siteUrl} — the origin absolute URLs in the output are built against. */\n siteUrl?: string;\n}\n\nexport interface PrerenderResult {\n written: string[];\n skipped: string[];\n}\n\n/** Renders one representation of a path, or `null` if the app didn't answer with it. */\nasync function renderVariant(\n fetch: PrerenderOptions['fetch'],\n url: string,\n variant: PrerenderVariant,\n): Promise<{ body: string } | { status: number } | null> {\n const response = await fetch(new Request(url, { headers: { Accept: VARIANTS[variant].accept } }));\n if (response.status !== 200) return { status: response.status };\n if (!(response.headers.get('Content-Type') ?? '').includes(VARIANTS[variant].contentType)) return null;\n return { body: await response.text() };\n}\n\nexport async function prerenderStaticRoutes(options: PrerenderOptions): Promise<PrerenderResult> {\n const { routes, fetch, ssgDir } = options;\n const staticRoutes = routes.filter((r): r is PageRoute => isPageRoute(r) && r.render === 'static');\n const origin = resolveSiteOrigin(options.siteUrl);\n\n if (staticRoutes.length > 0 && !options.siteUrl) {\n console.warn(\n ` ⚠ No siteUrl in rshono.config — prerendered pages are built against ${DEFAULT_SSG_ORIGIN}, so any absolute URL\\n` +\n ` they derive from a page's \\`url\\` prop (canonical tags, og:url, absolute links) will point there.`,\n );\n }\n\n const written: string[] = [];\n const skipped: string[] = [];\n\n for (const route of staticRoutes) {\n let paths: string[];\n if (!/[:*]/.test(route.path)) {\n paths = [route.path];\n } else {\n if (!route.staticPaths) {\n console.warn(` ⚠ Static route \"${route.path}\" has params but no staticPaths — will SSR per request.`);\n skipped.push(route.path);\n continue;\n }\n paths = (await route.staticPaths()).map((params) => interpolatePath(route.path, params));\n }\n\n for (const path of paths) {\n const document = await renderVariant(fetch, origin + path, 'html');\n if (document === null || !('body' in document)) {\n const rendered = document === null ? 'a non-HTML response' : `${document.status}`;\n console.warn(` ⚠ \"${path}\" rendered ${rendered} at build time — skipping, will SSR per request.`);\n skipped.push(path);\n continue;\n }\n\n const write = (variant: PrerenderVariant, body: string) => {\n const file = join(ssgDir, ssgFilePath(path, variant)!);\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, body);\n };\n write('html', document.body);\n\n // The soft-navigation representation of the same page. Best-effort: if it doesn't come back\n // cleanly the document is still valid on its own, and serving falls back to rendering flight\n // per request — the behaviour before this was written at all.\n const flight = await renderVariant(fetch, origin + path, 'flight');\n if (flight !== null && 'body' in flight) {\n write('flight', flight.body);\n } else {\n console.warn(` ⚠ \"${path}\" produced no flight payload — soft navigations to it will render per request.`);\n }\n\n written.push(path);\n }\n }\n\n return { written, skipped };\n}\n"]}
1
+ {"version":3,"file":"ssg.js","sourceRoot":"","sources":["../../src/server/ssg.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACxD,OAAO,EAAE,WAAW,EAA8B,MAAM,cAAc,CAAC;AACvE,OAAO,EACL,eAAe,EACf,kBAAkB,EAClB,WAAW,EACX,iBAAiB,EACjB,QAAQ,GAGT,MAAM,kBAAkB,CAAC;AAE1B;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,kBAAkB,CAAC;AAE9C;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,OAA2B;IAC3D,IAAI,CAAC,OAAO;QAAE,OAAO,kBAAkB,CAAC;IACxC,MAAM,MAAM,GAAG,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAClC,IAAI,CAAC,MAAM,IAAI,CAAC,MAAM,CAAC,QAAQ,KAAK,OAAO,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ,CAAC,EAAE,CAAC;QAC7E,MAAM,IAAI,KAAK,CAAC,4BAA4B,IAAI,CAAC,SAAS,CAAC,OAAO,CA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Aa,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAC5B,CAAC,CAAC;YACF,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;YAE7B,4FAA4F;YAC5F,0FAA0F;YAC1F,8BAA8B;YAC9B,MAAM,MAAM,GAAG,MAAM,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,EAAE,QAAQ,CAAC,CAAC;YACnE,IAAI,MAAM,CAAC,EAAE,EAAE,CAAC;gBACd,KAAK,CAAC,QAAQ,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC;YAC/B,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,IAAI,CAAC,QAAQ,IAAI,gFAAgF,CAAC,CAAC;YAC7G,CAAC;YAED,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACrB,CAAC;IACH,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC9B,CAAC","sourcesContent":["import { mkdirSync, writeFileSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, join, resolve, sep } from 'node:path';\nimport { isPageRoute, type PageRoute, type Route } from '../router.js';\nimport {\n createPageCache,\n prerenderedRelPath,\n ssgFilePath,\n toPrerenderedPage,\n VARIANTS,\n type PrerenderedPage,\n type PrerenderVariant,\n} from './prerendered.js';\n\n/**\n * Stand-in origin for a build that didn't declare {@link RshonoConfig.siteUrl}. Deliberately\n * obviously-wrong rather than a guess: a page that bakes this into a canonical tag should be easy\n * to spot, and the build warns when static routes are prerendered without a real origin.\n */\nconst DEFAULT_SSG_ORIGIN = 'http://localhost';\n\n/**\n * Resolve {@link RshonoConfig.siteUrl} to the origin prerendering should render against.\n *\n * A path is rejected rather than dropped: `'https://example.com/docs'` almost certainly means the\n * author expects a base path, and silently serving from the root would be a confusing way to find\n * out that isn't supported.\n */\nexport function resolveSiteOrigin(siteUrl: string | undefined): string {\n if (!siteUrl) return DEFAULT_SSG_ORIGIN;\n const parsed = URL.parse(siteUrl);\n if (!parsed || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) {\n throw new Error(`[rshono] invalid siteUrl ${JSON.stringify(siteUrl)} — use a full origin, e.g. 'https://example.com'.`);\n }\n if (parsed.pathname !== '/' || parsed.search || parsed.hash) {\n throw new Error(`[rshono] siteUrl ${JSON.stringify(siteUrl)} must be a bare origin — a base path is not supported.`);\n }\n return parsed.origin;\n}\n\nfunction interpolatePath(pattern: string, params: Record<string, string>): string {\n return pattern\n .split('/')\n .map((segment) => {\n if (!segment.startsWith(':')) {\n if (segment.includes('*')) {\n throw new Error(`Cannot prerender \"${pattern}\": wildcard segments are not supported by staticPaths.`);\n }\n return segment;\n }\n const name = segment.slice(1);\n if (!/^\\w+$/.test(name)) {\n throw new Error(`Cannot prerender \"${pattern}\": optional/regex params are not supported by staticPaths.`);\n }\n const value = params[name];\n if (value === undefined) {\n throw new Error(`staticPaths for \"${pattern}\" returned a param set without \"${name}\".`);\n }\n return encodeURIComponent(value);\n })\n .join('/');\n}\n\n/** Prerendered pages, keyed by the request that produced them (see {@link readPrerendered}). */\nconst pageCache = createPageCache();\n\nexport async function readPrerendered(ssgDir: string, requestPath: string, variant: PrerenderVariant = 'html'): Promise<PrerenderedPage | null> {\n // Keyed by what the request carried, not by the resolved filename, so a hit costs one Map lookup\n // instead of re-deriving the path every time. Safe because only *hits* are cached: an entry\n // exists only if this exact key already passed the checks below.\n const key = `${ssgDir}\\0${variant}\\0${requestPath}`;\n const cached = pageCache.get(key);\n if (cached) return cached;\n\n const relPath = prerenderedRelPath(requestPath, variant);\n if (relPath === null) return null;\n // Belt and braces: the shared guard already refused a traversal, and this proves the resolved file\n // is under the root whatever else the path contained.\n const root = resolve(ssgDir);\n const file = resolve(root, relPath);\n if (!file.startsWith(root + sep)) return null;\n\n // No encoding argument: the bytes are what gets served, and decoding them to a string here would\n // only mean re-encoding them on every request that hits the cache. Copied out of the Buffer rather\n // than kept as one, because `readFile` can hand back a view into Node's shared allocation pool and\n // this is retained for the life of the process.\n let body: Uint8Array<ArrayBuffer>;\n try {\n body = new Uint8Array(await readFile(file));\n } catch {\n return null;\n }\n\n const page = await toPrerenderedPage(body);\n pageCache.set(key, page);\n return page;\n}\n\ninterface PrerenderOptions {\n routes: readonly Route[];\n fetch: (request: Request) => Response | Promise<Response>;\n ssgDir: string;\n /** {@link RshonoConfig.siteUrl} — the origin absolute URLs in the output are built against. */\n siteUrl?: string;\n}\n\nexport interface PrerenderResult {\n written: string[];\n skipped: string[];\n}\n\n/**\n * One representation of a path, as the app answered for it at build time.\n *\n * Discriminated on `ok` rather than returned as a body-or-status-or-null union: both callers have to\n * tell \"the app rendered this\" from \"it did not\", and only one of them cares *why* — which as three\n * shapes made every read a `'body' in result` check against a value that could also be null.\n */\ntype RenderedVariant = { ok: true; body: string } | { ok: false; reason: string };\n\nasync function renderVariant(fetch: PrerenderOptions['fetch'], url: string, variant: PrerenderVariant): Promise<RenderedVariant> {\n const response = await fetch(new Request(url, { headers: { Accept: VARIANTS[variant].accept } }));\n if (response.status !== 200) return { ok: false, reason: `${response.status}` };\n if (!(response.headers.get('Content-Type') ?? '').includes(VARIANTS[variant].contentType)) {\n return { ok: false, reason: `a non-${VARIANTS[variant].contentType} response` };\n }\n return { ok: true, body: await response.text() };\n}\n\nexport async function prerenderStaticRoutes(options: PrerenderOptions): Promise<PrerenderResult> {\n const { routes, fetch, ssgDir } = options;\n const staticRoutes = routes.filter((r): r is PageRoute => isPageRoute(r) && r.render === 'static');\n const origin = resolveSiteOrigin(options.siteUrl);\n\n if (staticRoutes.length > 0 && !options.siteUrl) {\n console.warn(\n ` ⚠ No siteUrl in rshono.config — prerendered pages are built against ${DEFAULT_SSG_ORIGIN}, so any absolute URL\\n` +\n ` they derive from a page's \\`url\\` prop (canonical tags, og:url, absolute links) will point there.`,\n );\n }\n\n const written: string[] = [];\n const skipped: string[] = [];\n\n for (const route of staticRoutes) {\n let paths: string[];\n if (!/[:*]/.test(route.path)) {\n paths = [route.path];\n } else {\n if (!route.staticPaths) {\n console.warn(` ⚠ Static route \"${route.path}\" has params but no staticPaths — will SSR per request.`);\n skipped.push(route.path);\n continue;\n }\n paths = (await route.staticPaths()).map((params) => interpolatePath(route.path, params));\n }\n\n for (const path of paths) {\n const document = await renderVariant(fetch, origin + path, 'html');\n if (!document.ok) {\n console.warn(` ⚠ \"${path}\" rendered ${document.reason} at build time — skipping, will SSR per request.`);\n skipped.push(path);\n continue;\n }\n\n const write = (variant: PrerenderVariant, body: string) => {\n const file = join(ssgDir, ssgFilePath(path, variant)!);\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, body);\n };\n write('html', document.body);\n\n // The soft-navigation representation of the same page. Best-effort: if it doesn't come back\n // cleanly the document is still valid on its own, and serving falls back to rendering the\n // flight payload per request.\n const flight = await renderVariant(fetch, origin + path, 'flight');\n if (flight.ok) {\n write('flight', flight.body);\n } else {\n console.warn(` ⚠ \"${path}\" produced no flight payload — soft navigations to it will render per request.`);\n }\n\n written.push(path);\n }\n }\n\n return { written, skipped };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rshono/core",
3
- "version": "1.0.0-rc.7",
3
+ "version": "1.0.0-rc.8",
4
4
  "description": "Minimalist web framework — Hono + Rspack + React Server Components",
5
5
  "author": "Lasse <lasse@lassetange.com> (https://www.lassetange.com)",
6
6
  "license": "ISC",