@nifrajs/cli 5.5.1 → 5.6.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 (138) hide show
  1. package/CHANGELOG.md +155 -0
  2. package/dist/cdn-check.d.ts +7 -6
  3. package/dist/cdn-check.d.ts.map +1 -1
  4. package/dist/cdn-check.js +13 -1
  5. package/dist/cdn-check.js.map +1 -1
  6. package/dist/check-diagnostics.d.ts.map +1 -1
  7. package/dist/check-diagnostics.js +5 -3
  8. package/dist/check-diagnostics.js.map +1 -1
  9. package/dist/check-scan.d.ts.map +1 -1
  10. package/dist/check-scan.js +29 -2
  11. package/dist/check-scan.js.map +1 -1
  12. package/dist/cli.d.ts.map +1 -1
  13. package/dist/cli.js +14 -5
  14. package/dist/cli.js.map +1 -1
  15. package/dist/command-catalog.d.ts +14 -1
  16. package/dist/command-catalog.d.ts.map +1 -1
  17. package/dist/command-catalog.js +93 -0
  18. package/dist/command-catalog.js.map +1 -1
  19. package/dist/doctor.d.ts +9 -1
  20. package/dist/doctor.d.ts.map +1 -1
  21. package/dist/doctor.js +52 -0
  22. package/dist/doctor.js.map +1 -1
  23. package/dist/fix-recipes.d.ts.map +1 -1
  24. package/dist/fix-recipes.js +27 -0
  25. package/dist/fix-recipes.js.map +1 -1
  26. package/dist/frontend-guidance.d.ts +1 -1
  27. package/dist/frontend-guidance.d.ts.map +1 -1
  28. package/dist/frontend-guidance.js +17 -8
  29. package/dist/frontend-guidance.js.map +1 -1
  30. package/dist/introspect.js +1 -1
  31. package/dist/introspect.js.map +1 -1
  32. package/dist/load.d.ts +4 -1
  33. package/dist/load.d.ts.map +1 -1
  34. package/dist/load.js +8 -0
  35. package/dist/load.js.map +1 -1
  36. package/dist/mcp-exec.d.ts.map +1 -1
  37. package/dist/mcp-exec.js +57 -3
  38. package/dist/mcp-exec.js.map +1 -1
  39. package/dist/mcp-http.d.ts +2 -1
  40. package/dist/mcp-http.d.ts.map +1 -1
  41. package/dist/mcp-http.js +3 -2
  42. package/dist/mcp-http.js.map +1 -1
  43. package/dist/mcp-tool-meta.d.ts +21 -0
  44. package/dist/mcp-tool-meta.d.ts.map +1 -0
  45. package/dist/mcp-tool-meta.js +246 -0
  46. package/dist/mcp-tool-meta.js.map +1 -0
  47. package/dist/mcp.d.ts +3 -2
  48. package/dist/mcp.d.ts.map +1 -1
  49. package/dist/mcp.js +36 -98
  50. package/dist/mcp.js.map +1 -1
  51. package/dist/output-schemas.d.ts +8 -0
  52. package/dist/output-schemas.d.ts.map +1 -1
  53. package/dist/output-schemas.js +14 -0
  54. package/dist/output-schemas.js.map +1 -1
  55. package/dist/ppr-read-fix.d.ts +8 -0
  56. package/dist/ppr-read-fix.d.ts.map +1 -0
  57. package/dist/ppr-read-fix.js +356 -0
  58. package/dist/ppr-read-fix.js.map +1 -0
  59. package/dist/recipes/5.6.0.d.ts +10 -0
  60. package/dist/recipes/5.6.0.d.ts.map +1 -0
  61. package/dist/recipes/5.6.0.js +68 -0
  62. package/dist/recipes/5.6.0.js.map +1 -0
  63. package/dist/recipes/index.d.ts.map +1 -1
  64. package/dist/recipes/index.js +2 -0
  65. package/dist/recipes/index.js.map +1 -1
  66. package/dist/review.d.ts.map +1 -1
  67. package/dist/review.js +7 -2
  68. package/dist/review.js.map +1 -1
  69. package/dist/rules/codes.d.ts +8 -3
  70. package/dist/rules/codes.d.ts.map +1 -1
  71. package/dist/rules/codes.js +9 -4
  72. package/dist/rules/codes.js.map +1 -1
  73. package/dist/rules/explanations.d.ts.map +1 -1
  74. package/dist/rules/explanations.js +39 -13
  75. package/dist/rules/explanations.js.map +1 -1
  76. package/dist/rules/islands.d.ts +91 -0
  77. package/dist/rules/islands.d.ts.map +1 -1
  78. package/dist/rules/islands.js +757 -3
  79. package/dist/rules/islands.js.map +1 -1
  80. package/dist/rules/ppr.d.ts +16 -0
  81. package/dist/rules/ppr.d.ts.map +1 -0
  82. package/dist/rules/ppr.js +114 -0
  83. package/dist/rules/ppr.js.map +1 -0
  84. package/dist/rules/swap.d.ts +7 -0
  85. package/dist/rules/swap.d.ts.map +1 -0
  86. package/dist/rules/swap.js +338 -0
  87. package/dist/rules/swap.js.map +1 -0
  88. package/dist/scaffold-hole.d.ts +105 -0
  89. package/dist/scaffold-hole.d.ts.map +1 -0
  90. package/dist/scaffold-hole.js +688 -0
  91. package/dist/scaffold-hole.js.map +1 -0
  92. package/dist/scaffold.d.ts +5 -3
  93. package/dist/scaffold.d.ts.map +1 -1
  94. package/dist/scaffold.js +56 -46
  95. package/dist/scaffold.js.map +1 -1
  96. package/dist/verification-plan.d.ts.map +1 -1
  97. package/dist/verification-plan.js +12 -1
  98. package/dist/verification-plan.js.map +1 -1
  99. package/dist/web-app-options.d.ts +1 -1
  100. package/dist/web-app-options.d.ts.map +1 -1
  101. package/dist/web-app-options.js.map +1 -1
  102. package/docs/examples.json +63 -9
  103. package/docs/llms-full.txt +2060 -430
  104. package/docs/types.json +1300 -270
  105. package/package.json +11 -11
  106. package/src/cdn-check.ts +21 -7
  107. package/src/check-diagnostics.ts +5 -3
  108. package/src/check-scan.ts +34 -3
  109. package/src/cli.ts +14 -5
  110. package/src/command-catalog.ts +126 -0
  111. package/src/doctor.ts +44 -1
  112. package/src/fix-recipes.ts +28 -0
  113. package/src/frontend-guidance.ts +20 -8
  114. package/src/introspect.ts +1 -1
  115. package/src/load.ts +13 -0
  116. package/src/mcp-exec.ts +74 -3
  117. package/src/mcp-http.ts +3 -2
  118. package/src/mcp-tool-meta.ts +268 -0
  119. package/src/mcp.ts +35 -99
  120. package/src/output-schemas.ts +28 -0
  121. package/src/ppr-read-fix.ts +426 -0
  122. package/src/recipes/5.6.0.ts +69 -0
  123. package/src/recipes/index.ts +2 -0
  124. package/src/review.ts +7 -2
  125. package/src/rules/codes.ts +9 -4
  126. package/src/rules/explanations.ts +39 -13
  127. package/src/rules/islands.ts +875 -3
  128. package/src/rules/ppr.ts +143 -0
  129. package/src/rules/swap.ts +402 -0
  130. package/src/scaffold-hole.ts +880 -0
  131. package/src/scaffold.ts +60 -49
  132. package/src/verification-plan.ts +20 -1
  133. package/src/web-app-options.ts +1 -0
  134. package/dist/rules/nano.d.ts +0 -6
  135. package/dist/rules/nano.d.ts.map +0 -1
  136. package/dist/rules/nano.js +0 -273
  137. package/dist/rules/nano.js.map +0 -1
  138. package/src/rules/nano.ts +0 -307
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nifrajs/cli",
3
- "version": "5.5.1",
3
+ "version": "5.6.0",
4
4
  "description": "The nifra CLI - zero-config dev/build/start for a nifra app (`nifra dev`, `nifra build`, `nifra start`).",
5
5
  "keywords": [
6
6
  "bun",
@@ -70,16 +70,16 @@
70
70
  "access": "public"
71
71
  },
72
72
  "dependencies": {
73
- "@nifrajs/client": "5.5.1",
74
- "@nifrajs/core": "5.5.1",
75
- "@nifrajs/agent-review": "5.5.1",
76
- "@nifrajs/i18n": "5.5.1",
77
- "@nifrajs/mcp": "5.5.1",
78
- "@nifrajs/mcp-db": "5.5.1",
79
- "@nifrajs/runner": "5.5.1",
80
- "@nifrajs/schema": "5.5.1",
81
- "@nifrajs/testing": "5.5.1",
82
- "@nifrajs/web": "5.5.1"
73
+ "@nifrajs/client": "5.6.0",
74
+ "@nifrajs/core": "5.6.0",
75
+ "@nifrajs/agent-review": "5.6.0",
76
+ "@nifrajs/i18n": "5.6.0",
77
+ "@nifrajs/mcp": "5.6.0",
78
+ "@nifrajs/mcp-db": "5.6.0",
79
+ "@nifrajs/runner": "5.6.0",
80
+ "@nifrajs/schema": "5.6.0",
81
+ "@nifrajs/testing": "5.6.0",
82
+ "@nifrajs/web": "5.6.0"
83
83
  },
84
84
  "repository": {
85
85
  "type": "git",
package/src/cdn-check.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  /**
2
2
  * `nifra cdn-check <url>` - is a deployed page actually served by the CDN the way `withCdn` intends?
3
3
  *
4
- * Read-only: two GETs of the page and one shaped like a soft navigation (`x-nifra-data: 1`). It names
5
- * the CDN from its status header, and fails when nifra's internal headers reach the visitor or when
6
- * the CDN answers a navigation data request with the cached document (Cloudflare's zone cache ignores
7
- * `Vary`, so it needs a rule that bypasses the cache for that header). CLI only: an agent-facing tool
8
- * that fetches arbitrary URLs from this machine could reach its private network.
4
+ * Read-only: two GETs of the page, one shaped like a soft navigation (`x-nifra-data: 1`) and one like a
5
+ * slot swap (`x-nifra-swap`). It names the CDN from its status header, and fails when nifra's internal
6
+ * headers reach the visitor or when the CDN answers a navigation or swap request with the cached
7
+ * document (Cloudflare's zone cache ignores `Vary`, so it needs a rule that bypasses the cache for
8
+ * those headers). CLI only: an agent-facing tool that fetches arbitrary URLs from this machine could
9
+ * reach its private network.
9
10
  */
10
11
  import type { CommandSpec } from "./command-catalog.ts"
11
12
 
@@ -17,7 +18,7 @@ export interface CdnCheckInput {
17
18
  export type CdnName = "cloudflare" | "vercel" | "fastly" | "unknown"
18
19
 
19
20
  export interface CdnCheckRequest {
20
- readonly kind: "first" | "second" | "data"
21
+ readonly kind: "first" | "second" | "data" | "swap"
21
22
  readonly status: number
22
23
  readonly cache?: string | undefined
23
24
  readonly age?: string | undefined
@@ -147,6 +148,9 @@ export async function runCdnCheck(
147
148
  requests.push(summarize("second", second))
148
149
  const data = await record({ "x-nifra-data": "1" })
149
150
  requests.push(summarize("data", data))
151
+ // A slot no page renders: the app answers with the document, so only the cache status tells.
152
+ const swap = await record({ "x-nifra-swap": "nifra-cdn-check" })
153
+ requests.push(summarize("swap", swap))
150
154
 
151
155
  for (const res of [first, second, data]) {
152
156
  const leaked = INTERNAL.filter((name) => res.headers.has(name))
@@ -208,6 +212,16 @@ export async function runCdnCheck(
208
212
  : "a soft navigation (x-nifra-data: 1) got the cached document instead of the page data; the CDN is not honoring Vary: x-nifra-data",
209
213
  })
210
214
  }
215
+ if (isHit(cacheStatus(cdn, swap.headers))) {
216
+ findings.push({
217
+ level: "fail",
218
+ code: "swap-served-from-cache",
219
+ message:
220
+ cdn === "cloudflare"
221
+ ? "a slot swap (x-nifra-swap) was answered from cache. The zone cache ignores Vary: the Cache Rule that bypasses x-nifra-data must bypass requests with an x-nifra-swap header too"
222
+ : "a slot swap (x-nifra-swap) was answered from cache; the CDN must bypass its cache for requests carrying that header",
223
+ })
224
+ }
211
225
  return { url: input.url, cdn, requests, findings }
212
226
  }
213
227
 
@@ -226,7 +240,7 @@ function renderCdnCheck(out: CdnCheckOutput): readonly string[] {
226
240
  export const cdnCheckSpec: CommandSpec<CdnCheckInput, CdnCheckOutput> = {
227
241
  name: "cdn-check",
228
242
  summary:
229
- "Check a deployed page behind a CDN: is it served from cache, do internal or CDN-only headers reach the visitor, and does a soft navigation get page data rather than the cached document.",
243
+ "Check a deployed page behind a CDN: is it served from cache, do internal or CDN-only headers reach the visitor, and do a soft navigation and a slot swap get their own answer rather than the cached document.",
230
244
  input: {
231
245
  jsonSchema: {
232
246
  type: "object",
@@ -29,12 +29,13 @@ import { islandRules } from "./rules/islands.ts"
29
29
  import { retiredLayoutRule } from "./rules/layout.ts"
30
30
  import { LEGACY_RULE_CODES, LEGACY_RULE_ORDER, legacyRules } from "./rules/legacy.ts"
31
31
  import { mergeAuthGapRule } from "./rules/merge-auth.ts"
32
- import { nanoRules } from "./rules/nano.ts"
33
32
  import { pageRules } from "./rules/pages.ts"
33
+ import { pprRules } from "./rules/ppr.ts"
34
34
  import { routeStatementRule } from "./rules/route-statement.ts"
35
35
  import { routeRules } from "./rules/routes.ts"
36
36
  import { secretRules } from "./rules/secrets.ts"
37
37
  import { securityRules } from "./rules/security.ts"
38
+ import { swapRules } from "./rules/swap.ts"
38
39
  import { zoneRules } from "./rules/zones.ts"
39
40
 
40
41
  /** A single machine-readable check failure - the unit an agent (or CI) acts on. */
@@ -499,13 +500,14 @@ export async function collectCheckDiagnostics(
499
500
  ...routeRules,
500
501
  contractVisibilityRule,
501
502
  ...pageRules,
503
+ ...pprRules,
502
504
  mergeAuthGapRule,
503
505
  routeStatementRule,
504
506
  ...zoneRules,
505
507
  ...dataGuardRules,
506
508
  ...secretRules,
507
509
  ...islandRules,
508
- ...nanoRules,
510
+ ...swapRules,
509
511
  ]
510
512
  let registryDiagnostics: Diagnostic[] = []
511
513
  let builtInsSucceeded = false
@@ -573,7 +575,7 @@ export async function collectCheckDiagnostics(
573
575
  continue
574
576
  }
575
577
  // A structured informational contract note intentionally has no old human/legacy row. Every
576
- // other non-legacy rule (security, route, island, nano, or an application pack) retains the
578
+ // other non-legacy rule (security, route, island, or an application pack) retains the
577
579
  // existing fallback row keyed by its stable code.
578
580
  if (knownLegacyCodes.has(item.code)) continue
579
581
  compatibilityRows.push({
package/src/check-scan.ts CHANGED
@@ -2461,6 +2461,37 @@ function sqlMethod(ts: TypeScriptApi, call: TSApi.CallExpression): SqlSink | und
2461
2461
  ? { method, receiver: receiver?.getText() }
2462
2462
  : undefined
2463
2463
  const callee = call.expression
2464
+ // Svelte compiles this unbound rune; it is not a driver's raw-statement escape hatch.
2465
+ if (
2466
+ ts.isPropertyAccessExpression(callee) &&
2467
+ callee.name.text === "raw" &&
2468
+ ts.isIdentifier(callee.expression) &&
2469
+ callee.expression.text === "$state"
2470
+ ) {
2471
+ const source = callee.getSourceFile()
2472
+ const imported = source.statements.some((statement) => {
2473
+ if (ts.isImportEqualsDeclaration(statement)) return statement.name.text === "$state"
2474
+ if (!ts.isImportDeclaration(statement)) return false
2475
+ const clause = statement.importClause
2476
+ const bindings = clause?.namedBindings
2477
+ return (
2478
+ clause?.name?.text === "$state" ||
2479
+ (bindings !== undefined &&
2480
+ (ts.isNamespaceImport(bindings)
2481
+ ? bindings.name.text === "$state"
2482
+ : bindings.elements.some((binding) => binding.name.text === "$state")))
2483
+ )
2484
+ })
2485
+ let bound = imported || isShadowedAt(ts, callee.expression, "$state")
2486
+ for (
2487
+ let scope: TSApi.Node | undefined = callee.parent;
2488
+ scope !== undefined && !bound;
2489
+ scope = scope.parent
2490
+ ) {
2491
+ bound = directBinding(ts, source, scope, "$state") !== undefined
2492
+ }
2493
+ if (/\.svelte(?:\.[jt]s)?$/.test(source.fileName) && !bound) return undefined
2494
+ }
2464
2495
  if (ts.isIdentifier(callee)) return sink(callee.text, undefined)
2465
2496
  if (ts.isPropertyAccessExpression(callee)) return sink(callee.name.text, callee.expression)
2466
2497
  if (ts.isElementAccessExpression(callee) && ts.isStringLiteralLike(callee.argumentExpression)) {
@@ -3507,7 +3538,7 @@ export async function walkSource(
3507
3538
  // A backslash is a filename character on POSIX; only Windows separators need normalizing.
3508
3539
  const rel = sep === "\\" ? normalizeProjectPath(rawRel) : rawRel
3509
3540
  // A `.js` file outside a zone is tooling (a bundler config, a script, a vendored asset), not app code.
3510
- if (PLAIN_SCRIPT_FILE.test(rel) && !ZONED_PATH.test(rel)) continue
3541
+ if (PLAIN_SCRIPT_FILE.test(rel) && !ZONE_DIRECTORY.test(rel) && !ZONE_SUFFIX.test(rel)) continue
3511
3542
  if (!skip.test(rel) && (opts.ignore === undefined || !opts.ignore(rel))) rels.push(rel)
3512
3543
  }
3513
3544
  const ignored = await gitIgnored(cwd, rels)
@@ -3520,8 +3551,8 @@ export async function walkSource(
3520
3551
  }
3521
3552
 
3522
3553
  const PLAIN_SCRIPT_FILE = /\.[cm]?js$/
3523
- const ZONED_PATH =
3524
- /(^|\/)(?:routes|frontend|shared|backend)\/|\.(?:frontend|shared|backend|fn)\.[^/]+$/
3554
+ const ZONE_DIRECTORY = /(?:^|\/)(?:routes|frontend|shared|backend)\//
3555
+ const ZONE_SUFFIX = /\.(?:frontend|shared|backend|fn)\.[^/]+$/
3525
3556
  /** A single-file component: its `<script>` blocks are the code a build compiles. */
3526
3557
  export const COMPONENT_FILE = /\.(?:svelte|vue)$/
3527
3558
 
package/src/cli.ts CHANGED
@@ -134,8 +134,8 @@ Usage:
134
134
  to fix it.
135
135
  nifra cdn-check <url> Check a deployed page behind a CDN: served from cache, no
136
136
  internal or CDN-only headers reaching the visitor, and soft
137
- navigations get page data, not the cached document. Exits 1
138
- on a failure.
137
+ navigations and slot swaps get their own answer, not the
138
+ cached document. Exits 1 on a failure.
139
139
  nifra db schema [<table>] The development database declared as \`devDatabase\` in
140
140
  nifra.config.ts: tables, columns, keys, indexes.
141
141
  nifra db query "<sql>" [--explain [--analyze]] One read-only SELECT (or its plan), in a fresh
@@ -207,7 +207,8 @@ Usage:
207
207
  nifra_db_role (the declared dev database, read-only),
208
208
  nifra_explain (structured errors), nifra_inspect (request
209
209
  traces), nifra_learn (guided build path).
210
- nifra docs-mcp [--port <n>] Serve the PUBLIC docs MCP over HTTP (nifra_docs + nifra_example) -
210
+ nifra docs-mcp [--port <n>] Serve the PUBLIC docs MCP over HTTP (nifra_docs, nifra_example,
211
+ nifra_types, nifra_learn, nifra_frontend, nifra_gallery) -
211
212
  self-host on a VPS so any remote agent can learn nifra. Default :8787.
212
213
  nifra learn [<step>] Print the guided build-an-app path (the human view of nifra_learn):
213
214
  no arg for the step index, a number for one step's goal/do/verify.
@@ -296,6 +297,12 @@ Usage:
296
297
  and zone the other modules into frontend/, backend/ or shared/
297
298
  (--zones keeps them in place and lists them in package.json
298
299
  "nifra.zones"). Dry-run by default; --write applies.
300
+ nifra scaffold hole <route> <name> [--shared] [--interactive] [--timeout <ms>] [--server] [--json]
301
+ Experimental: add a partially prerendered hole to a route whose
302
+ backend half exports shellLoader - its definition and <Hole> in
303
+ the page, its loader and output schema in the backend half. A
304
+ Vue or Svelte page gets the code to paste; --server writes a
305
+ React server component for the hole.
299
306
  nifra types [--check] [--json] Generate each route's ./+types module under .nifra/types: its
300
307
  params, the data its output schemas let through, and api typed
301
308
  by backend/app.ts. dev, build and check refresh them too;
@@ -335,13 +342,12 @@ set in the process environment is never overwritten by a file.
335
342
  ${renderCommandCatalogHelp()}`
336
343
 
337
344
  // Kept in lockstep with packages/cli/package.json by check:publish's version-consistency gate.
338
- const CLI_VERSION = "5.5.1"
345
+ const CLI_VERSION = "5.6.0"
339
346
 
340
347
  // A render adapter + nifra server are opaque to the CLI (it just forwards them); cast at the seam.
341
348
  const asAdapter = (v: unknown): RenderAdapter => v as RenderAdapter
342
349
  const asBunPlugins = (v: readonly unknown[]): BunPlugin[] => v as BunPlugin[]
343
350
 
344
- // biome-ignore lint/plugin/requireSafetyCommentForTypeAssertion: Trusted application configuration supplies native Vite plugins; the pinned pipeline validates their hooks.
345
351
  const asComponentPlugins = (
346
352
  value: readonly unknown[],
347
353
  ): NonNullable<
@@ -584,6 +590,7 @@ async function dev(app: LoadedApp, flags: Flags): Promise<void> {
584
590
  ...(fw.define ? { define: fw.define } : {}),
585
591
  indicator: showsIndicator(flags, fw),
586
592
  allowedHosts: fw.dev?.allowedHosts ?? [],
593
+ live: fw.live?.clientEntry,
587
594
  createApp: (clientEntry, importQuery, dev) =>
588
595
  createWebApp({
589
596
  adapter: asAdapter(fw.adapter),
@@ -641,6 +648,7 @@ async function dev(app: LoadedApp, flags: Flags): Promise<void> {
641
648
  port: flags.port,
642
649
  ...(flags.allowDuplicateIdentity ? { allowDuplicateIdentity: true } : {}),
643
650
  indicator: showsIndicator(flags, fw),
651
+ live: fw.live?.clientEntry,
644
652
  ...(fw.conditions ? { conditions: fw.conditions } : {}),
645
653
  ...(fw.define ? { define: fw.define } : {}),
646
654
  // `load` resolves route modules through VITE, not through Bun. That is what makes the Vite
@@ -915,6 +923,7 @@ async function buildForTarget(
915
923
  ...(fw.cssCodeSplit !== undefined ? { cssCodeSplit: fw.cssCodeSplit } : {}),
916
924
  ...(fw.cssLoading !== undefined ? { cssLoading: fw.cssLoading } : {}),
917
925
  ...(fw.clientIp !== undefined ? { clientIp: fw.clientIp } : {}),
926
+ live: fw.live?.clientEntry,
918
927
  // Prerendering drives a built app: the static target is made of its pages, and a bun or node server
919
928
  // answers its prerendered pages from their file. Not under Vite, whose server bundle may rely on
920
929
  // transforms the prerender pass (Bun's runtime) does not apply: those pages keep rendering on demand.
@@ -30,6 +30,7 @@ import { collectPortResult, type PortResult, renderReport } from "./port.ts"
30
30
  import type { ReplayResult } from "./replay.ts"
31
31
  import { reviewSpec } from "./review.ts"
32
32
  import type { RouteTypesReport } from "./route-types.ts"
33
+ import type { HoleScaffoldResult } from "./scaffold-hole.ts"
33
34
  import type { SmokeReport } from "./smoke.ts"
34
35
  import type { StylexMigrationResult } from "./stylex-migrate.ts"
35
36
  import {
@@ -373,6 +374,19 @@ interface MigrateInput {
373
374
  readonly dir?: string | undefined
374
375
  }
375
376
 
377
+ /** `scaffold hole <route> <name>`: the parser admits only the `hole` kind. */
378
+ interface ScaffoldInput {
379
+ readonly kind: "hole"
380
+ readonly route: string
381
+ readonly name: string
382
+ readonly shared?: boolean | undefined
383
+ readonly interactive?: boolean | undefined
384
+ readonly timeout?: number | undefined
385
+ readonly server?: boolean | undefined
386
+ readonly json?: boolean | undefined
387
+ readonly dir?: string | undefined
388
+ }
389
+
376
390
  interface TargetInput {
377
391
  readonly target?: string | undefined
378
392
  readonly json?: boolean | undefined
@@ -750,6 +764,43 @@ const FIX_SCHEMA = input<FixInput>(
750
764
  },
751
765
  )
752
766
 
767
+ const SCAFFOLD_SCHEMA = input<ScaffoldInput>(
768
+ objectSchema(
769
+ {
770
+ kind: { type: "string", enum: ["hole"] },
771
+ route: { type: "string" },
772
+ name: { type: "string" },
773
+ shared: { type: "boolean" },
774
+ interactive: { type: "boolean" },
775
+ timeout: { type: "integer" },
776
+ server: { type: "boolean" },
777
+ json: { type: "boolean" },
778
+ dir: { type: "string" },
779
+ },
780
+ ["kind", "route", "name"],
781
+ ),
782
+ (value) => {
783
+ const raw = withDir(record(value))
784
+ if (raw.kind !== "hole")
785
+ throw new TypeError("scaffold what: `nifra scaffold hole <route> <name>`")
786
+ const route = optionalString(raw.route, "route")
787
+ const name = optionalString(raw.name, "name")
788
+ if (route === undefined || name === undefined)
789
+ throw new TypeError(
790
+ "`nifra scaffold hole <route> <name>` needs the route and the hole's name",
791
+ )
792
+ const timeout = optionalNumber(raw.timeout, "timeout")
793
+ return {
794
+ kind: "hole",
795
+ route,
796
+ name,
797
+ ...parseBooleanFlags(raw, ["shared", "interactive", "server", "json"]),
798
+ ...(timeout === undefined ? {} : { timeout }),
799
+ ...(raw.dir === undefined ? {} : { dir: raw.dir }),
800
+ }
801
+ },
802
+ )
803
+
753
804
  const MIGRATE_SCHEMA = input<MigrateInput>(
754
805
  objectSchema({
755
806
  kind: { type: "string", enum: ["layout"] },
@@ -1604,6 +1655,80 @@ const migrateSpec: CommandSpec<MigrateInput, MigrateCommandOutput> = {
1604
1655
  success: (out) => out.ok,
1605
1656
  }
1606
1657
 
1658
+ const scaffoldSpec: CommandSpec<ScaffoldInput, HoleScaffoldResult> = {
1659
+ name: "scaffold",
1660
+ summary:
1661
+ "Add a partially prerendered hole to a route (`scaffold hole <route> <name>`): its definition and `<Hole>` in the page, its loader in the backend half.",
1662
+ input: SCAFFOLD_SCHEMA,
1663
+ output: output({
1664
+ type: "object",
1665
+ properties: {
1666
+ ok: { type: "boolean" },
1667
+ page: { type: "string" },
1668
+ backend: { type: "string" },
1669
+ changed: { type: "array" },
1670
+ snippets: { type: "array" },
1671
+ next: { type: "array" },
1672
+ reason: { type: "string" },
1673
+ },
1674
+ required: ["ok", "page", "backend", "changed", "snippets", "next"],
1675
+ }),
1676
+ transports: ["cli"],
1677
+ stability: "experimental",
1678
+ argv: {
1679
+ positionals: ["kind", "route", "name"],
1680
+ flags: [
1681
+ { name: "shared", field: "shared", type: "boolean" },
1682
+ { name: "interactive", field: "interactive", type: "boolean" },
1683
+ { name: "timeout", field: "timeout", type: "number" },
1684
+ { name: "server", field: "server", type: "boolean" },
1685
+ { name: "json", field: "json", type: "boolean" },
1686
+ { name: "dir", field: "dir", type: "string" },
1687
+ ],
1688
+ },
1689
+ async run(value, ctx) {
1690
+ const dir = resolve(ctx.cwd, value.dir ?? ".")
1691
+ const app =
1692
+ ctx.loadApp !== undefined && value.dir === undefined
1693
+ ? await ctx.loadApp()
1694
+ : await import("./load.ts").then(({ loadApp }) => loadApp(dir))
1695
+ const { frameworkFromClientModule } = await import("./scaffold.ts")
1696
+ const { holeRouteFiles, routeTypeScript, scaffoldHole } = await import("./scaffold-hole.ts")
1697
+ const framework = frameworkFromClientModule(app.framework.clientModule)
1698
+ const { page, backend } = holeRouteFiles(value.route, framework)
1699
+ const loaded = await routeTypeScript(dir, [page, backend])
1700
+ if (loaded.unsupported !== undefined) throw loaded.unsupported
1701
+ if (loaded.compiler === undefined)
1702
+ throw new Error(
1703
+ "[nifra] scaffold hole places each edit through the route's syntax tree, so it needs TypeScript - run `bun add -d typescript`, then rerun it",
1704
+ )
1705
+ try {
1706
+ return await scaffoldHole(
1707
+ dir,
1708
+ value.route,
1709
+ value.name,
1710
+ framework,
1711
+ {
1712
+ shared: value.shared,
1713
+ interactive: value.interactive,
1714
+ timeout: value.timeout,
1715
+ server: value.server,
1716
+ },
1717
+ loaded.compiler,
1718
+ )
1719
+ } finally {
1720
+ await loaded.session?.close()
1721
+ }
1722
+ },
1723
+ render: (out) => [
1724
+ out.ok ? `✓ hole scaffolded on ${out.page}` : `✖ ${out.reason ?? "not scaffolded"}`,
1725
+ ...out.changed.map((file) => ` edit ${file}`),
1726
+ ...out.snippets.flatMap((snippet) => [` paste into ${snippet.file}:`, "", snippet.code, ""]),
1727
+ ...out.next.map((step) => ` next ${step}`),
1728
+ ],
1729
+ success: (out) => out.ok,
1730
+ }
1731
+
1607
1732
  const targetSpec: CommandSpec<TargetInput, TargetOutput> = {
1608
1733
  name: "target",
1609
1734
  summary:
@@ -2069,6 +2194,7 @@ export const commandSpecs = Object.freeze([
2069
2194
  doctorSpec,
2070
2195
  fixSpec,
2071
2196
  migrateSpec,
2197
+ scaffoldSpec,
2072
2198
  targetSpec,
2073
2199
  typesSpec,
2074
2200
  schemasSpec,
package/src/doctor.ts CHANGED
@@ -16,10 +16,11 @@
16
16
  * therefore also covers `*.test.ts`/`*.spec.ts`, which `nifra check` skips - `tsc` compiles them, so an
17
17
  * undeclared import there fails a clean `bun install --frozen-lockfile` build just the same.
18
18
  */
19
- import type { Dirent } from "node:fs"
19
+ import { type Dirent, existsSync } from "node:fs"
20
20
  import { readdir, realpath, stat } from "node:fs/promises"
21
21
  import { builtinModules } from "node:module"
22
22
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
23
+ import { discoverRoutes } from "@nifrajs/web/fs"
23
24
  import {
24
25
  collectIdentityParity,
25
26
  displayPath,
@@ -222,6 +223,13 @@ export interface DoctorResult {
222
223
  * Advisory (never folded into `ok`). `lock` is the lockfile, relative to the project.
223
224
  */
224
225
  readonly staleLinkLocks?: { readonly lock: string; readonly entries: readonly StaleLinkLock[] }
226
+ /**
227
+ * Route files that export `keepAlive` in an app where nothing names its sign-in cookie: no
228
+ * `@nifrajs/auth`, Better Auth or Auth.js dependency, no `identityCookies`, `rotateIdentityEpoch()`
229
+ * or `identityChanged()`. A sign-out there may leave the previous visitor's kept pages. Advisory
230
+ * (never folded into `ok`).
231
+ */
232
+ readonly keepAliveIdentity?: { readonly routes: readonly string[] }
225
233
  /** Static production-readiness evidence for the selected deploy target. */
226
234
  readonly readiness?: DoctorReadiness
227
235
  /** The explicit source boundary used by the dependency scan. */
@@ -855,6 +863,28 @@ async function inferDependencyFix(
855
863
  }
856
864
 
857
865
  /** Run doctor against the project at `cwd`: diff source imports vs declared deps. */
866
+ // Packages whose session cookies the identity epoch knows by their default names.
867
+ const KNOWN_AUTH_PACKAGES = [
868
+ "@nifrajs/auth",
869
+ "@nifrajs/authjs",
870
+ "better-auth",
871
+ "@auth/core",
872
+ "next-auth",
873
+ ]
874
+ const IDENTITY_SIGNAL = /\b(?:identityCookies\s*:|rotateIdentityEpoch\s*\(|identityChanged\s*\()/
875
+
876
+ function keepAliveRoutes(cwd: string): readonly string[] {
877
+ const routesDir = join(cwd, "routes")
878
+ if (!existsSync(routesDir)) return []
879
+ try {
880
+ return discoverRoutes(routesDir)
881
+ .routes.filter((route) => route.keepAlive === true)
882
+ .map((route) => `routes/${route.file}`)
883
+ } catch {
884
+ return []
885
+ }
886
+ }
887
+
858
888
  export async function collectDoctorResult(
859
889
  cwd: string,
860
890
  opts: { readonly target?: string; readonly strict?: boolean; readonly cliVersion?: string } = {},
@@ -867,6 +897,7 @@ export async function collectDoctorResult(
867
897
 
868
898
  const findings: DoctorFinding[] = []
869
899
  const manifestLists: ManifestList[] = []
900
+ let identitySignal = false
870
901
  // A standalone app owns its tests, so they remain in the declaration check. A workspace root owns
871
902
  // the published package source while its root devDependencies intentionally own shared tests,
872
903
  // benchmarks, and scaffold copy-surfaces. Keep that boundary explicit instead of reporting a
@@ -898,6 +929,7 @@ export async function collectDoctorResult(
898
929
  findings.push({ file: f.file, line: f.line, package: f.snippet })
899
930
  }
900
931
  manifestLists.push(...manifestListsIn(rel, content))
932
+ if (!identitySignal && IDENTITY_SIGNAL.test(content)) identitySignal = true
901
933
  },
902
934
  { includeTests: scanScope.includeTests, ignore: workspaceSurface },
903
935
  )
@@ -918,6 +950,10 @@ export async function collectDoctorResult(
918
950
  const lockDir = bunLockDir(cwd)
919
951
  const linkLocks = lockDir === undefined ? [] : staleLinkLocks(lockDir)
920
952
  const handBuilt = handBuiltManifests(cwd, manifestLists)
953
+ const unnamedIdentity =
954
+ identitySignal || KNOWN_AUTH_PACKAGES.some((name) => dependencySpec(pkg, name) !== undefined)
955
+ ? []
956
+ : keepAliveRoutes(cwd)
921
957
  // `staleDists`, `toolingDrift` and `staleMcpPins` are advisory (see DoctorResult): they never fail `ok`.
922
958
  return {
923
959
  ok:
@@ -937,6 +973,7 @@ export async function collectDoctorResult(
937
973
  ...(toolingDrift !== undefined ? { toolingDrift } : {}),
938
974
  ...(versionDrift !== undefined ? { versionDrift } : {}),
939
975
  ...(handBuilt.length > 0 ? { handBuiltManifests: handBuilt } : {}),
976
+ ...(unnamedIdentity.length > 0 ? { keepAliveIdentity: { routes: unnamedIdentity } } : {}),
940
977
  ...(staleMcpPins !== undefined && staleMcpPins.files.length > 0 ? { staleMcpPins } : {}),
941
978
  ...(lockDir !== undefined && linkLocks.length > 0
942
979
  ? {
@@ -1144,6 +1181,12 @@ export function doctorReport(result: DoctorResult, cliVersion?: string): string[
1144
1181
  for (const finding of result.handBuiltManifests ?? []) {
1145
1182
  lines.push(`⚠ ${handBuiltManifestMessage(finding)}\n`)
1146
1183
  }
1184
+ if (result.keepAliveIdentity !== undefined) {
1185
+ lines.push(
1186
+ `⚠ ${result.keepAliveIdentity.routes.join(", ")} keep pages alive, and nothing names this app's sign-in cookie (no @nifrajs/auth, Better Auth or Auth.js, no identityCookies): a sign-out may leave the previous visitor's pages one back away`,
1187
+ " fix: name the session cookie in createWebApp({ keepAlive: { identityCookies } }), or call identityChanged() from @nifrajs/web/client for token auth - /docs/keep-alive#sign-in\n",
1188
+ )
1189
+ }
1147
1190
  // Advisory: the agent's MCP server is launched from these pins, so a stale one answers for an old
1148
1191
  // release even when the CLI running doctor matches the project.
1149
1192
  if (result.staleMcpPins !== undefined) {
@@ -190,6 +190,34 @@ registerFixRecipe({
190
190
  },
191
191
  })
192
192
 
193
+ registerFixRecipe({
194
+ id: "ppr.read-to-hole",
195
+ description:
196
+ "Move a partially prerendered page's request read into a new dynamic hole: the read becomes the hole's loader, and the element that shows it the hole's render.",
197
+ onlyWhenNamed: true,
198
+ verify: "nifra check",
199
+ async apply(root, diagnostic) {
200
+ const file = diagnostic.file
201
+ if (file === undefined || (await resolveInsideProject(root, file)) === undefined) return []
202
+ const { loadApp } = await import("./load.ts")
203
+ const { backendFileOf, frameworkFromClientModule } = await import("./scaffold.ts")
204
+ const framework = frameworkFromClientModule((await loadApp(root)).framework.clientModule)
205
+ const { routeTypeScript } = await import("./scaffold-hole.ts")
206
+ const loaded = await routeTypeScript(root, [file, backendFileOf(file)])
207
+ if (loaded.unsupported !== undefined) throw loaded.unsupported
208
+ if (loaded.compiler === undefined)
209
+ throw new Error(
210
+ "[nifra] the hole fix places each edit through the page's syntax tree, so it needs TypeScript - run `bun add -d typescript`, then rerun the fix",
211
+ )
212
+ try {
213
+ const { moveReadToHole } = await import("./ppr-read-fix.ts")
214
+ return await moveReadToHole(root, file, diagnostic.line, framework, loaded.compiler)
215
+ } finally {
216
+ await loaded.session?.close()
217
+ }
218
+ },
219
+ })
220
+
193
221
  registerFixRecipe({
194
222
  id: "layout.migrate",
195
223
  description:
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * `nifra_frontend` - a symptom-indexed catalog of the mistakes an agent (or a human) hits on the client
3
3
  * side of a nifra app, across every adapter. It is the FRONTEND companion to `nifra_check`: where the
4
- * check statically flags the footguns nifra's own seam owns (server-only imports, the nano lane), this
4
+ * check statically flags the footguns nifra's own seam owns (server-only imports, island bindings), this
5
5
  * catalog covers the ones a static rule can't own cheaply - hydration nondeterminism, a duplicated
6
6
  * framework runtime, and the per-framework reactivity-loss idioms that each ecosystem's own linter is
7
7
  * the real authority on.
@@ -102,8 +102,8 @@ export const FRONTEND_GUIDANCE: readonly GuidanceEntry[] = [
102
102
  "The list is keyed by the array index (or not keyed at all), so add/remove/reorder maps the wrong item to an existing node.",
103
103
  fix: "Key each row by a stable, unique id from the item, never its position in the array.",
104
104
  verify:
105
- "The framework's own linter for JSX keys; on the vanilla nano lane, nifra_check flags an index key as NF-C022.",
106
- seeAlso: "list key stable id reconcile nano",
105
+ "The framework's own linter for JSX keys; for an islands bindList, nifra_check flags a positional key as NF-C022.",
106
+ seeAlso: "list key stable id reconcile bindList islands",
107
107
  },
108
108
  {
109
109
  id: "vue-lost-reactivity",
@@ -153,16 +153,28 @@ export const FRONTEND_GUIDANCE: readonly GuidanceEntry[] = [
153
153
  seeAlso: "eslint-plugin-react-hooks exhaustive-deps effect closure",
154
154
  },
155
155
  {
156
- id: "prefer-nano-or-island",
156
+ id: "prefer-reactive-island",
157
157
  adapters: ["vanilla"],
158
158
  symptom:
159
159
  "A vanilla page needs local state or a list a human edits, and hand-written DOM updates are getting fragile.",
160
160
  cause:
161
- "The islands lane is imperative and has no state primitive, so each update is hand-wired and a list means rebuilding the container.",
162
- fix: "Use the nano lane: `signal` + `computed(fn, [deps])` for state, `bindList` for a keyed list, `resource` for async. Every reactive edge is a visible call, so its mistakes are static lints.",
161
+ "An imperative defineIsland enhancer has no state primitive, so each update is hand-wired and a list means rebuilding the container.",
162
+ fix: "Mount the island with `bindIsland`: `state(key, fallback)` for state, `data-bind-*` attributes for the markup, `bindList` for a keyed list, `resource` for async. Everything the setup creates stops when the island unmounts.",
163
163
  verify:
164
- "nifra_check runs NF-C021 (discarded disposer), NF-C022 (index key), NF-C023 (missing dep) over the nano code.",
165
- seeAlso: "nano signal computed bindList resource islands",
164
+ "nifra_check runs NF-C047 (a binding names no state or handler), NF-C048 (a binding outside a bindIsland host) and NF-C022 (a positional list key) over the island code.",
165
+ seeAlso: "bindIsland state data-bind bindList resource islands",
166
+ },
167
+ {
168
+ id: "swap-a-region",
169
+ adapters: ["vanilla"],
170
+ symptom:
171
+ 'A search form, a filter or a "more" link on a vanilla page reloads the whole document to change one region.',
172
+ cause:
173
+ "A plain link or form always loads a full page, and a vanilla page has no client router to fetch only the part that changed.",
174
+ fix: 'Mark the region `data-swap-slot="results"` and make `slot("results", content)` its only content, add `data-swap="replace:results"` (or `append:results`) to the link or form, and call `enableSwap` from `@nifrajs/web/islands/swap` in place of `mountIslands`. The server answers with that slot of the same page; anything else loads normally.',
175
+ verify:
176
+ "nifra_check runs NF-C049 to NF-C052 over the swap markup and NF-C048 over bindings inside a slot.",
177
+ seeAlso: "data-swap data-swap-slot slot enableSwap islands",
166
178
  },
167
179
  ]
168
180
 
package/src/introspect.ts CHANGED
@@ -610,7 +610,7 @@ export function routeTableToJson(rows: readonly RouteTableEntry[]): {
610
610
  methods: r.methods,
611
611
  ...(r.file !== undefined ? { file: r.file } : {}),
612
612
  ...(r.kind === "api" ? { autoMounted: r.autoMounted === true } : {}),
613
- // biome-ignore lint/plugin/noConditionalEmptyObjectSpread: `--json` rows gain the key only where it is true, so existing consumers see no change.
613
+ // `--json` rows gain the key only where it is true, so existing consumers see no change.
614
614
  ...(r.inProcessOnly === true ? { inProcessOnly: true } : {}),
615
615
  ...(client === undefined
616
616
  ? {}