@nifrajs/cli 5.10.0 → 5.11.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 (61) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/cli.d.ts.map +1 -1
  3. package/dist/cli.js +10 -13
  4. package/dist/cli.js.map +1 -1
  5. package/dist/doctor.js +2 -2
  6. package/dist/doctor.js.map +1 -1
  7. package/dist/load.d.ts +2 -2
  8. package/dist/load.d.ts.map +1 -1
  9. package/dist/load.js +1 -1
  10. package/dist/load.js.map +1 -1
  11. package/dist/mcp-delegate.d.ts +17 -3
  12. package/dist/mcp-delegate.d.ts.map +1 -1
  13. package/dist/mcp-delegate.js +24 -9
  14. package/dist/mcp-delegate.js.map +1 -1
  15. package/dist/mcp-http.js +1 -1
  16. package/dist/mcp-relay.d.ts +37 -0
  17. package/dist/mcp-relay.d.ts.map +1 -0
  18. package/dist/mcp-relay.js +129 -0
  19. package/dist/mcp-relay.js.map +1 -0
  20. package/dist/mcp.d.ts.map +1 -1
  21. package/dist/mcp.js +55 -1
  22. package/dist/mcp.js.map +1 -1
  23. package/dist/migrate-layout.d.ts.map +1 -1
  24. package/dist/migrate-layout.js +45 -33
  25. package/dist/migrate-layout.js.map +1 -1
  26. package/dist/recipes/5.10.0.d.ts +3 -2
  27. package/dist/recipes/5.10.0.d.ts.map +1 -1
  28. package/dist/recipes/5.10.0.js +5 -4
  29. package/dist/recipes/5.10.0.js.map +1 -1
  30. package/dist/recipes/5.11.0.d.ts +10 -0
  31. package/dist/recipes/5.11.0.d.ts.map +1 -0
  32. package/dist/recipes/5.11.0.js +50 -0
  33. package/dist/recipes/5.11.0.js.map +1 -0
  34. package/dist/recipes/index.d.ts.map +1 -1
  35. package/dist/recipes/index.js +2 -0
  36. package/dist/recipes/index.js.map +1 -1
  37. package/dist/source-rewrites.d.ts +0 -5
  38. package/dist/source-rewrites.d.ts.map +1 -1
  39. package/dist/source-rewrites.js +232 -7
  40. package/dist/source-rewrites.js.map +1 -1
  41. package/dist/upgrade.d.ts +19 -1
  42. package/dist/upgrade.d.ts.map +1 -1
  43. package/dist/upgrade.js +55 -2
  44. package/dist/upgrade.js.map +1 -1
  45. package/docs/examples.json +2 -2
  46. package/docs/llms-full.txt +246 -63
  47. package/docs/types.json +316 -21
  48. package/package.json +11 -11
  49. package/src/cli.ts +10 -13
  50. package/src/doctor.ts +2 -2
  51. package/src/load.ts +6 -3
  52. package/src/mcp-delegate.ts +37 -11
  53. package/src/mcp-http.ts +1 -1
  54. package/src/mcp-relay.ts +155 -0
  55. package/src/mcp.ts +51 -1
  56. package/src/migrate-layout.ts +61 -29
  57. package/src/recipes/5.10.0.ts +5 -4
  58. package/src/recipes/5.11.0.ts +51 -0
  59. package/src/recipes/index.ts +2 -0
  60. package/src/source-rewrites.ts +250 -8
  61. package/src/upgrade.ts +71 -3
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nifrajs/cli",
3
- "version": "5.10.0",
3
+ "version": "5.11.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.10.0",
74
- "@nifrajs/core": "5.10.0",
75
- "@nifrajs/agent-review": "5.10.0",
76
- "@nifrajs/i18n": "5.10.0",
77
- "@nifrajs/mcp": "5.10.0",
78
- "@nifrajs/mcp-db": "5.10.0",
79
- "@nifrajs/runner": "5.10.0",
80
- "@nifrajs/schema": "5.10.0",
81
- "@nifrajs/testing": "5.10.0",
82
- "@nifrajs/web": "5.10.0"
73
+ "@nifrajs/client": "5.11.0",
74
+ "@nifrajs/core": "5.11.0",
75
+ "@nifrajs/agent-review": "5.11.0",
76
+ "@nifrajs/i18n": "5.11.0",
77
+ "@nifrajs/mcp": "5.11.0",
78
+ "@nifrajs/mcp-db": "5.11.0",
79
+ "@nifrajs/runner": "5.11.0",
80
+ "@nifrajs/schema": "5.11.0",
81
+ "@nifrajs/testing": "5.11.0",
82
+ "@nifrajs/web": "5.11.0"
83
83
  },
84
84
  "repository": {
85
85
  "type": "git",
package/src/cli.ts CHANGED
@@ -290,7 +290,9 @@ Usage:
290
290
  [--write] [--no-verify] installed version and it, oldest first: move removed packages,
291
291
  [--list] [--json] apply exact imports, pin every matching dependency (keeping
292
292
  [--exact] ^/~, or exact with --exact; a peer range only when it
293
- excludes the target), then verify with nifra check.
293
+ [--from <version>] excludes the target), then verify with nifra check. --from
294
+ names the installed version when the pins no longer do,
295
+ such as after bumping them by hand.
294
296
  [--allow-downgrade] Dry-run by default; --write applies, then verifies (--no-verify
295
297
  [--allow-linked-skew] to skip) and prints how hook scope changed (--no-hooks to skip)
296
298
  [--no-hooks] once the target is installed, else prints the install command
@@ -354,7 +356,7 @@ set in the process environment is never overwritten by a file.
354
356
  ${renderCommandCatalogHelp()}`
355
357
 
356
358
  // Kept in lockstep with packages/cli/package.json by check:publish's version-consistency gate.
357
- const CLI_VERSION = "5.10.0"
359
+ const CLI_VERSION = "5.11.0"
358
360
 
359
361
  // A render adapter + nifra server are opaque to the CLI (it just forwards them); cast at the seam.
360
362
  const asAdapter = (v: unknown): RenderAdapter => v as RenderAdapter
@@ -1451,19 +1453,14 @@ async function main(): Promise<void> {
1451
1453
  // recipe, then verified with `nifra check`. Dispatch before the eager `loadApp` - it must run on any
1452
1454
  // repo (API-only, not built, or mid-upgrade with edits that don't yet typecheck under dry-run).
1453
1455
  if (command === "upgrade") {
1454
- const { runUpgrade } = await import("./upgrade.ts")
1455
- const version = argv.slice(1).find((arg) => !arg.startsWith("-"))
1456
+ if (argv.includes("--help") || argv.includes("-h")) {
1457
+ console.log(HELP)
1458
+ return
1459
+ }
1460
+ const { parseUpgradeArgs, runUpgrade } = await import("./upgrade.ts")
1456
1461
  try {
1457
1462
  const ok = await runUpgrade(process.cwd(), {
1458
- ...(version !== undefined ? { version } : {}),
1459
- write: argv.includes("--write"),
1460
- json: argv.includes("--json"),
1461
- list: argv.includes("--list"),
1462
- verify: !argv.includes("--no-verify"),
1463
- hooks: !argv.includes("--no-hooks"),
1464
- allowDowngrade: argv.includes("--allow-downgrade"),
1465
- allowLinkedSkew: argv.includes("--allow-linked-skew"),
1466
- exact: argv.includes("--exact"),
1463
+ ...parseUpgradeArgs(argv.slice(1)),
1467
1464
  cliVersion: CLI_VERSION,
1468
1465
  })
1469
1466
  if (!ok) process.exitCode = 1
package/src/doctor.ts CHANGED
@@ -884,9 +884,9 @@ const KNOWN_AUTH_PACKAGES = [
884
884
  const IDENTITY_SIGNAL = /\b(?:identityCookies\s*:|rotateIdentityEpoch\s*\(|identityChanged\s*\()/
885
885
  // A session cookie renamed outright: Better Auth's `advanced.cookies.session_token.name`, Auth.js's
886
886
  // `cookies.sessionToken.name`, `@nifrajs/auth`'s `cookieName`. A Better Auth `cookiePrefix` keeps the
887
- // suffix the identity epoch matches, so it is not one.
887
+ // suffix the identity epoch matches, so it is not one, and neither is a type's `name: string`.
888
888
  const RENAMED_SESSION =
889
- /\b(?:session_token|sessionToken)\s*:\s*\{[^}]*\bname\s*:|\bcookieName\s*:\s*["'`]/
889
+ /\b(?:session_token|sessionToken)\s*:\s*\{[^}]*\bname\s*:\s*["'`]|\bcookieName\s*:\s*["'`]/
890
890
 
891
891
  // Below the app itself, only what a package loads at runtime is followed.
892
892
  const AUTH_RUNTIME_FIELDS = ["dependencies", "peerDependencies", "optionalDependencies"] as const
package/src/load.ts CHANGED
@@ -95,8 +95,8 @@ export interface NifraFramework {
95
95
  /** Client-visible environment prefix (default `"PUBLIC_"`; empty disables exposure). With both
96
96
  * configs, `nifra.config.ts` wins and `backend/framework.ts` fills it in when left unset. */
97
97
  readonly publicEnvPrefix?: string
98
- /** Reviewed false positives of `nifra build`'s secret scan, each `{ rule, file, reason }` (or
99
- * `{ rule: "private-env-value", env, reason }`). There is no exemption by value. */
98
+ /** Reviewed false positives of `nifra build`'s secret scan. A `file` scope applies throughout that
99
+ * file; for `private-env-value`, an `env` scope applies to every finding from that variable. */
100
100
  readonly secretExemptions?: readonly SecretExemption[]
101
101
  /** Vite production CSS output policy. `false` emits one aggregate stylesheet for the whole client. */
102
102
  readonly cssCodeSplit?: boolean
@@ -227,7 +227,10 @@ function assertFrameworkWebOptions(fw: Partial<NifraFramework>, configFile: stri
227
227
  wrong("publicEnvPrefix", 'a string such as "PUBLIC_", or "" to expose no environment variable')
228
228
  }
229
229
  if (fw.secretExemptions !== undefined && !Array.isArray(fw.secretExemptions)) {
230
- wrong("secretExemptions", "an array of { rule, file, reason } entries")
230
+ wrong(
231
+ "secretExemptions",
232
+ 'an array of { rule, file, reason } entries (or { rule: "private-env-value", env, reason })',
233
+ )
231
234
  }
232
235
  if (fw.target !== undefined && typeof fw.target !== "string") {
233
236
  wrong("target", 'a deploy target name such as "bun"')
@@ -90,18 +90,22 @@ export function isOtherInstall(dir: string): boolean {
90
90
  }
91
91
 
92
92
  /**
93
- * Hand this stdio session to the project's own CLI when it installs a different version, or the same
94
- * version from another directory. Resolves to the child's exit code once the session ends, or
95
- * `undefined` when this process should serve itself (this is the project's CLI, no project CLI or
96
- * bin, already a hand-off, or the spawn failed). Must run before anything reads stdin: the child
97
- * inherits the descriptor and owns the whole conversation.
93
+ * The command that runs the project's own CLI as `nifra mcp`, when the project installs a different
94
+ * version, or the same version from another directory. `undefined` when this process should serve
95
+ * itself: this is the project's CLI, no project CLI or bin, or this process is already a hand-off.
98
96
  */
99
- export async function delegateToProjectCli(options: {
100
- readonly cwd: string
97
+ export async function projectCliCommand(options: {
101
98
  readonly root: string
102
99
  readonly version: string
103
100
  readonly args: readonly string[]
104
- }): Promise<number | undefined> {
101
+ }): Promise<
102
+ | {
103
+ readonly cli: ProjectCli
104
+ readonly command: readonly string[]
105
+ readonly env: Record<string, string | undefined>
106
+ }
107
+ | undefined
108
+ > {
105
109
  if (process.env[MCP_DELEGATED_ENV] === "1") return undefined
106
110
  const cli = await findProjectCli(options.root)
107
111
  if (
@@ -112,10 +116,32 @@ export async function delegateToProjectCli(options: {
112
116
  return undefined
113
117
  // Not the `.bin` shim: its `bun` would load the project's `.env`, and the inherited
114
118
  // NIFRA_MCP_WITHOUT_ENV_FILES then tells that CLI the values are already gone.
115
- return handOffSession([process.execPath, "--no-env-file", cli.bin, "mcp", ...options.args], {
116
- cwd: options.cwd,
119
+ return {
120
+ cli,
121
+ command: [process.execPath, "--no-env-file", cli.bin, "mcp", ...options.args],
117
122
  env: { ...process.env, [MCP_DELEGATED_ENV]: "1" },
118
- announce: `[nifra] mcp: this CLI is ${options.version}; the project installs @nifrajs/cli ${cli.version} - serving this session from ${cli.bin}`,
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Hand this stdio session to the project's own CLI when it installs a different version, or the same
128
+ * version from another directory. Resolves to the child's exit code once the session ends, or
129
+ * `undefined` when this process should serve itself (see {@link projectCliCommand}, or the spawn
130
+ * failed). Must run before anything reads stdin: the child inherits the descriptor and owns the whole
131
+ * conversation.
132
+ */
133
+ export async function delegateToProjectCli(options: {
134
+ readonly cwd: string
135
+ readonly root: string
136
+ readonly version: string
137
+ readonly args: readonly string[]
138
+ }): Promise<number | undefined> {
139
+ const target = await projectCliCommand(options)
140
+ if (target === undefined) return undefined
141
+ return handOffSession(target.command, {
142
+ cwd: options.cwd,
143
+ env: target.env,
144
+ announce: `[nifra] mcp: this CLI is ${options.version}; the project installs @nifrajs/cli ${target.cli.version} - serving this session from ${target.cli.bin}`,
119
145
  })
120
146
  }
121
147
 
package/src/mcp-http.ts CHANGED
@@ -30,7 +30,7 @@ export { docsTools } from "./mcp-docs-tools.ts"
30
30
  export type { TypeEntry } from "./types-search.ts"
31
31
 
32
32
  // Kept in lockstep with packages/cli/package.json by check:publish's version-consistency gate.
33
- const VERSION = "5.10.0"
33
+ const VERSION = "5.11.0"
34
34
  const SERVER_INFO = { name: "nifra-docs", version: VERSION }
35
35
  // Derive the GET/health tool list from the tools actually served, so the line can never drift from them.
36
36
  const docsHealth = (tools: McpTool[]): string =>
@@ -0,0 +1,155 @@
1
+ /**
2
+ * `nifra mcp` after the project installed another CLI than the one serving the session. This process
3
+ * keeps the code it started with, so it would go on listing tools the new release removed and running
4
+ * them. It starts the project's CLI as a child instead, replays the handshake to it, and relays the
5
+ * rest of the conversation: the client's messages go in, and what the child sends comes back out. The
6
+ * start-of-session hand-off (`./mcp-delegate.ts`) is the same move made before stdin is read.
7
+ */
8
+
9
+ import type { StdioMessage } from "@nifrajs/mcp/stdio"
10
+ import {
11
+ isJsonRpcRequest,
12
+ isJsonRpcResponse,
13
+ type JsonRpcRequest,
14
+ type JsonRpcResponse,
15
+ rpcError,
16
+ } from "./mcp-protocol.ts"
17
+
18
+ type JsonRpcId = JsonRpcResponse["id"]
19
+
20
+ const HANDSHAKE_ID = "nifra-relay-handshake"
21
+ const HANDSHAKE_MS = 30_000
22
+ const CLOSE_MS = 5_000
23
+
24
+ const spawnChild = (
25
+ command: readonly string[],
26
+ cwd: string,
27
+ env: Record<string, string | undefined>,
28
+ ) => Bun.spawn([...command], { cwd, env, stdin: "pipe", stdout: "pipe", stderr: "inherit" })
29
+
30
+ export interface McpRelay {
31
+ /** Whether the child still runs. Once it ends the session is served locally again. */
32
+ readonly alive: boolean
33
+ /** Send a client message on. Resolves to the child's response, or `null` for a notification. */
34
+ request(message: JsonRpcRequest): Promise<JsonRpcResponse | null>
35
+ /** Pass the client's answer to a request the child made on. */
36
+ answer(message: JsonRpcResponse): void
37
+ /** End the child's input and wait for it. */
38
+ close(): Promise<void>
39
+ }
40
+
41
+ /**
42
+ * Start `command` as the session's server. Resolves to `undefined`, with the child gone, when it does
43
+ * not start or does not answer the replayed `initialize`; its response is not forwarded, since the
44
+ * client has had its own.
45
+ */
46
+ export async function startRelay(options: {
47
+ readonly command: readonly string[]
48
+ readonly cwd: string
49
+ readonly env: Record<string, string | undefined>
50
+ readonly initialize: JsonRpcRequest
51
+ /** Whether the client sent `notifications/initialized`. */
52
+ readonly initialized: boolean
53
+ /** Writes one message to the client. */
54
+ readonly send: (message: StdioMessage) => void
55
+ /** Written to stderr once the child answers. */
56
+ readonly announce: string
57
+ }): Promise<McpRelay | undefined> {
58
+ let child: ReturnType<typeof spawnChild>
59
+ try {
60
+ child = spawnChild(options.command, options.cwd, options.env)
61
+ } catch {
62
+ return undefined
63
+ }
64
+ let alive = true
65
+ const pending = new Map<JsonRpcId, (response: JsonRpcResponse | null) => void>()
66
+ const settle = (id: JsonRpcId, response: JsonRpcResponse | null): void => {
67
+ const resolve = pending.get(id)
68
+ pending.delete(id)
69
+ resolve?.(response)
70
+ }
71
+ const write = (message: object): boolean => {
72
+ try {
73
+ child.stdin.write(`${JSON.stringify(message)}\n`)
74
+ child.stdin.flush()
75
+ return true
76
+ } catch {
77
+ return false
78
+ }
79
+ }
80
+ const route = (line: string): void => {
81
+ let parsed: unknown
82
+ try {
83
+ parsed = JSON.parse(line)
84
+ } catch {
85
+ return
86
+ }
87
+ if (isJsonRpcResponse(parsed)) {
88
+ if (pending.has(parsed.id)) settle(parsed.id, parsed)
89
+ else options.send(parsed)
90
+ } else if (isJsonRpcRequest(parsed)) options.send(parsed)
91
+ }
92
+ const pumped = (async () => {
93
+ const decoder = new TextDecoder()
94
+ let buffered = ""
95
+ for await (const chunk of child.stdout) {
96
+ buffered += decoder.decode(chunk, { stream: true })
97
+ for (let at = buffered.indexOf("\n"); at !== -1; at = buffered.indexOf("\n")) {
98
+ const line = buffered.slice(0, at).trim()
99
+ buffered = buffered.slice(at + 1)
100
+ if (line !== "") route(line)
101
+ }
102
+ }
103
+ })().catch(() => {})
104
+ void child.exited.then(async () => {
105
+ await pumped
106
+ alive = false
107
+ for (const id of [...pending.keys()]) {
108
+ settle(id, rpcError(id, -32603, "the project's nifra CLI ended while it was answering"))
109
+ }
110
+ })
111
+
112
+ const handshake = new Promise<JsonRpcResponse | null>((resolve) => {
113
+ pending.set(HANDSHAKE_ID, resolve)
114
+ })
115
+ const timer = setTimeout(() => settle(HANDSHAKE_ID, null), HANDSHAKE_MS)
116
+ write({ ...options.initialize, id: HANDSHAKE_ID })
117
+ const answered = await handshake
118
+ clearTimeout(timer)
119
+ if (answered === null || "error" in answered) {
120
+ child.kill()
121
+ return undefined
122
+ }
123
+ if (options.initialized) write({ jsonrpc: "2.0", method: "notifications/initialized" })
124
+ process.stderr.write(`${options.announce}\n`)
125
+
126
+ return {
127
+ get alive() {
128
+ return alive
129
+ },
130
+ request(message) {
131
+ return new Promise((resolve) => {
132
+ if (message.id !== undefined) pending.set(message.id, resolve)
133
+ if (!write(message)) {
134
+ if (message.id === undefined) resolve(null)
135
+ else settle(message.id, rpcError(message.id, -32603, "the project's nifra CLI is gone"))
136
+ return
137
+ }
138
+ if (message.id === undefined) resolve(null)
139
+ })
140
+ },
141
+ answer(message) {
142
+ write(message)
143
+ },
144
+ async close() {
145
+ try {
146
+ child.stdin.end()
147
+ } catch {
148
+ // Already closed: the child is on its way out.
149
+ }
150
+ const killer = setTimeout(() => child.kill(), CLOSE_MS)
151
+ await child.exited
152
+ clearTimeout(killer)
153
+ },
154
+ }
155
+ }
package/src/mcp.ts CHANGED
@@ -56,7 +56,7 @@ import { loadDocsCorpus } from "./docs-search.ts"
56
56
  import { loadExamplesCorpus } from "./examples.ts"
57
57
  import type { AppLoader } from "./load.ts"
58
58
  import { loadMonorepoApps } from "./load.ts"
59
- import { delegateToProjectCli, refuseVersionSensitive } from "./mcp-delegate.ts"
59
+ import { delegateToProjectCli, projectCliCommand, refuseVersionSensitive } from "./mcp-delegate.ts"
60
60
  import { docsTools } from "./mcp-docs-tools.ts"
61
61
  import {
62
62
  createMcpProtocolState,
@@ -69,6 +69,7 @@ import {
69
69
  type McpTool,
70
70
  rpcError,
71
71
  } from "./mcp-protocol.ts"
72
+ import { type McpRelay, startRelay } from "./mcp-relay.ts"
72
73
  import { loadTypesCorpus } from "./types-search.ts"
73
74
 
74
75
  export {
@@ -267,6 +268,38 @@ export async function runMcpServer(
267
268
  const state = createMcpProtocolState()
268
269
  let rootsSupported = false
269
270
  let rootsRequestPending = false
271
+ // The project's own CLI, serving the session once the project installs one that is not this one.
272
+ let relay: McpRelay | undefined
273
+ let takingOver: Promise<McpRelay | undefined> | undefined
274
+ let relayFailed: string | undefined
275
+ let initializeRequest: JsonRpcRequest | undefined
276
+ let initializedSent = false
277
+ const takeOver = async (connection: StdioConnection): Promise<McpRelay | undefined> => {
278
+ // The child asks for roots with the id this process uses, so an answer in flight is not ambiguous.
279
+ if (!rootState.isProject || initializeRequest === undefined || rootsRequestPending)
280
+ return undefined
281
+ const target = await projectCliCommand({
282
+ root: rootState.root,
283
+ version,
284
+ args: explicitDir === undefined ? [] : [requested],
285
+ })
286
+ if (target === undefined) return undefined
287
+ const key = `${target.cli.bin}@${target.cli.version}`
288
+ if (relayFailed === key) return undefined
289
+ const started = await startRelay({
290
+ command: target.command,
291
+ cwd,
292
+ env: target.env,
293
+ initialize: initializeRequest,
294
+ initialized: initializedSent,
295
+ send: connection.send,
296
+ announce: `[nifra] mcp: this server is ${version}; the project now installs @nifrajs/cli ${target.cli.version} - serving the rest of this session from ${target.cli.bin}`,
297
+ })
298
+ if (started === undefined) relayFailed = key
299
+ // A client that listed the old tools lists them again.
300
+ else connection.send({ jsonrpc: "2.0", method: "notifications/tools/list_changed" })
301
+ return started
302
+ }
270
303
  const requestRoots = (connection: StdioConnection): void => {
271
304
  if (!rootsSupported || rootsRequestPending) return
272
305
  rootsRequestPending = true
@@ -293,6 +326,10 @@ export async function runMcpServer(
293
326
  const dispatchRootsAnswer = (message: JsonRpcResponse): boolean => {
294
327
  // The roots answer is a response to a request initiated by this server, not a client RPC request.
295
328
  // Serialize adoption with normal dispatch so a following request cannot observe a half-updated root.
329
+ if (relay?.alive === true) {
330
+ relay.answer(message)
331
+ return true
332
+ }
296
333
  if (message.id !== ROOTS_REQUEST_ID) return false
297
334
  if (!rootsRequestPending) return true
298
335
  rootsRequestPending = false
@@ -307,7 +344,19 @@ export async function runMcpServer(
307
344
  await rootsUpdate
308
345
  if (message.method === "initialize") {
309
346
  rootsSupported = clientSupportsRoots(message.params)
347
+ initializeRequest = message
348
+ }
349
+ if (message.method === "notifications/initialized") initializedSent = true
350
+ // An install during the session leaves this process listing and running the tools it started with.
351
+ if (
352
+ relay === undefined &&
353
+ (message.method === "tools/list" || message.method === "tools/call")
354
+ ) {
355
+ takingOver ??= takeOver(connection)
356
+ relay = await takingOver
357
+ takingOver = undefined
310
358
  }
359
+ if (relay?.alive === true) return relay.request(message)
311
360
  // An install during the session changes the nifra the project builds with, and this process keeps
312
361
  // the code it started with: re-read the installed version per call so no answer is for a stale one.
313
362
  if (message.method === "tools/call") drift = await detectToolingDrift(rootState.root, version)
@@ -392,6 +441,7 @@ export async function runMcpServer(
392
441
  onResponse: dispatchRootsAnswer,
393
442
  })
394
443
  } finally {
444
+ await relay?.close()
395
445
  closeWarmWorkers()
396
446
  }
397
447
  }
@@ -170,6 +170,22 @@ export interface LayoutMigrationOptions {
170
170
  readonly typescript?: typeof TS
171
171
  }
172
172
 
173
+ type LayoutMigrationReport = Omit<LayoutMigrationResult, "write">
174
+
175
+ /**
176
+ * The complete set of changes discovered by the layout migration. Planning keeps reading the
177
+ * project directly for now; applying the plan is the only mutating step in the migration command.
178
+ */
179
+ interface LayoutMigrationPlan {
180
+ readonly root: string
181
+ readonly original: ReadonlyMap<string, string>
182
+ readonly final: ReadonlyMap<string, string>
183
+ readonly toolingWrites: ReadonlyMap<string, string>
184
+ readonly scriptWrites: ReadonlyMap<string, string>
185
+ readonly moves: readonly { readonly from: string; readonly to: string }[]
186
+ readonly report: LayoutMigrationReport
187
+ }
188
+
173
189
  /** A file's text, as the migration sees it before writing. */
174
190
  type Files = Map<string, string>
175
191
 
@@ -2244,10 +2260,10 @@ function nestedAppHint(root: string): string {
2244
2260
  return `. ${found.map((name) => `${name}/routes/`).join(", ")} exists: run \`nifra migrate layout --dir ${first}\` to migrate the app there`
2245
2261
  }
2246
2262
 
2247
- export async function migrateLayout(
2263
+ async function planLayoutMigration(
2248
2264
  appRoot: string,
2249
2265
  options: LayoutMigrationOptions = {},
2250
- ): Promise<LayoutMigrationResult> {
2266
+ ): Promise<LayoutMigrationPlan> {
2251
2267
  const ts = options.typescript ?? (await importTypeScript())
2252
2268
  if (ts === undefined)
2253
2269
  throw new Error("[nifra] `nifra migrate layout` needs TypeScript: bun add -d typescript")
@@ -3185,44 +3201,60 @@ export async function migrateLayout(
3185
3201
  })
3186
3202
  }
3187
3203
 
3188
- if (options.write === true) {
3189
- for (const [file, text] of toolingWrites) writeFileSync(join(root, file), text)
3190
- for (const [file, text] of final) {
3191
- if (original.get(file) === text) continue
3192
- const path = join(root, file)
3193
- mkdirSync(dirname(path), { recursive: true })
3194
- writeFileSync(path, text)
3195
- }
3196
- const vacated: string[] = []
3197
- for (const file of original.keys()) {
3198
- if (final.has(file)) continue
3199
- rmSync(join(root, file), { force: true })
3200
- vacated.push(file)
3201
- }
3202
- for (const { from, to } of moves) {
3203
- if (original.has(from) || !existsSync(join(root, from))) continue
3204
- mkdirSync(dirname(join(root, to)), { recursive: true })
3205
- renameSync(join(root, from), join(root, to))
3206
- vacated.push(from)
3207
- }
3208
- for (const [file, text] of scriptWrites) writeFileSync(join(root, file), text)
3209
- pruneVacatedDirs(root, vacated)
3210
- }
3211
- return {
3204
+ const report: LayoutMigrationReport = {
3212
3205
  ok: issues.length === 0,
3213
- write: options.write === true,
3214
3206
  mode,
3215
3207
  followUps,
3216
3208
  splits: splits.sort((a, b) => codeUnitOrder(a.file, b.file)),
3217
3209
  moves,
3218
3210
  rewritten: rewritten.sort(),
3219
3211
  tooling,
3220
- schemas: schemas.map((entry) =>
3212
+ schemas,
3213
+ issues,
3214
+ }
3215
+ return { root, original, final, toolingWrites, scriptWrites, moves, report }
3216
+ }
3217
+
3218
+ /** Apply a planned migration in the same order the command historically used. */
3219
+ function applyLayoutMigration(plan: LayoutMigrationPlan): void {
3220
+ const { root, original, final, toolingWrites, scriptWrites, moves } = plan
3221
+ for (const [file, text] of toolingWrites) writeFileSync(join(root, file), text)
3222
+ for (const [file, text] of final) {
3223
+ if (original.get(file) === text) continue
3224
+ const path = join(root, file)
3225
+ mkdirSync(dirname(path), { recursive: true })
3226
+ writeFileSync(path, text)
3227
+ }
3228
+ const vacated: string[] = []
3229
+ for (const file of original.keys()) {
3230
+ if (final.has(file)) continue
3231
+ rmSync(join(root, file), { force: true })
3232
+ vacated.push(file)
3233
+ }
3234
+ for (const { from, to } of moves) {
3235
+ if (original.has(from) || !existsSync(join(root, from))) continue
3236
+ mkdirSync(dirname(join(root, to)), { recursive: true })
3237
+ renameSync(join(root, from), join(root, to))
3238
+ vacated.push(from)
3239
+ }
3240
+ for (const [file, text] of scriptWrites) writeFileSync(join(root, file), text)
3241
+ pruneVacatedDirs(root, vacated)
3242
+ }
3243
+
3244
+ export async function migrateLayout(
3245
+ appRoot: string,
3246
+ options: LayoutMigrationOptions = {},
3247
+ ): Promise<LayoutMigrationResult> {
3248
+ const plan = await planLayoutMigration(appRoot, options)
3249
+ if (options.write === true) applyLayoutMigration(plan)
3250
+ return {
3251
+ ...plan.report,
3252
+ write: options.write === true,
3253
+ schemas: plan.report.schemas.map((entry) =>
3221
3254
  options.write === true && entry.reason === undefined
3222
3255
  ? { ...entry, status: "generated" }
3223
3256
  : entry,
3224
3257
  ),
3225
- issues,
3226
3258
  }
3227
3259
  }
3228
3260
 
@@ -4,8 +4,9 @@ import type { UpgradeRecipe } from "./index.ts"
4
4
  * Upgrade recipe for Nifra 5.10.
5
5
  *
6
6
  * No import or dependency moves. Partial prerendering is stable, so `createWebApp` takes it as `ppr`
7
- * and the `ppr-option` source rewrite moves `experimental: { ppr }`. In-app links are typed: `navigate`,
8
- * `redirect` and React's `Link` take an `Href`, and the route table that types it replaces
7
+ * and the `ppr-option` source rewrite moves `experimental: { ppr }`. In-app links are typed:
8
+ * `navigate`, `redirect` and React's `Link` take an `Href`, the `href-navigation` source rewrite wraps
9
+ * the string paths they were given in `rawHref`, and the route table that types `href` replaces
9
10
  * `RouteSearch`. The query cache sends nothing to the browser unless the app names the queries, and
10
11
  * an identity change cancels a mutation still running; the notes say what an app sees differently.
11
12
  */
@@ -17,7 +18,7 @@ export const recipe: UpgradeRecipe = {
17
18
  { match: "nifra", to: "5.10.0" },
18
19
  ],
19
20
  importMoves: [],
20
- sourceRewrites: ["ppr-option"],
21
+ sourceRewrites: ["ppr-option", "href-navigation"],
21
22
  affects: [
22
23
  "@nifrajs/core",
23
24
  "@nifrajs/client",
@@ -33,7 +34,7 @@ export const recipe: UpgradeRecipe = {
33
34
  ],
34
35
  notes: [
35
36
  "Partial prerendering is stable: `createWebApp({ ppr: partialPrerendering(...) })` replaces `experimental: { ppr: partialPrerendering(...) }`, and the `experimental` option is removed. Passing it throws a `TypeError` that names `ppr`. The startup errors name `ppr.origin`, `ppr.deployment`, `ppr.store` and `ppr.storeSecret`. The `ppr-option` rewrite moves `experimental: { ppr }` in a `createWebApp` options literal; options with a spread, a second key under `experimental`, or an `experimental` built in another file are listed by line or left for you to check.",
36
- '`navigate()`, `redirect()` and the React `Link`, `NavLink` and `Navigate` take an `Href`, built by `href({ to, params, search, hash })` from `@nifrajs/web` (or an adapter\'s `/router` entry), or by `rawHref(path)` for a same-origin path built elsewhere. A string path, a template literal and the `{ to, search }` form of `navigate` are compile errors, so `tsc` lists each call: `navigate("/users/7")` becomes `navigate(href({ to: "/users/:id", params: { id: "7" } }))`, `redirect("/login")` becomes `redirect(href({ to: "/login" }))`, `<Link to="/pricing">` becomes `<Link to={href({ to: "/pricing" })}>`, and `navigate({ to, search, replace: true })` becomes `navigate(href({ to, search }), { replace: true })`. `redirect(url, { external: true })` is unchanged. `resolveNavigate`, `NavigateTargetInput` and `NavigateSearchOf` are removed from `@nifrajs/web`. `Link` and `NavLink` render the anchor without an `href`, and log a `console.error`, when `to` is not a same-origin path; `rawHref` throws a `TypeError` for one. `tsc` cannot see plain anchors, so search for `href="/` and ``href={`/``.',
37
+ '`navigate()`, `redirect()` and the React `Link`, `NavLink` and `Navigate` take an `Href`, built by `href({ to, params, search, hash })` from `@nifrajs/web` (or an adapter\'s `/router` entry), or by `rawHref(path)` for a same-origin path built elsewhere. A string path, a template literal and the `{ to, search }` form of `navigate` are compile errors, so `tsc` lists each call: `navigate("/users/7")` becomes `navigate(href({ to: "/users/:id", params: { id: "7" } }))`, `redirect("/login")` becomes `redirect(href({ to: "/login" }))`, `<Link to="/pricing">` becomes `<Link to={href({ to: "/pricing" })}>`, and `navigate({ to, search, replace: true })` becomes `navigate(href({ to, search }), { replace: true })`. `redirect(url, { external: true })` is unchanged. `resolveNavigate`, `NavigateTargetInput` and `NavigateSearchOf` are removed from `@nifrajs/web`. `Link` and `NavLink` render the anchor without an `href`, and log a `console.error`, when `to` is not a same-origin path; `rawHref` throws a `TypeError` for one. `tsc` cannot see plain anchors, so search for `href="/` and ``href={`/``. The `href-navigation` rewrite wraps a string path written whole at one of these calls (and the `to` of a `Link`, `NavLink` or `Navigate`) in `rawHref(path)`, which sends the same request; a template literal, a concatenation, a `navigate({ to })` object and a path `rawHref` refuses are listed by line, and `.vue` and `.svelte` templates are left for `tsc`. Replace a `rawHref` of one of the app\'s own pages with `href()` to have a dead link fail to compile.',
37
38
  '`nifra dev`, `nifra build`, `nifra check` and `nifra types` write `.nifra/types/routes.d.ts`, which fills `RouteTable` with one `{ params, search }` entry per URL pattern, and `href()` reads it. A route file that imports no `./+types/...` module does not load it: `nifra check` warns when a source imports a navigation API and no program loads the table, and listing `.nifra/types/routes.d.ts` under `files` in tsconfig.json clears it. `RouteSearch`, `generateRouteSearchTypes`, `GenerateRouteSearchTypesOptions`, `nifra sync-routes` and the `nifra_sync_routes` MCP tool are removed: delete `nifra-routes.d.ts` and its tsconfig `include` entry, and move a hand-written `RouteSearch` entry to `RouteTable` as `"/path": { params: ...; search: ... }`. A route file whose name holds `#` or `?` is an error that names the file.',
38
39
  "`dehydrate()` on a query client sends nothing unless `shouldDehydrateQuery` selects the queries, where a bare call sent every successful query, regular and infinite. Every dehydrated value is serialized into the page and readable by the visitor. Pass `shouldDehydrateQuery` naming the keys that are safe to send, or `() => true` when every successful query in that client is meant for the browser. Without it the browser starts with no cache for those queries and fetches them itself, so a component that rendered their data on the server can differ from it on the first client render.",
39
40
  "A mutation still running when the visitor's identity changes, in this tab or another tab of the site, is cancelled: its `mutate` promise rejects with `MutationCancelledError`, and its `onSuccess`, `onError` and `onSettled` callbacks do not run. The mutation function takes a second argument, `{ signal }`, an `AbortSignal` that is aborted at that moment; pass it to `fetch` to stop the request. A call site that awaits `mutateAsync` across a sign-in or sign-out catches that error.",
@@ -0,0 +1,51 @@
1
+ import type { UpgradeRecipe } from "./index.ts"
2
+
3
+ /**
4
+ * Upgrade recipe for Nifra 5.11.
5
+ *
6
+ * This release has no import or dependency moves. Its notes cover the CLI session and upgrade
7
+ * changes, the new route-slot and cache behavior, and the tightened security boundaries in the
8
+ * fixed package groups.
9
+ */
10
+ export const recipe: UpgradeRecipe = {
11
+ version: "5.11.0",
12
+ pins: [
13
+ { match: "@nifrajs/", to: "5.11.0" },
14
+ { match: "create-nifra", to: "5.11.0" },
15
+ { match: "nifra", to: "5.11.0" },
16
+ ],
17
+ importMoves: [],
18
+ affects: [
19
+ "@nifrajs/a2a",
20
+ "@nifrajs/agent",
21
+ "@nifrajs/auth",
22
+ "@nifrajs/authjs",
23
+ "@nifrajs/better-auth",
24
+ "@nifrajs/cli",
25
+ "@nifrajs/core",
26
+ "@nifrajs/middleware",
27
+ "@nifrajs/uploads",
28
+ "@nifrajs/web",
29
+ "@nifrajs/web-preact",
30
+ "@nifrajs/web-react",
31
+ "@nifrajs/web-solid",
32
+ "@nifrajs/web-svelte",
33
+ "@nifrajs/web-vue",
34
+ "create-nifra",
35
+ "nifra",
36
+ ],
37
+ notes: [
38
+ "During an MCP session, `nifra mcp` now takes over when the project installs a different `@nifrajs/cli`, replays the handshake, and sends `notifications/tools/list_changed`; a CLI that does not answer stays on the current session.",
39
+ "`nifra upgrade --from <version>` names the starting release when package pins were bumped by hand. Unknown options and extra arguments are refused, and the `servePublicDir` rewrite preserves the file's quote style.",
40
+ "`nifra doctor` reports a renamed session cookie only when the wrapper gives `sessionToken.name` a string, so a type-only wrapper no longer asks for `identityCookies`.",
41
+ "Route slots can be addressed independently with typed targets and server allowlists, with bindings for the supported web adapters. Existing routes keep their behavior unless they opt into a slot.",
42
+ "`withIdleTimeout(c, seconds, work)` accepts any route context, including contexts with body, query, or header schemas.",
43
+ "Auth guard denials share the `@nifrajs/core/guard-deny` owner and fail loudly when a denial both redirects and answers or uses a status outside 400-599; the auth packages keep their existing prefixes and options.",
44
+ "React server-component owner refreshes can progressively commit ready Suspense content through a bounded Flight stream. Request-dependent owner routes fail closed for shared storage, and `revalidateEndpoint({ app, store, secret })` purges an owner route by path.",
45
+ "Rate-limit headers must contain one valid IP address; valid values are canonicalized, and invalid values use the configured trusted fallback or fail closed.",
46
+ "A2A JSON/SSE output and agent SSE frames are bounded before serialization, so oversized output is rejected before it is constructed.",
47
+ "Uploads reject oversized image dimensions before metadata stripping decodes the source, with a stable `ImagePixelLimitError`.",
48
+ "Nonce-bearing hash-CSP owner documents stay out of shared caches, and non-200 refusals no longer memoize an owner URL as uncacheable.",
49
+ "The href-navigation upgrade rewrite wraps whole string destinations in `rawHref(path)` while leaving dynamic expressions and templates for manual or type-check guidance; use the typed `href()` helper for an app-owned page when possible.",
50
+ ],
51
+ }