@nifrajs/cli 5.5.0 → 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 (143) hide show
  1. package/CHANGELOG.md +172 -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/internal/source-facts.d.ts +2 -1
  31. package/dist/internal/source-facts.d.ts.map +1 -1
  32. package/dist/internal/source-facts.js +17 -11
  33. package/dist/internal/source-facts.js.map +1 -1
  34. package/dist/introspect.js +1 -1
  35. package/dist/introspect.js.map +1 -1
  36. package/dist/load.d.ts +4 -1
  37. package/dist/load.d.ts.map +1 -1
  38. package/dist/load.js +8 -0
  39. package/dist/load.js.map +1 -1
  40. package/dist/mcp-exec.d.ts.map +1 -1
  41. package/dist/mcp-exec.js +57 -3
  42. package/dist/mcp-exec.js.map +1 -1
  43. package/dist/mcp-http.d.ts +2 -1
  44. package/dist/mcp-http.d.ts.map +1 -1
  45. package/dist/mcp-http.js +3 -2
  46. package/dist/mcp-http.js.map +1 -1
  47. package/dist/mcp-tool-meta.d.ts +21 -0
  48. package/dist/mcp-tool-meta.d.ts.map +1 -0
  49. package/dist/mcp-tool-meta.js +246 -0
  50. package/dist/mcp-tool-meta.js.map +1 -0
  51. package/dist/mcp.d.ts +3 -2
  52. package/dist/mcp.d.ts.map +1 -1
  53. package/dist/mcp.js +36 -98
  54. package/dist/mcp.js.map +1 -1
  55. package/dist/output-schemas.d.ts +8 -0
  56. package/dist/output-schemas.d.ts.map +1 -1
  57. package/dist/output-schemas.js +14 -0
  58. package/dist/output-schemas.js.map +1 -1
  59. package/dist/ppr-read-fix.d.ts +8 -0
  60. package/dist/ppr-read-fix.d.ts.map +1 -0
  61. package/dist/ppr-read-fix.js +356 -0
  62. package/dist/ppr-read-fix.js.map +1 -0
  63. package/dist/recipes/5.6.0.d.ts +10 -0
  64. package/dist/recipes/5.6.0.d.ts.map +1 -0
  65. package/dist/recipes/5.6.0.js +68 -0
  66. package/dist/recipes/5.6.0.js.map +1 -0
  67. package/dist/recipes/index.d.ts.map +1 -1
  68. package/dist/recipes/index.js +2 -0
  69. package/dist/recipes/index.js.map +1 -1
  70. package/dist/review.d.ts.map +1 -1
  71. package/dist/review.js +7 -2
  72. package/dist/review.js.map +1 -1
  73. package/dist/rules/codes.d.ts +8 -3
  74. package/dist/rules/codes.d.ts.map +1 -1
  75. package/dist/rules/codes.js +9 -4
  76. package/dist/rules/codes.js.map +1 -1
  77. package/dist/rules/explanations.d.ts.map +1 -1
  78. package/dist/rules/explanations.js +39 -13
  79. package/dist/rules/explanations.js.map +1 -1
  80. package/dist/rules/islands.d.ts +91 -0
  81. package/dist/rules/islands.d.ts.map +1 -1
  82. package/dist/rules/islands.js +757 -3
  83. package/dist/rules/islands.js.map +1 -1
  84. package/dist/rules/ppr.d.ts +16 -0
  85. package/dist/rules/ppr.d.ts.map +1 -0
  86. package/dist/rules/ppr.js +114 -0
  87. package/dist/rules/ppr.js.map +1 -0
  88. package/dist/rules/swap.d.ts +7 -0
  89. package/dist/rules/swap.d.ts.map +1 -0
  90. package/dist/rules/swap.js +338 -0
  91. package/dist/rules/swap.js.map +1 -0
  92. package/dist/scaffold-hole.d.ts +105 -0
  93. package/dist/scaffold-hole.d.ts.map +1 -0
  94. package/dist/scaffold-hole.js +688 -0
  95. package/dist/scaffold-hole.js.map +1 -0
  96. package/dist/scaffold.d.ts +5 -3
  97. package/dist/scaffold.d.ts.map +1 -1
  98. package/dist/scaffold.js +56 -46
  99. package/dist/scaffold.js.map +1 -1
  100. package/dist/verification-plan.d.ts.map +1 -1
  101. package/dist/verification-plan.js +12 -1
  102. package/dist/verification-plan.js.map +1 -1
  103. package/dist/web-app-options.d.ts +1 -1
  104. package/dist/web-app-options.d.ts.map +1 -1
  105. package/dist/web-app-options.js.map +1 -1
  106. package/docs/examples.json +63 -9
  107. package/docs/llms-full.txt +2070 -437
  108. package/docs/types.json +1300 -270
  109. package/package.json +11 -11
  110. package/src/cdn-check.ts +21 -7
  111. package/src/check-diagnostics.ts +5 -3
  112. package/src/check-scan.ts +34 -3
  113. package/src/cli.ts +14 -5
  114. package/src/command-catalog.ts +126 -0
  115. package/src/doctor.ts +44 -1
  116. package/src/fix-recipes.ts +28 -0
  117. package/src/frontend-guidance.ts +20 -8
  118. package/src/internal/source-facts.ts +27 -13
  119. package/src/introspect.ts +1 -1
  120. package/src/load.ts +13 -0
  121. package/src/mcp-exec.ts +74 -3
  122. package/src/mcp-http.ts +3 -2
  123. package/src/mcp-tool-meta.ts +268 -0
  124. package/src/mcp.ts +35 -99
  125. package/src/output-schemas.ts +28 -0
  126. package/src/ppr-read-fix.ts +426 -0
  127. package/src/recipes/5.6.0.ts +69 -0
  128. package/src/recipes/index.ts +2 -0
  129. package/src/review.ts +7 -2
  130. package/src/rules/codes.ts +9 -4
  131. package/src/rules/explanations.ts +39 -13
  132. package/src/rules/islands.ts +875 -3
  133. package/src/rules/ppr.ts +143 -0
  134. package/src/rules/swap.ts +402 -0
  135. package/src/scaffold-hole.ts +880 -0
  136. package/src/scaffold.ts +60 -49
  137. package/src/verification-plan.ts +20 -1
  138. package/src/web-app-options.ts +1 -0
  139. package/dist/rules/nano.d.ts +0 -6
  140. package/dist/rules/nano.d.ts.map +0 -1
  141. package/dist/rules/nano.js +0 -273
  142. package/dist/rules/nano.js.map +0 -1
  143. package/src/rules/nano.ts +0 -307
package/src/mcp.ts CHANGED
@@ -40,8 +40,9 @@
40
40
  * handed to that CLI; when that is impossible the version-sensitive tools refuse rather than answer
41
41
  * for the wrong release (see `./mcp-delegate.ts`). The protocol is hand-rolled (newline-delimited JSON-RPC 2.0 over stdio), including
42
42
  * standard MCP progress notifications and request cancellation - no SDK dependency, the same
43
- * minimal-surface choice as the rest of nifra. The pure dispatch lives in `./mcp-protocol.ts`; this
44
- * module is the I/O shell (stdin loop, tool wiring, the run subprocess).
43
+ * minimal-surface choice as the rest of nifra. The pure dispatch lives in `./mcp-protocol.ts` and the
44
+ * stdio framing in `@nifrajs/mcp/stdio`; this module is the dispatch shell (roots, tool wiring, the run
45
+ * subprocess).
45
46
  *
46
47
  * This process runs no project code and holds none of the project's `.env`: the config, the backend
47
48
  * and everything they import run in a fresh subprocess per call (`./mcp-isolate.ts`), and a session
@@ -50,6 +51,7 @@
50
51
 
51
52
  import { stat } from "node:fs/promises"
52
53
  import { resolve } from "node:path"
54
+ import { runStdioTransport, type StdioConnection } from "@nifrajs/mcp/stdio"
53
55
  import { loadDocsCorpus } from "./docs-search.ts"
54
56
  import { loadExamplesCorpus } from "./examples.ts"
55
57
  import type { AppLoader } from "./load.ts"
@@ -59,9 +61,6 @@ import { docsTools } from "./mcp-docs-tools.ts"
59
61
  import {
60
62
  createMcpProtocolState,
61
63
  handleRpc,
62
- isJsonRpcRequest,
63
- isJsonRpcResponse,
64
- type JsonRpcNotification,
65
64
  type JsonRpcRequest,
66
65
  type JsonRpcResponse,
67
66
  type McpPrompt,
@@ -188,8 +187,6 @@ const ANSWERED_WITHOUT_THE_APP: ReadonlySet<string> = new Set([
188
187
  "notifications/initialized",
189
188
  "notifications/roots/list_changed",
190
189
  ])
191
- const MAX_STDIO_MESSAGE_BYTES = 8 * 1024 * 1024
192
- const STDIO_ENCODER = new TextEncoder()
193
190
 
194
191
  interface ProjectApp {
195
192
  readonly name: string
@@ -268,29 +265,12 @@ export async function runMcpServer(
268
265
  let drift: ToolingDrift | undefined = await detectToolingDrift(rootState.root, version)
269
266
  const serverInfo = { name: "nifra", version }
270
267
  const state = createMcpProtocolState()
271
- const send = (message: JsonRpcResponse | JsonRpcNotification): void => {
272
- let encoded: string
273
- try {
274
- encoded = JSON.stringify(message)
275
- } catch {
276
- encoded = JSON.stringify(
277
- rpcError(responseIdOf(message), -32603, "MCP response is not serializable"),
278
- )
279
- }
280
- if (STDIO_ENCODER.encode(encoded).byteLength > MAX_STDIO_MESSAGE_BYTES)
281
- encoded = JSON.stringify(
282
- rpcError(responseIdOf(message), -32603, "MCP response exceeded the size limit"),
283
- )
284
- process.stdout.write(`${encoded}\n`)
285
- }
286
268
  let rootsSupported = false
287
269
  let rootsRequestPending = false
288
- const requestRoots = (): void => {
270
+ const requestRoots = (connection: StdioConnection): void => {
289
271
  if (!rootsSupported || rootsRequestPending) return
290
272
  rootsRequestPending = true
291
- process.stdout.write(
292
- `${JSON.stringify({ jsonrpc: "2.0", id: ROOTS_REQUEST_ID, method: "roots/list" })}\n`,
293
- )
273
+ connection.send({ jsonrpc: "2.0", id: ROOTS_REQUEST_ID, method: "roots/list" })
294
274
  }
295
275
  const onRootsAnswer = async (message: JsonRpcResponse): Promise<void> => {
296
276
  const result = "result" in message ? message.result : undefined
@@ -310,15 +290,20 @@ export async function runMcpServer(
310
290
  // must see the adopted root, even though dispatches themselves run concurrently.
311
291
  let rootsUpdate: Promise<void> = Promise.resolve()
312
292
 
313
- const dispatchRootsAnswer = (message: JsonRpcResponse): void => {
293
+ const dispatchRootsAnswer = (message: JsonRpcResponse): boolean => {
314
294
  // The roots answer is a response to a request initiated by this server, not a client RPC request.
315
295
  // Serialize adoption with normal dispatch so a following request cannot observe a half-updated root.
316
- if (!rootsRequestPending) return
296
+ if (message.id !== ROOTS_REQUEST_ID) return false
297
+ if (!rootsRequestPending) return true
317
298
  rootsRequestPending = false
318
299
  rootsUpdate = onRootsAnswer(message).catch(() => {})
300
+ return true
319
301
  }
320
302
 
321
- const dispatch = async (message: JsonRpcRequest): Promise<void> => {
303
+ const dispatch = async (
304
+ message: JsonRpcRequest,
305
+ connection: StdioConnection,
306
+ ): Promise<JsonRpcResponse | null> => {
322
307
  await rootsUpdate
323
308
  if (message.method === "initialize") {
324
309
  rootsSupported = clientSupportsRoots(message.params)
@@ -338,13 +323,12 @@ export async function runMcpServer(
338
323
  prompts: projectPrompts(),
339
324
  instructions: rootInstructions(rootState, drift),
340
325
  },
341
- { state, sendNotification: send, exposeToolErrors: true },
326
+ { state, sendNotification: connection.send, exposeToolErrors: true },
342
327
  )
343
- if (response) send(response)
344
328
  // Ask for the client's workspace roots once the handshake completes, and again whenever the
345
- // client says they changed. The answer comes back through the interception above.
346
- if (method.startsWith("notifications/")) requestRoots()
347
- return
329
+ // client says they changed. The answer comes back through `dispatchRootsAnswer`.
330
+ if (method.startsWith("notifications/")) requestRoots(connection)
331
+ return response
348
332
  }
349
333
  const project = await ctx
350
334
  let activeTools: McpTool[]
@@ -386,76 +370,28 @@ export async function runMcpServer(
386
370
  ...project.features,
387
371
  instructions: rootInstructions(rootState, drift),
388
372
  }
389
- const response = await handleRpc(message, activeTools, serverInfo, features, {
373
+ return handleRpc(message, activeTools, serverInfo, features, {
390
374
  state,
391
- sendNotification: send,
375
+ sendNotification: connection.send,
392
376
  // The stdio caller is the developer's own agent: a failure it cannot read it cannot fix.
393
377
  exposeToolErrors: true,
394
378
  })
395
- if (response) send(response)
396
379
  }
397
380
 
398
- const decoder = new TextDecoder()
399
- let buffer = ""
400
- let bufferBytes = 0
401
- let discardingOversized = false
402
- const processLine = (rawLine: string): void => {
403
- const line = rawLine.trim()
404
- if (line === "") return
405
- if (STDIO_ENCODER.encode(rawLine).byteLength > MAX_STDIO_MESSAGE_BYTES) {
406
- send(rpcError(null, -32600, "MCP message exceeded the size limit"))
407
- return
408
- }
409
- let parsed: unknown
410
- try {
411
- parsed = JSON.parse(line) as unknown
412
- } catch {
413
- send(rpcError(null, -32700, "parse error"))
414
- return
415
- }
416
- if (isJsonRpcRequest(parsed)) {
417
- void dispatch(parsed).catch((err) => {
418
- const msg = err instanceof Error ? err.message : String(err)
419
- send(rpcError(parsed.id ?? null, -32603, msg))
420
- })
421
- } else if (isJsonRpcResponse(parsed) && parsed.id === ROOTS_REQUEST_ID) {
422
- dispatchRootsAnswer(parsed)
423
- } else {
424
- // Do not let null, arrays, scalars, responses for unknown ids, or malformed envelopes reach the
425
- // dispatch shell. In particular, reading `.id` from a hostile `null` must never crash the loop.
426
- send(rpcError(null, -32600, "Invalid Request"))
427
- }
428
- }
429
- for await (const chunk of Bun.stdin.stream()) {
430
- let text = decoder.decode(chunk as Uint8Array, { stream: true })
431
- if (discardingOversized) {
432
- const newline = text.indexOf("\n")
433
- if (newline === -1) continue
434
- text = text.slice(newline + 1)
435
- discardingOversized = false
436
- }
437
- buffer += text
438
- bufferBytes += STDIO_ENCODER.encode(text).byteLength
439
- let nl = buffer.indexOf("\n")
440
- while (nl !== -1) {
441
- const line = buffer.slice(0, nl)
442
- buffer = buffer.slice(nl + 1)
443
- bufferBytes = Math.max(0, bufferBytes - STDIO_ENCODER.encode(line).byteLength - 1)
444
- nl = buffer.indexOf("\n")
445
- processLine(line)
446
- }
447
- if (bufferBytes > MAX_STDIO_MESSAGE_BYTES) {
448
- buffer = ""
449
- bufferBytes = 0
450
- discardingOversized = true
451
- send(rpcError(null, -32600, "MCP message exceeded the size limit"))
452
- }
381
+ try {
382
+ await runStdioTransport({
383
+ onRequest: async (message, connection) => {
384
+ try {
385
+ return await dispatch(message, connection)
386
+ } catch (err) {
387
+ // Same audience as `exposeToolErrors`: a project that fails to load says why.
388
+ if (message.id === undefined) return null
389
+ return rpcError(message.id, -32603, err instanceof Error ? err.message : String(err))
390
+ }
391
+ },
392
+ onResponse: dispatchRootsAnswer,
393
+ })
394
+ } finally {
395
+ closeWarmWorkers()
453
396
  }
454
- closeWarmWorkers()
455
- }
456
-
457
- function responseIdOf(message: JsonRpcResponse | JsonRpcNotification): string | number | null {
458
- if (!("id" in message)) return null
459
- const id = message.id
460
- return id === null || typeof id === "string" || typeof id === "number" ? id : null
461
397
  }
@@ -496,6 +496,8 @@ interface ProbeRoute {
496
496
  readonly file: string
497
497
  readonly fns: readonly RouteFn[]
498
498
  readonly schemas: readonly OutputExport[]
499
+ /** Holes whose `boundaryLoaders` entry's `load` return type to read. */
500
+ readonly holes?: readonly string[]
499
501
  }
500
502
 
501
503
  /** Shapes keyed `<file>#<export>`: a route function's return type, or a schema's output type. */
@@ -532,6 +534,13 @@ function probeSource(routes: readonly ProbeRoute[]): {
532
534
  names.set(name, `${route.file}#${schema}`)
533
535
  lines.push(`declare const ${name}: __NifraDeclared<typeof __nifra_m${i}, "${schema}">`)
534
536
  }
537
+ route.holes?.forEach((hole, j) => {
538
+ const name = `__nifra_h${i}_${j}`
539
+ names.set(name, `${route.file}#boundaryLoaders.${hole}`)
540
+ lines.push(
541
+ `declare const ${name}: __NifraReturned<(typeof __nifra_m${i})["boundaryLoaders"][${JSON.stringify(hole)}], "load">`,
542
+ )
543
+ })
535
544
  })
536
545
  return { text: `${lines.join("\n")}\n`, names }
537
546
  }
@@ -1147,6 +1156,25 @@ export async function planOutputSchemas(
1147
1156
  return { entries, edits, warnings }
1148
1157
  }
1149
1158
 
1159
+ /**
1160
+ * What hole `hole`'s loader in the backend half `file` returns, with `text` read as that file: the
1161
+ * data a fix that writes the loader drafts its output schema from.
1162
+ */
1163
+ export async function holeLoaderShape(
1164
+ root: string,
1165
+ file: string,
1166
+ hole: string,
1167
+ text: string,
1168
+ ): Promise<{ readonly shape?: Shape; readonly warnings: readonly string[] }> {
1169
+ const { shapes, warnings } = await readShapes(
1170
+ root,
1171
+ [{ file, fns: [], schemas: [], holes: [hole] }],
1172
+ new Map([[file, text]]),
1173
+ )
1174
+ const shape = shapes.get(`${file}#boundaryLoaders.${hole}`)
1175
+ return shape === undefined ? { warnings } : { shape: dataShape(shape), warnings }
1176
+ }
1177
+
1150
1178
  // ---- entry points ------------------------------------------------------------------------------
1151
1179
 
1152
1180
  const ROUTE_BACKEND_TS = /\.backend\.[cm]?ts$/
@@ -0,0 +1,426 @@
1
+ /**
2
+ * `nifra fix --code NF-C053`: move a partially prerendered page's request read into a dynamic hole.
3
+ * The read must be held in one `const` of the page component's body, and every use of it must sit in
4
+ * one element of the markup the component returns. That element becomes the hole's render, reading
5
+ * the value from the hole's data, and the read becomes the hole's loader in the backend half, with an
6
+ * output schema drafted from its type. Anything else is refused with the reason, and nothing is
7
+ * written.
8
+ */
9
+ import { readFile, writeFile } from "node:fs/promises"
10
+ import type * as TS from "typescript"
11
+ import { holeLoaderShape, omittedPaths, type Shape, schemaSource } from "./output-schemas.ts"
12
+ import { lineOf } from "./rules/islands.ts"
13
+ import { REQUEST_READ_MODULE, requestReadCalls, requestReadImports } from "./rules/ppr.ts"
14
+ import type { Framework } from "./scaffold.ts"
15
+ import { backendFileOf } from "./scaffold.ts"
16
+ import {
17
+ ADAPTER,
18
+ apply,
19
+ backendPlan,
20
+ defaultComponent,
21
+ type Edit,
22
+ fallbackField,
23
+ HOLE_NAME,
24
+ type ImportNeed,
25
+ indentAt,
26
+ insideRoot,
27
+ localNames,
28
+ MAX_HOLES,
29
+ pagePlan,
30
+ returnedJsx,
31
+ topLevelNames,
32
+ } from "./scaffold-hole.ts"
33
+
34
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/
35
+
36
+ /** The TypeScript type `shape` describes, or undefined for one the hole's data cannot carry. */
37
+ function typeText(shape: Shape): string | undefined {
38
+ switch (shape.kind) {
39
+ case "string":
40
+ case "number":
41
+ case "boolean":
42
+ case "null":
43
+ return shape.kind
44
+ case "literal":
45
+ return JSON.stringify(shape.value)
46
+ case "array":
47
+ case "tuple": {
48
+ const items = shape.kind === "array" ? [shape.items] : shape.items
49
+ const types = items.map(typeText)
50
+ return types.some((type) => type === undefined)
51
+ ? undefined
52
+ : `readonly (${[...new Set(types)].join(" | ")})[]`
53
+ }
54
+ case "record": {
55
+ const values = typeText(shape.values)
56
+ return values === undefined ? undefined : `Readonly<Record<string, ${values}>>`
57
+ }
58
+ case "union": {
59
+ const types = shape.members.map(typeText)
60
+ return types.some((type) => type === undefined) ? undefined : types.join(" | ")
61
+ }
62
+ case "object": {
63
+ const fields: string[] = []
64
+ for (const field of shape.fields) {
65
+ const type = typeText(field.shape)
66
+ if (type === undefined) return undefined
67
+ const key = IDENTIFIER.test(field.name) ? field.name : JSON.stringify(field.name)
68
+ fields.push(`readonly ${key}${field.optional ? "?" : ""}: ${type}`)
69
+ }
70
+ return fields.length === 0 ? "{}" : `{ ${fields.join("; ")} }`
71
+ }
72
+ default:
73
+ return undefined
74
+ }
75
+ }
76
+
77
+ /** Whether `id` reads a binding: not a property name, a declared name or an intrinsic tag. */
78
+ function isReference(ts: typeof TS, id: TS.Identifier): boolean {
79
+ const parent = id.parent
80
+ if (parent === undefined || ts.isImportSpecifier(parent) || ts.isImportClause(parent))
81
+ return false
82
+ if (ts.isShorthandPropertyAssignment(parent)) return true
83
+ // A declaration's, property's or attribute's own name binds or labels; it reads nothing. Read by
84
+ // field, since TypeScript 7's API lacks some of the guards (`isPropertySignature`).
85
+ if ("name" in parent && parent.name === id) return false
86
+ if (ts.isQualifiedName(parent)) return parent.left === id
87
+ if (ts.isBindingElement(parent)) return parent.propertyName !== id
88
+ if (
89
+ ts.isJsxOpeningElement(parent) ||
90
+ ts.isJsxSelfClosingElement(parent) ||
91
+ ts.isJsxClosingElement(parent)
92
+ )
93
+ return !/^[a-z]/.test(id.text)
94
+ return true
95
+ }
96
+
97
+ /** Every identifier under `node` that reads a binding. */
98
+ function references(ts: typeof TS, node: TS.Node): TS.Identifier[] {
99
+ const found: TS.Identifier[] = []
100
+ const visit = (at: TS.Node): void => {
101
+ if (ts.isIdentifier(at) && isReference(ts, at)) found.push(at)
102
+ ts.forEachChild(at, visit)
103
+ }
104
+ visit(node)
105
+ return found
106
+ }
107
+
108
+ /** Each name `node` declares, as often as it declares it. */
109
+ function declarations(ts: typeof TS, node: TS.Node): string[] {
110
+ const names: string[] = []
111
+ const visit = (at: TS.Node): void => {
112
+ if (
113
+ (ts.isVariableDeclaration(at) ||
114
+ ts.isParameter(at) ||
115
+ ts.isBindingElement(at) ||
116
+ ts.isFunctionDeclaration(at)) &&
117
+ at.name !== undefined &&
118
+ ts.isIdentifier(at.name)
119
+ )
120
+ names.push(at.name.text)
121
+ ts.forEachChild(at, visit)
122
+ }
123
+ visit(node)
124
+ return names
125
+ }
126
+
127
+ const within = (sf: TS.SourceFile, outer: TS.Node, inner: TS.Node): boolean =>
128
+ outer.getStart(sf) <= inner.getStart(sf) && inner.getEnd() <= outer.getEnd()
129
+
130
+ /** `text`, its lines after the first moved from `from` indentation to `to`. */
131
+ function reindent(text: string, from: string, to: string): string {
132
+ return text
133
+ .split("\n")
134
+ .map((line, i) =>
135
+ i === 0 ? line : `${to}${line.startsWith(from) ? line.slice(from.length) : line.trimStart()}`,
136
+ )
137
+ .join("\n")
138
+ }
139
+
140
+ /** `visitorName` → `visitor-name`, or undefined when no hole name comes of it. */
141
+ function holeNameOf(local: string): string | undefined {
142
+ const name = local
143
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
144
+ .toLowerCase()
145
+ .replace(/[^a-z0-9]+/g, "-")
146
+ .replace(/^[^a-z]+|-+$/g, "")
147
+ .slice(0, 28)
148
+ .replace(/-+$/, "")
149
+ return HOLE_NAME.test(name) ? name : undefined
150
+ }
151
+
152
+ /**
153
+ * Move the request read `diagnostic` found at `line` of the page `file` (relative to `root`) into a new
154
+ * dynamic hole. Returns the files it wrote; throws with the reason when it cannot, writing nothing.
155
+ */
156
+ export async function moveReadToHole(
157
+ root: string,
158
+ file: string,
159
+ line: number | undefined,
160
+ framework: Framework,
161
+ ts: typeof TS,
162
+ ): Promise<readonly string[]> {
163
+ const refuse = (reason: string): never => {
164
+ throw new Error(`[nifra] ${file}: ${reason}; nothing was changed`)
165
+ }
166
+ const adapter = ADAPTER[framework]
167
+ if (adapter === undefined)
168
+ return refuse(
169
+ `the fix writes a JSX hole, and a ${framework} page renders none; move the read by hand (nifra scaffold hole prints the hole to start from)`,
170
+ )
171
+ if (!/\.[jt]sx$/.test(file)) return refuse("the fix edits a .tsx or .jsx page only")
172
+ const backend = backendFileOf(file)
173
+ const pagePath = insideRoot(root, file)
174
+ const backendPath = insideRoot(root, backend)
175
+ const pageSource = await readFile(pagePath, "utf8")
176
+ const backendSource = await readFile(backendPath, "utf8")
177
+ const sf = ts.createSourceFile(file, pageSource, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)
178
+ const backendFile = ts.createSourceFile(
179
+ backend,
180
+ backendSource,
181
+ ts.ScriptTarget.Latest,
182
+ true,
183
+ ts.ScriptKind.TS,
184
+ )
185
+
186
+ const reads = requestReadImports(ts, sf)
187
+ const call = requestReadCalls(ts, sf, reads).find((found) => lineOf(sf, found) === line)
188
+ if (call === undefined)
189
+ return refuse(
190
+ `no request read is at line ${line ?? "?"} any more; rerun \`nifra fix --code NF-C053\``,
191
+ )
192
+ const page = defaultComponent(ts, sf)
193
+ const body = page?.body
194
+ if (page === undefined || body === undefined || !ts.isBlock(body))
195
+ return refuse("the read is not in the body of the page's default-exported component")
196
+ let statement: TS.Node = call
197
+ while (statement.parent !== body) {
198
+ if (statement.parent === undefined || statement.parent === sf)
199
+ return refuse("the read is not in a statement of the page component's own body")
200
+ statement = statement.parent
201
+ }
202
+ const declaration = ts.isVariableStatement(statement)
203
+ ? statement.declarationList.declarations[0]
204
+ : undefined
205
+ if (
206
+ !ts.isVariableStatement(statement) ||
207
+ !/^const\s/.test(statement.declarationList.getText(sf)) ||
208
+ statement.declarationList.declarations.length !== 1 ||
209
+ declaration === undefined ||
210
+ !ts.isIdentifier(declaration.name) ||
211
+ declaration.initializer === undefined
212
+ )
213
+ return refuse("the read is not held in one `const <name> = ...` of the page component")
214
+ const local = declaration.name.text
215
+ const initializer = declaration.initializer
216
+
217
+ // The loader sees module scope in the backend half: globals and the request reads, not the page's
218
+ // own names or the component's.
219
+ const pageNames = topLevelNames(ts, sf)
220
+ const componentNames = new Set<string>()
221
+ localNames(ts, page, componentNames)
222
+ const ownNames = new Set(declarations(ts, initializer))
223
+ for (const id of references(ts, initializer)) {
224
+ if (reads.has(id.text) || ownNames.has(id.text)) continue
225
+ if (componentNames.has(id.text) || pageNames.has(id.text))
226
+ return refuse(
227
+ `the read uses \`${id.text}\`, which the page defines or imports, and a hole's loader runs in the backend half without it`,
228
+ )
229
+ }
230
+
231
+ if (declarations(ts, page).filter((name) => name === local).length > 1)
232
+ return refuse(`\`${local}\` is declared more than once in the page component`)
233
+ const uses = references(ts, body).filter((id) => id.text === local && !within(sf, statement, id))
234
+ if (uses.length === 0) return refuse(`\`${local}\` is not used in the page's markup`)
235
+ const jsx = returnedJsx(ts, page)
236
+ if (jsx === undefined)
237
+ return refuse("the page component does not return one JSX element the hole can go inside")
238
+ const outside = uses.find((use) => !within(sf, jsx, use))
239
+ if (outside !== undefined)
240
+ return refuse(
241
+ `\`${local}\` is also used outside the markup the page returns (line ${lineOf(sf, outside)}), and only markup moves into a hole`,
242
+ )
243
+
244
+ // The element the hole takes the place of: the innermost one holding every use.
245
+ const elementOf = (node: TS.Node): TS.Node | undefined => {
246
+ for (let at = node.parent; at !== undefined; at = at.parent)
247
+ if (ts.isJsxElement(at) || ts.isJsxSelfClosingElement(at) || ts.isJsxFragment(at)) return at
248
+ return undefined
249
+ }
250
+ const holdsAll = (node: TS.Node): boolean => uses.every((use) => within(sf, node, use))
251
+ const [first] = uses
252
+ let target = first === undefined ? undefined : elementOf(first)
253
+ while (target !== undefined && !holdsAll(target)) target = elementOf(target)
254
+ if (target === undefined || target === jsx)
255
+ return refuse(
256
+ `the uses of \`${local}\` span the page's root element; wrap them in one element, then rerun the fix`,
257
+ )
258
+ const subtree = target
259
+ for (const id of references(ts, subtree)) {
260
+ if (id.text === local) continue
261
+ if (componentNames.has(id.text))
262
+ return refuse(
263
+ `the markup that uses \`${local}\` also uses \`${id.text}\`, which the page component declares, and a hole renders from its loader's data alone`,
264
+ )
265
+ if (reads.has(id.text))
266
+ return refuse(`the markup that uses \`${local}\` reads the request itself`)
267
+ }
268
+ const interactive = (() => {
269
+ let found = false
270
+ const visit = (node: TS.Node): void => {
271
+ if (ts.isJsxAttribute(node) && /^on[A-Z]/.test(node.name.getText(sf))) found = true
272
+ if (!found) ts.forEachChild(node, visit)
273
+ }
274
+ visit(subtree)
275
+ return found
276
+ })()
277
+
278
+ // The hole's name, unused by the page's boundaries and the backend half's loaders.
279
+ const base = holeNameOf(local) ?? "request"
280
+ const usedNames = (name: string): readonly string[] => [
281
+ ...pagePlan(ts, sf, name, framework, { fields: [], imports: [] }).names,
282
+ ...backendPlan(ts, backendFile, name, { body: [], imports: [] }).keys,
283
+ ]
284
+ let name = base
285
+ for (let n = 2; usedNames(name).includes(name); n++) name = `${base}-${n}`
286
+ const loaderKeys = backendPlan(ts, backendFile, name, { body: [], imports: [] }).keys
287
+ if (loaderKeys.length >= MAX_HOLES)
288
+ return refuse(
289
+ `${backend} already has ${loaderKeys.length} hole loaders, the most a route may have`,
290
+ )
291
+
292
+ const readImports: ImportNeed[] = []
293
+ const backendNames = topLevelNames(ts, backendFile)
294
+ const backendReads = requestReadImports(ts, backendFile)
295
+ const readsUsed = new Set(references(ts, initializer).map((id) => id.text))
296
+ for (const [binding, imported] of reads) {
297
+ if (!readsUsed.has(binding)) continue
298
+ if (backendNames.has(binding) && backendReads.get(binding) !== imported)
299
+ return refuse(`${backend} already declares \`${binding}\``)
300
+ readImports.push({ module: REQUEST_READ_MODULE, name: binding, imported })
301
+ }
302
+ const statementIndent = indentAt(pageSource, statement.getStart(sf))
303
+ const read = reindent(initializer.getText(sf), statementIndent, "")
304
+ const loader = (output: string) => ({
305
+ body: [
306
+ "// Read for each visitor, under the hole's own deadline; the shell never sees it.",
307
+ ...`load: () => ({ ${local}: ${read} }),`.split("\n"),
308
+ ...`output: ${output},`.split("\n"),
309
+ ],
310
+ imports: [{ module: "@nifrajs/schema", name: "t" }, ...readImports],
311
+ })
312
+ const probe = backendPlan(ts, backendFile, name, loader("t.json()"))
313
+ if (probe.reason !== undefined) return refuse(`${backend}: ${probe.reason}`)
314
+ const { shape, warnings } = await holeLoaderShape(
315
+ root,
316
+ backend,
317
+ name,
318
+ apply(backendSource, probe.edits),
319
+ )
320
+ if (warnings.length > 0)
321
+ return refuse(`the read's type could not be read: ${warnings.join("; ")}`)
322
+ const field =
323
+ shape?.kind === "object" ? shape.fields.find((entry) => entry.name === local) : undefined
324
+ const data: Shape | undefined =
325
+ field === undefined ? undefined : { kind: "object", fields: [field] }
326
+ const dataType = data === undefined ? undefined : typeText(data)
327
+ if (data === undefined || dataType === undefined || omittedPaths(data).length > 0)
328
+ return refuse(
329
+ `the read's value is not a type the fix can describe with a schema (strings, numbers, booleans, null, and arrays and objects of them); move it by hand`,
330
+ )
331
+ const back = backendPlan(ts, backendFile, name, loader(schemaSource(data)))
332
+ if (back.reason !== undefined) return refuse(`${backend}: ${back.reason}`)
333
+
334
+ // The render reads the value from the hole's data, under a parameter name the markup leaves free.
335
+ const subtreeNames = new Set(references(ts, subtree).map((id) => id.text))
336
+ const param = ["data", "hole", "holeData"].find((candidate) => !subtreeNames.has(candidate))
337
+ if (param === undefined) return refuse("the markup uses every name the fix would give the data")
338
+ const start = subtree.getStart(sf)
339
+ const renames: Edit[] = uses.map((use) =>
340
+ use.parent !== undefined && ts.isShorthandPropertyAssignment(use.parent)
341
+ ? {
342
+ at: use.getStart(sf) - start,
343
+ remove: use.getWidth(sf),
344
+ text: `${local}: ${param}.${local}`,
345
+ }
346
+ : { at: use.getStart(sf) - start, remove: use.getWidth(sf), text: `${param}.${local}` },
347
+ )
348
+ const markup = reindent(apply(subtree.getText(sf), renames), indentAt(pageSource, start), " ")
349
+ const signature = `render: (${param}: ${dataType}) =>`
350
+ const render =
351
+ markup.includes("\n") || signature.length + markup.length > 90
352
+ ? `${signature} (\n ${markup}\n),`
353
+ : `${signature} ${markup},`
354
+ const front = pagePlan(ts, sf, name, framework, {
355
+ fields: [
356
+ 'mode: "dynamic",',
357
+ ...(interactive ? ["interactive: true, // its event handlers hydrate with the hole"] : []),
358
+ render,
359
+ fallbackField(framework),
360
+ ],
361
+ imports: [],
362
+ replaces: subtree,
363
+ })
364
+ if (front.reason !== undefined) return refuse(front.reason)
365
+
366
+ // The read's statement goes, with its line when it has one to itself.
367
+ const lineStart = pageSource.lastIndexOf("\n", statement.getStart(sf) - 1) + 1
368
+ const lineEnd = pageSource.indexOf("\n", statement.getEnd())
369
+ const ownLines =
370
+ pageSource.slice(lineStart, statement.getStart(sf)).trim() === "" &&
371
+ pageSource.slice(statement.getEnd(), lineEnd === -1 ? undefined : lineEnd).trim() === ""
372
+ const edits: Edit[] = [
373
+ ...front.edits,
374
+ ownLines
375
+ ? {
376
+ at: lineStart,
377
+ remove: (lineEnd === -1 ? pageSource.length : lineEnd + 1) - lineStart,
378
+ text: "",
379
+ }
380
+ : { at: statement.getStart(sf), remove: statement.getWidth(sf), text: "" },
381
+ ]
382
+ // A read import nothing else in the page uses goes too.
383
+ const stillUsed = new Set(
384
+ references(ts, sf)
385
+ .filter((id) => reads.has(id.text) && !within(sf, statement, id))
386
+ .map((id) => id.text),
387
+ )
388
+ for (const imported of sf.statements) {
389
+ if (
390
+ !ts.isImportDeclaration(imported) ||
391
+ !ts.isStringLiteral(imported.moduleSpecifier) ||
392
+ imported.moduleSpecifier.text !== REQUEST_READ_MODULE
393
+ )
394
+ continue
395
+ const clause = imported.importClause
396
+ const bindings = clause?.namedBindings
397
+ if (clause === undefined || bindings === undefined || !ts.isNamedImports(bindings)) continue
398
+ const kept = bindings.elements.filter(
399
+ (element) => !reads.has(element.name.text) || stillUsed.has(element.name.text),
400
+ )
401
+ if (kept.length === bindings.elements.length) continue
402
+ if (kept.length === 0 && clause.name === undefined) {
403
+ // From the line break before it: a new import may be placed right where this one ends.
404
+ const start = imported.getStart(sf)
405
+ const from = start > 0 && pageSource[start - 1] === "\n" ? start - 1 : start
406
+ edits.push({ at: from, remove: imported.getEnd() - from, text: "" })
407
+ } else
408
+ edits.push({
409
+ at: bindings.getStart(sf),
410
+ remove: bindings.getWidth(sf),
411
+ text: `{ ${kept.map((element) => element.getText(sf)).join(", ")} }`,
412
+ })
413
+ }
414
+
415
+ const fixed = apply(pageSource, edits)
416
+ // An import removed from the very top leaves the line break that followed it.
417
+ await writeFile(
418
+ pagePath,
419
+ fixed.startsWith("\n") && !pageSource.startsWith("\n") ? fixed.slice(1) : fixed,
420
+ "utf8",
421
+ )
422
+ await writeFile(backendPath, apply(backendSource, back.edits), "utf8")
423
+ const { refreshRouteTypes } = await import("./route-types.ts")
424
+ refreshRouteTypes(root, () => {})
425
+ return [file, backend]
426
+ }