@nifrajs/web 2.1.0 → 2.3.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 (194) hide show
  1. package/README.md +3 -3
  2. package/dist/build-vite.d.ts +68 -0
  3. package/dist/build-vite.d.ts.map +1 -0
  4. package/dist/build-vite.js +433 -0
  5. package/dist/build-vite.js.map +1 -0
  6. package/dist/build.d.ts +174 -65
  7. package/dist/build.d.ts.map +1 -1
  8. package/dist/build.js +376 -135
  9. package/dist/build.js.map +1 -1
  10. package/dist/bun-dev-entry.d.ts +83 -0
  11. package/dist/bun-dev-entry.d.ts.map +1 -0
  12. package/dist/bun-dev-entry.js +136 -0
  13. package/dist/bun-dev-entry.js.map +1 -0
  14. package/dist/chunk-names.js +1 -1
  15. package/dist/client.d.ts +3 -9
  16. package/dist/client.d.ts.map +1 -1
  17. package/dist/client.js +209 -27
  18. package/dist/client.js.map +1 -1
  19. package/dist/conformance.d.ts +2 -2
  20. package/dist/conformance.js +3 -3
  21. package/dist/deferred.d.ts +11 -11
  22. package/dist/deferred.d.ts.map +1 -1
  23. package/dist/deferred.js +16 -16
  24. package/dist/dev-error.d.ts +2 -2
  25. package/dist/dev-error.js +3 -3
  26. package/dist/dev-port.d.ts +36 -0
  27. package/dist/dev-port.d.ts.map +1 -0
  28. package/dist/dev-port.js +48 -0
  29. package/dist/dev-port.js.map +1 -0
  30. package/dist/dev.d.ts +62 -5
  31. package/dist/dev.d.ts.map +1 -1
  32. package/dist/dev.js +419 -60
  33. package/dist/dev.js.map +1 -1
  34. package/dist/draft.d.ts +44 -7
  35. package/dist/draft.d.ts.map +1 -1
  36. package/dist/draft.js +92 -9
  37. package/dist/draft.js.map +1 -1
  38. package/dist/fn-state.d.ts +56 -0
  39. package/dist/fn-state.d.ts.map +1 -0
  40. package/dist/fn-state.js +77 -0
  41. package/dist/fn-state.js.map +1 -0
  42. package/dist/fn.d.ts +111 -0
  43. package/dist/fn.d.ts.map +1 -0
  44. package/dist/fn.js +125 -0
  45. package/dist/fn.js.map +1 -0
  46. package/dist/fonts-google.d.ts +9 -9
  47. package/dist/fonts-google.js +10 -10
  48. package/dist/fonts.d.ts +7 -7
  49. package/dist/fonts.js +1 -1
  50. package/dist/forms.d.ts +8 -8
  51. package/dist/fs.d.ts +15 -2
  52. package/dist/fs.d.ts.map +1 -1
  53. package/dist/fs.js +8 -2
  54. package/dist/fs.js.map +1 -1
  55. package/dist/index.d.ts +266 -74
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +869 -179
  58. package/dist/index.js.map +1 -1
  59. package/dist/internal/head-attributes.d.ts +15 -0
  60. package/dist/internal/head-attributes.d.ts.map +1 -0
  61. package/dist/internal/head-attributes.js +99 -0
  62. package/dist/internal/head-attributes.js.map +1 -0
  63. package/dist/internal/script-types.d.ts +14 -0
  64. package/dist/internal/script-types.d.ts.map +1 -0
  65. package/dist/internal/script-types.js +17 -0
  66. package/dist/internal/script-types.js.map +1 -0
  67. package/dist/internal/server-boundary.d.ts +60 -0
  68. package/dist/internal/server-boundary.d.ts.map +1 -0
  69. package/dist/internal/server-boundary.js +174 -0
  70. package/dist/internal/server-boundary.js.map +1 -0
  71. package/dist/internal/timing-safe-equal.d.ts +16 -0
  72. package/dist/internal/timing-safe-equal.d.ts.map +1 -0
  73. package/dist/internal/timing-safe-equal.js +26 -0
  74. package/dist/internal/timing-safe-equal.js.map +1 -0
  75. package/dist/internal/vite-import.d.ts +63 -0
  76. package/dist/internal/vite-import.d.ts.map +1 -0
  77. package/dist/internal/vite-import.js +94 -0
  78. package/dist/internal/vite-import.js.map +1 -0
  79. package/dist/islands.d.ts +5 -5
  80. package/dist/islands.js +5 -5
  81. package/dist/isr.d.ts +15 -15
  82. package/dist/isr.d.ts.map +1 -1
  83. package/dist/isr.js +8 -21
  84. package/dist/isr.js.map +1 -1
  85. package/dist/llms-txt.d.ts.map +1 -1
  86. package/dist/llms-txt.js +12 -6
  87. package/dist/llms-txt.js.map +1 -1
  88. package/dist/manifest.d.ts +121 -40
  89. package/dist/manifest.d.ts.map +1 -1
  90. package/dist/manifest.js +136 -26
  91. package/dist/manifest.js.map +1 -1
  92. package/dist/module-graph.d.ts +91 -0
  93. package/dist/module-graph.d.ts.map +1 -0
  94. package/dist/module-graph.js +92 -0
  95. package/dist/module-graph.js.map +1 -0
  96. package/dist/navigation.d.ts +120 -5
  97. package/dist/navigation.d.ts.map +1 -1
  98. package/dist/navigation.js +37 -5
  99. package/dist/navigation.js.map +1 -1
  100. package/dist/plugins/css-modules.d.ts +3 -3
  101. package/dist/plugins/css-modules.d.ts.map +1 -1
  102. package/dist/plugins/css-modules.js +0 -0
  103. package/dist/plugins/css-modules.js.map +1 -1
  104. package/dist/plugins/kit.d.ts +8 -8
  105. package/dist/plugins/kit.js +9 -9
  106. package/dist/plugins/scss.js +3 -3
  107. package/dist/plugins/vite-leak-guard.d.ts +45 -0
  108. package/dist/plugins/vite-leak-guard.d.ts.map +1 -0
  109. package/dist/plugins/vite-leak-guard.js +67 -0
  110. package/dist/plugins/vite-leak-guard.js.map +1 -0
  111. package/dist/plugins/vite-server-fn.d.ts +23 -0
  112. package/dist/plugins/vite-server-fn.d.ts.map +1 -0
  113. package/dist/plugins/vite-server-fn.js +51 -0
  114. package/dist/plugins/vite-server-fn.js.map +1 -0
  115. package/dist/plugins/vite-server-only.d.ts +49 -0
  116. package/dist/plugins/vite-server-only.d.ts.map +1 -0
  117. package/dist/plugins/vite-server-only.js +57 -0
  118. package/dist/plugins/vite-server-only.js.map +1 -0
  119. package/dist/prerender.d.ts +5 -5
  120. package/dist/prerender.js +7 -7
  121. package/dist/public-dir.d.ts +36 -0
  122. package/dist/public-dir.d.ts.map +1 -0
  123. package/dist/public-dir.js +89 -0
  124. package/dist/public-dir.js.map +1 -0
  125. package/dist/query.d.ts +10 -10
  126. package/dist/query.js +15 -15
  127. package/dist/route-manifest.d.ts +91 -0
  128. package/dist/route-manifest.d.ts.map +1 -0
  129. package/dist/route-manifest.js +128 -0
  130. package/dist/route-manifest.js.map +1 -0
  131. package/dist/router.d.ts +94 -22
  132. package/dist/router.d.ts.map +1 -1
  133. package/dist/router.js +170 -58
  134. package/dist/router.js.map +1 -1
  135. package/dist/search.d.ts +94 -0
  136. package/dist/search.d.ts.map +1 -0
  137. package/dist/search.js +232 -0
  138. package/dist/search.js.map +1 -0
  139. package/dist/server-only.d.ts +6 -6
  140. package/dist/server-only.js +7 -7
  141. package/dist/service-worker.d.ts +56 -0
  142. package/dist/service-worker.d.ts.map +1 -0
  143. package/dist/service-worker.js +127 -0
  144. package/dist/service-worker.js.map +1 -0
  145. package/dist/vite.d.ts +25 -17
  146. package/dist/vite.d.ts.map +1 -1
  147. package/dist/vite.js +75 -33
  148. package/dist/vite.js.map +1 -1
  149. package/package.json +48 -4
  150. package/server-manifest.d.ts +31 -0
  151. package/src/build-vite.ts +553 -0
  152. package/src/build.ts +563 -172
  153. package/src/bun-dev-entry.ts +184 -0
  154. package/src/chunk-names.ts +1 -1
  155. package/src/client.ts +221 -30
  156. package/src/conformance.ts +3 -3
  157. package/src/deferred.ts +17 -17
  158. package/src/dev-error.ts +3 -3
  159. package/src/dev-port.ts +63 -0
  160. package/src/dev.ts +468 -66
  161. package/src/draft.ts +124 -12
  162. package/src/fn-state.ts +107 -0
  163. package/src/fn.ts +199 -0
  164. package/src/fonts-google.ts +13 -13
  165. package/src/fonts.ts +7 -7
  166. package/src/forms.ts +8 -8
  167. package/src/fs.ts +24 -6
  168. package/src/index.ts +1174 -225
  169. package/src/internal/head-attributes.ts +109 -0
  170. package/src/internal/script-types.ts +18 -0
  171. package/src/internal/server-boundary.ts +187 -0
  172. package/src/internal/timing-safe-equal.ts +24 -0
  173. package/src/internal/vite-import.ts +92 -0
  174. package/src/islands.ts +7 -7
  175. package/src/isr.ts +18 -30
  176. package/src/llms-txt.ts +13 -5
  177. package/src/manifest.ts +264 -48
  178. package/src/module-graph.ts +146 -0
  179. package/src/navigation.ts +151 -5
  180. package/src/plugins/css-modules.ts +0 -0
  181. package/src/plugins/kit.ts +11 -11
  182. package/src/plugins/scss.ts +3 -3
  183. package/src/plugins/vite-leak-guard.ts +110 -0
  184. package/src/plugins/vite-server-fn.ts +67 -0
  185. package/src/plugins/vite-server-only.ts +75 -0
  186. package/src/prerender.ts +10 -10
  187. package/src/public-dir.ts +108 -0
  188. package/src/query.ts +22 -22
  189. package/src/route-manifest.ts +240 -0
  190. package/src/router.ts +288 -74
  191. package/src/search.ts +297 -0
  192. package/src/server-only.ts +7 -7
  193. package/src/service-worker.ts +165 -0
  194. package/src/vite.ts +103 -49
@@ -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
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Constant-time string equality, shared by every secret check in `@nifrajs/web`. Internal: no
3
+ * `exports` entry points here, so it never becomes public API.
4
+ *
5
+ * One owner per package rather than a copy per call site - this is the primitive whose whole value
6
+ * lies in a detail (no early exit) that a well-meaning "simplification" silently removes, and a bug
7
+ * in it is invisible in review and in tests, since a timing-unsafe compare returns the same answers.
8
+ */
9
+
10
+ /**
11
+ * Compare two strings without leaking, via timing, where they first differ. A length mismatch returns
12
+ * `false` up front: the length isn't the secret, and different-length buffers can't be compared in
13
+ * constant time anyway. Encodes to bytes first so multi-byte characters compare by content, not by
14
+ * UTF-16 code unit.
15
+ */
16
+ export function timingSafeEqual(a: string, b: string): boolean {
17
+ const enc = new TextEncoder()
18
+ const ba = enc.encode(a)
19
+ const bb = enc.encode(b)
20
+ if (ba.length !== bb.length) return false
21
+ let diff = 0
22
+ for (let i = 0; i < ba.length; i++) diff |= (ba[i] as number) ^ (bb[i] as number)
23
+ return diff === 0
24
+ }
@@ -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
@@ -7,8 +7,9 @@
7
7
  * This module is the store primitive; the SWR wrapper (`withISR`) builds on it next.
8
8
  */
9
9
  import { isDraftEnabled } from "./draft.ts"
10
+ import { timingSafeEqual } from "./internal/timing-safe-equal.ts"
10
11
 
11
- /** A cached SSR response — the bytes + metadata a {@link CacheStore} persists. */
12
+ /** A cached SSR response - the bytes + metadata a {@link CacheStore} persists. */
12
13
  export interface CachedResponse {
13
14
  /** The rendered document (UTF-8 HTML, fully buffered). */
14
15
  readonly body: string
@@ -37,7 +38,7 @@ export interface CacheStore {
37
38
  }
38
39
 
39
40
  export interface MemoryCacheStoreOptions {
40
- /** 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
41
42
  * won't propagate across instances and each instance caches separately. */
42
43
  readonly allowInProduction?: boolean
43
44
  /** Hard cap on entries; the least-recently-used is evicted past it (default 500). */
@@ -46,7 +47,7 @@ export interface MemoryCacheStoreOptions {
46
47
 
47
48
  /**
48
49
  * In-process ISR cache. Refuses to run in production unless explicitly allowed (mirrors the
49
- * 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
50
51
  * read or write bumps the entry, so the least-recently-used evicts past `max` (a hot, frequently-read
51
52
  * page survives a burst of new pages).
52
53
  */
@@ -69,7 +70,7 @@ export class MemoryCacheStore implements CacheStore {
69
70
  get(key: string): Promise<CachedResponse | undefined> {
70
71
  const value = this.cache.get(key)
71
72
  // LRU: a read bumps the entry to the tail so the bounded evict drops the LEAST-RECENTLY-USED,
72
- // 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.
73
74
  if (value !== undefined) {
74
75
  this.cache.delete(key)
75
76
  this.cache.set(key, value)
@@ -95,7 +96,7 @@ export class MemoryCacheStore implements CacheStore {
95
96
  }
96
97
 
97
98
  /**
98
- * 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
99
100
  * {@link KVCacheStore} uses. Structural (not a dependency on `@cloudflare/workers-types`) so any
100
101
  * KV-like binding satisfies it and tests can pass an in-memory double.
101
102
  */
@@ -111,9 +112,9 @@ export interface KVNamespaceLike {
111
112
  export interface KVCacheStoreOptions {
112
113
  /**
113
114
  * GC backstop (**seconds**) written as the KV entry's `expirationTtl`, so abandoned entries
114
- * 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
115
116
  * stale-while-revalidate into a *blocking* miss (the entry vanishes instead of being served stale
116
- * 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
117
118
  * overwritten on regeneration or purged via `revalidateEndpoint`.
118
119
  */
119
120
  readonly expirationTtl?: number
@@ -145,7 +146,7 @@ const isCachedResponse = (value: unknown): value is CachedResponse => {
145
146
 
146
147
  /**
147
148
  * A {@link CacheStore} backed by a **Cloudflare Workers KV** namespace (or any {@link KVNamespaceLike}
148
- * 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
149
150
  * hold *across* worker instances (unlike the per-instance {@link MemoryCacheStore}). Entries serialize
150
151
  * to JSON; every read is validated before it's trusted (a malformed/version-skewed entry is treated as
151
152
  * a miss). Construct it in your Workers `fetch` from the binding: `new KVCacheStore(env.ISR_CACHE)`.
@@ -190,13 +191,13 @@ export class KVCacheStore implements CacheStore {
190
191
  }
191
192
  }
192
193
 
193
- /** 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
194
195
  * lifetime so background regeneration finishes). Off-edge it's absent and regen runs fire-and-forget. */
195
196
  export interface ISRPlatform {
196
197
  readonly waitUntil?: (promise: Promise<unknown>) => void
197
198
  }
198
199
 
199
- /** 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). */
200
201
  export interface ISRApp {
201
202
  fetch(req: Request, platform?: ISRPlatform): Response | Promise<Response>
202
203
  }
@@ -207,7 +208,7 @@ export const ISR_STATUS_HEADER = "x-nifra-isr"
207
208
 
208
209
  /**
209
210
  * Response header a route uses to advertise its ISR freshness (**seconds**) to a {@link withISR}
210
- * 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
211
212
  * from the action-revalidation `x-nifra-revalidate` header (a CSV path list the *client* parses to
212
213
  * refetch): this one is an integer TTL the *wrapper* reads, so the two channels never alias.
213
214
  */
@@ -219,14 +220,14 @@ export interface ISROptions {
219
220
  * behind). A route overrides it per-page via `export const revalidate` (surfaced as the
220
221
  * `x-nifra-isr-revalidate` response header). */
221
222
  readonly revalidate: number
222
- /** Monotonic clock (ms) — injected for testability; production passes `() => Date.now()`. */
223
+ /** Monotonic clock (ms) - injected for testability; production passes `() => Date.now()`. */
223
224
  readonly now: () => number
224
225
  /** Cache key for a request. Default: `origin + pathname + search` so host-routed apps do not share
225
226
  * entries across tenants. Return `null` to bypass the cache for this request (it goes straight to the
226
227
  * app, uncached). */
227
228
  readonly key?: (req: Request) => string | null
228
229
  /** Draft/preview secret (the same one given to `createWebApp({ draftSecret })` + `enableDraft`). When
229
- * 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
230
231
  * fresh, and a draft render is never written to the store (it can't poison the public cache). */
231
232
  readonly draftSecret?: string
232
233
  }
@@ -306,7 +307,7 @@ function sanitizeCachedHeaders(headers: Readonly<Record<string, string>>): Recor
306
307
  * Wrap a nifra app with **Incremental Static Regeneration**: a cacheable page is served from
307
308
  * {@link CacheStore} when fresh, served **stale while a fresh copy regenerates in the background**
308
309
  * (`platform.waitUntil` on edge), or rendered + stored on a miss. Framework-agnostic (it caches the
309
- * 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
310
311
  * `export default`, etc. Regeneration is single-flight per key (no stampede on a hot stale page).
311
312
  *
312
313
  * Each route's freshness comes from the `revalidate` header the app sets (per-route
@@ -351,7 +352,7 @@ export function withISR(
351
352
  })
352
353
  }
353
354
 
354
- // 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
355
356
  // stale hit retries. Never throws (it runs detached / under waitUntil).
356
357
  const regenerate = async (
357
358
  req: Request,
@@ -406,32 +407,19 @@ export function withISR(
406
407
  const jsonError = (status: number, error: string): Response =>
407
408
  Response.json({ ok: false, error }, { status })
408
409
 
409
- /** Constant-time string equality (XOR-accumulate, no early exit). A length mismatch returns `false`
410
- * up front — the length isn't the secret, and different-length buffers can't be compared in constant
411
- * time anyway. Used to check the on-demand revalidation token without leaking it via timing. */
412
- function timingSafeEqual(a: string, b: string): boolean {
413
- const enc = new TextEncoder()
414
- const ba = enc.encode(a)
415
- const bb = enc.encode(b)
416
- if (ba.length !== bb.length) return false
417
- let diff = 0
418
- for (let i = 0; i < ba.length; i++) diff |= (ba[i] as number) ^ (bb[i] as number)
419
- return diff === 0
420
- }
421
-
422
410
  export interface RevalidateEndpointOptions {
423
411
  readonly store: CacheStore
424
412
  /** Shared secret; the request's token must match it (constant-time). */
425
413
  readonly secret: string
426
414
  /** Header carrying the secret. Default `x-nifra-revalidate-token`. */
427
415
  readonly tokenHeader?: string
428
- /** 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
429
417
  * revalidation request's origin plus the purged path, matching `withISR`'s default host-aware key. */
430
418
  readonly key?: (path: string, req: Request) => string
431
419
  }
432
420
 
433
421
  /**
434
- * 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
435
423
  * so the next request re-renders. `POST` with the secret in the token header and the path as `?path=`
436
424
  * or a JSON `{ "path": "/blog/x" }` body. The token is checked in **constant time** (wrong/missing →
437
425
  * `401`); a missing/relative path → `400`; non-POST → `405`. Mount it on a nifra route, e.g.