@nifrajs/web 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/README.md +3 -3
  2. package/dist/build-vite.d.ts +4 -4
  3. package/dist/build-vite.d.ts.map +1 -1
  4. package/dist/build-vite.js +20 -74
  5. package/dist/build-vite.js.map +1 -1
  6. package/dist/build.d.ts +64 -42
  7. package/dist/build.d.ts.map +1 -1
  8. package/dist/build.js +100 -78
  9. package/dist/build.js.map +1 -1
  10. package/dist/bun-dev-entry.d.ts +1 -1
  11. package/dist/bun-dev-entry.js +1 -1
  12. package/dist/chunk-names.js +1 -1
  13. package/dist/client.d.ts +3 -9
  14. package/dist/client.d.ts.map +1 -1
  15. package/dist/client.js +201 -29
  16. package/dist/client.js.map +1 -1
  17. package/dist/conformance.d.ts +2 -2
  18. package/dist/conformance.js +3 -3
  19. package/dist/deferred.d.ts +11 -11
  20. package/dist/deferred.d.ts.map +1 -1
  21. package/dist/deferred.js +16 -16
  22. package/dist/dev-diagnostics.d.ts +20 -0
  23. package/dist/dev-diagnostics.d.ts.map +1 -0
  24. package/dist/dev-diagnostics.js +34 -0
  25. package/dist/dev-diagnostics.js.map +1 -0
  26. package/dist/dev-error.d.ts +10 -13
  27. package/dist/dev-error.d.ts.map +1 -1
  28. package/dist/dev-error.js +51 -37
  29. package/dist/dev-error.js.map +1 -1
  30. package/dist/dev-port.d.ts +3 -3
  31. package/dist/dev-port.d.ts.map +1 -1
  32. package/dist/dev-port.js +10 -4
  33. package/dist/dev-port.js.map +1 -1
  34. package/dist/dev.d.ts +4 -4
  35. package/dist/dev.d.ts.map +1 -1
  36. package/dist/dev.js +28 -12
  37. package/dist/dev.js.map +1 -1
  38. package/dist/diagnostic.d.ts +93 -0
  39. package/dist/diagnostic.d.ts.map +1 -0
  40. package/dist/diagnostic.js +205 -0
  41. package/dist/diagnostic.js.map +1 -0
  42. package/dist/draft.d.ts +12 -12
  43. package/dist/draft.js +11 -11
  44. package/dist/fn-state.d.ts +56 -0
  45. package/dist/fn-state.d.ts.map +1 -0
  46. package/dist/fn-state.js +77 -0
  47. package/dist/fn-state.js.map +1 -0
  48. package/dist/fn.d.ts +111 -0
  49. package/dist/fn.d.ts.map +1 -0
  50. package/dist/fn.js +125 -0
  51. package/dist/fn.js.map +1 -0
  52. package/dist/fonts-google.d.ts +9 -9
  53. package/dist/fonts-google.js +10 -10
  54. package/dist/fonts.d.ts +7 -7
  55. package/dist/fonts.js +1 -1
  56. package/dist/forms.d.ts +8 -8
  57. package/dist/fs.d.ts +1 -1
  58. package/dist/fs.js +1 -1
  59. package/dist/index.d.ts +151 -70
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +317 -139
  62. package/dist/index.js.map +1 -1
  63. package/dist/internal/head-attributes.d.ts +15 -0
  64. package/dist/internal/head-attributes.d.ts.map +1 -0
  65. package/dist/internal/head-attributes.js +99 -0
  66. package/dist/internal/head-attributes.js.map +1 -0
  67. package/dist/internal/script-types.d.ts +14 -0
  68. package/dist/internal/script-types.d.ts.map +1 -0
  69. package/dist/internal/script-types.js +17 -0
  70. package/dist/internal/script-types.js.map +1 -0
  71. package/dist/internal/server-boundary.d.ts +60 -0
  72. package/dist/internal/server-boundary.d.ts.map +1 -0
  73. package/dist/internal/server-boundary.js +174 -0
  74. package/dist/internal/server-boundary.js.map +1 -0
  75. package/dist/internal/timing-safe-equal.d.ts +1 -1
  76. package/dist/internal/timing-safe-equal.js +1 -1
  77. package/dist/internal/vite-import.d.ts +63 -0
  78. package/dist/internal/vite-import.d.ts.map +1 -0
  79. package/dist/internal/vite-import.js +94 -0
  80. package/dist/internal/vite-import.js.map +1 -0
  81. package/dist/islands.d.ts +5 -5
  82. package/dist/islands.js +5 -5
  83. package/dist/isr.d.ts +15 -15
  84. package/dist/isr.js +7 -7
  85. package/dist/manifest.d.ts +73 -35
  86. package/dist/manifest.d.ts.map +1 -1
  87. package/dist/manifest.js +10 -16
  88. package/dist/manifest.js.map +1 -1
  89. package/dist/module-graph.d.ts +5 -5
  90. package/dist/module-graph.js +4 -4
  91. package/dist/navigation.d.ts +120 -5
  92. package/dist/navigation.d.ts.map +1 -1
  93. package/dist/navigation.js +37 -5
  94. package/dist/navigation.js.map +1 -1
  95. package/dist/plugins/css-modules.d.ts +3 -3
  96. package/dist/plugins/css-modules.js +0 -0
  97. package/dist/plugins/kit.d.ts +8 -8
  98. package/dist/plugins/kit.js +9 -9
  99. package/dist/plugins/scss.js +3 -3
  100. package/dist/plugins/vite-leak-guard.d.ts +1 -1
  101. package/dist/plugins/vite-leak-guard.js +1 -1
  102. package/dist/plugins/vite-server-fn.d.ts +23 -0
  103. package/dist/plugins/vite-server-fn.d.ts.map +1 -0
  104. package/dist/plugins/vite-server-fn.js +51 -0
  105. package/dist/plugins/vite-server-fn.js.map +1 -0
  106. package/dist/plugins/vite-server-only.d.ts +49 -0
  107. package/dist/plugins/vite-server-only.d.ts.map +1 -0
  108. package/dist/plugins/vite-server-only.js +57 -0
  109. package/dist/plugins/vite-server-only.js.map +1 -0
  110. package/dist/prerender.d.ts +5 -5
  111. package/dist/prerender.js +7 -7
  112. package/dist/query.d.ts +10 -10
  113. package/dist/query.js +15 -15
  114. package/dist/route-manifest.d.ts +1 -1
  115. package/dist/route-manifest.js +2 -2
  116. package/dist/router.d.ts +30 -21
  117. package/dist/router.d.ts.map +1 -1
  118. package/dist/router.js +62 -32
  119. package/dist/router.js.map +1 -1
  120. package/dist/search.d.ts +94 -0
  121. package/dist/search.d.ts.map +1 -0
  122. package/dist/search.js +232 -0
  123. package/dist/search.js.map +1 -0
  124. package/dist/server-only.d.ts +6 -6
  125. package/dist/server-only.js +7 -7
  126. package/dist/service-worker.d.ts +56 -0
  127. package/dist/service-worker.d.ts.map +1 -0
  128. package/dist/service-worker.js +127 -0
  129. package/dist/service-worker.js.map +1 -0
  130. package/dist/vite.d.ts +16 -14
  131. package/dist/vite.d.ts.map +1 -1
  132. package/dist/vite.js +51 -24
  133. package/dist/vite.js.map +1 -1
  134. package/package.json +38 -4
  135. package/server-manifest.d.ts +31 -0
  136. package/src/build-vite.ts +24 -77
  137. package/src/build.ts +137 -105
  138. package/src/bun-dev-entry.ts +1 -1
  139. package/src/chunk-names.ts +1 -1
  140. package/src/client.ts +215 -32
  141. package/src/conformance.ts +3 -3
  142. package/src/deferred.ts +17 -17
  143. package/src/dev-diagnostics.ts +47 -0
  144. package/src/dev-error.ts +64 -33
  145. package/src/dev-port.ts +17 -5
  146. package/src/dev.ts +36 -20
  147. package/src/diagnostic.ts +284 -0
  148. package/src/draft.ts +15 -15
  149. package/src/fn-state.ts +107 -0
  150. package/src/fn.ts +199 -0
  151. package/src/fonts-google.ts +13 -13
  152. package/src/fonts.ts +7 -7
  153. package/src/forms.ts +8 -8
  154. package/src/fs.ts +2 -2
  155. package/src/index.ts +460 -181
  156. package/src/internal/head-attributes.ts +109 -0
  157. package/src/internal/script-types.ts +18 -0
  158. package/src/internal/server-boundary.ts +187 -0
  159. package/src/internal/timing-safe-equal.ts +1 -1
  160. package/src/internal/vite-import.ts +92 -0
  161. package/src/islands.ts +7 -7
  162. package/src/isr.ts +17 -17
  163. package/src/manifest.ts +83 -42
  164. package/src/module-graph.ts +6 -6
  165. package/src/navigation.ts +151 -5
  166. package/src/plugins/css-modules.ts +0 -0
  167. package/src/plugins/kit.ts +11 -11
  168. package/src/plugins/scss.ts +3 -3
  169. package/src/plugins/vite-leak-guard.ts +2 -2
  170. package/src/plugins/vite-server-fn.ts +67 -0
  171. package/src/plugins/vite-server-only.ts +75 -0
  172. package/src/prerender.ts +10 -10
  173. package/src/query.ts +22 -22
  174. package/src/route-manifest.ts +3 -3
  175. package/src/router.ts +98 -45
  176. package/src/search.ts +297 -0
  177. package/src/server-only.ts +7 -7
  178. package/src/service-worker.ts +165 -0
  179. package/src/vite.ts +61 -32
@@ -0,0 +1,109 @@
1
+ /**
2
+ * The one trust boundary for route-owned `<meta>` and `<link>` attributes.
3
+ *
4
+ * Both SSR and soft navigation consume this normalized representation. Keeping policy here prevents
5
+ * the two renderers from disagreeing about whether a descriptor is executable or otherwise unsafe.
6
+ */
7
+
8
+ export type HeadTag = "meta" | "link"
9
+ export type HeadAttributeValue = string | boolean | undefined
10
+ export type TrustedHeadAttribute = readonly [name: string, value: string | true]
11
+
12
+ const SAFE_ATTR_NAME = /^[a-z][a-z0-9-]*$/
13
+ const DATA_ATTR_NAME = /^data-[a-z0-9-]+$/
14
+ const EVENT_ATTR_NAME = /^on/i
15
+
16
+ const META_ATTRIBUTES: ReadonlySet<string> = new Set([
17
+ "charset",
18
+ "content",
19
+ "http-equiv",
20
+ "itemprop",
21
+ "media",
22
+ "name",
23
+ "property",
24
+ "scheme",
25
+ ])
26
+
27
+ const LINK_ATTRIBUTES: ReadonlySet<string> = new Set([
28
+ "as",
29
+ "blocking",
30
+ "color",
31
+ "crossorigin",
32
+ "disabled",
33
+ "fetchpriority",
34
+ "href",
35
+ "hreflang",
36
+ "imagesizes",
37
+ "imagesrcset",
38
+ "integrity",
39
+ "media",
40
+ "nonce",
41
+ "referrerpolicy",
42
+ "rel",
43
+ "sizes",
44
+ "title",
45
+ "type",
46
+ ])
47
+
48
+ // Browsers ignore embedded ASCII whitespace/control characters while recognizing URL schemes. Remove
49
+ // them before checking so `java\nscript:` cannot evade the scheme policy. Relative and protocol-relative
50
+ // URLs are allowed; an explicit scheme must be HTTP(S). This rejects active and local schemes such as
51
+ // javascript:, vbscript:, data:, blob:, and file: before a descriptor reaches either renderer.
52
+ function hasDisallowedLinkScheme(value: string): boolean {
53
+ let compact = ""
54
+ for (const char of value) {
55
+ const code = char.charCodeAt(0)
56
+ if (code > 0x20 && code !== 0x7f) compact += char.toLowerCase()
57
+ }
58
+ const scheme = /^([a-z][a-z0-9+.-]*):/.exec(compact)?.[1]
59
+ return scheme !== undefined && scheme !== "http" && scheme !== "https"
60
+ }
61
+
62
+ /**
63
+ * Normalize one descriptor. `null` means the entire element is unsafe (currently meta refresh).
64
+ * Unknown attributes are dropped: future platform attributes must be reviewed and added explicitly.
65
+ */
66
+ export function trustedHeadAttributes(
67
+ tag: HeadTag,
68
+ attrs: Readonly<object>,
69
+ ): readonly TrustedHeadAttribute[] | null {
70
+ if (typeof attrs !== "object" || attrs === null) return []
71
+ let entries: Array<[string, unknown]>
72
+ try {
73
+ entries = Object.entries(attrs)
74
+ } catch {
75
+ // A route can cross this runtime boundary through untyped JavaScript or a cast. A hostile Proxy/getter
76
+ // must not strand SSR or a soft navigation; reject the descriptor rather than partially trusting it.
77
+ return []
78
+ }
79
+
80
+ if (tag === "meta") {
81
+ for (const [rawName, value] of entries) {
82
+ if (
83
+ rawName.toLowerCase() === "http-equiv" &&
84
+ typeof value === "string" &&
85
+ value.trim().toLowerCase() === "refresh"
86
+ )
87
+ return null
88
+ }
89
+ }
90
+
91
+ const allowed = tag === "meta" ? META_ATTRIBUTES : LINK_ATTRIBUTES
92
+ const out: TrustedHeadAttribute[] = []
93
+ for (const [rawName, value] of entries) {
94
+ if (value === undefined || value === false) continue
95
+ if (value !== true && typeof value !== "string") continue
96
+ const name = rawName.toLowerCase()
97
+ if (!SAFE_ATTR_NAME.test(name) || EVENT_ATTR_NAME.test(name)) continue
98
+ if (!allowed.has(name) && !DATA_ATTR_NAME.test(name)) continue
99
+ if (
100
+ tag === "link" &&
101
+ name === "href" &&
102
+ typeof value === "string" &&
103
+ hasDisallowedLinkScheme(value)
104
+ )
105
+ continue
106
+ out.push([name, value === true ? true : value])
107
+ }
108
+ return out
109
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The `type` values each head-script slot accepts, owned in one place because both halves enforce it:
3
+ * the server's `headTags` and the client's `applyHead` on a soft navigation. A head that renders and
4
+ * then throws on the next navigation is worse than one that never rendered.
5
+ *
6
+ * Allowlists rather than escaping. Both slots interpolate `type` into an attribute, and a value
7
+ * outside these sets is a mistake - emitting an escaped version of it would produce a `<script>` the
8
+ * browser treats as inert data under a name nobody meant. Escaping is for values; this is a keyword.
9
+ */
10
+
11
+ /** Data, never executed by the browser. */
12
+ export const INERT_SCRIPT_TYPES: ReadonlySet<string> = new Set([
13
+ "application/ld+json",
14
+ "application/json",
15
+ ])
16
+
17
+ /** Executed. Only reachable through `unsafeScript`, which additionally requires a CSP nonce. */
18
+ export const EXECUTABLE_SCRIPT_TYPES: ReadonlySet<string> = new Set(["module", "text/javascript"])
@@ -0,0 +1,187 @@
1
+ /**
2
+ * The server/client boundary, owned in one place.
3
+ *
4
+ * The client build must never ship server-only code, or server-only config, to a browser. Three
5
+ * conventions enforce that, and each has to mean the SAME thing in every pipeline that builds the client
6
+ * - the Bun client build, the Vite dev server, the Vite production build, and `nifra dev --bun`'s refusal
7
+ * (which cannot transform, so it refuses to start instead):
8
+ *
9
+ * - `*.server` modules - emptied, so a secret / `node:` / native import subtree never reaches the client.
10
+ * - `*.fn` modules - replaced with HTTP stubs, so the function bodies (and their imports) stay server-side.
11
+ * - public-env prefix - which environment variables the client bundle is allowed to inline.
12
+ *
13
+ * When each pipeline re-encoded one of these rules, they drifted. A hand-written glob
14
+ * `**\/*.server.{ts,tsx,js,jsx}` missed the extensionless `db.server` and the `.mts`/`.cts`/`.mjs`/`.cjs`
15
+ * forms the regex matches, waving a module the build empties straight into the browser. So the matchers,
16
+ * the replacement bodies, and the env mapping get exactly one definition here; every pipeline imports it,
17
+ * and parity tests assert the Bun and Vite halves emit identical bytes. A matcher that decides whether a
18
+ * secret can reach a browser gets one owner, not four.
19
+ */
20
+
21
+ // Both module conventions match a filename SUFFIX with the identical optional source-extension tail -
22
+ // `.ts`, `.tsx`, `.mts`, `.cts`, `.mjs`, `.cjs`, `.js`, `.jsx`, or none (the extensionless `db.server` /
23
+ // `todos.fn`). Kept adjacent so the shared shape is visible, and a parity test pins that the two never
24
+ // diverge on which extensions count - a copied-then-edited second tail is exactly how the old glob drifted.
25
+
26
+ /** Matches `db.server.ts`, `auth.server.tsx`, `x.server.mjs`, and the extensionless `foo.server`. */
27
+ export const SERVER_ONLY_MODULE = /\.server(\.[cm]?[jt]sx?)?$/
28
+ /** Modules whose exports become client stubs. Mirrors the `.server` convention's shape. */
29
+ export const SERVER_FN_MODULE = /\.fn(\.[cm]?[jt]sx?)?$/
30
+
31
+ // ---------------------------------------------------------------------------------------------------
32
+ // `.server` - empty a server-only module in the client build.
33
+ // ---------------------------------------------------------------------------------------------------
34
+
35
+ /**
36
+ * The replacement body for an emptied module. A Proxy rather than `export {}` so any named OR default
37
+ * import resolves to `undefined` instead of failing the bundle with a missing-export error - the client
38
+ * degrades at the call site it wrote, not at link time in a file it never named.
39
+ *
40
+ * Shared so the Bun and Vite pipelines emit the same bytes; a parity test asserts it.
41
+ */
42
+ export const SERVER_ONLY_REPLACEMENT = "module.exports = new Proxy({}, { get: () => undefined })"
43
+
44
+ const EXPORTED_DECLARATION =
45
+ /\bexport\s+(?:declare\s+)?(?:async\s+)?(?:const|let|var|function|class|enum)\s+([A-Za-z_$][\w$]*)/g
46
+ const EXPORTED_LIST = /\bexport\s*\{([^}]*)\}(?:\s*from\s*["'][^"']+["'])?/g
47
+
48
+ /**
49
+ * Vite dev serves native ESM, so the Bun/CommonJS proxy above is invalid there. Emit inert ESM
50
+ * bindings derived from the source's public names while discarding the implementation and imports.
51
+ * An unsupported exotic export fails closed at ESM link time; server code is never served as fallback.
52
+ */
53
+ export function viteServerOnlyReplacement(source: string): string {
54
+ const names = new Set<string>()
55
+ let hasDefault = /\bexport\s+default\b/.test(source)
56
+
57
+ for (const match of source.matchAll(EXPORTED_DECLARATION)) names.add(match[1] as string)
58
+ for (const match of source.matchAll(EXPORTED_LIST)) {
59
+ for (const raw of (match[1] ?? "").split(",")) {
60
+ const item = raw.trim().replace(/^type\s+/, "")
61
+ if (item === "") continue
62
+ const parts = item.split(/\s+as\s+/)
63
+ const exported = (parts[1] ?? parts[0] ?? "").trim()
64
+ if (exported === "default") hasDefault = true
65
+ else if (/^[A-Za-z_$][\w$]*$/.test(exported)) names.add(exported)
66
+ }
67
+ }
68
+
69
+ const bindings = [...names].sort().map((name) => `export const ${name} = undefined`)
70
+ if (hasDefault) bindings.push("export default undefined")
71
+ return `// Generated by @nifrajs/web: server-only implementation removed from the browser.\n${bindings.join("\n")}\n`
72
+ }
73
+
74
+ // ---------------------------------------------------------------------------------------------------
75
+ // `.fn` - turn a server-function module into the client stubs that call it.
76
+ // ---------------------------------------------------------------------------------------------------
77
+
78
+ /**
79
+ * The server half of a server function must never reach a browser: it closes over database handles,
80
+ * secrets and everything else the module imports. So the CLIENT build does not bundle these modules at
81
+ * all - it replaces each one with a stub per export that POSTs to the route the server mounted.
82
+ *
83
+ * The generation is pure on purpose. The Bun and Vite pipelines both need this transform and must
84
+ * produce byte-identical stubs, so it lives here and each bundler contributes only its own plugin shell.
85
+ * A divergence between the two would be a client that works in dev and 404s in production.
86
+ *
87
+ * The exports are found by scanning the SOURCE rather than importing it - importing would execute the
88
+ * module, which is precisely what must not happen in a client build - and the declaration form is fixed:
89
+ *
90
+ * export const addTodo = serverFn({ … }, async (input, c) => { … })
91
+ *
92
+ * Anything else is refused rather than skipped: a server function the scanner cannot see would be absent
93
+ * from the client and fail as `addTodo is not a function` at runtime, far from the cause.
94
+ */
95
+
96
+ /** `export const NAME = serverFn(` at the start of a line - the one declaration form. */
97
+ const DECLARATION = /^[\t ]*export\s+const\s+([A-Za-z_$][\w$]*)\s*=\s*serverFn\s*\(/gm
98
+ /** Any mention of `serverFn(` as a call, used to prove nothing was missed. */
99
+ const ANY_CALL = /\bserverFn\s*\(/g
100
+ /** Line comments and block comments, stripped before scanning so prose cannot register as code. */
101
+ const COMMENTS = /\/\*[\s\S]*?\*\/|(^|[^:])\/\/.*$/gm
102
+
103
+ /**
104
+ * The namespace a `*.fn.ts` module is mounted under: its filename without the `.fn` suffix.
105
+ *
106
+ * Deriving it from the filename rather than the full path keeps the build machine's directory layout
107
+ * out of a public URL, and keeps the route readable in logs. It also means the mount on the server -
108
+ * `serverFunctions("todos", …)` - has to use the same word, which is the one thing a reader must check
109
+ * by eye today; {@link SERVER_FN_MODULE} files are named for it precisely to make that obvious.
110
+ */
111
+ export function serverFnNamespace(filePath: string): string {
112
+ const base = filePath.replaceAll("\\", "/").split("/").pop() ?? ""
113
+ return base.replace(SERVER_FN_MODULE, "")
114
+ }
115
+
116
+ /** The server functions a module declares, in source order. */
117
+ export function scanServerFnExports(source: string): string[] {
118
+ const code = source.replaceAll(COMMENTS, "$1")
119
+ const names = [...code.matchAll(DECLARATION)].map((m) => m[1] as string)
120
+ const calls = [...code.matchAll(ANY_CALL)].length
121
+ if (calls > names.length) {
122
+ throw new Error(
123
+ "[nifra/fn] a server function is declared in a form the client transform cannot read. Use " +
124
+ "`export const name = serverFn(…)` at the top level: the client build scans the source rather " +
125
+ "than importing it (importing would run your server code during a browser build), so a " +
126
+ "declaration it cannot see would be missing from the client and fail as `name is not a function`.",
127
+ )
128
+ }
129
+ return names
130
+ }
131
+
132
+ /**
133
+ * The client replacement for a `*.fn.ts` module: one stub per export, and none of the original code.
134
+ *
135
+ * `credentials: "same-origin"` is explicit rather than relied upon - the server refuses a cross-origin
136
+ * call, and stating it here means the browser never sends cookies somewhere that would reject them.
137
+ * The content type is not decoration either: it is what makes a cross-origin form unable to forge one
138
+ * of these calls, so the stub and the server guard have to agree on it.
139
+ */
140
+ export function generateServerFnStub(source: string, namespace: string): string {
141
+ const names = scanServerFnExports(source)
142
+ const calls = names
143
+ .map((name) => `export const ${name} = (input) => __nifraCall(${JSON.stringify(name)}, input)`)
144
+ .join("\n")
145
+ return `// Generated by @nifrajs/web: the server half of this module never reaches the browser.
146
+ const __nifraBase = ${JSON.stringify(`/_nifra/fn/${namespace}`)}
147
+
148
+ async function __nifraCall(name, input) {
149
+ const response = await fetch(\`\${__nifraBase}/\${name}\`, {
150
+ method: "POST",
151
+ headers: { "content-type": "application/json" },
152
+ body: JSON.stringify(input === undefined ? {} : input),
153
+ credentials: "same-origin",
154
+ })
155
+ if (response.status === 404) {
156
+ throw new Error(
157
+ \`[nifra/fn] \${name} is not mounted at \${__nifraBase}. The client derives that path from this \` +
158
+ \`file's name, so the server's serverFunctions(...) namespace has to match it.\`,
159
+ )
160
+ }
161
+ if (!response.ok) {
162
+ let detail = ""
163
+ try {
164
+ detail = JSON.stringify(await response.json())
165
+ } catch {
166
+ // A non-JSON error body is not worth a second failure; the status carries enough.
167
+ }
168
+ throw new Error(\`[nifra/fn] \${name} failed: \${response.status}\${detail ? \` \${detail}\` : ""}\`)
169
+ }
170
+ return response.status === 204 ? undefined : await response.json()
171
+ }
172
+
173
+ ${calls}
174
+ `
175
+ }
176
+
177
+ // ---------------------------------------------------------------------------------------------------
178
+ // public-env - which environment variables the client bundle may inline.
179
+ // ---------------------------------------------------------------------------------------------------
180
+
181
+ /** Translate Nifra's public-env contract to Vite's `envPrefix` option. */
182
+ export function vitePublicEnvPrefix(prefix: string | undefined): string {
183
+ const configured = prefix ?? "PUBLIC_"
184
+ // Vite rejects an empty prefix. Environment-variable names cannot contain NUL, so this sentinel
185
+ // cannot match an ambient key and faithfully represents Nifra's "expose nothing" setting.
186
+ return configured === "" ? "\0nifra-public-env-disabled" : configured
187
+ }
@@ -2,7 +2,7 @@
2
2
  * Constant-time string equality, shared by every secret check in `@nifrajs/web`. Internal: no
3
3
  * `exports` entry points here, so it never becomes public API.
4
4
  *
5
- * One owner per package rather than a copy per call site — this is the primitive whose whole value
5
+ * One owner per package rather than a copy per call site - this is the primitive whose whole value
6
6
  * lies in a detail (no early exit) that a well-meaning "simplification" silently removes, and a bug
7
7
  * in it is invisible in review and in tests, since a timing-unsafe compare returns the same answers.
8
8
  */
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The one place nifra imports Vite from.
3
+ *
4
+ * ## Why this is a module and not two `await import("vite")` calls
5
+ *
6
+ * Vite must not be imported before {@link relaxCaptureStackTrace} has run, and that requirement is
7
+ * invisible at the call site. It was invisible in exactly the way that matters: the production build
8
+ * relaxed first, the dev server did not, and the dev server's import ran earlier in the test process.
9
+ * ESM caches a module that throws while EVALUATING, so once vite failed there it kept failing - every
10
+ * later `loadVite` re-threw the cached error, with its shim correctly installed and no longer able to
11
+ * help. One unguarded import poisons vite for the whole process.
12
+ *
13
+ * So the import lives here and the guard is not optional. A caller cannot get the module without it.
14
+ */
15
+
16
+ /** Marks the shim as installed, so repeated imports do not wrap a wrapper. */
17
+ const RELAXED: unique symbol = Symbol.for("@nifrajs/web/relaxed-capture-stack-trace")
18
+
19
+ /**
20
+ * Restore V8's `Error.captureStackTrace` contract on a runtime that is stricter than it.
21
+ *
22
+ * `captureStackTrace` is a V8 API and V8 decorates ANY object handed to it. Some runtimes require a
23
+ * real Error - one with the internal slot - and throw "First argument must be an Error object".
24
+ *
25
+ * That breaks importing vite outright. Vite bundles `follow-redirects`, which builds its error types
26
+ * the pre-class way:
27
+ *
28
+ * function CustomError(props) { Error.captureStackTrace(this, this.constructor); … }
29
+ * CustomError.prototype = new (baseClass || Error)()
30
+ *
31
+ * The last line CONSTRUCTS `baseClass` while defining the subclass, so `this` inherits from Error but
32
+ * was never built by it - and the throw lands during module evaluation, before vite exports anything.
33
+ *
34
+ * Decorating a stack is best-effort by definition, so swallowing the refusal loses nothing: the shim
35
+ * delegates and suppresses only that. Installed once and deliberately not restored, since the strict
36
+ * behaviour is the deviation and a library evaluated later meets the same wall.
37
+ *
38
+ * ## Why it does not probe first
39
+ *
40
+ * It used to construct an object like follow-redirects' and install the shim only if the runtime
41
+ * refused it. That shipped and CI still failed, because the probe was not the same shape as the real
42
+ * call: it passed `Object.create(Error.prototype)` and no `constructorOpt`, while follow-redirects
43
+ * passes an object whose prototype is an Error INSTANCE plus `this.constructor`. One Bun build accepts
44
+ * the former and rejects the latter, so the probe reported "permissive" and installed nothing.
45
+ *
46
+ * A probe has to predict every caller's construction pattern to be right, and is silently wrong when
47
+ * it guesses short. Installing unconditionally cannot fail that way.
48
+ */
49
+ export function relaxCaptureStackTrace(): void {
50
+ const strict = Error.captureStackTrace
51
+ if (typeof strict !== "function") return
52
+ if ((Error as unknown as Record<PropertyKey, unknown>)[RELAXED] === true) return
53
+ try {
54
+ Error.captureStackTrace = ((target: object, constructorOpt?: unknown) => {
55
+ try {
56
+ ;(strict as (t: object, c?: unknown) => void).call(Error, target, constructorOpt)
57
+ } catch {
58
+ // The runtime refused to decorate this object. A missing `.stack` is not worth failing over.
59
+ }
60
+ }) as typeof Error.captureStackTrace
61
+ Object.defineProperty(Error, RELAXED, { value: true, configurable: true })
62
+ } catch {
63
+ // The property is frozen or non-writable. Nothing can be done about the import that follows, but
64
+ // failing HERE would replace vite's own error with an assignment error - strictly less
65
+ // informative than letting the import fail and be reported by the caller.
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Import the project's Vite, with the stack-trace contract restored first.
71
+ *
72
+ * Callers keep their own error message - the dev server and the production build fail for the same
73
+ * reasons but need to say different things - so this deliberately lets the cause through untouched.
74
+ * Use {@link isViteUnresolved} to tell "vite is not installed" from "vite failed to load".
75
+ */
76
+ export async function importVite<T>(): Promise<T> {
77
+ relaxCaptureStackTrace()
78
+ return (await import("vite")) as unknown as T
79
+ }
80
+
81
+ /**
82
+ * Whether a failed {@link importVite} means vite is absent rather than broken.
83
+ *
84
+ * `vite` is an OPTIONAL peer, so a project without it fails to RESOLVE - the common case, and the one
85
+ * worth naming. But vite can also resolve and fail while EVALUATING, which is not a missing dependency
86
+ * at all: vite 8 loads rolldown's native binding on import, and a binding that will not load surfaces
87
+ * the same way. Telling that user to install what they already installed sends them the wrong way.
88
+ */
89
+ export function isViteUnresolved(cause: unknown): boolean {
90
+ const message = cause instanceof Error ? cause.message : String(cause)
91
+ return /cannot find (?:package|module)|ERR_MODULE_NOT_FOUND/i.test(message)
92
+ }
package/src/islands.ts CHANGED
@@ -1,16 +1,16 @@
1
1
  /**
2
- * @nifrajs/web/islands — the framework-agnostic islands client runtime.
2
+ * @nifrajs/web/islands - the framework-agnostic islands client runtime.
3
3
  *
4
4
  * An "island" is a server-rendered `<nifra-island>` element whose interactivity is mounted by a small
5
5
  * **plain-DOM** enhancer instead of a framework runtime. On a route that opts out of full-document
6
6
  * hydration (`export const hydrate = false`), the page ships **zero** framework JS; only the island
7
7
  * bundle (this runtime + your enhancers) loads. This variant ships ~99% less client JS than full
8
- * React hydration on a mostly-static page — the framework runtime is the cost, and islands skip it
8
+ * React hydration on a mostly-static page - the framework runtime is the cost, and islands skip it
9
9
  * entirely here.
10
10
  *
11
11
  * Server side: render the marker with `@nifrajs/web-react`'s `<Island>` (or any framework's host element
12
12
  * `<nifra-island data-id data-strategy data-props>`). Props are JSON-encoded inline in `data-props`
13
- * (attribute-escaped by the framework) — no central registry, so concurrent SSR renders never share
13
+ * (attribute-escaped by the framework) - no central registry, so concurrent SSR renders never share
14
14
  * state. Client side: bundle one entry that calls `mountIslands({ <id>: enhancer })` and load it via
15
15
  * the route's `islandScripts`.
16
16
  */
@@ -23,10 +23,10 @@ export type IslandCleanup = () => void
23
23
 
24
24
  /**
25
25
  * Enhances one island element with its (typed) props. Return a cleanup function to tear down on
26
- * `dispose()` (listeners, observers) — optional; an enhancer with nothing to clean up returns nothing.
26
+ * `dispose()` (listeners, observers) - optional; an enhancer with nothing to clean up returns nothing.
27
27
  * The `void` member is the no-cleanup case, the same shape as React's `EffectCallback`.
28
28
  */
29
- // biome-ignore lint/suspicious/noConfusingVoidType: `void` = "no cleanup returned", like React's EffectCallback — cleanup is optional.
29
+ // biome-ignore lint/suspicious/noConfusingVoidType: `void` = "no cleanup returned", like React's EffectCallback - cleanup is optional.
30
30
  export type IslandEnhancer<P = unknown> = (el: HTMLElement, props: P) => IslandCleanup | void
31
31
 
32
32
  const NOOP = (): void => {}
@@ -79,7 +79,7 @@ function whenStrategy(el: HTMLElement, strategy: IslandStrategy, run: () => void
79
79
  /**
80
80
  * Find every `<nifra-island data-id>` under `root` (default `document`) and enhance each with the
81
81
  * matching enhancer, honoring its `data-strategy`. An island whose `id` has no enhancer is left as
82
- * inert SSR HTML (forward-compatible). An enhancer that throws is isolated — it never blocks the
82
+ * inert SSR HTML (forward-compatible). An enhancer that throws is isolated - it never blocks the
83
83
  * others (each island is independent). Returns a disposer that cancels pending triggers and runs every
84
84
  * enhancer's cleanup (call it on soft-nav teardown; harmless if your app never navigates).
85
85
  */
@@ -114,7 +114,7 @@ export function mountIslands(
114
114
  try {
115
115
  dispose()
116
116
  } catch {
117
- // best-effort teardown — a failing cleanup must not block the rest
117
+ // best-effort teardown - a failing cleanup must not block the rest
118
118
  }
119
119
  }
120
120
  }
package/src/isr.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  import { isDraftEnabled } from "./draft.ts"
10
10
  import { timingSafeEqual } from "./internal/timing-safe-equal.ts"
11
11
 
12
- /** A cached SSR response — the bytes + metadata a {@link CacheStore} persists. */
12
+ /** A cached SSR response - the bytes + metadata a {@link CacheStore} persists. */
13
13
  export interface CachedResponse {
14
14
  /** The rendered document (UTF-8 HTML, fully buffered). */
15
15
  readonly body: string
@@ -38,7 +38,7 @@ export interface CacheStore {
38
38
  }
39
39
 
40
40
  export interface MemoryCacheStoreOptions {
41
- /** Allow the in-memory store in production. Off by default — per-instance caching means revalidation
41
+ /** Allow the in-memory store in production. Off by default - per-instance caching means revalidation
42
42
  * won't propagate across instances and each instance caches separately. */
43
43
  readonly allowInProduction?: boolean
44
44
  /** Hard cap on entries; the least-recently-used is evicted past it (default 500). */
@@ -47,7 +47,7 @@ export interface MemoryCacheStoreOptions {
47
47
 
48
48
  /**
49
49
  * In-process ISR cache. Refuses to run in production unless explicitly allowed (mirrors the
50
- * rate-limit `MemoryStore` — a per-instance cache is unsafe across instances). Bounded **LRU**: a
50
+ * rate-limit `MemoryStore` - a per-instance cache is unsafe across instances). Bounded **LRU**: a
51
51
  * read or write bumps the entry, so the least-recently-used evicts past `max` (a hot, frequently-read
52
52
  * page survives a burst of new pages).
53
53
  */
@@ -70,7 +70,7 @@ export class MemoryCacheStore implements CacheStore {
70
70
  get(key: string): Promise<CachedResponse | undefined> {
71
71
  const value = this.cache.get(key)
72
72
  // LRU: a read bumps the entry to the tail so the bounded evict drops the LEAST-RECENTLY-USED,
73
- // not the oldest-written — otherwise a burst of new pages would evict a hot, frequently-read one.
73
+ // not the oldest-written - otherwise a burst of new pages would evict a hot, frequently-read one.
74
74
  if (value !== undefined) {
75
75
  this.cache.delete(key)
76
76
  this.cache.set(key, value)
@@ -96,7 +96,7 @@ export class MemoryCacheStore implements CacheStore {
96
96
  }
97
97
 
98
98
  /**
99
- * Minimal structural shape of a Cloudflare Workers **KV namespace** binding — just the three methods
99
+ * Minimal structural shape of a Cloudflare Workers **KV namespace** binding - just the three methods
100
100
  * {@link KVCacheStore} uses. Structural (not a dependency on `@cloudflare/workers-types`) so any
101
101
  * KV-like binding satisfies it and tests can pass an in-memory double.
102
102
  */
@@ -112,9 +112,9 @@ export interface KVNamespaceLike {
112
112
  export interface KVCacheStoreOptions {
113
113
  /**
114
114
  * GC backstop (**seconds**) written as the KV entry's `expirationTtl`, so abandoned entries
115
- * eventually evict. MUST exceed your longest `revalidate` window — otherwise KV expiry turns a
115
+ * eventually evict. MUST exceed your longest `revalidate` window - otherwise KV expiry turns a
116
116
  * stale-while-revalidate into a *blocking* miss (the entry vanishes instead of being served stale
117
- * while it regenerates) — and be ≥ 60 (Cloudflare KV's minimum). Omit ⇒ entries persist until
117
+ * while it regenerates) - and be ≥ 60 (Cloudflare KV's minimum). Omit ⇒ entries persist until
118
118
  * overwritten on regeneration or purged via `revalidateEndpoint`.
119
119
  */
120
120
  readonly expirationTtl?: number
@@ -146,7 +146,7 @@ const isCachedResponse = (value: unknown): value is CachedResponse => {
146
146
 
147
147
  /**
148
148
  * A {@link CacheStore} backed by a **Cloudflare Workers KV** namespace (or any {@link KVNamespaceLike}
149
- * binding) — the production-grade shared/durable store ISR wants: cached pages and on-demand purges
149
+ * binding) - the production-grade shared/durable store ISR wants: cached pages and on-demand purges
150
150
  * hold *across* worker instances (unlike the per-instance {@link MemoryCacheStore}). Entries serialize
151
151
  * to JSON; every read is validated before it's trusted (a malformed/version-skewed entry is treated as
152
152
  * a miss). Construct it in your Workers `fetch` from the binding: `new KVCacheStore(env.ISR_CACHE)`.
@@ -191,13 +191,13 @@ export class KVCacheStore implements CacheStore {
191
191
  }
192
192
  }
193
193
 
194
- /** Minimal platform shape `withISR` needs — just `waitUntil` (edge runtimes extend the response
194
+ /** Minimal platform shape `withISR` needs - just `waitUntil` (edge runtimes extend the response
195
195
  * lifetime so background regeneration finishes). Off-edge it's absent and regen runs fire-and-forget. */
196
196
  export interface ISRPlatform {
197
197
  readonly waitUntil?: (promise: Promise<unknown>) => void
198
198
  }
199
199
 
200
- /** The app `withISR` wraps — anything with a `fetch(req, platform?)` (a `createWebApp` result). */
200
+ /** The app `withISR` wraps - anything with a `fetch(req, platform?)` (a `createWebApp` result). */
201
201
  export interface ISRApp {
202
202
  fetch(req: Request, platform?: ISRPlatform): Response | Promise<Response>
203
203
  }
@@ -208,7 +208,7 @@ export const ISR_STATUS_HEADER = "x-nifra-isr"
208
208
 
209
209
  /**
210
210
  * Response header a route uses to advertise its ISR freshness (**seconds**) to a {@link withISR}
211
- * wrapper — `createWebApp` emits it from a route's `export const revalidate`. Deliberately distinct
211
+ * wrapper - `createWebApp` emits it from a route's `export const revalidate`. Deliberately distinct
212
212
  * from the action-revalidation `x-nifra-revalidate` header (a CSV path list the *client* parses to
213
213
  * refetch): this one is an integer TTL the *wrapper* reads, so the two channels never alias.
214
214
  */
@@ -220,14 +220,14 @@ export interface ISROptions {
220
220
  * behind). A route overrides it per-page via `export const revalidate` (surfaced as the
221
221
  * `x-nifra-isr-revalidate` response header). */
222
222
  readonly revalidate: number
223
- /** Monotonic clock (ms) — injected for testability; production passes `() => Date.now()`. */
223
+ /** Monotonic clock (ms) - injected for testability; production passes `() => Date.now()`. */
224
224
  readonly now: () => number
225
225
  /** Cache key for a request. Default: `origin + pathname + search` so host-routed apps do not share
226
226
  * entries across tenants. Return `null` to bypass the cache for this request (it goes straight to the
227
227
  * app, uncached). */
228
228
  readonly key?: (req: Request) => string | null
229
229
  /** Draft/preview secret (the same one given to `createWebApp({ draftSecret })` + `enableDraft`). When
230
- * set, a request carrying a valid signed draft cookie **bypasses the cache** — editors always render
230
+ * set, a request carrying a valid signed draft cookie **bypasses the cache** - editors always render
231
231
  * fresh, and a draft render is never written to the store (it can't poison the public cache). */
232
232
  readonly draftSecret?: string
233
233
  }
@@ -307,7 +307,7 @@ function sanitizeCachedHeaders(headers: Readonly<Record<string, string>>): Recor
307
307
  * Wrap a nifra app with **Incremental Static Regeneration**: a cacheable page is served from
308
308
  * {@link CacheStore} when fresh, served **stale while a fresh copy regenerates in the background**
309
309
  * (`platform.waitUntil` on edge), or rendered + stored on a miss. Framework-agnostic (it caches the
310
- * rendered bytes). Returns a `fetch(req, platform?)` handler — hand it to `Bun.serve`/the Workers
310
+ * rendered bytes). Returns a `fetch(req, platform?)` handler - hand it to `Bun.serve`/the Workers
311
311
  * `export default`, etc. Regeneration is single-flight per key (no stampede on a hot stale page).
312
312
  *
313
313
  * Each route's freshness comes from the `revalidate` header the app sets (per-route
@@ -352,7 +352,7 @@ export function withISR(
352
352
  })
353
353
  }
354
354
 
355
- // Background regeneration (single-flight per key) — a failed regen keeps the stale entry; the next
355
+ // Background regeneration (single-flight per key) - a failed regen keeps the stale entry; the next
356
356
  // stale hit retries. Never throws (it runs detached / under waitUntil).
357
357
  const regenerate = async (
358
358
  req: Request,
@@ -413,13 +413,13 @@ export interface RevalidateEndpointOptions {
413
413
  readonly secret: string
414
414
  /** Header carrying the secret. Default `x-nifra-revalidate-token`. */
415
415
  readonly tokenHeader?: string
416
- /** Map a to-purge path → its cache key — MUST match the `withISR` `key` fn. The default uses the
416
+ /** Map a to-purge path → its cache key - MUST match the `withISR` `key` fn. The default uses the
417
417
  * revalidation request's origin plus the purged path, matching `withISR`'s default host-aware key. */
418
418
  readonly key?: (path: string, req: Request) => string
419
419
  }
420
420
 
421
421
  /**
422
- * An **on-demand revalidation** (purge) endpoint — a `fetch` handler that drops a path's cached entry
422
+ * An **on-demand revalidation** (purge) endpoint - a `fetch` handler that drops a path's cached entry
423
423
  * so the next request re-renders. `POST` with the secret in the token header and the path as `?path=`
424
424
  * or a JSON `{ "path": "/blog/x" }` body. The token is checked in **constant time** (wrong/missing →
425
425
  * `401`); a missing/relative path → `400`; non-POST → `405`. Mount it on a nifra route, e.g.