@nifrajs/cli 5.2.0 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/dist/assure-hydration.d.ts.map +1 -1
  3. package/dist/assure-hydration.js +6 -2
  4. package/dist/assure-hydration.js.map +1 -1
  5. package/dist/check-diagnostics.d.ts.map +1 -1
  6. package/dist/check-diagnostics.js +2 -0
  7. package/dist/check-diagnostics.js.map +1 -1
  8. package/dist/check-scan.d.ts +9 -3
  9. package/dist/check-scan.d.ts.map +1 -1
  10. package/dist/check-scan.js +61 -24
  11. package/dist/check-scan.js.map +1 -1
  12. package/dist/check.d.ts.map +1 -1
  13. package/dist/check.js +3 -3
  14. package/dist/check.js.map +1 -1
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +22 -14
  17. package/dist/cli.js.map +1 -1
  18. package/dist/db-tool.d.ts.map +1 -1
  19. package/dist/db-tool.js +2 -1
  20. package/dist/db-tool.js.map +1 -1
  21. package/dist/env-file.d.ts.map +1 -1
  22. package/dist/env-file.js +41 -8
  23. package/dist/env-file.js.map +1 -1
  24. package/dist/internal/source-facts.d.ts +20 -4
  25. package/dist/internal/source-facts.d.ts.map +1 -1
  26. package/dist/internal/source-facts.js +248 -32
  27. package/dist/internal/source-facts.js.map +1 -1
  28. package/dist/mcp-exec.d.ts +1 -0
  29. package/dist/mcp-exec.d.ts.map +1 -1
  30. package/dist/mcp-exec.js +11 -3
  31. package/dist/mcp-exec.js.map +1 -1
  32. package/dist/mcp-http.js +1 -1
  33. package/dist/mcp-io.d.ts +23 -3
  34. package/dist/mcp-io.d.ts.map +1 -1
  35. package/dist/mcp-io.js +59 -12
  36. package/dist/mcp-io.js.map +1 -1
  37. package/dist/mcp-isolate.d.ts.map +1 -1
  38. package/dist/mcp-isolate.js +2 -1
  39. package/dist/mcp-isolate.js.map +1 -1
  40. package/dist/migrate-layout.d.ts.map +1 -1
  41. package/dist/migrate-layout.js +1 -0
  42. package/dist/migrate-layout.js.map +1 -1
  43. package/dist/recipes/5.3.0.d.ts +11 -0
  44. package/dist/recipes/5.3.0.d.ts.map +1 -0
  45. package/dist/recipes/5.3.0.js +35 -0
  46. package/dist/recipes/5.3.0.js.map +1 -0
  47. package/dist/recipes/5.4.0.d.ts +10 -0
  48. package/dist/recipes/5.4.0.d.ts.map +1 -0
  49. package/dist/recipes/5.4.0.js +25 -0
  50. package/dist/recipes/5.4.0.js.map +1 -0
  51. package/dist/recipes/index.d.ts.map +1 -1
  52. package/dist/recipes/index.js +4 -0
  53. package/dist/recipes/index.js.map +1 -1
  54. package/dist/review.d.ts.map +1 -1
  55. package/dist/review.js +2 -0
  56. package/dist/review.js.map +1 -1
  57. package/dist/rules/codes.d.ts +2 -0
  58. package/dist/rules/codes.d.ts.map +1 -1
  59. package/dist/rules/codes.js +2 -0
  60. package/dist/rules/codes.js.map +1 -1
  61. package/dist/rules/explanations.d.ts.map +1 -1
  62. package/dist/rules/explanations.js +12 -2
  63. package/dist/rules/explanations.js.map +1 -1
  64. package/dist/rules/pages.d.ts +25 -1
  65. package/dist/rules/pages.d.ts.map +1 -1
  66. package/dist/rules/pages.js +149 -33
  67. package/dist/rules/pages.js.map +1 -1
  68. package/dist/rules/route-statement.d.ts +10 -0
  69. package/dist/rules/route-statement.d.ts.map +1 -0
  70. package/dist/rules/route-statement.js +150 -0
  71. package/dist/rules/route-statement.js.map +1 -0
  72. package/dist/upgrade.d.ts +43 -10
  73. package/dist/upgrade.d.ts.map +1 -1
  74. package/dist/upgrade.js +161 -45
  75. package/dist/upgrade.js.map +1 -1
  76. package/docs/llms-full.txt +508 -190
  77. package/docs/types.json +217 -31
  78. package/package.json +11 -11
  79. package/src/assure-hydration.ts +7 -1
  80. package/src/check-diagnostics.ts +2 -0
  81. package/src/check-scan.ts +64 -25
  82. package/src/check.ts +8 -3
  83. package/src/cli.ts +22 -14
  84. package/src/db-tool.ts +2 -0
  85. package/src/env-file.ts +42 -7
  86. package/src/internal/source-facts.ts +312 -39
  87. package/src/mcp-exec.ts +13 -2
  88. package/src/mcp-http.ts +1 -1
  89. package/src/mcp-io.ts +72 -12
  90. package/src/mcp-isolate.ts +2 -0
  91. package/src/migrate-layout.ts +1 -0
  92. package/src/recipes/5.3.0.ts +36 -0
  93. package/src/recipes/5.4.0.ts +26 -0
  94. package/src/recipes/index.ts +4 -0
  95. package/src/review.ts +2 -0
  96. package/src/rules/codes.ts +2 -0
  97. package/src/rules/explanations.ts +12 -2
  98. package/src/rules/pages.ts +193 -33
  99. package/src/rules/route-statement.ts +170 -0
  100. package/src/upgrade.ts +202 -47
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nifrajs/cli",
3
- "version": "5.2.0",
3
+ "version": "5.4.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.2.0",
74
- "@nifrajs/core": "5.2.0",
75
- "@nifrajs/agent-review": "5.2.0",
76
- "@nifrajs/i18n": "5.2.0",
77
- "@nifrajs/mcp": "5.2.0",
78
- "@nifrajs/mcp-db": "5.2.0",
79
- "@nifrajs/runner": "5.2.0",
80
- "@nifrajs/schema": "5.2.0",
81
- "@nifrajs/testing": "5.2.0",
82
- "@nifrajs/web": "5.2.0"
73
+ "@nifrajs/client": "5.4.0",
74
+ "@nifrajs/core": "5.4.0",
75
+ "@nifrajs/agent-review": "5.4.0",
76
+ "@nifrajs/i18n": "5.4.0",
77
+ "@nifrajs/mcp": "5.4.0",
78
+ "@nifrajs/mcp-db": "5.4.0",
79
+ "@nifrajs/runner": "5.4.0",
80
+ "@nifrajs/schema": "5.4.0",
81
+ "@nifrajs/testing": "5.4.0",
82
+ "@nifrajs/web": "5.4.0"
83
83
  },
84
84
  "repository": {
85
85
  "type": "git",
@@ -20,6 +20,8 @@ import {
20
20
  readBoundedStream,
21
21
  readHeadTail,
22
22
  signalProcessGroup,
23
+ stopGroupAndWait,
24
+ stopGroupOnExit,
23
25
  } from "./mcp-io.ts"
24
26
  import { frameworkWebAppOptions } from "./web-app-options.ts"
25
27
 
@@ -649,6 +651,7 @@ export async function runHydrationAssurance(
649
651
  detached: OWN_PROCESS_GROUP,
650
652
  },
651
653
  )
654
+ stopGroupOnExit(proc)
652
655
  const stopper = escalatingStop((name) => signalProcessGroup(proc, name))
653
656
  let stopped: string | undefined
654
657
  const stop = (reason: string): void => {
@@ -657,7 +660,10 @@ export async function runHydrationAssurance(
657
660
  }
658
661
  const onAbort = (): void => stop("cancelled")
659
662
  control.signal?.addEventListener("abort", onAbort, { once: true })
660
- const releaseSignals = forwardTerminalSignals(() => stop("interrupted"))
663
+ const releaseSignals = forwardTerminalSignals(() => {
664
+ stopped ??= "interrupted"
665
+ return stopGroupAndWait(proc)
666
+ })
661
667
  const timeoutMs = control.timeoutMs ?? HYDRATION_RUN_TIMEOUT_MS
662
668
  const timer = setTimeout(() => stop(`timed out after ${timeoutMs} ms`), timeoutMs)
663
669
  try {
@@ -31,6 +31,7 @@ import { LEGACY_RULE_CODES, LEGACY_RULE_ORDER, legacyRules } from "./rules/legac
31
31
  import { mergeAuthGapRule } from "./rules/merge-auth.ts"
32
32
  import { nanoRules } from "./rules/nano.ts"
33
33
  import { pageRules } from "./rules/pages.ts"
34
+ import { routeStatementRule } from "./rules/route-statement.ts"
34
35
  import { routeRules } from "./rules/routes.ts"
35
36
  import { secretRules } from "./rules/secrets.ts"
36
37
  import { securityRules } from "./rules/security.ts"
@@ -499,6 +500,7 @@ export async function collectCheckDiagnostics(
499
500
  contractVisibilityRule,
500
501
  ...pageRules,
501
502
  mergeAuthGapRule,
503
+ routeStatementRule,
502
504
  ...zoneRules,
503
505
  ...dataGuardRules,
504
506
  ...secretRules,
package/src/check-scan.ts CHANGED
@@ -352,7 +352,9 @@ export function parseSimpleFetchCall(snippet: string): SimpleFetchCall | undefin
352
352
  return { path, method, start: match.index, end: close + 1 }
353
353
  }
354
354
 
355
- const SERVER_CONSTRUCTION = /(?<![.\w])server\s*\(|new\s+Hono(?:<[^>]+>)?\s*\(/
355
+ // `createWebApp(...)` returns the same `Server`, so a route chained onto it is a backend route.
356
+ const NIFRA_SERVER_CONSTRUCTION = /(?<![.\w])(?:server|createWebApp)\s*\(/
357
+ const SERVER_CONSTRUCTION = /(?<![.\w])(?:server|createWebApp)\s*\(|new\s+Hono(?:<[^>]+>)?\s*\(/
356
358
 
357
359
  function isPotentialBackendSource(
358
360
  code: string,
@@ -3364,43 +3366,80 @@ function serverOnlyChains(
3364
3366
  // (redirects, files, streams). Fix is to return a plain object, or declare `{ response: t.… }` to type it.
3365
3367
  const RESPONSE_RETURN = /(?:=>\s*|return\s+)(?:new\s+Response|Response\s*\.\s*json)\s*\(/g
3366
3368
 
3367
- /** Scan a backend module (one that calls `server(`) for handlers returning a raw `Response`, which collapses
3368
- * the typed client's `data` to `never`. Pure + line-accurate; returns `[]` for files with no `server(` call. */
3369
+ /**
3370
+ * Scan a backend module (one that calls `server(` or `createWebApp(`) for handlers returning a raw
3371
+ * `Response`, which collapses the typed client's `data` to `never`. Pure + line-accurate; returns `[]`
3372
+ * for any other file. With an AST it also follows what the lexical pattern cannot see: a local holding
3373
+ * the Response, the context's `json()`/`text()`, and - given `project` - a helper imported from a
3374
+ * relative module whose export returns one, reported at each route's return. It skips a handler the
3375
+ * client still types: one that also returns a plain value, or whose route declares `response`.
3376
+ */
3369
3377
  export function scanResponseRoutes(
3370
3378
  file: string,
3371
3379
  content: string,
3372
3380
  facts?: SourceFacts,
3381
+ project?: ReadonlyMap<string, string>,
3373
3382
  ): SourceFinding[] {
3374
3383
  // Strip comments + template literals first: a commented-out or doc-example `return new Response(`
3375
3384
  // must not raise a spurious advisory. Lengths are preserved, so lineAt + the raw-line snippet align.
3376
3385
  const code = stripComments(content)
3377
- if (!/(?<![.\w])server\s*\(/.test(code)) return []
3386
+ if (!NIFRA_SERVER_CONSTRUCTION.test(code)) return []
3378
3387
  const out: SourceFinding[] = []
3379
3388
  const lines = content.split("\n")
3389
+ // A `// nifra-expect NF-C007` comment (or the `raw-response` slug) marks an intentional raw Response
3390
+ // (a file/redirect that can't be a typed route), silencing this advisory with or without a reason.
3391
+ // It counts on the return line or in the comment block directly above, so a TRAILING comment on one
3392
+ // route's return line can't leak down onto the next route. `stripComments` blanks it in `code` (so it
3393
+ // never affects the match); the raw `lines` still carry it.
3394
+ const report = (line: number): void => {
3395
+ if (commentBlockExpectation(lines, line, RAW_RESPONSE_EXPECTATION) !== undefined) return
3396
+ out.push({ file, line, snippet: (lines[line - 1] ?? "").trim() })
3397
+ }
3398
+ const source = facts?.parse(file, content)
3399
+ const exportsByImport = new Map<string, boolean>()
3400
+ const importReturnsResponse =
3401
+ facts === undefined || project === undefined
3402
+ ? undefined
3403
+ : (specifier: string, name: string): boolean => {
3404
+ const key = `${specifier}\0${name}`
3405
+ let answer = exportsByImport.get(key)
3406
+ if (answer === undefined) {
3407
+ const target = projectModule(project, file, specifier)
3408
+ const text = target === undefined ? undefined : project.get(target)
3409
+ const module =
3410
+ target === undefined || text === undefined ? undefined : facts.parse(target, text)
3411
+ answer = module !== undefined && facts.exportReturnsResponse(module, name)
3412
+ exportsByImport.set(key, answer)
3413
+ }
3414
+ return answer
3415
+ }
3416
+ const routes =
3417
+ facts === undefined || source === undefined
3418
+ ? undefined
3419
+ : facts.untypedResponseRoutes(source, importReturnsResponse)
3380
3420
  RESPONSE_RETURN.lastIndex = 0
3381
3421
  for (let m = RESPONSE_RETURN.exec(code); m !== null; m = RESPONSE_RETURN.exec(code)) {
3382
- if (facts !== undefined) {
3383
- const source = facts.parse(file, content)
3384
- // A parseable AST rejects `return new Response(` text that only lives in a normal string, and
3385
- // one outside a route handler (an auth stage's `rejected` helper, say). On malformed source we
3386
- // keep the lexical candidate; the typecheck gate will report the syntax error.
3387
- if (
3388
- source !== undefined &&
3389
- (facts.isResponseSyntaxAt(source, m.index) !== true ||
3390
- !facts.isRouteHandlerAt(source, m.index))
3391
- )
3392
- continue
3393
- }
3394
- const line = lineAt(content, m.index)
3395
- // A `// nifra-expect NF-C007` comment (or the `raw-response` slug) marks an intentional raw Response
3396
- // (a file/redirect that can't be a typed route), silencing this advisory with or without a reason.
3397
- // It counts on the return line or in the comment block directly above, so a TRAILING comment on one
3398
- // route's return line can't leak down onto the next route. `stripComments` blanks it in `code` (so it
3399
- // never affects the match); the raw `lines` still carry it.
3400
- if (commentBlockExpectation(lines, line, RAW_RESPONSE_EXPECTATION) !== undefined) continue
3401
- out.push({ file, line, snippet: (lines[line - 1] ?? "").trim() })
3422
+ // A parseable AST rejects `return new Response(` text that only lives in a normal string, one
3423
+ // outside a route handler (an auth stage's `rejected` helper, say), and one in a handler the client
3424
+ // still types: it returns a plain value too, or its route declares `response`. On malformed
3425
+ // source we keep the lexical candidate; the typecheck gate will report the syntax error.
3426
+ if (
3427
+ facts !== undefined &&
3428
+ source !== undefined &&
3429
+ (facts.isResponseSyntaxAt(source, m.index) !== true || routes?.isUntypedAt(m.index) !== true)
3430
+ )
3431
+ continue
3432
+ report(lineAt(content, m.index))
3402
3433
  }
3403
- return out
3434
+ if (routes === undefined) return out
3435
+ const reported = new Set(out.map((finding) => finding.line))
3436
+ for (const position of routes.indirectReturns) {
3437
+ const line = lineAt(content, position)
3438
+ if (reported.has(line)) continue
3439
+ reported.add(line)
3440
+ report(line)
3441
+ }
3442
+ return out.sort((a, b) => a.line - b.line)
3404
3443
  }
3405
3444
 
3406
3445
  /** What suppresses the {@link scanResponseRoutes} advisory for an intentional raw Response. */
package/src/check.ts CHANGED
@@ -38,7 +38,12 @@ import { createApiOnlyProbe, createNifraProjectProbe } from "./internal/nifra-pr
38
38
  import { createSpecifierResolver } from "./internal/project-specifiers.ts"
39
39
  import { createSourceFacts } from "./internal/source-facts.ts"
40
40
  import { loadProjectTypeScript, type TypeScriptApi } from "./internal/typescript-import.ts"
41
- import { forwardTerminalSignals, OWN_PROCESS_GROUP, signalProcessGroup } from "./mcp-io.ts"
41
+ import {
42
+ forwardTerminalSignals,
43
+ OWN_PROCESS_GROUP,
44
+ signalProcessGroup,
45
+ stopGroupAndWait,
46
+ } from "./mcp-io.ts"
42
47
  // Type-only: `pipeline-report.ts` imports this module's source scanners, so a value import here would
43
48
  // close a cycle. Doctor is what actually runs the collector (see the `pipeline` rule below).
44
49
  import type { ContractCheckFacts, ProjectFactsSeed } from "./project-facts.ts"
@@ -209,7 +214,7 @@ async function runTsc(
209
214
  stop()
210
215
  }
211
216
  signal?.addEventListener("abort", abort, { once: true })
212
- const releaseSignals = forwardTerminalSignals(stop)
217
+ const releaseSignals = forwardTerminalSignals(() => stopGroupAndWait(proc))
213
218
  let out = ""
214
219
  let err = ""
215
220
  let code: number | null = null
@@ -479,7 +484,7 @@ async function buildProjectScan(
479
484
  for (const { file, content } of sourceFiles) {
480
485
  staticRoutes.push(...scanStaticRouteText(file, content, sourceFacts, project))
481
486
  routePaths.push(...scanUnresolvedRoutePaths(file, content, project, sourceFacts))
482
- responseRoutes.push(...scanResponseRoutes(file, content, sourceFacts))
487
+ responseRoutes.push(...scanResponseRoutes(file, content, sourceFacts, project))
483
488
  if (sqlCompiler !== undefined)
484
489
  interpolatedSql.push(...scanSqlSites(file, content, sqlCompiler, sqlImports))
485
490
  }
package/src/cli.ts CHANGED
@@ -145,7 +145,8 @@ Usage:
145
145
  nifra build [--out <dir>] [--report] Emit a complete deploy directory.
146
146
  [--target <t>] Target a FULL deploy dir for <t>:
147
147
  bun | node | deno | cloudflare | vercel | static. Packages
148
- buildClient + buildServer (+ prerender for static) so an app
148
+ buildClient + buildServer (+ prerender for static, bun and
149
+ node, whose server answers those pages from file) so an app
149
150
  no longer hand-writes build-<target>.ts + _worker.ts +
150
151
  _routes.json. The server entry is generated from your
151
152
  backend/framework.ts (adapter) + backend/app.ts + routes/.
@@ -275,15 +276,18 @@ Usage:
275
276
  nifra upgrade <version> Upgrade to <version>, running every release recipe between the
276
277
  [--write] [--no-verify] installed version and it, oldest first: move removed packages,
277
278
  [--list] [--json] apply exact imports, pin every matching dependency (keeping
278
- [--exact] ^/~, or exact with --exact), then verify with nifra check.
279
- [--allow-downgrade] Dry-run by default; --write applies then verifies (--no-verify
280
- [--allow-linked-skew] to skip), then prints how hook scope changed (--no-hooks to
281
- [--no-hooks] skip). --list shows the targets with each newer release's
282
- notes. A version newer than this CLI prints the command for
283
- that release's CLI. Fail-closed on an unknown version, a
284
- rollback (--allow-downgrade overrides), or a linked repository
285
- that loads its own nifra at another version
286
- (--allow-linked-skew overrides). Deterministic + idempotent.
279
+ [--exact] ^/~, or exact with --exact; a peer range only when it
280
+ excludes the target), then verify with nifra check.
281
+ [--allow-downgrade] Dry-run by default; --write applies, then verifies (--no-verify
282
+ [--allow-linked-skew] to skip) and prints how hook scope changed (--no-hooks to skip)
283
+ [--no-hooks] once the target is installed, else prints the install command
284
+ to run first. --list shows the targets with each newer
285
+ release's notes. A version newer than this CLI prints the
286
+ command for that release's CLI. Fail-closed on an unknown
287
+ version, a rollback (--allow-downgrade overrides), or a
288
+ linked repository that loads its own nifra at another
289
+ version (--allow-linked-skew overrides). Deterministic +
290
+ idempotent.
287
291
  nifra migrate layout [--write] [--zones] [--json]
288
292
  Move an app onto the frontend/backend split: split each route
289
293
  into x.tsx + x.backend.ts, fold _middleware.ts into
@@ -330,7 +334,7 @@ set in the process environment is never overwritten by a file.
330
334
  ${renderCommandCatalogHelp()}`
331
335
 
332
336
  // Kept in lockstep with packages/cli/package.json by check:publish's version-consistency gate.
333
- const CLI_VERSION = "5.2.0"
337
+ const CLI_VERSION = "5.4.0"
334
338
 
335
339
  // A render adapter + nifra server are opaque to the CLI (it just forwards them); cast at the seam.
336
340
  const asAdapter = (v: unknown): RenderAdapter => v as RenderAdapter
@@ -910,8 +914,12 @@ async function buildForTarget(
910
914
  ...(fw.cssCodeSplit !== undefined ? { cssCodeSplit: fw.cssCodeSplit } : {}),
911
915
  ...(fw.cssLoading !== undefined ? { cssLoading: fw.cssLoading } : {}),
912
916
  ...(fw.clientIp !== undefined ? { clientIp: fw.clientIp } : {}),
913
- // The static target needs a built app to drive prerendering - only build it when targeting static.
914
- ...(target === "static" ? { prerenderApp: await buildPrerenderApp(app) } : {}),
917
+ // Prerendering drives a built app: the static target is made of its pages, and a bun or node server
918
+ // answers its prerendered pages from their file. Not under Vite, whose server bundle may rely on
919
+ // transforms the prerender pass (Bun's runtime) does not apply: those pages keep rendering on demand.
920
+ ...(target === "static" || (!useVite && (target === "bun" || target === "node"))
921
+ ? { prerenderApp: await buildPrerenderApp(app) }
922
+ : {}),
915
923
  })
916
924
  // A production build must not certify itself green while a workspace-linked dependency ships a dist
917
925
  // artifact older than (or absent next to) its source: the `bun`->src condition let this compile read
@@ -925,7 +933,7 @@ async function buildForTarget(
925
933
  if (flags.report) console.log(`\n${renderSizeReport(result.size)}`)
926
934
  }
927
935
 
928
- /** Build the app FACTORY for the `static` target's prerender pass. Registers the
936
+ /** Build the app FACTORY for the prerender pass of the `static`, `bun` and `node` targets. Registers the
929
937
  * framework's SSR Bun plugins (so `.vue`/`.svelte`/Solid routes import) once, then return a factory that
930
938
  * `createWebApp`s the app for the client build's manifest. The client entry MUST be the real content-hashed
931
939
  * bundle (`client.entry`) - it's the hydration `<script src>` the prerendered HTML emits, so a placeholder
package/src/db-tool.ts CHANGED
@@ -38,6 +38,7 @@ import {
38
38
  readBoundedLines,
39
39
  readBoundedStream,
40
40
  signalProcessGroup,
41
+ stopGroupOnExit,
41
42
  } from "./mcp-io.ts"
42
43
 
43
44
  /** Added to the declared `timeoutMs` before the subprocess is killed. */
@@ -138,6 +139,7 @@ export async function runDbChild(
138
139
  stderr: "pipe",
139
140
  detached: OWN_PROCESS_GROUP,
140
141
  })
142
+ stopGroupOnExit(proc)
141
143
  let killedFor: "startup" | "deadline" | "cancel" | undefined
142
144
  const kill = (reason: NonNullable<typeof killedFor>): void => {
143
145
  if (killedFor !== undefined) return
package/src/env-file.ts CHANGED
@@ -16,7 +16,9 @@
16
16
  * would make the command look like it verified an environment it never loaded.
17
17
  */
18
18
  import { readdir, readFile } from "node:fs/promises"
19
+ import { devNull } from "node:os"
19
20
  import { resolve } from "node:path"
21
+ import { readBoundedStream } from "./mcp-io.ts"
20
22
 
21
23
  const ENV_FILE_FLAG = "--env-file"
22
24
 
@@ -179,24 +181,57 @@ async function envFromFiles(
179
181
  return added
180
182
  }
181
183
 
182
- /** What `process.env` holds in a Bun process started in `cwd` with `env` and the runtime `flags`. */
184
+ const PROBE_TIMEOUT_MS = 10_000
185
+ const PROBE_MAX_BYTES = 4 * 1024 * 1024
186
+
187
+ /**
188
+ * What `process.env` holds in a Bun process started in `cwd` with `env` and the runtime `flags`. The
189
+ * empty `--config` keeps the project's bunfig preloads out: both probes would differ by none of what
190
+ * they set, and one that keeps its process alive held `nifra mcp` before it ever answered. A probe
191
+ * that still fails to answer in time fails the start, rather than serving with values it cannot tell
192
+ * came from a file.
193
+ */
183
194
  async function childEnv(
184
195
  cwd: string,
185
196
  env: Record<string, string | undefined>,
186
197
  flags: readonly string[],
187
198
  ): Promise<Record<string, string>> {
188
199
  const proc = Bun.spawn(
189
- [process.execPath, ...flags, "-e", "process.stdout.write(JSON.stringify(process.env))"],
200
+ [
201
+ process.execPath,
202
+ `--config=${devNull}`,
203
+ ...flags,
204
+ "-e",
205
+ "process.stdout.write(JSON.stringify(process.env), () => process.exit(0))",
206
+ ],
190
207
  { cwd, env, stdin: "ignore", stdout: "pipe", stderr: "ignore" },
191
208
  )
192
- const [text] = await Promise.all([new Response(proc.stdout).text(), proc.exited])
209
+ let failure: string | undefined
210
+ const timer = setTimeout(() => {
211
+ failure = `took longer than ${PROBE_TIMEOUT_MS}ms`
212
+ proc.kill("SIGKILL")
213
+ }, PROBE_TIMEOUT_MS)
193
214
  let value: unknown
194
215
  try {
195
- value = JSON.parse(text)
196
- } catch {
197
- return {}
216
+ const [output, code] = await Promise.all([
217
+ readBoundedStream(proc.stdout, PROBE_MAX_BYTES, () => proc.kill("SIGKILL")),
218
+ proc.exited,
219
+ ])
220
+ if (output.truncated) failure ??= `printed more than ${PROBE_MAX_BYTES} bytes`
221
+ else if (code !== 0) failure ??= `exited with code ${code}`
222
+ else value = JSON.parse(output.text)
223
+ } catch (error) {
224
+ failure ??= error instanceof Error ? error.message : String(error)
225
+ } finally {
226
+ clearTimeout(timer)
227
+ }
228
+ if (failure !== undefined || typeof value !== "object" || value === null) {
229
+ throw new Error(
230
+ `[nifra] could not tell which variables the .env files in ${cwd} set: a Bun probe ${
231
+ failure ?? "printed no environment"
232
+ }`,
233
+ )
198
234
  }
199
- if (typeof value !== "object" || value === null) return {}
200
235
  return Object.fromEntries(
201
236
  Object.entries(value).filter(
202
237
  (entry): entry is [string, string] => typeof entry[1] === "string",