@nifrajs/cli 5.5.1 → 5.7.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 (205) hide show
  1. package/CHANGELOG.md +314 -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 +9 -3
  8. package/dist/check-diagnostics.js.map +1 -1
  9. package/dist/check-scan.d.ts +6 -0
  10. package/dist/check-scan.d.ts.map +1 -1
  11. package/dist/check-scan.js +30 -32
  12. package/dist/check-scan.js.map +1 -1
  13. package/dist/check.d.ts.map +1 -1
  14. package/dist/check.js +35 -12
  15. package/dist/check.js.map +1 -1
  16. package/dist/cli.d.ts +4 -0
  17. package/dist/cli.d.ts.map +1 -1
  18. package/dist/cli.js +66 -9
  19. package/dist/cli.js.map +1 -1
  20. package/dist/command-catalog.d.ts +19 -1
  21. package/dist/command-catalog.d.ts.map +1 -1
  22. package/dist/command-catalog.js +111 -6
  23. package/dist/command-catalog.js.map +1 -1
  24. package/dist/contracts.d.ts +42 -4
  25. package/dist/contracts.d.ts.map +1 -1
  26. package/dist/contracts.js +288 -9
  27. package/dist/contracts.js.map +1 -1
  28. package/dist/doctor.d.ts +12 -2
  29. package/dist/doctor.d.ts.map +1 -1
  30. package/dist/doctor.js +67 -1
  31. package/dist/doctor.js.map +1 -1
  32. package/dist/fix-recipes.d.ts.map +1 -1
  33. package/dist/fix-recipes.js +27 -0
  34. package/dist/fix-recipes.js.map +1 -1
  35. package/dist/frontend-guidance.d.ts +1 -1
  36. package/dist/frontend-guidance.d.ts.map +1 -1
  37. package/dist/frontend-guidance.js +17 -8
  38. package/dist/frontend-guidance.js.map +1 -1
  39. package/dist/internal/git-ignored.d.ts +12 -0
  40. package/dist/internal/git-ignored.d.ts.map +1 -0
  41. package/dist/internal/git-ignored.js +49 -0
  42. package/dist/internal/git-ignored.js.map +1 -0
  43. package/dist/internal/source-facts.d.ts +29 -0
  44. package/dist/internal/source-facts.d.ts.map +1 -1
  45. package/dist/internal/source-facts.js +160 -0
  46. package/dist/internal/source-facts.js.map +1 -1
  47. package/dist/introspect.js +1 -1
  48. package/dist/introspect.js.map +1 -1
  49. package/dist/load.d.ts +7 -1
  50. package/dist/load.d.ts.map +1 -1
  51. package/dist/load.js +18 -0
  52. package/dist/load.js.map +1 -1
  53. package/dist/local-cli.d.ts +15 -0
  54. package/dist/local-cli.d.ts.map +1 -0
  55. package/dist/local-cli.js +74 -0
  56. package/dist/local-cli.js.map +1 -0
  57. package/dist/lock-links.d.ts +0 -7
  58. package/dist/lock-links.d.ts.map +1 -1
  59. package/dist/lock-links.js +5 -44
  60. package/dist/lock-links.js.map +1 -1
  61. package/dist/mcp-delegate.d.ts +13 -5
  62. package/dist/mcp-delegate.d.ts.map +1 -1
  63. package/dist/mcp-delegate.js +24 -8
  64. package/dist/mcp-delegate.js.map +1 -1
  65. package/dist/mcp-exec.d.ts.map +1 -1
  66. package/dist/mcp-exec.js +57 -3
  67. package/dist/mcp-exec.js.map +1 -1
  68. package/dist/mcp-http.d.ts +2 -1
  69. package/dist/mcp-http.d.ts.map +1 -1
  70. package/dist/mcp-http.js +3 -2
  71. package/dist/mcp-http.js.map +1 -1
  72. package/dist/mcp-tool-meta.d.ts +21 -0
  73. package/dist/mcp-tool-meta.d.ts.map +1 -0
  74. package/dist/mcp-tool-meta.js +246 -0
  75. package/dist/mcp-tool-meta.js.map +1 -0
  76. package/dist/mcp.d.ts +3 -2
  77. package/dist/mcp.d.ts.map +1 -1
  78. package/dist/mcp.js +36 -98
  79. package/dist/mcp.js.map +1 -1
  80. package/dist/openapi-types.d.ts.map +1 -1
  81. package/dist/openapi-types.js +45 -2
  82. package/dist/openapi-types.js.map +1 -1
  83. package/dist/output-schemas.d.ts +8 -0
  84. package/dist/output-schemas.d.ts.map +1 -1
  85. package/dist/output-schemas.js +14 -0
  86. package/dist/output-schemas.js.map +1 -1
  87. package/dist/ppr-read-fix.d.ts +8 -0
  88. package/dist/ppr-read-fix.d.ts.map +1 -0
  89. package/dist/ppr-read-fix.js +356 -0
  90. package/dist/ppr-read-fix.js.map +1 -0
  91. package/dist/recipes/5.6.0.d.ts +10 -0
  92. package/dist/recipes/5.6.0.d.ts.map +1 -0
  93. package/dist/recipes/5.6.0.js +68 -0
  94. package/dist/recipes/5.6.0.js.map +1 -0
  95. package/dist/recipes/5.7.0.d.ts +12 -0
  96. package/dist/recipes/5.7.0.d.ts.map +1 -0
  97. package/dist/recipes/5.7.0.js +70 -0
  98. package/dist/recipes/5.7.0.js.map +1 -0
  99. package/dist/recipes/index.d.ts +13 -0
  100. package/dist/recipes/index.d.ts.map +1 -1
  101. package/dist/recipes/index.js +4 -0
  102. package/dist/recipes/index.js.map +1 -1
  103. package/dist/review.d.ts.map +1 -1
  104. package/dist/review.js +9 -2
  105. package/dist/review.js.map +1 -1
  106. package/dist/rules/codes.d.ts +10 -3
  107. package/dist/rules/codes.d.ts.map +1 -1
  108. package/dist/rules/codes.js +11 -4
  109. package/dist/rules/codes.js.map +1 -1
  110. package/dist/rules/explanations.d.ts.map +1 -1
  111. package/dist/rules/explanations.js +52 -16
  112. package/dist/rules/explanations.js.map +1 -1
  113. package/dist/rules/islands.d.ts +91 -0
  114. package/dist/rules/islands.d.ts.map +1 -1
  115. package/dist/rules/islands.js +757 -3
  116. package/dist/rules/islands.js.map +1 -1
  117. package/dist/rules/legacy.js +1 -1
  118. package/dist/rules/legacy.js.map +1 -1
  119. package/dist/rules/ppr.d.ts +16 -0
  120. package/dist/rules/ppr.d.ts.map +1 -0
  121. package/dist/rules/ppr.js +114 -0
  122. package/dist/rules/ppr.js.map +1 -0
  123. package/dist/rules/swap.d.ts +7 -0
  124. package/dist/rules/swap.d.ts.map +1 -0
  125. package/dist/rules/swap.js +338 -0
  126. package/dist/rules/swap.js.map +1 -0
  127. package/dist/rules/text-slot-boolean.d.ts +8 -0
  128. package/dist/rules/text-slot-boolean.d.ts.map +1 -0
  129. package/dist/rules/text-slot-boolean.js +57 -0
  130. package/dist/rules/text-slot-boolean.js.map +1 -0
  131. package/dist/rules/undeclared-response.d.ts +9 -0
  132. package/dist/rules/undeclared-response.d.ts.map +1 -0
  133. package/dist/rules/undeclared-response.js +93 -0
  134. package/dist/rules/undeclared-response.js.map +1 -0
  135. package/dist/scaffold-hole.d.ts +105 -0
  136. package/dist/scaffold-hole.d.ts.map +1 -0
  137. package/dist/scaffold-hole.js +688 -0
  138. package/dist/scaffold-hole.js.map +1 -0
  139. package/dist/scaffold.d.ts +5 -3
  140. package/dist/scaffold.d.ts.map +1 -1
  141. package/dist/scaffold.js +56 -46
  142. package/dist/scaffold.js.map +1 -1
  143. package/dist/upgrade.d.ts +34 -8
  144. package/dist/upgrade.d.ts.map +1 -1
  145. package/dist/upgrade.js +197 -25
  146. package/dist/upgrade.js.map +1 -1
  147. package/dist/verification-plan.d.ts.map +1 -1
  148. package/dist/verification-plan.js +12 -1
  149. package/dist/verification-plan.js.map +1 -1
  150. package/dist/version-drift.js +1 -1
  151. package/dist/version-drift.js.map +1 -1
  152. package/dist/web-app-options.d.ts +1 -1
  153. package/dist/web-app-options.d.ts.map +1 -1
  154. package/dist/web-app-options.js.map +1 -1
  155. package/docs/examples.json +70 -10
  156. package/docs/llms-full.txt +3162 -1196
  157. package/docs/types.json +1473 -322
  158. package/package.json +11 -11
  159. package/src/cdn-check.ts +21 -7
  160. package/src/check-diagnostics.ts +9 -3
  161. package/src/check-scan.ts +35 -32
  162. package/src/check.ts +32 -10
  163. package/src/cli.ts +71 -9
  164. package/src/command-catalog.ts +149 -6
  165. package/src/contracts.ts +348 -14
  166. package/src/doctor.ts +62 -3
  167. package/src/fix-recipes.ts +28 -0
  168. package/src/frontend-guidance.ts +20 -8
  169. package/src/internal/git-ignored.ts +47 -0
  170. package/src/internal/source-facts.ts +198 -0
  171. package/src/introspect.ts +1 -1
  172. package/src/load.ts +29 -0
  173. package/src/local-cli.ts +83 -0
  174. package/src/lock-links.ts +5 -43
  175. package/src/mcp-delegate.ts +30 -9
  176. package/src/mcp-exec.ts +74 -3
  177. package/src/mcp-http.ts +3 -2
  178. package/src/mcp-tool-meta.ts +268 -0
  179. package/src/mcp.ts +35 -99
  180. package/src/openapi-types.ts +43 -2
  181. package/src/output-schemas.ts +28 -0
  182. package/src/ppr-read-fix.ts +426 -0
  183. package/src/recipes/5.6.0.ts +69 -0
  184. package/src/recipes/5.7.0.ts +72 -0
  185. package/src/recipes/index.ts +18 -0
  186. package/src/review.ts +9 -2
  187. package/src/rules/codes.ts +11 -4
  188. package/src/rules/explanations.ts +52 -16
  189. package/src/rules/islands.ts +875 -3
  190. package/src/rules/legacy.ts +1 -1
  191. package/src/rules/ppr.ts +143 -0
  192. package/src/rules/swap.ts +402 -0
  193. package/src/rules/text-slot-boolean.ts +56 -0
  194. package/src/rules/undeclared-response.ts +92 -0
  195. package/src/scaffold-hole.ts +880 -0
  196. package/src/scaffold.ts +60 -49
  197. package/src/upgrade.ts +229 -33
  198. package/src/verification-plan.ts +20 -1
  199. package/src/version-drift.ts +1 -1
  200. package/src/web-app-options.ts +2 -0
  201. package/dist/rules/nano.d.ts +0 -6
  202. package/dist/rules/nano.d.ts.map +0 -1
  203. package/dist/rules/nano.js +0 -273
  204. package/dist/rules/nano.js.map +0 -1
  205. package/src/rules/nano.ts +0 -307
@@ -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
@@ -513,6 +527,8 @@ interface RouteDiffCommandOutput extends DiffCommandOutput {
513
527
  interface ContractsCommandOutput {
514
528
  readonly ok: boolean
515
529
  readonly lock?: ContractsLock
530
+ /** `snapshot`: each route whose declared schema the lock records as `null`. */
531
+ readonly unreflected?: readonly { readonly route: string; readonly parts: readonly string[] }[]
516
532
  readonly diagnostics?: readonly unknown[]
517
533
  readonly present?: boolean
518
534
  readonly vacuous?: boolean
@@ -750,6 +766,43 @@ const FIX_SCHEMA = input<FixInput>(
750
766
  },
751
767
  )
752
768
 
769
+ const SCAFFOLD_SCHEMA = input<ScaffoldInput>(
770
+ objectSchema(
771
+ {
772
+ kind: { type: "string", enum: ["hole"] },
773
+ route: { type: "string" },
774
+ name: { type: "string" },
775
+ shared: { type: "boolean" },
776
+ interactive: { type: "boolean" },
777
+ timeout: { type: "integer" },
778
+ server: { type: "boolean" },
779
+ json: { type: "boolean" },
780
+ dir: { type: "string" },
781
+ },
782
+ ["kind", "route", "name"],
783
+ ),
784
+ (value) => {
785
+ const raw = withDir(record(value))
786
+ if (raw.kind !== "hole")
787
+ throw new TypeError("scaffold what: `nifra scaffold hole <route> <name>`")
788
+ const route = optionalString(raw.route, "route")
789
+ const name = optionalString(raw.name, "name")
790
+ if (route === undefined || name === undefined)
791
+ throw new TypeError(
792
+ "`nifra scaffold hole <route> <name>` needs the route and the hole's name",
793
+ )
794
+ const timeout = optionalNumber(raw.timeout, "timeout")
795
+ return {
796
+ kind: "hole",
797
+ route,
798
+ name,
799
+ ...parseBooleanFlags(raw, ["shared", "interactive", "server", "json"]),
800
+ ...(timeout === undefined ? {} : { timeout }),
801
+ ...(raw.dir === undefined ? {} : { dir: raw.dir }),
802
+ }
803
+ },
804
+ )
805
+
753
806
  const MIGRATE_SCHEMA = input<MigrateInput>(
754
807
  objectSchema({
755
808
  kind: { type: "string", enum: ["layout"] },
@@ -1604,6 +1657,80 @@ const migrateSpec: CommandSpec<MigrateInput, MigrateCommandOutput> = {
1604
1657
  success: (out) => out.ok,
1605
1658
  }
1606
1659
 
1660
+ const scaffoldSpec: CommandSpec<ScaffoldInput, HoleScaffoldResult> = {
1661
+ name: "scaffold",
1662
+ summary:
1663
+ "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.",
1664
+ input: SCAFFOLD_SCHEMA,
1665
+ output: output({
1666
+ type: "object",
1667
+ properties: {
1668
+ ok: { type: "boolean" },
1669
+ page: { type: "string" },
1670
+ backend: { type: "string" },
1671
+ changed: { type: "array" },
1672
+ snippets: { type: "array" },
1673
+ next: { type: "array" },
1674
+ reason: { type: "string" },
1675
+ },
1676
+ required: ["ok", "page", "backend", "changed", "snippets", "next"],
1677
+ }),
1678
+ transports: ["cli"],
1679
+ stability: "experimental",
1680
+ argv: {
1681
+ positionals: ["kind", "route", "name"],
1682
+ flags: [
1683
+ { name: "shared", field: "shared", type: "boolean" },
1684
+ { name: "interactive", field: "interactive", type: "boolean" },
1685
+ { name: "timeout", field: "timeout", type: "number" },
1686
+ { name: "server", field: "server", type: "boolean" },
1687
+ { name: "json", field: "json", type: "boolean" },
1688
+ { name: "dir", field: "dir", type: "string" },
1689
+ ],
1690
+ },
1691
+ async run(value, ctx) {
1692
+ const dir = resolve(ctx.cwd, value.dir ?? ".")
1693
+ const app =
1694
+ ctx.loadApp !== undefined && value.dir === undefined
1695
+ ? await ctx.loadApp()
1696
+ : await import("./load.ts").then(({ loadApp }) => loadApp(dir))
1697
+ const { frameworkFromClientModule } = await import("./scaffold.ts")
1698
+ const { holeRouteFiles, routeTypeScript, scaffoldHole } = await import("./scaffold-hole.ts")
1699
+ const framework = frameworkFromClientModule(app.framework.clientModule)
1700
+ const { page, backend } = holeRouteFiles(value.route, framework)
1701
+ const loaded = await routeTypeScript(dir, [page, backend])
1702
+ if (loaded.unsupported !== undefined) throw loaded.unsupported
1703
+ if (loaded.compiler === undefined)
1704
+ throw new Error(
1705
+ "[nifra] scaffold hole places each edit through the route's syntax tree, so it needs TypeScript - run `bun add -d typescript`, then rerun it",
1706
+ )
1707
+ try {
1708
+ return await scaffoldHole(
1709
+ dir,
1710
+ value.route,
1711
+ value.name,
1712
+ framework,
1713
+ {
1714
+ shared: value.shared,
1715
+ interactive: value.interactive,
1716
+ timeout: value.timeout,
1717
+ server: value.server,
1718
+ },
1719
+ loaded.compiler,
1720
+ )
1721
+ } finally {
1722
+ await loaded.session?.close()
1723
+ }
1724
+ },
1725
+ render: (out) => [
1726
+ out.ok ? `✓ hole scaffolded on ${out.page}` : `✖ ${out.reason ?? "not scaffolded"}`,
1727
+ ...out.changed.map((file) => ` edit ${file}`),
1728
+ ...out.snippets.flatMap((snippet) => [` paste into ${snippet.file}:`, "", snippet.code, ""]),
1729
+ ...out.next.map((step) => ` next ${step}`),
1730
+ ],
1731
+ success: (out) => out.ok,
1732
+ }
1733
+
1607
1734
  const targetSpec: CommandSpec<TargetInput, TargetOutput> = {
1608
1735
  name: "target",
1609
1736
  summary:
@@ -1864,14 +1991,29 @@ const contractsSpec: CommandSpec<ContractsInput, ContractsCommandOutput> = {
1864
1991
  async run(value, ctx) {
1865
1992
  const mod = await import("./contracts.ts")
1866
1993
  if (value.action === "snapshot")
1867
- return { ok: true, lock: await mod.snapshotContracts(ctx.cwd, value.out) }
1868
- const result = await mod.checkContractsLock(ctx.cwd)
1994
+ return { ok: true, ...(await mod.snapshotContractsReport(ctx.cwd, value.out)) }
1995
+ const result = await mod.checkContractsLock(ctx.cwd, value.out)
1869
1996
  return { ok: result.present && result.diagnostics.length === 0, ...result }
1870
1997
  },
1871
- render: (out) => [
1872
- out.ok ? "✓ contracts are current" : "✖ contract drift",
1873
- ...(out.diagnostics ?? []).map((d) => ` ${(d as { message: string }).message}`),
1874
- ],
1998
+ render: (out, input) => {
1999
+ const file = input?.out ?? "contracts.lock.json"
2000
+ if (input?.action === "snapshot")
2001
+ return [
2002
+ `✓ wrote ${file} (${Object.keys(out.lock?.routes ?? {}).length} routes)`,
2003
+ ...(out.unreflected ?? []).map(
2004
+ (entry) =>
2005
+ ` ⚠ ${entry.route}: ${entry.parts.join(", ")} declares a schema nifra cannot read, locked as null - a change to it goes unnoticed`,
2006
+ ),
2007
+ ]
2008
+ return [
2009
+ out.ok
2010
+ ? "✓ contracts are current"
2011
+ : out.present === false
2012
+ ? `✖ no ${file}: run \`nifra contracts snapshot\``
2013
+ : "✖ contract drift",
2014
+ ...(out.diagnostics ?? []).map((d) => ` ${(d as { message: string }).message}`),
2015
+ ]
2016
+ },
1875
2017
  success: (out) => out.ok,
1876
2018
  }
1877
2019
 
@@ -2069,6 +2211,7 @@ export const commandSpecs = Object.freeze([
2069
2211
  doctorSpec,
2070
2212
  fixSpec,
2071
2213
  migrateSpec,
2214
+ scaffoldSpec,
2072
2215
  targetSpec,
2073
2216
  typesSpec,
2074
2217
  schemasSpec,
package/src/contracts.ts CHANGED
@@ -6,13 +6,25 @@ import {
6
6
  reflectedRoutesFromEvidence,
7
7
  snapshotProjectEvidence,
8
8
  } from "@nifrajs/core/evidence"
9
- import type { ReflectedRoute } from "@nifrajs/core/reflection"
9
+ import type { ReflectedRoute, SchemaReflection } from "@nifrajs/core/reflection"
10
10
  import { BACKEND_APP_FILE } from "./app-files.ts"
11
11
  import { codeUnitOrder } from "./internal/code-unit-order.ts"
12
12
 
13
+ /** One declared part of a route's contract: `body`, `query`, `params`, `headers`, `cookies`,
14
+ * `response`, `sse` or `errors.<status>`. */
15
+ export interface ContractPart {
16
+ /** Hash of the part's schema, or `null` where it is declared in a form nifra cannot read. */
17
+ readonly digest: string | null
18
+ /** The type of each top-level field, `name?` for an optional one, when the schema is an object. */
19
+ readonly fields?: Readonly<Record<string, string>>
20
+ }
21
+
13
22
  export interface ContractDigest {
14
23
  readonly request: string
15
24
  readonly response: string
25
+ /** Each part the route declares. Absent in a lock written before parts were recorded: such a lock
26
+ * compares by side, and never covered headers or cookies. */
27
+ readonly parts?: Readonly<Record<string, ContractPart>>
16
28
  }
17
29
 
18
30
  export interface ContractsLock {
@@ -133,6 +145,115 @@ export async function emptySchemaDigest(): Promise<string> {
133
145
  return sha256(JSON.stringify(canonical(schemaValue(undefined, "request"))))
134
146
  }
135
147
 
148
+ const PART_ORDER = ["body", "query", "params", "headers", "cookies", "response", "sse"] as const
149
+ const REQUEST_PARTS: ReadonlySet<string> = new Set([
150
+ "body",
151
+ "query",
152
+ "params",
153
+ "headers",
154
+ "cookies",
155
+ ])
156
+ const sideOf = (part: string): "request" | "response" =>
157
+ REQUEST_PARTS.has(part) ? "request" : "response"
158
+
159
+ function partRank(part: string): number {
160
+ const at = PART_ORDER.findIndex((name) => name === part)
161
+ return at === -1 ? PART_ORDER.length : at
162
+ }
163
+
164
+ const partOrder = (a: string, b: string): number => partRank(a) - partRank(b) || codeUnitOrder(a, b)
165
+
166
+ function declaredParts(schema: ReflectedRoute["schema"]): Array<[string, SchemaReflection]> {
167
+ if (schema === undefined) return []
168
+ const parts: Array<[string, SchemaReflection]> = []
169
+ for (const part of PART_ORDER) {
170
+ const value = schema[part]
171
+ if (value !== undefined) parts.push([part, value])
172
+ }
173
+ for (const [status, value] of Object.entries(schema.errors ?? {}))
174
+ parts.push([`errors.${status}`, value])
175
+ return parts.sort(([a], [b]) => partOrder(a, b))
176
+ }
177
+
178
+ const MAX_ENUM_LABEL = 6
179
+
180
+ /** A short type name for one field schema, for the lock and a check message to show. */
181
+ function typeLabel(schema: unknown): string {
182
+ if (schema === true) return "unknown"
183
+ if (schema === false) return "never"
184
+ const record = recordOf(schema)
185
+ if (record === undefined) return "unknown"
186
+ if (Object.hasOwn(record, "const")) return JSON.stringify(record.const) ?? "unknown"
187
+ const values = record.enum
188
+ if (Array.isArray(values))
189
+ return values.length > MAX_ENUM_LABEL
190
+ ? `enum(${values.length})`
191
+ : values.map((value) => JSON.stringify(value)).join(" | ")
192
+ const union = record.anyOf ?? record.oneOf
193
+ if (Array.isArray(union)) return union.map((item) => typeLabel(item)).join(" | ")
194
+ const ref = record.$ref
195
+ if (typeof ref === "string") return ref.slice(ref.lastIndexOf("/") + 1)
196
+ const type = record.type
197
+ const types = Array.isArray(type) ? type : [type]
198
+ const labels: string[] = []
199
+ for (const name of types) {
200
+ if (typeof name !== "string") continue
201
+ if (name !== "array") labels.push(name)
202
+ else {
203
+ const item = typeLabel(record.items)
204
+ labels.push(item.includes(" | ") ? `(${item})[]` : `${item}[]`)
205
+ }
206
+ }
207
+ return labels.length === 0 ? "unknown" : labels.join(" | ")
208
+ }
209
+
210
+ /** Each part `route` declares, hashed alone, with its top-level fields. */
211
+ export async function contractParts(route: ReflectedRoute): Promise<Record<string, ContractPart>> {
212
+ const entries = await Promise.all(
213
+ declaredParts(route.schema).map(async ([part, value]): Promise<[string, ContractPart]> => {
214
+ const schema = value.jsonSchema ?? value.fields
215
+ if (schema === undefined) return [part, { digest: null }]
216
+ const digest = await sha256(JSON.stringify(canonical(schema)))
217
+ if (value.fields === undefined) return [part, { digest }]
218
+ const fields = value.fields
219
+ .map((field): [string, string] => [
220
+ field.required ? field.name : `${field.name}?`,
221
+ typeLabel(field.schema),
222
+ ])
223
+ .sort(([a], [b]) => codeUnitOrder(a, b))
224
+ return [part, { digest, fields: Object.fromEntries(fields) }]
225
+ }),
226
+ )
227
+ return Object.fromEntries(entries)
228
+ }
229
+
230
+ /** Per side, the digests of a route whose schema says nothing on that side: none declared, or every
231
+ * part declared in a form reflection cannot read (hashed as `null`). A lock entry holding one never
232
+ * guarded that side. */
233
+ async function blindDigests(): Promise<Record<"request" | "response", ReadonlySet<string>>> {
234
+ const of = async (side: "request" | "response") =>
235
+ new Set([
236
+ await sha256(JSON.stringify(canonical(schemaValue(undefined, side)))),
237
+ await sha256(JSON.stringify(canonical(schemaValue({}, side)))),
238
+ ])
239
+ return { request: await of("request"), response: await of("response") }
240
+ }
241
+
242
+ const unread = (value: SchemaReflection | undefined): boolean =>
243
+ value !== undefined && value.jsonSchema === undefined && value.fields === undefined
244
+
245
+ /** The parts of `route` that declare a schema reflection cannot read: hashed as `null`, as if absent,
246
+ * so the lock never notices a change to them. */
247
+ export function unreflectedParts(route: ReflectedRoute): string[] {
248
+ const schema = route.schema
249
+ if (schema === undefined) return []
250
+ const parts: string[] = []
251
+ for (const part of PART_ORDER) if (unread(schema[part])) parts.push(part)
252
+ for (const [status, value] of Object.entries(schema.errors ?? {}))
253
+ if (unread(value)) parts.push(`errors.${status}`)
254
+ return parts
255
+ }
256
+
136
257
  /** Whether every route in `lock` hashes to the empty-schema digest (so no route declares a schema). An
137
258
  * empty `routes` map is NOT vacuous in this sense - there is no route whose contract went unguarded. */
138
259
  export async function isVacuousLock(lock: ContractsLock): Promise<boolean> {
@@ -150,7 +271,11 @@ export async function buildContractsLock(
150
271
  const routes = Object.fromEntries(
151
272
  await Promise.all(
152
273
  reflected.map(
153
- async (route) => [`${route.method} ${route.path}`, await digestRoute(route)] as const,
274
+ async (route) =>
275
+ [
276
+ `${route.method} ${route.path}`,
277
+ { ...(await digestRoute(route)), parts: await contractParts(route) },
278
+ ] as const,
154
279
  ),
155
280
  ),
156
281
  )
@@ -192,13 +317,73 @@ export function validatesBeforeAuthentication(route: ReflectedRoute): boolean {
192
317
  return auth.length > 0 && auth.every((evidence) => evidence.source !== "nifra.authenticate")
193
318
  }
194
319
 
320
+ /** A route whose declared schema the lock records as `null` in `parts`. */
321
+ export interface UnreflectedRoute {
322
+ readonly route: string
323
+ readonly parts: readonly string[]
324
+ }
325
+
195
326
  export async function snapshotContracts(
196
327
  cwd: string,
197
328
  out = DEFAULT_CONTRACTS_LOCK,
198
329
  ): Promise<ContractsLock> {
199
- const lock = await buildContractsLock(await loadBackend(cwd))
330
+ return (await snapshotContractsReport(cwd, out)).lock
331
+ }
332
+
333
+ /** {@link snapshotContracts}, plus each route whose declared schema the lock records as `null`. */
334
+ export async function snapshotContractsReport(
335
+ cwd: string,
336
+ out = DEFAULT_CONTRACTS_LOCK,
337
+ ): Promise<{ lock: ContractsLock; unreflected: UnreflectedRoute[] }> {
338
+ const evidence = snapshotProjectEvidence(await loadBackend(cwd))
339
+ const lock = await buildContractsLock(undefined, evidence)
200
340
  await Bun.write(resolve(cwd, out), `${JSON.stringify(lock, null, 2)}\n`)
201
- return lock
341
+ const unreflected = reflectedRoutesFromEvidence(evidence)
342
+ .map((route) => ({ route: `${route.method} ${route.path}`, parts: unreflectedParts(route) }))
343
+ .filter((entry) => entry.parts.length > 0)
344
+ .sort((a, b) => codeUnitOrder(a.route, b.route))
345
+ return { lock, unreflected }
346
+ }
347
+
348
+ /** The lock entries of `lock` whose request or response digest says that side was never guarded. */
349
+ export async function blindLockEntries(
350
+ lock: ContractsLock,
351
+ ): Promise<Array<{ route: string; sides: Array<"request" | "response"> }>> {
352
+ const blind = await blindDigests()
353
+ const entries: Array<{ route: string; sides: Array<"request" | "response"> }> = []
354
+ for (const [route, digest] of Object.entries(lock.routes)) {
355
+ const sides = (["request", "response"] as const).filter((side) => blind[side].has(digest[side]))
356
+ if (sides.length > 0) entries.push({ route, sides })
357
+ }
358
+ return entries
359
+ }
360
+
361
+ function parseFields(value: unknown): Record<string, string> | undefined {
362
+ const record = recordOf(value)
363
+ if (record === undefined) return undefined
364
+ const fields: Array<[string, string]> = []
365
+ for (const [name, label] of Object.entries(record)) {
366
+ if (typeof label !== "string") return undefined
367
+ fields.push([name, label])
368
+ }
369
+ return Object.fromEntries(fields)
370
+ }
371
+
372
+ function parseParts(route: string, value: unknown): Record<string, ContractPart> {
373
+ const record = recordOf(value)
374
+ if (record === undefined) throw new TypeError(`invalid contract parts for ${route}`)
375
+ const parts: Array<[string, ContractPart]> = []
376
+ for (const [name, raw] of Object.entries(record)) {
377
+ const part = recordOf(raw)
378
+ const digest = part?.digest
379
+ if (digest !== null && !(typeof digest === "string" && DIGEST.test(digest)))
380
+ throw new TypeError(`invalid contract part ${name} for ${route}`)
381
+ const fields = part?.fields === undefined ? undefined : parseFields(part.fields)
382
+ if (part?.fields !== undefined && fields === undefined)
383
+ throw new TypeError(`invalid contract part ${name} fields for ${route}`)
384
+ parts.push([name, fields === undefined ? { digest } : { digest, fields }])
385
+ }
386
+ return Object.fromEntries(parts)
202
387
  }
203
388
 
204
389
  export function parseContractsLock(value: unknown): ContractsLock {
@@ -225,18 +410,109 @@ export function parseContractsLock(value: unknown): ContractsLock {
225
410
  !DIGEST.test(response)
226
411
  )
227
412
  throw new TypeError(`invalid contract ${key}`)
228
- routes[key] = { request, response }
413
+ const parts = item?.parts === undefined ? undefined : parseParts(key, item.parts)
414
+ routes[key] = parts === undefined ? { request, response } : { request, response, parts }
229
415
  }
230
416
  return typeof digest === "number" ? { version: 1, digest, routes } : { version: 1, routes }
231
417
  }
232
418
 
419
+ /** One lock mismatch. `sides` names what differs for a `changed` or `newly-covered` route, and
420
+ * `parts` which declared parts, when the lock records them (empty when only an edited side digest
421
+ * moved). */
422
+ export interface ContractDiagnostic {
423
+ readonly route?: string
424
+ readonly kind?: "added" | "removed" | "changed" | "newly-covered"
425
+ readonly sides?: readonly ("request" | "response")[]
426
+ readonly parts?: readonly string[]
427
+ readonly message: string
428
+ }
429
+
430
+ const own = (record: Readonly<Record<string, string>>, key: string): string | undefined =>
431
+ Object.hasOwn(record, key) ? record[key] : undefined
432
+
433
+ /** `+ added: type, - removed: type, kept: was -> now` between two field summaries. */
434
+ function fieldChanges(
435
+ before: Readonly<Record<string, string>>,
436
+ after: Readonly<Record<string, string>>,
437
+ ): string[] {
438
+ const names = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort(codeUnitOrder)
439
+ const changes: string[] = []
440
+ for (const name of names) {
441
+ const was = own(before, name)
442
+ const now = own(after, name)
443
+ if (was === now) continue
444
+ if (was === undefined) changes.push(`+ ${name}: ${now}`)
445
+ else if (now === undefined) changes.push(`- ${name}: ${was}`)
446
+ else changes.push(`${name}: ${was} -> ${now}`)
447
+ }
448
+ return changes
449
+ }
450
+
451
+ interface PartDrift {
452
+ readonly part: string
453
+ /** Locked as `null` and read now: the lock never guarded it. */
454
+ readonly uncovered: boolean
455
+ readonly detail: string
456
+ }
457
+
458
+ function partDrift(
459
+ before: Readonly<Record<string, ContractPart>>,
460
+ after: Readonly<Record<string, ContractPart>>,
461
+ ): PartDrift[] {
462
+ const names = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort(partOrder)
463
+ const drift: PartDrift[] = []
464
+ for (const part of names) {
465
+ const was = Object.hasOwn(before, part) ? before[part] : undefined
466
+ const now = Object.hasOwn(after, part) ? after[part] : undefined
467
+ if (was?.digest === now?.digest) continue
468
+ if (was === undefined || now === undefined) {
469
+ const added = now === undefined ? [] : fieldChanges({}, now.fields ?? {})
470
+ drift.push({
471
+ part,
472
+ uncovered: false,
473
+ detail:
474
+ was !== undefined
475
+ ? `${part} no longer declared`
476
+ : now?.digest === null
477
+ ? `${part} declared, in a form nifra cannot read`
478
+ : `${part} ${["declared", ...added].join(", ")}`,
479
+ })
480
+ continue
481
+ }
482
+ if (was.digest === null) {
483
+ drift.push({ part, uncovered: true, detail: part })
484
+ continue
485
+ }
486
+ const fields =
487
+ now.digest === null || was.fields === undefined || now.fields === undefined
488
+ ? []
489
+ : fieldChanges(was.fields, now.fields)
490
+ drift.push({
491
+ part,
492
+ uncovered: false,
493
+ detail:
494
+ now.digest === null
495
+ ? `${part} now in a form nifra cannot read`
496
+ : fields.length > 0
497
+ ? `${part} ${fields.join(", ")}`
498
+ : was.fields !== undefined && now.fields !== undefined
499
+ ? `${part} changed below its top-level fields`
500
+ : `${part} changed`,
501
+ })
502
+ }
503
+ return drift
504
+ }
505
+
506
+ const sidesOf = (parts: readonly string[]): Array<"request" | "response"> =>
507
+ (["request", "response"] as const).filter((side) => parts.some((part) => sideOf(part) === side))
508
+
233
509
  export async function checkContractsLock(
234
510
  cwd: string,
235
511
  file = DEFAULT_CONTRACTS_LOCK,
236
512
  ): Promise<{
237
513
  present: boolean
238
514
  vacuous: boolean
239
- diagnostics: Array<{ route?: string; message: string }>
515
+ diagnostics: Array<ContractDiagnostic>
240
516
  /** `METHOD /path` of every route the backend serves, read when the lock made the check load it. */
241
517
  served?: readonly string[]
242
518
  /** `METHOD /path` of each route {@link validatesBeforeAuthentication} names, read alongside `served`. */
@@ -252,7 +528,7 @@ export async function checkContractsLock(
252
528
  const inputBeforeAuth = reflectedRoutesFromEvidence(evidence)
253
529
  .filter(validatesBeforeAuthentication)
254
530
  .map((route) => `${route.method} ${route.path}`)
255
- const diagnostics: Array<{ route?: string; message: string }> = []
531
+ const diagnostics: ContractDiagnostic[] = []
256
532
  // Digests of two formats never compare, so this still fails; it just names the real cause.
257
533
  if (parsed.digest !== undefined && parsed.digest !== CONTRACT_DIGEST_FORMAT) {
258
534
  const newer = parsed.digest > CONTRACT_DIGEST_FORMAT
@@ -261,21 +537,79 @@ export async function checkContractsLock(
261
537
  })
262
538
  return { present: true, vacuous, diagnostics, served, inputBeforeAuth }
263
539
  }
540
+ const blind = await blindDigests()
264
541
  const keys = new Set([...Object.keys(parsed.routes), ...Object.keys(current.routes)])
265
542
  for (const key of [...keys].sort()) {
266
543
  const before = parsed.routes[key]
267
544
  const after = current.routes[key]
268
- if (
269
- before === undefined ||
270
- after === undefined ||
271
- before.request !== after.request ||
272
- before.response !== after.response
273
- ) {
545
+ if (before === undefined || after === undefined) {
274
546
  diagnostics.push({
275
547
  route: key,
276
- message: `contract changed for ${key}; if intentional run \`nifra contracts snapshot\` and include the lock update in the same change.`,
548
+ kind: before === undefined ? "added" : "removed",
549
+ message:
550
+ before === undefined
551
+ ? `${key} is served but not in ${file}; if intentional run \`nifra contracts snapshot\` and include the lock update in the same change.`
552
+ : `${key} is in ${file} but no longer served; if intentional run \`nifra contracts snapshot\` and include the lock update in the same change.`,
277
553
  })
554
+ continue
278
555
  }
556
+ // Between two digests that guard nothing there is nothing to compare.
557
+ const sides = (["request", "response"] as const).filter(
558
+ (side) =>
559
+ before[side] !== after[side] &&
560
+ !(blind[side].has(before[side]) && blind[side].has(after[side])),
561
+ )
562
+ if (before.parts !== undefined && after.parts !== undefined) {
563
+ const drift = partDrift(before.parts, after.parts)
564
+ const changed = drift.filter((item) => !item.uncovered)
565
+ // A side digest that moved with no part to show for it (an edited lock) still fails.
566
+ const unexplained = sides.filter((side) => !drift.some((item) => sideOf(item.part) === side))
567
+ if (changed.length > 0 || unexplained.length > 0) {
568
+ const parts = changed.map((item) => item.part)
569
+ const changedSides = sidesOf(parts)
570
+ const all = (["request", "response"] as const).filter(
571
+ (side) => changedSides.includes(side) || unexplained.includes(side),
572
+ )
573
+ const detail =
574
+ changed.length > 0 ? `: ${changed.map((item) => item.detail).join("; ")}` : ""
575
+ diagnostics.push({
576
+ route: key,
577
+ kind: "changed",
578
+ sides: all,
579
+ parts,
580
+ message: `contract changed for ${key} (${all.join(" and ")})${detail}; if intentional run \`nifra contracts snapshot\` and include the lock update in the same change.`,
581
+ })
582
+ }
583
+ const uncovered = drift.filter((item) => item.uncovered).map((item) => item.part)
584
+ if (uncovered.length > 0)
585
+ diagnostics.push({
586
+ route: key,
587
+ kind: "newly-covered",
588
+ sides: sidesOf(uncovered),
589
+ parts: uncovered,
590
+ message: `${key} ${uncovered.join(", ")}: ${file} locked the schema declared there as null (nifra could not read it), and this nifra reads it, so the lock never guarded it. Review the schema, then run \`nifra contracts snapshot\` to start guarding it.`,
591
+ })
592
+ continue
593
+ }
594
+ if (sides.length === 0) continue
595
+ // The lock cannot tell an older nifra that could not read a schema from a route that declared
596
+ // none, so this still fails: passing it would leave the side unguarded until someone snapshots.
597
+ const uncovered = sides.filter((side) => blind[side].has(before[side]))
598
+ const changed = sides.filter((side) => !blind[side].has(before[side]))
599
+ if (changed.length > 0)
600
+ diagnostics.push({
601
+ route: key,
602
+ kind: "changed",
603
+ sides: changed,
604
+ message: `contract changed for ${key} (${changed.join(" and ")}); if intentional run \`nifra contracts snapshot\` and include the lock update in the same change.`,
605
+ })
606
+ if (uncovered.length > 0)
607
+ diagnostics.push({
608
+ route: key,
609
+ kind: "newly-covered",
610
+ sides: uncovered,
611
+ message: `${key} ${uncovered.join(" and ")}: ${file} records no schema there (the route declared none, or an older nifra could not read it), and the route now has one, so the lock never guarded it. Review the schema, then run \`nifra contracts snapshot\` to start guarding it.`,
612
+ })
279
613
  }
280
614
  if (diagnostics.length > 0 && parsed.digest === undefined) {
281
615
  diagnostics.push({