@nifrajs/cli 5.2.0 → 5.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 (100) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/dist/assure-hydration.d.ts.map +1 -1
  3. package/dist/assure-hydration.js +6 -2
  4. package/dist/assure-hydration.js.map +1 -1
  5. package/dist/check-diagnostics.d.ts.map +1 -1
  6. package/dist/check-diagnostics.js +2 -0
  7. package/dist/check-diagnostics.js.map +1 -1
  8. package/dist/check-scan.d.ts +9 -3
  9. package/dist/check-scan.d.ts.map +1 -1
  10. package/dist/check-scan.js +61 -24
  11. package/dist/check-scan.js.map +1 -1
  12. package/dist/check.d.ts.map +1 -1
  13. package/dist/check.js +3 -3
  14. package/dist/check.js.map +1 -1
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +22 -14
  17. package/dist/cli.js.map +1 -1
  18. package/dist/db-tool.d.ts.map +1 -1
  19. package/dist/db-tool.js +2 -1
  20. package/dist/db-tool.js.map +1 -1
  21. package/dist/env-file.d.ts.map +1 -1
  22. package/dist/env-file.js +41 -8
  23. package/dist/env-file.js.map +1 -1
  24. package/dist/internal/source-facts.d.ts +20 -4
  25. package/dist/internal/source-facts.d.ts.map +1 -1
  26. package/dist/internal/source-facts.js +248 -32
  27. package/dist/internal/source-facts.js.map +1 -1
  28. package/dist/mcp-exec.d.ts +1 -0
  29. package/dist/mcp-exec.d.ts.map +1 -1
  30. package/dist/mcp-exec.js +11 -3
  31. package/dist/mcp-exec.js.map +1 -1
  32. package/dist/mcp-http.js +1 -1
  33. package/dist/mcp-io.d.ts +23 -3
  34. package/dist/mcp-io.d.ts.map +1 -1
  35. package/dist/mcp-io.js +59 -12
  36. package/dist/mcp-io.js.map +1 -1
  37. package/dist/mcp-isolate.d.ts.map +1 -1
  38. package/dist/mcp-isolate.js +2 -1
  39. package/dist/mcp-isolate.js.map +1 -1
  40. package/dist/migrate-layout.d.ts.map +1 -1
  41. package/dist/migrate-layout.js +1 -0
  42. package/dist/migrate-layout.js.map +1 -1
  43. package/dist/recipes/5.3.0.d.ts +11 -0
  44. package/dist/recipes/5.3.0.d.ts.map +1 -0
  45. package/dist/recipes/5.3.0.js +35 -0
  46. package/dist/recipes/5.3.0.js.map +1 -0
  47. package/dist/recipes/5.4.0.d.ts +10 -0
  48. package/dist/recipes/5.4.0.d.ts.map +1 -0
  49. package/dist/recipes/5.4.0.js +25 -0
  50. package/dist/recipes/5.4.0.js.map +1 -0
  51. package/dist/recipes/index.d.ts.map +1 -1
  52. package/dist/recipes/index.js +4 -0
  53. package/dist/recipes/index.js.map +1 -1
  54. package/dist/review.d.ts.map +1 -1
  55. package/dist/review.js +2 -0
  56. package/dist/review.js.map +1 -1
  57. package/dist/rules/codes.d.ts +2 -0
  58. package/dist/rules/codes.d.ts.map +1 -1
  59. package/dist/rules/codes.js +2 -0
  60. package/dist/rules/codes.js.map +1 -1
  61. package/dist/rules/explanations.d.ts.map +1 -1
  62. package/dist/rules/explanations.js +12 -2
  63. package/dist/rules/explanations.js.map +1 -1
  64. package/dist/rules/pages.d.ts +25 -1
  65. package/dist/rules/pages.d.ts.map +1 -1
  66. package/dist/rules/pages.js +149 -33
  67. package/dist/rules/pages.js.map +1 -1
  68. package/dist/rules/route-statement.d.ts +10 -0
  69. package/dist/rules/route-statement.d.ts.map +1 -0
  70. package/dist/rules/route-statement.js +150 -0
  71. package/dist/rules/route-statement.js.map +1 -0
  72. package/dist/upgrade.d.ts +43 -10
  73. package/dist/upgrade.d.ts.map +1 -1
  74. package/dist/upgrade.js +161 -45
  75. package/dist/upgrade.js.map +1 -1
  76. package/docs/llms-full.txt +508 -190
  77. package/docs/types.json +217 -31
  78. package/package.json +11 -11
  79. package/src/assure-hydration.ts +7 -1
  80. package/src/check-diagnostics.ts +2 -0
  81. package/src/check-scan.ts +64 -25
  82. package/src/check.ts +8 -3
  83. package/src/cli.ts +22 -14
  84. package/src/db-tool.ts +2 -0
  85. package/src/env-file.ts +42 -7
  86. package/src/internal/source-facts.ts +312 -39
  87. package/src/mcp-exec.ts +13 -2
  88. package/src/mcp-http.ts +1 -1
  89. package/src/mcp-io.ts +72 -12
  90. package/src/mcp-isolate.ts +2 -0
  91. package/src/migrate-layout.ts +1 -0
  92. package/src/recipes/5.3.0.ts +36 -0
  93. package/src/recipes/5.4.0.ts +26 -0
  94. package/src/recipes/index.ts +4 -0
  95. package/src/review.ts +2 -0
  96. package/src/rules/codes.ts +2 -0
  97. package/src/rules/explanations.ts +12 -2
  98. package/src/rules/pages.ts +193 -33
  99. package/src/rules/route-statement.ts +170 -0
  100. package/src/upgrade.ts +202 -47
@@ -0,0 +1,26 @@
1
+ import type { UpgradeRecipe } from "./index.ts"
2
+
3
+ /**
4
+ * Upgrade recipe for Nifra 5.4.
5
+ *
6
+ * No import or dependency moves. A `node` build needs the adapter of the same release, and static
7
+ * files answer validators, ranges and types the same way on every runtime; each note says what an
8
+ * app or a client sees differently.
9
+ */
10
+ export const recipe: UpgradeRecipe = {
11
+ version: "5.4.0",
12
+ pins: [
13
+ { match: "@nifrajs/", to: "5.4.0" },
14
+ { match: "create-nifra", to: "5.4.0" },
15
+ { match: "nifra", to: "5.4.0" },
16
+ ],
17
+ importMoves: [],
18
+ notes: [
19
+ "The server entry a `node` build generates passes the app itself to `@nifrajs/node`'s `serve` and serves files with the adapter's own reader, so it needs the `@nifrajs/node` of the same release. With an older adapter installed the build stops before bundling, names both versions and leaves the last deploy dir in place, where a 5.3 adapter used to build and then throw when the server started. Upgrade `@nifrajs/node` with the rest.",
20
+ "Static files carry a strong `ETag` from their content (128 bits of SHA-256) on the Bun entry and `nifra dev` (`servePublicDir`), `@nifrajs/node`'s `static` reader and the generated Deno entry, the same for the same bytes on every instance. The Node reader's `\"<mtime>-<size>\"` tag is gone, so clients and caches revalidate each file once after the upgrade. `Last-Modified` is sent only while a file's mtime is its own last change, so a file whose mtime a copy or build set (every file in a container image) is sent without one and `If-Modified-Since` cannot validate it. An `If-Range` date no longer keeps a range for a tagged file; a client resumes by the tag.",
21
+ "The generated Deno entry answers static files with `etag` and `last-modified`, a `304` with no body for a current copy (HEAD included), and honors `Range` only when `If-Range` is absent or names the file's current validator, as the Bun and Node entries do. On Bun and Deno `If-None-Match` is evaluated before `If-Modified-Since`, so a stale entity tag no longer gets a `304` from the date beside it.",
22
+ "`@nifrajs/node`'s `serve({ static })` types files from the same table as `servePublicDir`, so `.pdf`, `.mp4`, `.xml`, `.csv` and other common types are no longer sent as `application/octet-stream`. It serves `/.well-known` by default, refuses a visible name that links to a dotfile, and answers a link that leaves the directory with `404` where it answered `403`. `static` also takes an array of mounts, a `files` list a mount is limited to, and `cacheControl`.",
23
+ "`@nifrajs/node`'s `static` reader parses `Range` with `@nifrajs/core/range`, like the other runtimes: overlapping or adjacent ranges are served as the one range they cover, a satisfiable range listed with unsatisfiable ones is served, an inverted range (`bytes=9-0`) answers `416` where it was ignored, a zero-length suffix (`bytes=-0`) sends the whole file where it answered `416`, and a `Range` longer than 16 KiB is ignored.",
24
+ "On Bun, `servePublicDir` (the Bun entry and `nifra dev`) sends `content-length` for files up to 1 MiB, whole or ranged, where Bun used to send them chunked with no length. Files above 1 MiB are still sent chunked.",
25
+ ],
26
+ }
@@ -14,6 +14,8 @@ import { recipe as v4_0_0 } from "./4.0.0.ts"
14
14
  import { recipe as v5_0_0 } from "./5.0.0.ts"
15
15
  import { recipe as v5_1_0 } from "./5.1.0.ts"
16
16
  import { recipe as v5_2_0 } from "./5.2.0.ts"
17
+ import { recipe as v5_3_0 } from "./5.3.0.ts"
18
+ import { recipe as v5_4_0 } from "./5.4.0.ts"
17
19
 
18
20
  /** A pin rule: every dependency whose name starts with `match` is set to version `to`. */
19
21
  export interface PinRule {
@@ -61,6 +63,8 @@ const RECIPES: Record<string, UpgradeRecipe> = {
61
63
  [v5_0_0.version]: v5_0_0,
62
64
  [v5_1_0.version]: v5_1_0,
63
65
  [v5_2_0.version]: v5_2_0,
66
+ [v5_3_0.version]: v5_3_0,
67
+ [v5_4_0.version]: v5_4_0,
64
68
  }
65
69
 
66
70
  export function getRecipe(version: string): UpgradeRecipe | undefined {
package/src/review.ts CHANGED
@@ -155,6 +155,8 @@ export const CHECK_CODES: Readonly<Record<string, ReviewCheckId>> = {
155
155
  "NF-C041": "route-boundary",
156
156
  "NF-C042": "route-boundary",
157
157
  "NF-C043": "security",
158
+ "NF-C044": "route-boundary",
159
+ "NF-C045": "typed-client",
158
160
  "NF-D001": "dependency",
159
161
  "NF-D002": "dependency",
160
162
  "NF-D003": "dependency",
@@ -40,6 +40,8 @@ export const RULE_CODES = Object.freeze({
40
40
  "NF-C041": "Server-only export in a route frontend file",
41
41
  "NF-C042": "Layout loader refuses access without a gate",
42
42
  "NF-C043": "Merged routes skip the parent's authentication",
43
+ "NF-C044": "createWebApp passes no copy chunks",
44
+ "NF-C045": "Route registered outside the typed chain",
43
45
  "NF-C020": "Island enhancer cleanup check",
44
46
  "NF-C021": "nano binding cleanup check",
45
47
  "NF-C022": "nano bindList key check",
@@ -191,8 +191,8 @@ export const RULE_EXPLANATIONS: Readonly<Record<BuiltInCode, RuleExplanation>> =
191
191
  docs: "/docs/routing",
192
192
  },
193
193
  "NF-C035": {
194
- why: "backend/framework.ts sets no apiPrefix, so the backend is reachable from loaders only and a browser call to /api reaches page routing.",
195
- fix: 'Export `apiPrefix = "/api"` to serve it over HTTP, or `apiPrefix = ""` to keep it loader-only.',
194
+ why: "backend/framework.ts sets no apiPrefix, so the backend is reachable from loaders only and a browser call to /api reaches page routing; or an app module's own createWebApp call mounts the backend at another apiPrefix than `nifra dev` serves it at.",
195
+ fix: 'Export `apiPrefix = "/api"` to serve it over HTTP, or `apiPrefix = ""` to keep it loader-only. At a createWebApp call, import `apiPrefix` from backend/framework.ts, or, when another server already serves the backend there, mark the call `// nifra-expect NF-C035: <reason>`.',
196
196
  command: "nifra fix --code NF-C035",
197
197
  docs: "/docs/backends",
198
198
  },
@@ -238,6 +238,16 @@ export const RULE_EXPLANATIONS: Readonly<Record<BuiltInCode, RuleExplanation>> =
238
238
  fix: "Apply the auth plugin on the merged server, or declare its routes in a group() of this server. A module that is public on purpose takes `// nifra-expect NF-C043: <reason>` on the merge line.",
239
239
  docs: "/docs/plugins",
240
240
  },
241
+ "NF-C044": {
242
+ why: "A production client build moves the app's copy tables into one chunk per locale, and a page loads its locale's chunk from the `copyChunks` its server lists. A createWebApp call with a clientEntry and no copyChunks lists none, so the first page that renders copy fails in production, while `nifra dev`, which never splits, passes.",
243
+ fix: 'Pass the client build\'s `copyChunks` to createWebApp: the generated server manifest exports it (`import { copyChunks } from "./server-manifest"`), and `buildClient()` returns it. A server that never serves those pages takes `// nifra-expect NF-C044: <reason>` on the call.',
244
+ docs: "/docs/i18n",
245
+ },
246
+ "NF-C045": {
247
+ why: "A route registration returns a new type that records the route. Called as a statement of its own, the route runs, but the exported server's type never includes it, so the typed client has no such call.",
248
+ fix: "Chain the registration onto the server's declaration, or declare the routes on their own server() and merge() it. A route kept off the type on purpose takes `// nifra-expect NF-C045: <reason>` above the statement.",
249
+ docs: "/docs/api#typed-client",
250
+ },
241
251
  "NF-D001": {
242
252
  why: "The doctor gate of `nifra assure` found an undeclared import or a package installed more than once.",
243
253
  fix: "Run `nifra doctor` for the details and the fix of each finding.",
@@ -22,6 +22,7 @@ import { type Diagnostic, diagnostic } from "../diagnostics.ts"
22
22
  import { codeUnitOrder } from "../internal/code-unit-order.ts"
23
23
  import { hasWebConfig } from "../internal/nifra-project.ts"
24
24
  import { scriptKindOf } from "../internal/script-kind.ts"
25
+ import { commentBlockExpectation } from "./comment-markers.ts"
25
26
  import type { CheckRule } from "./index.ts"
26
27
  import { loadRuleTypeScript } from "./typescript.ts"
27
28
 
@@ -206,8 +207,48 @@ const unwrapExpression = (ts: typeof TSApi, node: TSApi.Expression): TSApi.Expre
206
207
  export interface EntryApiMount {
207
208
  readonly line: number
208
209
  readonly apiPrefix: EntryApiPrefix
210
+ /** The line of the `apiPrefix` property that decides it, when one does. */
211
+ readonly prefixLine: number | undefined
209
212
  }
210
213
 
214
+ /** A module's matcher for `createWebApp` callees imported from `@nifrajs/web`, by name or through a
215
+ * namespace; `undefined` when the module imports it neither way. */
216
+ function createWebAppCallee(
217
+ ts: typeof TSApi,
218
+ tree: TSApi.SourceFile,
219
+ ): ((callee: TSApi.Expression) => boolean) | undefined {
220
+ const names = new Set<string>()
221
+ const namespaces = new Set<string>()
222
+ for (const statement of tree.statements) {
223
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier))
224
+ continue
225
+ const bindings = statement.importClause?.namedBindings
226
+ if (bindings === undefined || statement.moduleSpecifier.text !== WEB_PACKAGE) continue
227
+ if (ts.isNamespaceImport(bindings)) namespaces.add(bindings.name.text)
228
+ else
229
+ for (const element of bindings.elements)
230
+ if ((element.propertyName ?? element.name).text === "createWebApp")
231
+ names.add(element.name.text)
232
+ }
233
+ if (names.size === 0 && namespaces.size === 0) return undefined
234
+ return (callee) =>
235
+ ts.isIdentifier(callee)
236
+ ? names.has(callee.text)
237
+ : ts.isPropertyAccessExpression(callee) &&
238
+ ts.isIdentifier(callee.expression) &&
239
+ namespaces.has(callee.expression.text) &&
240
+ callee.name.text === "createWebApp"
241
+ }
242
+
243
+ const objectPropertyName = (
244
+ ts: typeof TSApi,
245
+ property: TSApi.ObjectLiteralElementLike,
246
+ ): string | undefined =>
247
+ property.name !== undefined &&
248
+ (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name))
249
+ ? property.name.text
250
+ : undefined
251
+
211
252
  /**
212
253
  * Every `createWebApp({ api, ... })` call in a module, `createWebApp` imported from `@nifrajs/web`.
213
254
  * `apiPrefix` reads as a string literal, a same-module string `const`, or the framework config's own
@@ -219,27 +260,23 @@ export function entryApiMounts(
219
260
  tree: TSApi.SourceFile,
220
261
  file: string,
221
262
  ): EntryApiMount[] {
222
- const webNames = new Set<string>()
223
- const webNamespaces = new Set<string>()
263
+ const isCreateWebApp = createWebAppCallee(ts, tree)
264
+ if (isCreateWebApp === undefined) return []
224
265
  const configNames = new Set<string>()
225
266
  const configNamespaces = new Set<string>()
226
267
  const strings = new Map<string, string>()
227
268
  for (const statement of tree.statements) {
228
269
  if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {
229
- const from = statement.moduleSpecifier.text
230
270
  const bindings = statement.importClause?.namedBindings
231
- const isWeb = from === WEB_PACKAGE
232
- const isConfig = namesFrameworkConfig(file, from)
233
- if (bindings === undefined || (!isWeb && !isConfig)) continue
271
+ if (bindings === undefined || !namesFrameworkConfig(file, statement.moduleSpecifier.text))
272
+ continue
234
273
  if (ts.isNamespaceImport(bindings)) {
235
- ;(isWeb ? webNamespaces : configNamespaces).add(bindings.name.text)
274
+ configNamespaces.add(bindings.name.text)
236
275
  continue
237
276
  }
238
- for (const element of bindings.elements) {
239
- const imported = (element.propertyName ?? element.name).text
240
- if (isWeb && imported === "createWebApp") webNames.add(element.name.text)
241
- if (isConfig && imported === "apiPrefix") configNames.add(element.name.text)
242
- }
277
+ for (const element of bindings.elements)
278
+ if ((element.propertyName ?? element.name).text === "apiPrefix")
279
+ configNames.add(element.name.text)
243
280
  continue
244
281
  }
245
282
  if (
@@ -260,7 +297,6 @@ export function entryApiMounts(
260
297
  strings.set(declaration.name.text, init.text)
261
298
  }
262
299
  }
263
- if (webNames.size === 0 && webNamespaces.size === 0) return []
264
300
 
265
301
  const readPrefix = (node: TSApi.Expression): EntryApiPrefix => {
266
302
  const expr = unwrapExpression(ts, node)
@@ -280,19 +316,6 @@ export function entryApiMounts(
280
316
  return { kind: "config" }
281
317
  return { kind: "unreadable" }
282
318
  }
283
- const isCreateWebApp = (callee: TSApi.Expression): boolean =>
284
- ts.isIdentifier(callee)
285
- ? webNames.has(callee.text)
286
- : ts.isPropertyAccessExpression(callee) &&
287
- ts.isIdentifier(callee.expression) &&
288
- webNamespaces.has(callee.expression.text) &&
289
- callee.name.text === "createWebApp"
290
- const propertyName = (property: TSApi.ObjectLiteralElementLike): string | undefined =>
291
- property.name !== undefined &&
292
- (ts.isIdentifier(property.name) || ts.isStringLiteral(property.name))
293
- ? property.name.text
294
- : undefined
295
-
296
319
  const mounts: EntryApiMount[] = []
297
320
  const visit = (node: TSApi.Node): void => {
298
321
  const arg = ts.isCallExpression(node) ? node.arguments[0] : undefined
@@ -302,19 +325,26 @@ export function entryApiMounts(
302
325
  isCreateWebApp(node.expression) &&
303
326
  options !== undefined &&
304
327
  ts.isObjectLiteralExpression(options) &&
305
- options.properties.some((property) => propertyName(property) === "api")
328
+ options.properties.some((property) => objectPropertyName(ts, property) === "api")
306
329
  ) {
307
330
  // The last of an `apiPrefix` property and a spread decides, as it does at runtime.
308
331
  let apiPrefix: EntryApiPrefix = { kind: "literal", value: "", unset: true }
332
+ let prefixNode: TSApi.Node | undefined
309
333
  for (const property of options.properties) {
310
334
  if (ts.isSpreadAssignment(property)) apiPrefix = { kind: "unreadable" }
311
- else if (propertyName(property) !== "apiPrefix") continue
335
+ else if (objectPropertyName(ts, property) !== "apiPrefix") continue
312
336
  else if (ts.isPropertyAssignment(property)) apiPrefix = readPrefix(property.initializer)
313
337
  else if (ts.isShorthandPropertyAssignment(property)) apiPrefix = readPrefix(property.name)
314
338
  else apiPrefix = { kind: "unreadable" }
339
+ prefixNode = ts.isSpreadAssignment(property) ? undefined : property
315
340
  }
316
- const line = tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1
317
- mounts.push({ line, apiPrefix })
341
+ const lineOf = (at: TSApi.Node): number =>
342
+ tree.getLineAndCharacterOfPosition(at.getStart(tree)).line + 1
343
+ mounts.push({
344
+ line: lineOf(node),
345
+ apiPrefix,
346
+ prefixLine: prefixNode === undefined ? undefined : lineOf(prefixNode),
347
+ })
318
348
  }
319
349
  ts.forEachChild(node, visit)
320
350
  }
@@ -322,6 +352,8 @@ export function entryApiMounts(
322
352
  return mounts
323
353
  }
324
354
 
355
+ const ENTRY_PREFIX_EXPECTATION = ["NF-C035"]
356
+
325
357
  const servedAt = (prefix: string): string => (prefix === "" ? "nowhere" : `at ${prefix}`)
326
358
 
327
359
  /**
@@ -350,19 +382,30 @@ async function entryApiPrefixFindings(
350
382
  true,
351
383
  scriptKindOf(ts, file),
352
384
  )
353
- for (const { line, apiPrefix } of entryApiMounts(ts, tree, file)) {
385
+ const lines = text.split("\n")
386
+ for (const { line, apiPrefix, prefixLine } of entryApiMounts(ts, tree, file)) {
354
387
  if (apiPrefix.kind !== "literal" || apiPrefix.value === expected) continue
388
+ if (
389
+ [line, prefixLine].some(
390
+ (at) => at !== undefined && commentBlockExpectation(lines, at, ENTRY_PREFIX_EXPECTATION),
391
+ )
392
+ )
393
+ continue
355
394
  const specifier = posix.relative(posix.dirname(file), origin.replace(SCRIPT_SOURCE, ""))
356
395
  const passed = apiPrefix.unset
357
396
  ? "no apiPrefix"
358
397
  : `apiPrefix ${JSON.stringify(apiPrefix.value)}`
398
+ const hatch =
399
+ expected === ""
400
+ ? "Mark a deliberate difference with `// nifra-expect NF-C035: <reason>` above the call."
401
+ : `If another server already serves this backend at ${expected}, mark the call with \`// nifra-expect NF-C035: <reason>\` instead${apiPrefix.value === "" ? ": an apiPrefix here would add a second path to it that skips that server's middleware" : ""}.`
359
402
  findings.push(
360
403
  diagnostic({
361
404
  code: "NF-C035",
362
405
  severity: "warn",
363
406
  file,
364
407
  line,
365
- message: `${file} calls createWebApp with a backend and ${passed}, so the server it starts serves the backend ${servedAt(apiPrefix.value)}, while \`nifra dev\` serves it ${servedAt(expected)} (${origin}). Pass the framework config's value: \`import { apiPrefix } from "${specifier.startsWith(".") ? specifier : `./${specifier}`}"\` and \`createWebApp({ ..., apiPrefix })\`.`,
408
+ message: `${file} calls createWebApp with a backend and ${passed}, so the server it starts serves the backend ${servedAt(apiPrefix.value)}, while \`nifra dev\` serves it ${servedAt(expected)} (${origin}). Pass the framework config's value: \`import { apiPrefix } from "${specifier.startsWith(".") ? specifier : `./${specifier}`}"\` and \`createWebApp({ ..., apiPrefix })\`. ${hatch}`,
366
409
  evidence: [
367
410
  `createWebApp apiPrefix: ${apiPrefix.unset ? "unset" : JSON.stringify(apiPrefix.value)}`,
368
411
  `${origin} apiPrefix: ${JSON.stringify(expected)}`,
@@ -382,7 +425,8 @@ async function entryApiPrefixFindings(
382
425
  *
383
426
  * An app module that calls `createWebApp` itself is checked against the same value, since only the
384
427
  * framework config reaches `nifra dev`: a backend it mounts at another `apiPrefix`, or with none, is
385
- * served in production where dev never served it.
428
+ * served in production where dev never served it. No static read sees a mount another server makes,
429
+ * so `// nifra-expect NF-C035: <reason>` on the call or its `apiPrefix` line accepts the difference.
386
430
  */
387
431
  export const implicitApiMountRule: CheckRule = {
388
432
  code: "NF-C035",
@@ -424,6 +468,121 @@ export const implicitApiMountRule: CheckRule = {
424
468
  },
425
469
  }
426
470
 
471
+ const COPY_MODULE = "@nifrajs/i18n/copy"
472
+ const SERVER_MANIFEST = /(?:^|\/)server-manifest(?:\.[cm]?[jt]s)?$/
473
+ const ENTRY_COPY_EXPECTATION = ["NF-C044"]
474
+
475
+ /** A `createWebApp` call that serves a client build and passes no `copyChunks`. */
476
+ export interface EntryCopyChunksGap {
477
+ readonly line: number
478
+ /** The generated server manifest the module imports from, when it does. */
479
+ readonly manifest: string | undefined
480
+ }
481
+
482
+ /**
483
+ * Every `createWebApp({ clientEntry, ... })` call in a module that passes no `copyChunks`. A call with
484
+ * no `clientEntry` ships no client build; one whose options come from a spread, a variable or a
485
+ * computed key may carry `copyChunks`, so it is left out. Pure.
486
+ */
487
+ export function entryCopyChunksGaps(
488
+ ts: typeof TSApi,
489
+ tree: TSApi.SourceFile,
490
+ ): EntryCopyChunksGap[] {
491
+ const isCreateWebApp = createWebAppCallee(ts, tree)
492
+ if (isCreateWebApp === undefined) return []
493
+ let manifest: string | undefined
494
+ for (const statement of tree.statements)
495
+ if (
496
+ manifest === undefined &&
497
+ ts.isImportDeclaration(statement) &&
498
+ ts.isStringLiteral(statement.moduleSpecifier) &&
499
+ SERVER_MANIFEST.test(statement.moduleSpecifier.text)
500
+ )
501
+ manifest = statement.moduleSpecifier.text
502
+ const gaps: EntryCopyChunksGap[] = []
503
+ const visit = (node: TSApi.Node): void => {
504
+ const arg = ts.isCallExpression(node) ? node.arguments[0] : undefined
505
+ const options = arg === undefined ? undefined : unwrapExpression(ts, arg)
506
+ if (
507
+ ts.isCallExpression(node) &&
508
+ isCreateWebApp(node.expression) &&
509
+ options !== undefined &&
510
+ ts.isObjectLiteralExpression(options)
511
+ ) {
512
+ const names = options.properties.map((property) =>
513
+ ts.isSpreadAssignment(property) ? undefined : objectPropertyName(ts, property),
514
+ )
515
+ if (
516
+ names.includes("clientEntry") &&
517
+ !names.includes("copyChunks") &&
518
+ !names.includes(undefined)
519
+ )
520
+ gaps.push({
521
+ line: tree.getLineAndCharacterOfPosition(node.getStart(tree)).line + 1,
522
+ manifest,
523
+ })
524
+ }
525
+ ts.forEachChild(node, visit)
526
+ }
527
+ visit(tree)
528
+ return gaps
529
+ }
530
+
531
+ /**
532
+ * NF-C044: an app module calls `createWebApp` with a client build and no `copyChunks` while the app
533
+ * defines copy tables (`@nifrajs/i18n/copy`). A production client build moves the tables into one
534
+ * chunk per locale, which a page loads from the `copyChunks` its server lists, so the first page that
535
+ * renders copy fails. `nifra dev` never splits them, so dev and e2e pass. The split reads the source
536
+ * with the app's TypeScript compiler API, which TypeScript 7 lacks; such an app ships its tables whole,
537
+ * so it is left out.
538
+ */
539
+ export const entryCopyChunksRule: CheckRule = {
540
+ code: "NF-C044",
541
+ title: "createWebApp passes no copy chunks",
542
+ async scan(ctx) {
543
+ const scripts = ctx.sources.files.filter((file) => SCRIPT_SOURCE.test(file)).sort(codeUnitOrder)
544
+ const definer = scripts.find((file) => ctx.sources.read(file)?.includes(COPY_MODULE) === true)
545
+ if (definer === undefined) return []
546
+ const candidates = scripts.filter(
547
+ (file) => ctx.sources.read(file)?.includes("createWebApp") === true,
548
+ )
549
+ if (candidates.length === 0) return []
550
+ const ts = (await loadRuleTypeScript(ctx)).compiler
551
+ if (ts === undefined || Number.parseInt(ts.version, 10) >= 7) return []
552
+ const findings: Diagnostic[] = []
553
+ for (const file of candidates) {
554
+ const text = ctx.sources.read(file) ?? ""
555
+ const tree = ts.createSourceFile(
556
+ file,
557
+ text,
558
+ ts.ScriptTarget.Latest,
559
+ true,
560
+ scriptKindOf(ts, file),
561
+ )
562
+ const lines = text.split("\n")
563
+ for (const { line, manifest } of entryCopyChunksGaps(ts, tree)) {
564
+ if (commentBlockExpectation(lines, line, ENTRY_COPY_EXPECTATION)) continue
565
+ const pass =
566
+ manifest === undefined
567
+ ? "the `copyChunks` its `clientEntry` comes with (the generated server manifest's export, or `buildClient()`'s result)"
568
+ : `\`import { copyChunks } from "${manifest}"\``
569
+ findings.push(
570
+ diagnostic({
571
+ code: "NF-C044",
572
+ severity: "warn",
573
+ file,
574
+ line,
575
+ message: `${file} calls createWebApp with a clientEntry and no copyChunks, while ${definer} defines copy tables. A production client build moves them into one chunk per locale, and a page loads its locale's chunk from the copyChunks the server lists, so the first page that renders copy fails ("no copy chunk for locale"); \`nifra dev\` never splits them, so dev and e2e pass. Pass ${pass} and \`createWebApp({ ..., copyChunks })\`. Mark a deliberate omission with \`// nifra-expect NF-C044: <reason>\` above the call.`,
576
+ evidence: ["createWebApp copyChunks: unset", `copy tables: ${definer}`],
577
+ verify: "nifra check",
578
+ }),
579
+ )
580
+ }
581
+ }
582
+ return findings
583
+ },
584
+ }
585
+
427
586
  const appendLine = (source: string, line: string): string =>
428
587
  source === "" ? line : `${source}${source.endsWith("\n") ? "" : "\n"}${line}`
429
588
 
@@ -789,6 +948,7 @@ export const pageRules = Object.freeze([
789
948
  shadowedPageRule,
790
949
  statusLayoutRule,
791
950
  implicitApiMountRule,
951
+ entryCopyChunksRule,
792
952
  layoutMetaDataRule,
793
953
  frontendServerExportRule,
794
954
  ungatedLayoutRefusalRule,
@@ -0,0 +1,170 @@
1
+ import type * as TSApi from "typescript"
2
+ import { type Diagnostic, diagnostic } from "../diagnostics.ts"
3
+ import { scriptKindOf } from "../internal/script-kind.ts"
4
+ import type { TypeScriptApi } from "../internal/typescript-import.ts"
5
+ import { commentBlockExpectation } from "./comment-markers.ts"
6
+ import type { CheckRule } from "./index.ts"
7
+ import { loadRuleTypeScript } from "./typescript.ts"
8
+
9
+ const ROUTE_STATEMENT_EXPECTATION = ["NF-C045", "route-statement"]
10
+ const SERVER_FACTORY = /(?<![.\w$])(?:server|createWebApp)\s*\(/
11
+
12
+ /** The `Server` methods whose return type is the only place the route they add is recorded. */
13
+ const REGISTRY_METHODS: ReadonlySet<string> = new Set([
14
+ "get",
15
+ "post",
16
+ "put",
17
+ "patch",
18
+ "delete",
19
+ "sse",
20
+ "ws",
21
+ "tool",
22
+ "group",
23
+ "merge",
24
+ ])
25
+
26
+ function unwrap(ts: TypeScriptApi, node: TSApi.Expression): TSApi.Expression {
27
+ let current = node
28
+ while (
29
+ ts.isParenthesizedExpression(current) ||
30
+ ts.isAsExpression(current) ||
31
+ ts.isSatisfiesExpression(current) ||
32
+ ts.isNonNullExpression(current)
33
+ )
34
+ current = current.expression
35
+ return current
36
+ }
37
+
38
+ /** The member calls of a chain, outermost first, and the expression it starts from. */
39
+ function chainOf(
40
+ ts: TypeScriptApi,
41
+ expression: TSApi.Expression,
42
+ ): { readonly calls: readonly TSApi.CallExpression[]; readonly root: TSApi.Expression } {
43
+ const calls: TSApi.CallExpression[] = []
44
+ let current = unwrap(ts, expression)
45
+ while (ts.isCallExpression(current) && ts.isPropertyAccessExpression(current.expression)) {
46
+ calls.push(current)
47
+ current = unwrap(ts, current.expression.expression)
48
+ }
49
+ return { calls, root: current }
50
+ }
51
+
52
+ function isServerFactoryCall(ts: TypeScriptApi, node: TSApi.Expression): boolean {
53
+ return (
54
+ ts.isCallExpression(node) &&
55
+ ts.isIdentifier(node.expression) &&
56
+ (node.expression.text === "server" || node.expression.text === "createWebApp")
57
+ )
58
+ }
59
+
60
+ /** Names bound to a `server(...)`/`createWebApp(...)` chain whose type leaves the file: exported, or
61
+ * read by a `typeof` (the shape `client<typeof app>` and `export type App = typeof app` take). */
62
+ function typedServerBindings(ts: TypeScriptApi, tree: TSApi.SourceFile): ReadonlySet<string> {
63
+ const servers = new Set<string>()
64
+ const exported = new Set<string>()
65
+ const typed = new Set<string>()
66
+ const isExported = (modifiers: readonly TSApi.ModifierLike[] | undefined): boolean =>
67
+ modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) === true
68
+ const visit = (node: TSApi.Node): void => {
69
+ if (
70
+ ts.isVariableDeclaration(node) &&
71
+ ts.isIdentifier(node.name) &&
72
+ node.initializer !== undefined &&
73
+ isServerFactoryCall(ts, chainOf(ts, node.initializer).root)
74
+ )
75
+ servers.add(node.name.text)
76
+ else if (ts.isVariableStatement(node) && isExported(node.modifiers)) {
77
+ for (const declaration of node.declarationList.declarations)
78
+ if (ts.isIdentifier(declaration.name)) exported.add(declaration.name.text)
79
+ } else if (
80
+ ts.isExportDeclaration(node) &&
81
+ node.moduleSpecifier === undefined &&
82
+ node.exportClause !== undefined &&
83
+ ts.isNamedExports(node.exportClause)
84
+ ) {
85
+ for (const element of node.exportClause.elements)
86
+ exported.add((element.propertyName ?? element.name).text)
87
+ } else if (ts.isExportAssignment(node) && ts.isIdentifier(node.expression))
88
+ exported.add(node.expression.text)
89
+ else if (ts.isTypeQueryNode(node) && ts.isIdentifier(node.exprName))
90
+ typed.add(node.exprName.text)
91
+ ts.forEachChild(node, visit)
92
+ }
93
+ visit(tree)
94
+ return new Set([...servers].filter((name) => exported.has(name) || typed.has(name)))
95
+ }
96
+
97
+ function routeLabel(ts: TypeScriptApi, call: TSApi.CallExpression, method: string): string {
98
+ const first = call.arguments[0]
99
+ return first !== undefined && ts.isStringLiteralLike(first)
100
+ ? `${method}("${first.text}", ...)`
101
+ : `${method}(...)`
102
+ }
103
+
104
+ /**
105
+ * NF-C045: a route added to a typed server as its own statement - `app.get("/x", h)` on a line of its
106
+ * own, its result unused. Each registration returns a NEW type that records the route, so the statement
107
+ * registers the route at runtime while `typeof app` - what the typed client and an `App` export read -
108
+ * never contains it, and the client call fails to compile with no hint why. Reported only for a binding
109
+ * whose type leaves the file (exported, or read by `typeof`); a server nothing types is unaffected.
110
+ */
111
+ export const routeStatementRule: CheckRule = {
112
+ code: "NF-C045",
113
+ title: "Route registered outside the typed chain",
114
+ async scan(ctx) {
115
+ const loaded = await loadRuleTypeScript(ctx)
116
+ if (loaded.diagnostics !== undefined) return loaded.diagnostics
117
+ // Without TypeScript there is no typed client to keep in step.
118
+ const ts = loaded.compiler
119
+ if (ts === undefined) return []
120
+ const findings: Diagnostic[] = []
121
+ for (const file of ctx.project.source.files) {
122
+ if (!/\.[cm]?tsx?$/.test(file)) continue
123
+ const text = ctx.project.source.read(file)
124
+ if (text === undefined || !SERVER_FACTORY.test(text)) continue
125
+ const tree = ts.createSourceFile(
126
+ file,
127
+ text,
128
+ ts.ScriptTarget.Latest,
129
+ true,
130
+ scriptKindOf(ts, file),
131
+ )
132
+ const bindings = typedServerBindings(ts, tree)
133
+ if (bindings.size === 0) continue
134
+ const lines = text.split("\n")
135
+ for (const statement of tree.statements) {
136
+ if (!ts.isExpressionStatement(statement)) continue
137
+ const { calls, root } = chainOf(ts, statement.expression)
138
+ if (!ts.isIdentifier(root) || !bindings.has(root.text)) continue
139
+ // Innermost first: the route the statement adds before anything chained after it.
140
+ const registration = [...calls].reverse().find((call) => {
141
+ const callee = call.expression
142
+ return ts.isPropertyAccessExpression(callee) && REGISTRY_METHODS.has(callee.name.text)
143
+ })
144
+ if (registration === undefined || !ts.isPropertyAccessExpression(registration.expression))
145
+ continue
146
+ const line = tree.getLineAndCharacterOfPosition(statement.getStart(tree)).line + 1
147
+ if (commentBlockExpectation(lines, line, ROUTE_STATEMENT_EXPECTATION)?.reason !== undefined)
148
+ continue
149
+ const name = root.text
150
+ const route = routeLabel(ts, registration, registration.expression.name.text)
151
+ findings.push(
152
+ diagnostic({
153
+ code: "NF-C045",
154
+ severity: "warn",
155
+ file,
156
+ line,
157
+ message: `\`${name}.${route}\` is a statement of its own, so \`typeof ${name}\` does not include it: the route runs, but the typed client built from \`typeof ${name}\` has no such call. Chain it onto the server's declaration, or merge() a server that declares it.`,
158
+ evidence: [
159
+ "each route registration returns a new type that records the route; a discarded result drops it",
160
+ `\`${name}\` is exported or read by \`typeof\`, so its type is what a typed client sees`,
161
+ "a route kept off the type on purpose: `// nifra-expect NF-C045: <reason>` above the statement",
162
+ ],
163
+ verify: "nifra check",
164
+ }),
165
+ )
166
+ }
167
+ }
168
+ return findings
169
+ },
170
+ }