@j0hanz/filesystem-mcp 2.1.8 → 2.2.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 (90) hide show
  1. package/README.md +1 -2
  2. package/dist/core/cursor.d.ts +11 -0
  3. package/dist/core/cursor.d.ts.map +1 -1
  4. package/dist/core/cursor.js +10 -0
  5. package/dist/core/cursor.js.map +1 -1
  6. package/dist/core/glob.d.ts +4 -13
  7. package/dist/core/glob.d.ts.map +1 -1
  8. package/dist/core/glob.js +11 -6
  9. package/dist/core/glob.js.map +1 -1
  10. package/dist/core/input-required.d.ts +8 -0
  11. package/dist/core/input-required.d.ts.map +1 -1
  12. package/dist/core/input-required.js +10 -0
  13. package/dist/core/input-required.js.map +1 -1
  14. package/dist/core/observability.d.ts.map +1 -1
  15. package/dist/core/observability.js +2 -1
  16. package/dist/core/observability.js.map +1 -1
  17. package/dist/core/primitives.d.ts +7 -0
  18. package/dist/core/primitives.d.ts.map +1 -1
  19. package/dist/core/primitives.js +15 -8
  20. package/dist/core/primitives.js.map +1 -1
  21. package/dist/core/search.d.ts +3 -4
  22. package/dist/core/search.d.ts.map +1 -1
  23. package/dist/core/search.js +5 -5
  24. package/dist/core/search.js.map +1 -1
  25. package/dist/core/util.d.ts.map +1 -1
  26. package/dist/core/util.js +2 -11
  27. package/dist/core/util.js.map +1 -1
  28. package/dist/instructions.js +11 -11
  29. package/dist/instructions.js.map +1 -1
  30. package/dist/server.d.ts +1 -9
  31. package/dist/server.d.ts.map +1 -1
  32. package/dist/server.js +15 -25
  33. package/dist/server.js.map +1 -1
  34. package/dist/tools/define.d.ts.map +1 -1
  35. package/dist/tools/define.js +4 -4
  36. package/dist/tools/define.js.map +1 -1
  37. package/dist/tools/delete.d.ts +2 -0
  38. package/dist/tools/delete.d.ts.map +1 -0
  39. package/dist/tools/{delete-file.js → delete.js} +5 -5
  40. package/dist/tools/delete.js.map +1 -0
  41. package/dist/tools/find-files.d.ts +2 -0
  42. package/dist/tools/find-files.d.ts.map +1 -0
  43. package/dist/tools/{search-files.js → find-files.js} +14 -19
  44. package/dist/tools/find-files.js.map +1 -0
  45. package/dist/tools/index.d.ts +6 -6
  46. package/dist/tools/index.d.ts.map +1 -1
  47. package/dist/tools/index.js +15 -15
  48. package/dist/tools/index.js.map +1 -1
  49. package/dist/tools/list-roots.d.ts +2 -0
  50. package/dist/tools/list-roots.d.ts.map +1 -0
  51. package/dist/tools/{roots.js → list-roots.js} +2 -2
  52. package/dist/tools/list-roots.js.map +1 -0
  53. package/dist/tools/list.d.ts.map +1 -1
  54. package/dist/tools/list.js +28 -32
  55. package/dist/tools/list.js.map +1 -1
  56. package/dist/tools/move.d.ts.map +1 -1
  57. package/dist/tools/move.js +3 -3
  58. package/dist/tools/move.js.map +1 -1
  59. package/dist/tools/read.d.ts +1 -1
  60. package/dist/tools/read.d.ts.map +1 -1
  61. package/dist/tools/read.js +1 -1
  62. package/dist/tools/read.js.map +1 -1
  63. package/dist/tools/replace-text.d.ts +2 -0
  64. package/dist/tools/replace-text.d.ts.map +1 -0
  65. package/dist/tools/{replace-in-files.js → replace-text.js} +5 -5
  66. package/dist/tools/replace-text.js.map +1 -0
  67. package/dist/tools/search-text.d.ts +2 -0
  68. package/dist/tools/search-text.d.ts.map +1 -0
  69. package/dist/tools/{search-content.js → search-text.js} +7 -12
  70. package/dist/tools/search-text.js.map +1 -0
  71. package/dist/tools/stat.d.ts +1 -1
  72. package/dist/tools/stat.d.ts.map +1 -1
  73. package/dist/tools/stat.js +1 -1
  74. package/dist/tools/stat.js.map +1 -1
  75. package/package.json +1 -1
  76. package/dist/tools/delete-file.d.ts +0 -2
  77. package/dist/tools/delete-file.d.ts.map +0 -1
  78. package/dist/tools/delete-file.js.map +0 -1
  79. package/dist/tools/replace-in-files.d.ts +0 -2
  80. package/dist/tools/replace-in-files.d.ts.map +0 -1
  81. package/dist/tools/replace-in-files.js.map +0 -1
  82. package/dist/tools/roots.d.ts +0 -2
  83. package/dist/tools/roots.d.ts.map +0 -1
  84. package/dist/tools/roots.js.map +0 -1
  85. package/dist/tools/search-content.d.ts +0 -2
  86. package/dist/tools/search-content.d.ts.map +0 -1
  87. package/dist/tools/search-content.js.map +0 -1
  88. package/dist/tools/search-files.d.ts +0 -2
  89. package/dist/tools/search-files.d.ts.map +0 -1
  90. package/dist/tools/search-files.js.map +0 -1
package/README.md CHANGED
@@ -259,7 +259,6 @@ All tools are scoped to the configured roots. Call `list_roots` first to discove
259
259
  ```text
260
260
  filesystem-mcp/
261
261
  ├── __tests__/ Test suites
262
- ├── scripts/ Build and task utilities
263
262
  ├── src/
264
263
  │ ├── core/ Path guarding, filesystem abstraction, concurrency, observability
265
264
  │ ├── tools/ Tool definitions and registration
@@ -280,7 +279,7 @@ the narrow dependency contract it consumes.
280
279
  | `src/core/path.ts` | `PathGuard` — validates every path against allowed roots |
281
280
  | `src/core/fs.ts` | `GuardedFileSystem` — guarded filesystem facade |
282
281
  | `src/tools/define.ts` | Tool registration and execution framework |
283
- | `src/tools/batch.ts` | Batch helpers (runOverPaths, normalizeBatchItems) |
282
+ | `src/tools/batch.ts` | Batch helpers (runOverPaths, isTotalFailure) |
284
283
  | `src/server.ts` | Builds shared dependencies and invokes the three registrars |
285
284
  | `src/transport.ts` | Owns stdio and Streamable HTTP setup around the server factory |
286
285
 
@@ -24,6 +24,17 @@ export interface PaginatedPage<T, M, R> extends Page<T, M> {
24
24
  /** The externalized full set. First page only, and only when incomplete. */
25
25
  readonly resource?: R;
26
26
  }
27
+ /**
28
+ * The single home of the pagination cache-key rule: `JSON.stringify` of a
29
+ * flat object whose `method` names the tool and whose remaining fields
30
+ * identify the query. The literal's field order fixes key stability;
31
+ * `method` keeps tool key spaces disjoint. Byte-identical to the three
32
+ * hand-written tool builders it replaces.
33
+ */
34
+ export declare function pageQueryKey(query: {
35
+ readonly method: string;
36
+ readonly path: string;
37
+ } & Record<string, unknown>): string;
27
38
  /**
28
39
  * The one replay-or-produce branch every paged tool runs. A cursor replays a
29
40
  * stored snapshot; without one, `produce` runs the query and its result is
@@ -1 +1 @@
1
- {"version":3,"file":"cursor.d.ts","sourceRoot":"","sources":["../../src/core/cursor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAgB,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAgCvE;;;;GAIG;AACH,MAAM,WAAW,YAAY,CAAC,CAAC,EAAE,CAAC;IAChC,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC,EAAE,CAAC;IAC7B,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAC;IACrB,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;CAC7B;AAED,UAAU,IAAI,CAAC,CAAC,EAAE,CAAC;IACjB,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC,EAAE,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAC;IACrB,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,SAAS,CAAC;IACxC;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,WAAW,aAAa,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAE,SAAQ,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC;IACxD,4EAA4E;IAC5E,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;CACvB;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE;IAC9C,KAAK,EAAE,iBAAiB,CAAC;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,OAAO,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAC3C,WAAW,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,SAAS,CAAC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C,EAAE,MAAM,EAAE;IAC9C,KAAK,EAAE,iBAAiB,CAAC;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,OAAO,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAC3C,WAAW,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,SAAS,CAAC,EAAE,EAAE,QAAQ,EAAE,CAAC,KAAK,CAAC,CAAC,GAAG,SAAS,CAAC;CACrE,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAwBlC"}
@@ -17,6 +17,16 @@ function pageResult(snapshotId, offset, pageSize, snapshot) {
17
17
  : undefined,
18
18
  };
19
19
  }
20
+ /**
21
+ * The single home of the pagination cache-key rule: `JSON.stringify` of a
22
+ * flat object whose `method` names the tool and whose remaining fields
23
+ * identify the query. The literal's field order fixes key stability;
24
+ * `method` keeps tool key spaces disjoint. Byte-identical to the three
25
+ * hand-written tool builders it replaces.
26
+ */
27
+ export function pageQueryKey(query) {
28
+ return JSON.stringify(query);
29
+ }
20
30
  /**
21
31
  * The one replay-or-produce branch every paged tool runs. A cursor replays a
22
32
  * stored snapshot; without one, `produce` runs the query and its result is
@@ -1 +1 @@
1
- {"version":3,"file":"cursor.js","sourceRoot":"","sources":["../../src/core/cursor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAOhD,SAAS,gBAAgB,CAAC,MAAkB;IAC1C,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AACnE,CAAC;AAED,SAAS,UAAU,CACjB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,qBAAqB,CAAC,CAAC;IACzC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,OAAO;YAAE,MAAM,KAAK,CAAC;QAC1C,MAAM,IAAI,OAAO,CACf,SAAS,CAAC,aAAa,EACvB,aAAa,EAAE,CAAC,OAAO,EACvB,SAAS,EACT,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAC3C,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { ErrorCode, FsError } from './errors.js';\nimport type { PageSnapshot, PageSnapshotStore } from './page-store.js';\nimport { invalidCursor } from './page-store.js';\n\ninterface PageCursor {\n readonly snapshotId: string;\n readonly offset: number;\n}\n\nfunction encodePageCursor(cursor: PageCursor): string {\n return Buffer.from(JSON.stringify(cursor)).toString('base64url');\n}\n\nfunction pageResult<T, M>(\n snapshotId: string,\n offset: number,\n pageSize: number,\n snapshot: PageSnapshot<T, M>,\n): Page<T, M> {\n if (offset >= snapshot.items.length) throw invalidCursor();\n const page = snapshot.items.slice(offset, offset + pageSize);\n const nextOffset = offset + page.length;\n return {\n page,\n metadata: snapshot.metadata,\n offset,\n nextCursor:\n nextOffset < snapshot.items.length\n ? encodePageCursor({ snapshotId, offset: nextOffset })\n : undefined,\n };\n}\n\n/**\n * The full result set a paged tool produced, before slicing. `truncated` is the\n * engine's own stop state — the hard result cap or a timeout cut the set — and\n * says nothing about page size.\n */\nexport interface ProducedPage<T, M> {\n readonly items: readonly T[];\n readonly metadata: M;\n readonly truncated: boolean;\n}\n\ninterface Page<T, M> {\n readonly page: readonly T[];\n readonly metadata: M;\n readonly nextCursor: string | undefined;\n /**\n * Index of this page's first item in the full set. A tool that reports\n * progress in its text needs it: without it every page can only say how many\n * rows it holds, which is the same number on page 1 and page 9.\n */\n readonly offset: number;\n}\n\nexport interface PaginatedPage<T, M, R> extends Page<T, M> {\n /** The externalized full set. First page only, and only when incomplete. */\n readonly resource?: R;\n}\n\n/**\n * The one replay-or-produce branch every paged tool runs. A cursor replays a\n * stored snapshot; without one, `produce` runs the query and its result is\n * snapshotted for later pages.\n *\n * The response is incomplete when the set spans more than one page or the\n * engine truncated it. Then — and only on the first page — `externalize`\n * stores the full set and its handle rides back as `resource`. Replayed pages\n * never carry it: the stored entry expires on the resource store's own TTL and\n * LRU, not this snapshot's, so replaying its URI would hand back a dead\n * pointer. Nor do they mint a new one; the set was already stored whole.\n */\nexport async function paginate<T, M, R>(params: {\n store: PageSnapshotStore;\n queryKey: string;\n cursor: string | undefined;\n pageSize: number;\n produce: () => Promise<ProducedPage<T, M>>;\n externalize?: ((items: readonly T[], metadata: M) => R) | undefined;\n}): Promise<PaginatedPage<T, M, R>> {\n if (params.cursor !== undefined) {\n const decoded = decodePageCursor(params.cursor);\n const snapshot = params.store.read<T, M>(decoded.snapshotId, params.queryKey);\n return pageResult(decoded.snapshotId, decoded.offset, params.pageSize, snapshot);\n }\n const produced = await params.produce();\n const { items, metadata } = produced;\n const incomplete = items.length > params.pageSize || produced.truncated;\n const first: Page<T, M> =\n items.length <= params.pageSize\n ? { page: items, metadata, nextCursor: undefined, offset: 0 }\n : pageResult(\n params.store.create({\n queryKey: params.queryKey,\n items,\n metadata,\n }),\n 0,\n params.pageSize,\n { items, metadata },\n );\n if (!incomplete || params.externalize === undefined) return first;\n return { ...first, resource: params.externalize(produced.items, produced.metadata) };\n}\n\nfunction decodePageCursor(cursor: string): PageCursor {\n try {\n const text = Buffer.from(cursor, 'base64url').toString('utf-8');\n const parsed = JSON.parse(text) as { snapshotId?: unknown; offset?: unknown };\n if (\n typeof parsed.snapshotId === 'string' &&\n parsed.snapshotId.length > 0 &&\n typeof parsed.offset === 'number' &&\n Number.isInteger(parsed.offset) &&\n parsed.offset >= 0\n ) {\n return { snapshotId: parsed.snapshotId, offset: parsed.offset };\n }\n throw new Error('Invalid page cursor');\n } catch (error) {\n if (error instanceof FsError) throw error;\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n invalidCursor().message,\n undefined,\n error instanceof Error ? error : undefined,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"cursor.js","sourceRoot":"","sources":["../../src/core/cursor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAOhD,SAAS,gBAAgB,CAAC,MAAkB;IAC1C,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AACnE,CAAC;AAED,SAAS,UAAU,CACjB,UAAkB,EAClB,MAAc,EACd,QAAgB,EAChB,QAA4B;IAE5B,IAAI,MAAM,IAAI,QAAQ,CAAC,KAAK,CAAC,MAAM;QAAE,MAAM,aAAa,EAAE,CAAC;IAC3D,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,QAAQ,CAAC,CAAC;IAC7D,MAAM,UAAU,GAAG,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;IACxC,OAAO;QACL,IAAI;QACJ,QAAQ,EAAE,QAAQ,CAAC,QAAQ;QAC3B,MAAM;QACN,UAAU,EACR,UAAU,GAAG,QAAQ,CAAC,KAAK,CAAC,MAAM;YAChC,CAAC,CAAC,gBAAgB,CAAC,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC;YACtD,CAAC,CAAC,SAAS;KAChB,CAAC;AACJ,CAAC;AA8BD;;;;;;GAMG;AACH,MAAM,UAAU,YAAY,CAC1B,KAAmF;IAEnF,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAU,MAOvC;IACC,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,EAAE,CA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IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;QAChE,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAA+C,CAAC;QAC9E,IACE,OAAO,MAAM,CAAC,UAAU,KAAK,QAAQ;YACrC,MAAM,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC;YAC5B,OAAO,MAAM,CAAC,MAAM,KAAK,QAAQ;YACjC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC;YAC/B,MAAM,CAAC,MAAM,IAAI,CAAC,EAClB,CAAC;YACD,OAAO,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC;QAClE,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;IACzC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,OAAO;YAAE,MAAM,KAAK,CAAC;QAC1C,MAAM,IAAI,OAAO,CACf,SAAS,CAAC,aAAa,EACvB,aAAa,EAAE,CAAC,OAAO,EACvB,SAAS,EACT,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAC3C,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { ErrorCode, FsError } from './errors.js';\nimport type { PageSnapshot, PageSnapshotStore } from './page-store.js';\nimport { invalidCursor } from './page-store.js';\n\ninterface PageCursor {\n readonly snapshotId: string;\n readonly offset: number;\n}\n\nfunction encodePageCursor(cursor: PageCursor): string {\n return Buffer.from(JSON.stringify(cursor)).toString('base64url');\n}\n\nfunction pageResult<T, M>(\n snapshotId: string,\n offset: number,\n pageSize: number,\n snapshot: PageSnapshot<T, M>,\n): Page<T, M> {\n if (offset >= snapshot.items.length) throw invalidCursor();\n const page = snapshot.items.slice(offset, offset + pageSize);\n const nextOffset = offset + page.length;\n return {\n page,\n metadata: snapshot.metadata,\n offset,\n nextCursor:\n nextOffset < snapshot.items.length\n ? encodePageCursor({ snapshotId, offset: nextOffset })\n : undefined,\n };\n}\n\n/**\n * The full result set a paged tool produced, before slicing. `truncated` is the\n * engine's own stop state — the hard result cap or a timeout cut the set — and\n * says nothing about page size.\n */\nexport interface ProducedPage<T, M> {\n readonly items: readonly T[];\n readonly metadata: M;\n readonly truncated: boolean;\n}\n\ninterface Page<T, M> {\n readonly page: readonly T[];\n readonly metadata: M;\n readonly nextCursor: string | undefined;\n /**\n * Index of this page's first item in the full set. A tool that reports\n * progress in its text needs it: without it every page can only say how many\n * rows it holds, which is the same number on page 1 and page 9.\n */\n readonly offset: number;\n}\n\nexport interface PaginatedPage<T, M, R> extends Page<T, M> {\n /** The externalized full set. First page only, and only when incomplete. */\n readonly resource?: R;\n}\n\n/**\n * The single home of the pagination cache-key rule: `JSON.stringify` of a\n * flat object whose `method` names the tool and whose remaining fields\n * identify the query. The literal's field order fixes key stability;\n * `method` keeps tool key spaces disjoint. Byte-identical to the three\n * hand-written tool builders it replaces.\n */\nexport function pageQueryKey(\n query: { readonly method: string; readonly path: string } & Record<string, unknown>,\n): string {\n return JSON.stringify(query);\n}\n\n/**\n * The one replay-or-produce branch every paged tool runs. A cursor replays a\n * stored snapshot; without one, `produce` runs the query and its result is\n * snapshotted for later pages.\n *\n * The response is incomplete when the set spans more than one page or the\n * engine truncated it. Then — and only on the first page — `externalize`\n * stores the full set and its handle rides back as `resource`. Replayed pages\n * never carry it: the stored entry expires on the resource store's own TTL and\n * LRU, not this snapshot's, so replaying its URI would hand back a dead\n * pointer. Nor do they mint a new one; the set was already stored whole.\n */\nexport async function paginate<T, M, R>(params: {\n store: PageSnapshotStore;\n queryKey: string;\n cursor: string | undefined;\n pageSize: number;\n produce: () => Promise<ProducedPage<T, M>>;\n externalize?: ((items: readonly T[], metadata: M) => R) | undefined;\n}): Promise<PaginatedPage<T, M, R>> {\n if (params.cursor !== undefined) {\n const decoded = decodePageCursor(params.cursor);\n const snapshot = params.store.read<T, M>(decoded.snapshotId, params.queryKey);\n return pageResult(decoded.snapshotId, decoded.offset, params.pageSize, snapshot);\n }\n const produced = await params.produce();\n const { items, metadata } = produced;\n const incomplete = items.length > params.pageSize || produced.truncated;\n const first: Page<T, M> =\n items.length <= params.pageSize\n ? { page: items, metadata, nextCursor: undefined, offset: 0 }\n : pageResult(\n params.store.create({\n queryKey: params.queryKey,\n items,\n metadata,\n }),\n 0,\n params.pageSize,\n { items, metadata },\n );\n if (!incomplete || params.externalize === undefined) return first;\n return { ...first, resource: params.externalize(produced.items, produced.metadata) };\n}\n\nfunction decodePageCursor(cursor: string): PageCursor {\n try {\n const text = Buffer.from(cursor, 'base64url').toString('utf-8');\n const parsed = JSON.parse(text) as { snapshotId?: unknown; offset?: unknown };\n if (\n typeof parsed.snapshotId === 'string' &&\n parsed.snapshotId.length > 0 &&\n typeof parsed.offset === 'number' &&\n Number.isInteger(parsed.offset) &&\n parsed.offset >= 0\n ) {\n return { snapshotId: parsed.snapshotId, offset: parsed.offset };\n }\n throw new Error('Invalid page cursor');\n } catch (error) {\n if (error instanceof FsError) throw error;\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n invalidCursor().message,\n undefined,\n error instanceof Error ? error : undefined,\n );\n }\n}\n"]}
@@ -1,17 +1,7 @@
1
- import type { Ignore } from 'ignore';
2
1
  import { type DirentLike } from './primitives.js';
3
2
  import type { EntryType } from './primitives.js';
4
3
  export type { EntryType };
5
4
  export declare function isSafeGlobSyntax(pattern: string): boolean;
6
- export declare class GitignoreManager {
7
- private matchers;
8
- addMatcher(dir: string, matcher: Ignore): void;
9
- static load(root: string, signal?: AbortSignal): Promise<GitignoreManager>;
10
- size(): number;
11
- isIgnored(relativePath: string, isDirectory: boolean): boolean;
12
- private checkPath;
13
- }
14
- export declare function loadRootGitignore(root: string, signal?: AbortSignal): Promise<GitignoreManager | null>;
15
5
  export interface GlobEntry {
16
6
  path: string;
17
7
  dirent: DirentLike;
@@ -19,14 +9,15 @@ export interface GlobEntry {
19
9
  export interface GlobEntriesOptions {
20
10
  cwd: string;
21
11
  pattern: string;
22
- excludePatterns?: readonly string[];
23
12
  includeHidden?: boolean;
24
13
  baseNameMatch?: boolean;
25
14
  maxDepth?: number;
26
15
  onlyFiles?: boolean;
27
16
  suppressErrors?: boolean;
28
- respectGitignore?: boolean;
17
+ /** Skip what a walk should not surface: DEFAULT_EXCLUDE_PATTERNS and .gitignore. */
18
+ skipIgnored?: boolean;
19
+ /** Bounds the `.gitignore` discovery `skipIgnored` runs before the walk. */
20
+ signal?: AbortSignal;
29
21
  }
30
22
  export declare function globEntries(options: GlobEntriesOptions): AsyncGenerator<GlobEntry>;
31
- export declare const DEFAULT_EXCLUDE_PATTERNS: string[];
32
23
  //# sourceMappingURL=glob.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"glob.d.ts","sourceRoot":"","sources":["../../src/core/glob.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAOrC,OAAO,EAAE,KAAK,UAAU,EAAe,MAAM,iBAAiB,CAAC;AAC/D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEjD,YAAY,EAAE,SAAS,EAAE,CAAC;AAE1B,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAsBzD;AA4BD,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,QAAQ,CAA6B;IAE7C,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI;WAIjC,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,gBAAgB,CAAC;IA6BhF,IAAI,IAAI,MAAM;IAId,SAAS,CAAC,YAAY,EAAE,MAAM,EAAE,WAAW,EAAE,OAAO,GAAG,OAAO;IAqB9D,O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IACxB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,oFAAoF;IACpF,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,4EAA4E;IAC5E,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAkND,wBAAuB,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,cAAc,CAAC,SAAS,CAAC,CAczF"}
package/dist/core/glob.js CHANGED
@@ -46,7 +46,7 @@ async function loadGitignoreFiles(root, gitignorePaths, manager, signal) {
46
46
  }
47
47
  }, GLOB_BATCH_CONCURRENCY, signal);
48
48
  }
49
- export class GitignoreManager {
49
+ class GitignoreManager {
50
50
  matchers = new Map();
51
51
  addMatcher(dir, matcher) {
52
52
  this.matchers.set(dir, matcher);
@@ -144,7 +144,7 @@ export class GitignoreManager {
144
144
  return ignored;
145
145
  }
146
146
  }
147
- export async function loadRootGitignore(root, signal) {
147
+ async function loadRootGitignore(root, signal) {
148
148
  const manager = await GitignoreManager.load(root, signal);
149
149
  if (manager.size() === 0) {
150
150
  return null;
@@ -230,7 +230,7 @@ function normalizeGlobOptions(options) {
230
230
  const normalized = {
231
231
  cwd,
232
232
  patterns,
233
- exclude: (options.excludePatterns ?? []).map(toPosixPath),
233
+ exclude: options.skipIgnored ? DEFAULT_EXCLUDE_PATTERNS.map(toPosixPath) : [],
234
234
  suppressErrors: options.suppressErrors ?? false,
235
235
  };
236
236
  if (options.maxDepth !== undefined) {
@@ -299,6 +299,11 @@ async function* processGlobPattern(pattern, plan, seen, onlyFiles, excludeFunc)
299
299
  }
300
300
  try {
301
301
  for await (const match of iterable) {
302
+ // A function `exclude` only prunes descent in fs.glob — it still yields
303
+ // the rejected dirent itself, and any rejected entry below the top level.
304
+ // An array `exclude` drops both. Re-apply the predicate so the two agree.
305
+ if (typeof excludeFunc === 'function' && excludeFunc(match))
306
+ continue;
302
307
  yield* processDirentMatch(match, cwd, maxDepth, seen, onlyFiles);
303
308
  }
304
309
  }
@@ -310,8 +315,8 @@ async function* processGlobPattern(pattern, plan, seen, onlyFiles, excludeFunc)
310
315
  }
311
316
  export async function* globEntries(options) {
312
317
  let gitignoreMatcher = null;
313
- if (options.respectGitignore) {
314
- gitignoreMatcher = await loadRootGitignore(options.cwd);
318
+ if (options.skipIgnored) {
319
+ gitignoreMatcher = await loadRootGitignore(options.cwd, options.signal);
315
320
  }
316
321
  const plan = normalizeGlobOptions(options);
317
322
  const seen = new Set();
@@ -321,7 +326,7 @@ export async function* globEntries(options) {
321
326
  yield* processGlobPattern(pattern, plan, seen, onlyFiles, excludeFunc);
322
327
  }
323
328
  }
324
- export const DEFAULT_EXCLUDE_PATTERNS = [
329
+ const DEFAULT_EXCLUDE_PATTERNS = [
325
330
  '**/node_modules',
326
331
  '**/node_modules/**',
327
332
  '**/dist',
@@ -1 +1 @@
1
- {"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/core/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAG1F,OAAO,MAAM,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AACrD,OAAO,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAC5C,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAmB,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAK/D,MAAM,UAAU,gBAAgB,CAAC,OAAe;IAC9C,IA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ACrD,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;QAC7B,gBAAgB,GAAG,MAAM,iBAAiB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC1D,CAAC;IAED,MAAM,IAAI,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC;IAC5C,MAAM,WAAW,GAAG,mBAAmB,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,gBAAgB,CAAC,CAAC;IAElF,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;QACpC,KAAK,CAAC,CAAC,kBAAkB,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,WAAW,CAAC,CAAC;IACzE,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACtC,iBAAiB;IACjB,oBAAoB;IACpB,SAAS;IACT,YAAY;IACZ,UAAU;IACV,aAAa;IACb,aAAa;IACb,gBAAgB;IAChB,SAAS;IACT,YAAY;IACZ,YAAY;IACZ,eAAe;IACf,UAAU;IACV,aAAa;IACb,cAAc;IACd,UAAU;IACV,aAAa;IACb,UAAU;IACV,aAAa;IACb,YAAY;IACZ,eAAe;IACf,gBAAgB;IAChB,mBAAmB;IACnB,WAAW;IACX,cAAc;IACd,UAAU;IACV,aAAa;IACb,kBAAkB;IAClB,qBAAqB;IACrB,qBAAqB;IACrB,wBAAwB;IACxB,QAAQ;IACR,WAAW;IACX,QAAQ;IACR,WAAW;IACX,UAAU;IACV,aAAa;IACb,kBAAkB;IAClB,mBAAmB;IACnB,mBAAmB;IACnB,cAAc;CACf,CAAC","sourcesContent":["import { glob as fsGlob, readFile as fsReadFile } from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, join, posix, relative, resolve } from 'node:path';\n\nimport type { Ignore } from 'ignore';\nimport ignore from 'ignore';\n\nimport { processInParallel } from './concurrency.js';\nimport { formatUnknownErrorMessage } from './errors.js';\nimport { Logger } from './observability.js';\nimport { isWindowsDriveRelativePath } from './path-utils.js';\nimport { type DirentLike, toPosixPath } from './primitives.js';\nimport type { EntryType } from './primitives.js';\n\nexport type { EntryType };\n\nexport function isSafeGlobSyntax(pattern: string): boolean {\n if (!pattern || pattern.trim().length === 0) {\n return false;\n }\n if (isAbsolute(pattern)) {\n return false;\n }\n if (isWindowsDriveRelativePath(pattern)) {\n return false;\n }\n if (pattern.includes('..')) {\n return false;\n }\n // Reject glob-engine-specific traversal bypass forms that some engines\n // expand as path separators or parent-directory references.\n if (/\\{[^}]*\\.\\.[^}]*\\}/u.test(pattern)) {\n return false;\n }\n if (pattern.includes('[..]')) {\n return false;\n }\n return true;\n}\n\nasync function loadGitignoreFiles(\n root: string,\n gitignorePaths: readonly string[],\n manager: GitignoreManager,\n signal?: AbortSignal,\n): Promise<void> {\n await processInParallel(\n gitignorePaths,\n async (relPath) => {\n const absPath = join(root, relPath);\n try {\n const contents = await fsReadFile(absPath, { encoding: 'utf-8', signal });\n const matcher = ignore();\n matcher.add(contents);\n const dir = toPosixPath(dirname(relPath));\n manager.addMatcher(dir === '.' ? '' : dir, matcher);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n Logger.warn(`Failed to read .gitignore at ${absPath}: ${formatUnknownErrorMessage(error)}`);\n }\n },\n GLOB_BATCH_CONCURRENCY,\n signal,\n );\n}\n\nexport class GitignoreManager {\n private matchers = new Map<string, Ignore>();\n\n addMatcher(dir: string, matcher: Ignore): void {\n this.matchers.set(dir, matcher);\n }\n\n static async load(root: string, signal?: AbortSignal): Promise<GitignoreManager> {\n const manager = new GitignoreManager();\n try {\n const gitignorePaths: string[] = [];\n const gitignoreEntries = fsGlob('**/.gitignore', {\n cwd: root,\n exclude: (entry: string) => {\n const name = basename(entry);\n if (name === 'node_modules' || name === '.git' || name === '.hg' || name === '.svn') {\n return true;\n }\n return false;\n },\n });\n for await (const match of gitignoreEntries) {\n if (signal?.aborted) break;\n gitignorePaths.push(match);\n }\n\n await loadGitignoreFiles(root, gitignorePaths, manager, signal);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n Logger.warn(\n `Failed to enumerate .gitignore files under ${root}: ${formatUnknownErrorMessage(error)}`,\n );\n }\n return manager;\n }\n\n size(): number {\n return this.matchers.size;\n }\n\n isIgnored(relativePath: string, isDirectory: boolean): boolean {\n const normalized = toPosixPath(relativePath);\n if (normalized === '' || normalized === '.') return false;\n const parts = normalized.split('/');\n\n // 1. Check parent directories first\n let currentDir = '';\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n currentDir = currentDir ? `${currentDir}/${part}` : part;\n\n if (this.checkPath(currentDir, true)) {\n return true;\n }\n }\n\n // 2. Check the file/directory itself\n return this.checkPath(normalized, isDirectory);\n }\n\n private checkPath(posixPath: string, isDirectory: boolean): boolean {\n const parts = posixPath.split('/');\n const pathToCheck = isDirectory\n ? posixPath.endsWith('/')\n ? posixPath\n : `${posixPath}/`\n : posixPath;\n\n let ignored = false;\n\n // Check root level\n const rootMatcher = this.matchers.get('');\n if (rootMatcher) {\n const res = rootMatcher.test(pathToCheck);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n\n // Check subdirectories\n let currentDir = '';\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n currentDir = currentDir ? `${currentDir}/${part}` : part;\n\n const matcher = this.matchers.get(currentDir);\n if (matcher) {\n const relParts = parts.slice(i + 1);\n const relPath = relParts.join('/');\n const relPathToCheck = isDirectory\n ? relPath.endsWith('/')\n ? relPath\n : `${relPath}/`\n : relPath;\n\n const res = matcher.test(relPathToCheck);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n }\n\n return ignored;\n }\n}\n\nexport async function loadRootGitignore(\n root: string,\n signal?: AbortSignal,\n): Promise<GitignoreManager | null> {\n const manager = await GitignoreManager.load(root, signal);\n if (manager.size() === 0) {\n return null;\n }\n return manager;\n}\n\ninterface GlobDirentLike extends DirentLike {\n name: string;\n parentPath?: string;\n}\n\nexport interface GlobEntry {\n path: string;\n dirent: DirentLike;\n}\n\nexport interface GlobEntriesOptions {\n cwd: string;\n pattern: string;\n excludePatterns?: readonly string[];\n includeHidden?: boolean;\n baseNameMatch?: boolean;\n maxDepth?: number;\n onlyFiles?: boolean;\n suppressErrors?: boolean;\n respectGitignore?: boolean;\n}\n\ninterface NormalizedGlob {\n cwd: string;\n patterns: readonly string[];\n exclude: readonly string[];\n suppressErrors: boolean;\n maxDepth?: number;\n}\n\nconst GLOB_MAGIC_RE = /[*?[\\]{}!]/u;\nconst GLOB_BATCH_CONCURRENCY = 64;\nconst SEP = '/';\nconst DOT_CHAR_CODE = 46;\nfunction normalizePattern(pattern: string, baseNameMatch: boolean): string {\n const normalized = toPosixPath(pattern);\n\n if (!baseNameMatch) return normalized;\n if (normalized.includes(SEP)) return normalized;\n return `**/${normalized}`;\n}\n\nfunction splitPatternPrefix(normalizedPattern: string): {\n prefix: string;\n remainder: string;\n} {\n if (!GLOB_MAGIC_RE.test(normalizedPattern)) {\n return { prefix: '', remainder: normalizedPattern };\n }\n\n const segments = normalizedPattern.split(SEP);\n const splitIndex = segments.findIndex((seg) => GLOB_MAGIC_RE.test(seg));\n\n if (splitIndex <= 0) {\n return { prefix: '', remainder: normalizedPattern };\n }\n\n return {\n prefix: segments.slice(0, splitIndex).join(SEP) + SEP,\n remainder: segments.slice(splitIndex).join(SEP),\n };\n}\n\nfunction addFirstDotSegment(patterns: Set<string>, prefix: string, remainder: string): void {\n if (remainder.length === 0) return;\n const segments = remainder.split(SEP);\n const idx = segments.findIndex((seg) => seg !== '**' && seg.length > 0);\n\n if (idx !== -1) {\n const original = segments[idx];\n if (original && original.charCodeAt(0) !== DOT_CHAR_CODE) {\n const newSegments = [...segments];\n newSegments[idx] = `.${original}`;\n patterns.add(`${prefix}${newSegments.join(SEP)}`);\n }\n }\n}\n\nfunction expandHiddenGlobstars(patterns: Set<string>, prefix: string, remainder: string): void {\n // Trailing bare globstar — `src/**`, `**` (remainder is exactly `**`, no\n // following segment). The pattern itself already matches every non-dot\n // entry under the prefix; add the two hidden complements fs.glob skips:\n // dotfiles/dot-dirs anywhere, and the contents of dot-dirs anywhere.\n if (remainder === '**') {\n patterns.add(`${prefix}**/.*`);\n patterns.add(`${prefix}**/.*/**`);\n return;\n }\n\n if (!remainder.startsWith('**/')) return;\n\n const afterGlobstar = remainder.slice(3);\n // Node fs.glob skips leading-dot entries unless the matching segment itself\n // starts with '.', and its `dot` option is not honored. So `**/*` alone misses\n // hidden files. Two depth-agnostic patterns cover everything the per-depth\n // unroll did: contents of dot-directories anywhere, and dotfiles/dotdirs\n // anywhere.\n patterns.add(`${prefix}**/.*/**/${afterGlobstar}`);\n const addDotFile = afterGlobstar.length > 0 && afterGlobstar.charCodeAt(0) !== DOT_CHAR_CODE;\n if (addDotFile) patterns.add(`${prefix}**/.${afterGlobstar}`);\n}\n\nfunction buildHiddenPatterns(normalizedPattern: string): readonly string[] {\n const patterns = new Set<string>([normalizedPattern]);\n const { prefix, remainder } = splitPatternPrefix(normalizedPattern);\n\n addFirstDotSegment(patterns, prefix, remainder);\n expandHiddenGlobstars(patterns, prefix, remainder);\n\n return Array.from(patterns);\n}\n\nfunction normalizeGlobOptions(options: GlobEntriesOptions): NormalizedGlob {\n const cwd = resolve(options.cwd);\n const normalizedPattern = normalizePattern(options.pattern, options.baseNameMatch ?? false);\n\n const patterns = options.includeHidden\n ? buildHiddenPatterns(normalizedPattern)\n : [normalizedPattern];\n\n const normalized: NormalizedGlob = {\n cwd,\n patterns,\n exclude: (options.excludePatterns ?? []).map(toPosixPath),\n suppressErrors: options.suppressErrors ?? false,\n };\n\n if (options.maxDepth !== undefined) {\n normalized.maxDepth = options.maxDepth;\n }\n\n return normalized;\n}\n\nfunction resolveDirentBase(cwd: string, parentPath: string | undefined): string {\n if (!parentPath) return cwd;\n return isAbsolute(parentPath) ? parentPath : resolve(cwd, parentPath);\n}\n\nfunction* processDirentMatch(\n match: GlobDirentLike,\n cwd: string,\n maxDepth: number | undefined,\n seen: Set<string>,\n onlyFiles: boolean,\n): Generator<GlobEntry> {\n const base = resolveDirentBase(cwd, match.parentPath);\n const absolutePath = resolve(base, match.name);\n\n if (maxDepth !== undefined) {\n const rel = relative(cwd, absolutePath);\n if (rel.split(/[/\\\\]/u).length - 1 > maxDepth) return;\n }\n\n if (seen.has(absolutePath)) return;\n seen.add(absolutePath);\n\n if (onlyFiles && !match.isFile()) return;\n yield { path: absolutePath, dirent: match };\n}\n\nfunction createExcludeFilter(\n cwd: string,\n excludePatterns: readonly string[],\n gitignoreMatcher?: GitignoreManager | null,\n): ((match: GlobDirentLike) => boolean) | readonly string[] {\n if (!gitignoreMatcher) {\n return excludePatterns;\n }\n\n return (match: GlobDirentLike) => {\n const relPath = match.parentPath\n ? relative(cwd, join(match.parentPath, match.name))\n : match.name;\n\n const posixRel = toPosixPath(relPath);\n\n // Gitignore check\n const isDir = match.isDirectory();\n if (gitignoreMatcher.isIgnored(posixRel, isDir)) {\n return true;\n }\n\n // Also check explicit exclude patterns\n if (excludePatterns.length > 0) {\n for (const ex of excludePatterns) {\n if (posix.matchesGlob(posixRel, ex)) return true;\n }\n }\n\n return false;\n };\n}\n\nasync function* processGlobPattern(\n pattern: string,\n plan: NormalizedGlob,\n seen: Set<string>,\n onlyFiles: boolean,\n excludeFunc: ((match: GlobDirentLike) => boolean) | readonly string[],\n): AsyncGenerator<GlobEntry> {\n const { cwd, maxDepth, suppressErrors } = plan;\n let iterable: AsyncIterable<GlobDirentLike>;\n try {\n iterable = fsGlob(pattern, {\n cwd,\n exclude: excludeFunc,\n withFileTypes: true,\n }) as AsyncIterable<GlobDirentLike>;\n } catch (error) {\n if (suppressErrors) return;\n throw error;\n }\n\n try {\n for await (const match of iterable) {\n yield* processDirentMatch(match, cwd, maxDepth, seen, onlyFiles);\n }\n } catch (error) {\n if (!suppressErrors) throw error;\n Logger.warn(\n `globEntries: suppressed mid-walk error for pattern \"${pattern}\": ${formatUnknownErrorMessage(error)}`,\n );\n }\n}\n\nexport async function* globEntries(options: GlobEntriesOptions): AsyncGenerator<GlobEntry> {\n let gitignoreMatcher: GitignoreManager | null = null;\n if (options.respectGitignore) {\n gitignoreMatcher = await loadRootGitignore(options.cwd);\n }\n\n const plan = normalizeGlobOptions(options);\n const seen = new Set<string>();\n const onlyFiles = options.onlyFiles ?? true;\n const excludeFunc = createExcludeFilter(plan.cwd, plan.exclude, gitignoreMatcher);\n\n for (const pattern of plan.patterns) {\n yield* processGlobPattern(pattern, plan, seen, onlyFiles, excludeFunc);\n }\n}\n\nexport const DEFAULT_EXCLUDE_PATTERNS = [\n '**/node_modules',\n '**/node_modules/**',\n '**/dist',\n '**/dist/**',\n '**/build',\n '**/build/**',\n '**/coverage',\n '**/coverage/**',\n '**/.git',\n '**/.git/**',\n '**/.vscode',\n '**/.vscode/**',\n '**/.idea',\n '**/.idea/**',\n '**/.DS_Store',\n '**/.next',\n '**/.next/**',\n '**/.nuxt',\n '**/.nuxt/**',\n '**/.output',\n '**/.output/**',\n '**/.svelte-kit',\n '**/.svelte-kit/**',\n '**/.cache',\n '**/.cache/**',\n '**/.yarn',\n '**/.yarn/**',\n '**/jspm_packages',\n '**/jspm_packages/**',\n '**/bower_components',\n '**/bower_components/**',\n '**/out',\n '**/out/**',\n '**/tmp',\n '**/tmp/**',\n '**/.temp',\n '**/.temp/**',\n '**/npm-debug.log',\n '**/yarn-debug.log',\n '**/yarn-error.log',\n '**/Thumbs.db',\n];\n"]}
1
+ {"version":3,"file":"glob.js","sourceRoot":"","sources":["../../src/core/glob.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC1E,OAAO,E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;IAC/B,iBAAiB;IACjB,oBAAoB;IACpB,SAAS;IACT,YAAY;IACZ,UAAU;IACV,aAAa;IACb,aAAa;IACb,gBAAgB;IAChB,SAAS;IACT,YAAY;IACZ,YAAY;IACZ,eAAe;IACf,UAAU;IACV,aAAa;IACb,cAAc;IACd,UAAU;IACV,aAAa;IACb,UAAU;IACV,aAAa;IACb,YAAY;IACZ,eAAe;IACf,gBAAgB;IAChB,mBAAmB;IACnB,WAAW;IACX,cAAc;IACd,UAAU;IACV,aAAa;IACb,kBAAkB;IAClB,qBAAqB;IACrB,qBAAqB;IACrB,wBAAwB;IACxB,QAAQ;IACR,WAAW;IACX,QAAQ;IACR,WAAW;IACX,UAAU;IACV,aAAa;IACb,kBAAkB;IAClB,mBAAmB;IACnB,mBAAmB;IACnB,cAAc;CACf,CAAC","sourcesContent":["import { glob as fsGlob, readFile as fsReadFile } from 'node:fs/promises';\nimport { basename, dirname, isAbsolute, join, posix, relative, resolve } from 'node:path';\n\nimport type { Ignore } from 'ignore';\nimport ignore from 'ignore';\n\nimport { processInParallel } from './concurrency.js';\nimport { formatUnknownErrorMessage } from './errors.js';\nimport { Logger } from './observability.js';\nimport { isWindowsDriveRelativePath } from './path-utils.js';\nimport { type DirentLike, toPosixPath } from './primitives.js';\nimport type { EntryType } from './primitives.js';\n\nexport type { EntryType };\n\nexport function isSafeGlobSyntax(pattern: string): boolean {\n if (!pattern || pattern.trim().length === 0) {\n return false;\n }\n if (isAbsolute(pattern)) {\n return false;\n }\n if (isWindowsDriveRelativePath(pattern)) {\n return false;\n }\n if (pattern.includes('..')) {\n return false;\n }\n // Reject glob-engine-specific traversal bypass forms that some engines\n // expand as path separators or parent-directory references.\n if (/\\{[^}]*\\.\\.[^}]*\\}/u.test(pattern)) {\n return false;\n }\n if (pattern.includes('[..]')) {\n return false;\n }\n return true;\n}\n\nasync function loadGitignoreFiles(\n root: string,\n gitignorePaths: readonly string[],\n manager: GitignoreManager,\n signal?: AbortSignal,\n): Promise<void> {\n await processInParallel(\n gitignorePaths,\n async (relPath) => {\n const absPath = join(root, relPath);\n try {\n const contents = await fsReadFile(absPath, { encoding: 'utf-8', signal });\n const matcher = ignore();\n matcher.add(contents);\n const dir = toPosixPath(dirname(relPath));\n manager.addMatcher(dir === '.' ? '' : dir, matcher);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n Logger.warn(`Failed to read .gitignore at ${absPath}: ${formatUnknownErrorMessage(error)}`);\n }\n },\n GLOB_BATCH_CONCURRENCY,\n signal,\n );\n}\n\nclass GitignoreManager {\n private matchers = new Map<string, Ignore>();\n\n addMatcher(dir: string, matcher: Ignore): void {\n this.matchers.set(dir, matcher);\n }\n\n static async load(root: string, signal?: AbortSignal): Promise<GitignoreManager> {\n const manager = new GitignoreManager();\n try {\n const gitignorePaths: string[] = [];\n const gitignoreEntries = fsGlob('**/.gitignore', {\n cwd: root,\n exclude: (entry: string) => {\n const name = basename(entry);\n if (name === 'node_modules' || name === '.git' || name === '.hg' || name === '.svn') {\n return true;\n }\n return false;\n },\n });\n for await (const match of gitignoreEntries) {\n if (signal?.aborted) break;\n gitignorePaths.push(match);\n }\n\n await loadGitignoreFiles(root, gitignorePaths, manager, signal);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') throw error;\n Logger.warn(\n `Failed to enumerate .gitignore files under ${root}: ${formatUnknownErrorMessage(error)}`,\n );\n }\n return manager;\n }\n\n size(): number {\n return this.matchers.size;\n }\n\n isIgnored(relativePath: string, isDirectory: boolean): boolean {\n const normalized = toPosixPath(relativePath);\n if (normalized === '' || normalized === '.') return false;\n const parts = normalized.split('/');\n\n // 1. Check parent directories first\n let currentDir = '';\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n currentDir = currentDir ? `${currentDir}/${part}` : part;\n\n if (this.checkPath(currentDir, true)) {\n return true;\n }\n }\n\n // 2. Check the file/directory itself\n return this.checkPath(normalized, isDirectory);\n }\n\n private checkPath(posixPath: string, isDirectory: boolean): boolean {\n const parts = posixPath.split('/');\n const pathToCheck = isDirectory\n ? posixPath.endsWith('/')\n ? posixPath\n : `${posixPath}/`\n : posixPath;\n\n let ignored = false;\n\n // Check root level\n const rootMatcher = this.matchers.get('');\n if (rootMatcher) {\n const res = rootMatcher.test(pathToCheck);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n\n // Check subdirectories\n let currentDir = '';\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!part) continue;\n currentDir = currentDir ? `${currentDir}/${part}` : part;\n\n const matcher = this.matchers.get(currentDir);\n if (matcher) {\n const relParts = parts.slice(i + 1);\n const relPath = relParts.join('/');\n const relPathToCheck = isDirectory\n ? relPath.endsWith('/')\n ? relPath\n : `${relPath}/`\n : relPath;\n\n const res = matcher.test(relPathToCheck);\n if (res.ignored) ignored = true;\n if (res.unignored) ignored = false;\n }\n }\n\n return ignored;\n }\n}\n\nasync function loadRootGitignore(\n root: string,\n signal?: AbortSignal,\n): Promise<GitignoreManager | null> {\n const manager = await GitignoreManager.load(root, signal);\n if (manager.size() === 0) {\n return null;\n }\n return manager;\n}\n\ninterface GlobDirentLike extends DirentLike {\n name: string;\n parentPath?: string;\n}\n\nexport interface GlobEntry {\n path: string;\n dirent: DirentLike;\n}\n\nexport interface GlobEntriesOptions {\n cwd: string;\n pattern: string;\n includeHidden?: boolean;\n baseNameMatch?: boolean;\n maxDepth?: number;\n onlyFiles?: boolean;\n suppressErrors?: boolean;\n /** Skip what a walk should not surface: DEFAULT_EXCLUDE_PATTERNS and .gitignore. */\n skipIgnored?: boolean;\n /** Bounds the `.gitignore` discovery `skipIgnored` runs before the walk. */\n signal?: AbortSignal;\n}\n\ninterface NormalizedGlob {\n cwd: string;\n patterns: readonly string[];\n exclude: readonly string[];\n suppressErrors: boolean;\n maxDepth?: number;\n}\n\nconst GLOB_MAGIC_RE = /[*?[\\]{}!]/u;\nconst GLOB_BATCH_CONCURRENCY = 64;\nconst SEP = '/';\nconst DOT_CHAR_CODE = 46;\nfunction normalizePattern(pattern: string, baseNameMatch: boolean): string {\n const normalized = toPosixPath(pattern);\n\n if (!baseNameMatch) return normalized;\n if (normalized.includes(SEP)) return normalized;\n return `**/${normalized}`;\n}\n\nfunction splitPatternPrefix(normalizedPattern: string): {\n prefix: string;\n remainder: string;\n} {\n if (!GLOB_MAGIC_RE.test(normalizedPattern)) {\n return { prefix: '', remainder: normalizedPattern };\n }\n\n const segments = normalizedPattern.split(SEP);\n const splitIndex = segments.findIndex((seg) => GLOB_MAGIC_RE.test(seg));\n\n if (splitIndex <= 0) {\n return { prefix: '', remainder: normalizedPattern };\n }\n\n return {\n prefix: segments.slice(0, splitIndex).join(SEP) + SEP,\n remainder: segments.slice(splitIndex).join(SEP),\n };\n}\n\nfunction addFirstDotSegment(patterns: Set<string>, prefix: string, remainder: string): void {\n if (remainder.length === 0) return;\n const segments = remainder.split(SEP);\n const idx = segments.findIndex((seg) => seg !== '**' && seg.length > 0);\n\n if (idx !== -1) {\n const original = segments[idx];\n if (original && original.charCodeAt(0) !== DOT_CHAR_CODE) {\n const newSegments = [...segments];\n newSegments[idx] = `.${original}`;\n patterns.add(`${prefix}${newSegments.join(SEP)}`);\n }\n }\n}\n\nfunction expandHiddenGlobstars(patterns: Set<string>, prefix: string, remainder: string): void {\n // Trailing bare globstar — `src/**`, `**` (remainder is exactly `**`, no\n // following segment). The pattern itself already matches every non-dot\n // entry under the prefix; add the two hidden complements fs.glob skips:\n // dotfiles/dot-dirs anywhere, and the contents of dot-dirs anywhere.\n if (remainder === '**') {\n patterns.add(`${prefix}**/.*`);\n patterns.add(`${prefix}**/.*/**`);\n return;\n }\n\n if (!remainder.startsWith('**/')) return;\n\n const afterGlobstar = remainder.slice(3);\n // Node fs.glob skips leading-dot entries unless the matching segment itself\n // starts with '.', and its `dot` option is not honored. So `**/*` alone misses\n // hidden files. Two depth-agnostic patterns cover everything the per-depth\n // unroll did: contents of dot-directories anywhere, and dotfiles/dotdirs\n // anywhere.\n patterns.add(`${prefix}**/.*/**/${afterGlobstar}`);\n const addDotFile = afterGlobstar.length > 0 && afterGlobstar.charCodeAt(0) !== DOT_CHAR_CODE;\n if (addDotFile) patterns.add(`${prefix}**/.${afterGlobstar}`);\n}\n\nfunction buildHiddenPatterns(normalizedPattern: string): readonly string[] {\n const patterns = new Set<string>([normalizedPattern]);\n const { prefix, remainder } = splitPatternPrefix(normalizedPattern);\n\n addFirstDotSegment(patterns, prefix, remainder);\n expandHiddenGlobstars(patterns, prefix, remainder);\n\n return Array.from(patterns);\n}\n\nfunction normalizeGlobOptions(options: GlobEntriesOptions): NormalizedGlob {\n const cwd = resolve(options.cwd);\n const normalizedPattern = normalizePattern(options.pattern, options.baseNameMatch ?? false);\n\n const patterns = options.includeHidden\n ? buildHiddenPatterns(normalizedPattern)\n : [normalizedPattern];\n\n const normalized: NormalizedGlob = {\n cwd,\n patterns,\n exclude: options.skipIgnored ? DEFAULT_EXCLUDE_PATTERNS.map(toPosixPath) : [],\n suppressErrors: options.suppressErrors ?? false,\n };\n\n if (options.maxDepth !== undefined) {\n normalized.maxDepth = options.maxDepth;\n }\n\n return normalized;\n}\n\nfunction resolveDirentBase(cwd: string, parentPath: string | undefined): string {\n if (!parentPath) return cwd;\n return isAbsolute(parentPath) ? parentPath : resolve(cwd, parentPath);\n}\n\nfunction* processDirentMatch(\n match: GlobDirentLike,\n cwd: string,\n maxDepth: number | undefined,\n seen: Set<string>,\n onlyFiles: boolean,\n): Generator<GlobEntry> {\n const base = resolveDirentBase(cwd, match.parentPath);\n const absolutePath = resolve(base, match.name);\n\n if (maxDepth !== undefined) {\n const rel = relative(cwd, absolutePath);\n if (rel.split(/[/\\\\]/u).length - 1 > maxDepth) return;\n }\n\n if (seen.has(absolutePath)) return;\n seen.add(absolutePath);\n\n if (onlyFiles && !match.isFile()) return;\n yield { path: absolutePath, dirent: match };\n}\n\nfunction createExcludeFilter(\n cwd: string,\n excludePatterns: readonly string[],\n gitignoreMatcher?: GitignoreManager | null,\n): ((match: GlobDirentLike) => boolean) | readonly string[] {\n if (!gitignoreMatcher) {\n return excludePatterns;\n }\n\n return (match: GlobDirentLike) => {\n const relPath = match.parentPath\n ? relative(cwd, join(match.parentPath, match.name))\n : match.name;\n\n const posixRel = toPosixPath(relPath);\n\n // Gitignore check\n const isDir = match.isDirectory();\n if (gitignoreMatcher.isIgnored(posixRel, isDir)) {\n return true;\n }\n\n // Also check explicit exclude patterns\n if (excludePatterns.length > 0) {\n for (const ex of excludePatterns) {\n if (posix.matchesGlob(posixRel, ex)) return true;\n }\n }\n\n return false;\n };\n}\n\nasync function* processGlobPattern(\n pattern: string,\n plan: NormalizedGlob,\n seen: Set<string>,\n onlyFiles: boolean,\n excludeFunc: ((match: GlobDirentLike) => boolean) | readonly string[],\n): AsyncGenerator<GlobEntry> {\n const { cwd, maxDepth, suppressErrors } = plan;\n let iterable: AsyncIterable<GlobDirentLike>;\n try {\n iterable = fsGlob(pattern, {\n cwd,\n exclude: excludeFunc,\n withFileTypes: true,\n }) as AsyncIterable<GlobDirentLike>;\n } catch (error) {\n if (suppressErrors) return;\n throw error;\n }\n\n try {\n for await (const match of iterable) {\n // A function `exclude` only prunes descent in fs.glob — it still yields\n // the rejected dirent itself, and any rejected entry below the top level.\n // An array `exclude` drops both. Re-apply the predicate so the two agree.\n if (typeof excludeFunc === 'function' && excludeFunc(match)) continue;\n yield* processDirentMatch(match, cwd, maxDepth, seen, onlyFiles);\n }\n } catch (error) {\n if (!suppressErrors) throw error;\n Logger.warn(\n `globEntries: suppressed mid-walk error for pattern \"${pattern}\": ${formatUnknownErrorMessage(error)}`,\n );\n }\n}\n\nexport async function* globEntries(options: GlobEntriesOptions): AsyncGenerator<GlobEntry> {\n let gitignoreMatcher: GitignoreManager | null = null;\n if (options.skipIgnored) {\n gitignoreMatcher = await loadRootGitignore(options.cwd, options.signal);\n }\n\n const plan = normalizeGlobOptions(options);\n const seen = new Set<string>();\n const onlyFiles = options.onlyFiles ?? true;\n const excludeFunc = createExcludeFilter(plan.cwd, plan.exclude, gitignoreMatcher);\n\n for (const pattern of plan.patterns) {\n yield* processGlobPattern(pattern, plan, seen, onlyFiles, excludeFunc);\n }\n}\n\nconst DEFAULT_EXCLUDE_PATTERNS = [\n '**/node_modules',\n '**/node_modules/**',\n '**/dist',\n '**/dist/**',\n '**/build',\n '**/build/**',\n '**/coverage',\n '**/coverage/**',\n '**/.git',\n '**/.git/**',\n '**/.vscode',\n '**/.vscode/**',\n '**/.idea',\n '**/.idea/**',\n '**/.DS_Store',\n '**/.next',\n '**/.next/**',\n '**/.nuxt',\n '**/.nuxt/**',\n '**/.output',\n '**/.output/**',\n '**/.svelte-kit',\n '**/.svelte-kit/**',\n '**/.cache',\n '**/.cache/**',\n '**/.yarn',\n '**/.yarn/**',\n '**/jspm_packages',\n '**/jspm_packages/**',\n '**/bower_components',\n '**/bower_components/**',\n '**/out',\n '**/out/**',\n '**/tmp',\n '**/tmp/**',\n '**/.temp',\n '**/.temp/**',\n '**/npm-debug.log',\n '**/yarn-debug.log',\n '**/yarn-error.log',\n '**/Thumbs.db',\n];\n"]}
@@ -91,6 +91,14 @@ interface PendingRoundTripOpts {
91
91
  readonly buildInputs: (pending: readonly string[]) => readonly PendingInput[];
92
92
  }
93
93
  export declare function pendingRoundTrip(opts: PendingRoundTripOpts): Promise<InputRequiredResult | undefined>;
94
+ /**
95
+ * Round-trip key for `pendingSorted[index]` — the single home of the
96
+ * `confirm_${i}` convention. The build side mints it with the map index; the
97
+ * read side re-derives it from the same sorted pending set the requestState
98
+ * binds (R9), so a format change lands here once instead of at six call
99
+ * sites.
100
+ */
101
+ export declare function confirmKey(index: number): string;
94
102
  /**
95
103
  * Read one pending item's boolean confirmation from a retried request's
96
104
  * `inputResponses`. Returns `true` only when the client explicitly accepted AND
@@ -1 +1 @@
1
- {"version":3,"file":"input-required.d.ts","sourceRoot":"","sources":["../../src/core/input-required.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,kBAAkB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C,EAAE,EAAE,SAAS,CAAC;IACvB,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAC;IACpC,QAAQ,CAAC,YAAY,EAAE,CAAC,MAAM,YAAY,GAAG,SAAS,CAAC,GAAG,SAAS,CAAC;IACpE;;;;OAIG;IACH,QAAQ,CAAC,kBAAkB,CAAC,EAAE,kBAAkB,GAAG,SAAS,CAAC;IAC7D,QAAQ,CAAC,WAAW,EAAE,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,KAAK,SAAS,YAAY,EAAE,CAAC;CAC/E;AAwCD,wBAAsB,gBAAgB,CACpC,IAAI,EAAE,oBAAoB,GACzB,OAAO,CAAC,mBAAmB,GAAG,SAAS,CAAC,CAqB1C;AAUD;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEhD;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAC9C,GAAG,EAAE,MAAM,GACV,OAAO,CAET;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAC9C,GAAG,EAAE,MAAM,GACV,MAAM,GAAG,SAAS,CAEpB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,uBAAuB,CACrC,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAC9C,GAAG,EAAE,MAAM,GACV,MAAM,EAAE,GAAG,SAAS,CAEtB"}
@@ -172,6 +172,16 @@ export async function pendingRoundTrip(opts) {
172
172
  const ConfirmContent = z.object({ confirm: z.boolean() });
173
173
  const ChoiceContent = z.object({ choice: z.string() });
174
174
  const MultiChoiceContent = z.object({ choice: z.array(z.string()) });
175
+ /**
176
+ * Round-trip key for `pendingSorted[index]` — the single home of the
177
+ * `confirm_${i}` convention. The build side mints it with the map index; the
178
+ * read side re-derives it from the same sorted pending set the requestState
179
+ * binds (R9), so a format change lands here once instead of at six call
180
+ * sites.
181
+ */
182
+ export function confirmKey(index) {
183
+ return `confirm_${index}`;
184
+ }
175
185
  /**
176
186
  * Read one pending item's boolean confirmation from a retried request's
177
187
  * `inputResponses`. Returns `true` only when the client explicitly accepted AND
@@ -1 +1 @@
1
- {"version":3,"file":"input-required.js","sourceRoot":"","sources":["../../src/core/input-required.ts"],"names":[],"mappings":"AAmBA,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,aAAa,GACd,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAmC5C;;;;;;;GAOG;AACH,SAAS,yBAAyB;IAChC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IAChD,IAAI,GAAG,EAAE,CAAC;QACR,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QACvC,IAAI,KAAK,CAAC,MAAM,IAAI,EAAE;YAAE,OAAO,KAAK,CAAC;QACrC,MAAM,CAAC,IAAI,CACT,2BAA2B,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,8HAA8H,CAC9K,CAAC;IACJ,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,+EAA+E;AAC/E,kFAAkF;AAClF,IAAI,KAAkD,CAAC;AAEvD,SAAS,oBAAoB;IAC3B,KAAK,KAAK,uBAAuB,CAAe;QAC9C,GAAG,EAAE,yBAAyB,EAAE,IAAI,WAAW,CAAC,EAAE,CAAC;KACpD,CAAC,CAAC;IACH,OAAO,KAAK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AAC1D,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AACvD,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;AAErE;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CACjC,SAA8C,EAC9C,GAAW;IAEX,OAAO,eAAe,CAAC,SAAS,EAAE,GAAG,EAAE,cAAc,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;AAC3E,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,kBAAkB,CAChC,SAA8C,EAC9C,GAAW;IAEX,OAAO,eAAe,CAAC,SAAS,EAAE,GAAG,EAAE,aAAa,CAAC,EAAE,MAAM,CAAC;AAChE,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,uBAAuB,CACrC,SAA8C,EAC9C,GAAW;IAEX,OAAO,eAAe,CAAC,SAAS,EAAE,GAAG,EAAE,kBAAkB,CAAC,EAAE,MAAM,CAAC;AACrE,CAAC;AAED;;;;;GAKG;AACH,SAAS,UAAU,CAAC,CAAoB,EAAE,CAAoB;IAC5D,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACxC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAAE,OAAO,KAAK,CAAC;IACnE,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["// Shared infrastructure for the SEP-2577 `input_required` multi-round-trip\n// destructive-confirmation flows (recursive delete, move overwrite, out-of-root\n// access grant). A handler returns `inputRequired(...)` instead of the deprecated\n// push-style server-to-client elicitation request; the client retries the same\n// `tools/call` carrying `inputResponses`, and the handler re-enters from the top\n// reading the verified `requestState` and the accepted responses.\n//\n// `requestState` round-trips through the client (attacker-controlled on\n// re-entry), so it is sealed with the SDK's HMAC-SHA256 codec. The payload binds\n// each confirmation to its operation kind and sorted target-path set (spec R9,\n// R10); the handler additionally rejects any retry whose decoded paths do not\n// match the retried request's parameters (the codec only proves the state was\n// not tampered — it cannot see the current args).\nimport type {\n ClientCapabilities,\n InputRequest,\n InputRequiredResult,\n RequestStateCodec,\n} from '@modelcontextprotocol/server';\nimport {\n acceptedContent,\n createRequestStateCodec,\n inputRequired,\n} from '@modelcontextprotocol/server';\n\nimport { randomBytes } from 'node:crypto';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode, FsError } from './errors.js';\nimport { Logger } from './observability.js';\n\n/** The destructive operation a pending confirmation authorizes. */\ntype PendingOp = 'delete' | 'move' | 'copy' | 'grant';\n\n/**\n * Integrity-protected state minted into an `input_required` result and echoed\n * back by the client on retry. `paths` is the sorted canonical set of target\n * paths the confirmation covers; the handler compares it to the retried\n * request's parameters and rejects a mismatch (R9).\n */\nexport interface PendingState {\n readonly op: PendingOp;\n readonly paths: readonly string[];\n}\n\n/** One embedded form-mode confirmation, keyed within the call. */\ninterface PendingInput {\n /** Server-assigned key, unique within the `tools/call`. */\n readonly key: string;\n /** Human-readable prompt for this item. */\n readonly message: string;\n /**\n * When set, the form offers a titled single-select enum (`choice` field)\n * instead of a boolean `confirm`. Each entry is a `{ value, title }` pair.\n */\n readonly choices?: readonly { value: string; title: string }[];\n /**\n * When set with `choices`, the form offers a multi-select enum: `choice` is\n * a string array (`MultiSelectEnumSchema` shape) and the caller reads the\n * accepted set with `readAcceptedMultiChoice`. Single-select otherwise.\n */\n readonly multi?: boolean;\n}\n\n/**\n * HMAC key for the requestState codec. Read once from\n * `FS_REQUEST_STATE_KEY` (UTF-8, must be >=32 bytes); a random\n * 32-byte key is generated at boot when the env var is unset or too short. A\n * per-process key is correct for stdio and the single-node HTTP leg (decision\n * record 11). A server restart invalidates in-flight tokens; the client\n * re-requests, which is fail-closed and safe.\n */\nfunction configuredRequestStateKey(): Uint8Array | undefined {\n const env = process.env['FS_REQUEST_STATE_KEY'];\n if (env) {\n const bytes = Buffer.from(env, 'utf8');\n if (bytes.length >= 32) return bytes;\n Logger.warn(\n `FS_REQUEST_STATE_KEY is ${String(bytes.length)} bytes; 32 are required. Falling back to a random per-boot key — in-flight input_required rounds will not survive a restart.`,\n );\n }\n return undefined;\n}\n\n// Built on first use, not at module load, so an unset env var costs nothing at\n// import and the random per-boot fallback is minted only once something needs it.\nlet codec: RequestStateCodec<PendingState> | undefined;\n\nfunction getRequestStateCodec(): RequestStateCodec<PendingState> {\n codec ??= createRequestStateCodec<PendingState>({\n key: configuredRequestStateKey() ?? randomBytes(32),\n });\n return codec;\n}\n\n/**\n * The codec: `mint` seals a `PendingState` into the opaque wire string a\n * handler returns from `inputRequired({ requestState })`; `verify` drops into\n * `ServerOptions.requestState.verify` and throws on tamper, expiry, or bind\n * mismatch (the seam answers with the frozen `-32602`).\n */\nexport const requestStateCodec: RequestStateCodec<PendingState> = {\n mint: (payload, ctx) => getRequestStateCodec().mint(payload, ctx),\n verify: (state, ctx) => getRequestStateCodec().verify(state, ctx),\n};\n\n/**\n * Build a single-select enum confirmation input. The form renders a `choice`\n * field whose options are the titled `choices`; the caller reads the selection\n * with `readAcceptedChoice`.\n */\nexport function choiceInput(\n key: string,\n message: string,\n choices: readonly { value: string; title: string }[],\n): PendingInput {\n return { key, message, choices };\n}\n\n/**\n * Build a multi-select enum confirmation input. Like `choiceInput` but the\n * form renders `choice` as a string array (`MultiSelectEnumSchema` shape), so\n * the client may accept a subset; the caller reads the accepted set with\n * `readAcceptedMultiChoice`.\n */\nexport function multiSelectInput(\n key: string,\n message: string,\n choices: readonly { value: string; title: string }[],\n): PendingInput {\n return {\n key,\n message,\n choices,\n multi: true,\n };\n}\n\n/**\n * Build an `input_required` result carrying one boolean confirmation per pending\n * item, plus the integrity-protected `requestState` sealing the operation kind\n * and sorted target paths. `mint` is async (HMAC + base64url).\n */\nexport async function buildInputRequired(\n pending: PendingState,\n inputs: readonly PendingInput[],\n): Promise<InputRequiredResult> {\n const inputRequests: Record<string, InputRequest> = {};\n for (const input of inputs) {\n const requestedSchema = input.choices\n ? input.multi\n ? {\n // Multi-select enum (matches MultiSelectEnumSchema): `choice` is a\n // string array; the client may accept a subset of the offered dirs.\n type: 'object' as const,\n properties: {\n choice: {\n type: 'array' as const,\n items: {\n anyOf: input.choices.map((c) => ({ const: c.value, title: c.title })),\n },\n },\n },\n required: ['choice'],\n }\n : {\n type: 'object' as const,\n properties: {\n choice: {\n type: 'string' as const,\n oneOf: input.choices.map((c) => ({ const: c.value, title: c.title })),\n },\n },\n required: ['choice'],\n }\n : {\n type: 'object' as const,\n properties: { confirm: { type: 'boolean' as const, title: 'Confirm' } },\n required: ['confirm'],\n };\n inputRequests[input.key] = inputRequired.elicit({\n message: input.message,\n requestedSchema,\n });\n }\n const requestState = await requestStateCodec.mint({\n op: pending.op,\n paths: [...pending.paths].sort(),\n });\n return inputRequired({ inputRequests, requestState });\n}\n\n/**\n * The shared read-state → `buildInputRequired` → mismatch-throw flow used by\n * every destructive-confirmation handler (delete, move, grant). No verified\n * state, OR a verified state belonging to a different `op` (e.g. a chained\n * call's grant round already resolved and this is now that same call's own\n * delete/move confirmation round), mints a fresh `input_required` for this\n * op. A retry whose verified state matches this op but not the pending path\n * set throws `FsError(INVALID_INPUT)` (R9) — uniformly surfaced as an\n * `isError` tool result by the handler's catch. Returns `undefined` on a\n * matching same-op retry so the caller proceeds.\n *\n * One home for the R9 binding check means a future fix cannot miss two of three\n * sites. The caller supplies `buildInputs` so only the prompt text varies.\n */\ninterface PendingRoundTripOpts {\n readonly op: PendingOp;\n readonly pending: readonly string[];\n readonly requestState: (() => PendingState | undefined) | undefined;\n /**\n * What the client declared it can do, or `undefined` when this connection\n * cannot say. Only a positively-absent `elicitation` short-circuits; see\n * {@link assertCanElicit}.\n */\n readonly clientCapabilities?: ClientCapabilities | undefined;\n readonly buildInputs: (pending: readonly string[]) => readonly PendingInput[];\n}\n\n/**\n * What to tell the model when the round-trip cannot happen. Each names the way\n * forward that does not need a confirmation, or says plainly that there is\n * none — a dead end the model can report is worth more than a retry loop.\n */\nconst NO_ELICITATION_HINT: Readonly<Record<PendingOp, string>> = {\n delete:\n 'Deleting a non-empty directory needs a confirmation this client cannot show. ' +\n 'Delete the entries inside it individually, or connect a client that declares the elicitation capability.',\n move:\n 'Overwriting an existing destination needs a confirmation this client cannot show. ' +\n 'Delete the destination first, or move to a path that does not exist yet.',\n copy:\n 'Overwriting an existing destination needs a confirmation this client cannot show. ' +\n 'Pass overwrite=true to replace it without confirming, or copy to a path that does not exist yet.',\n grant:\n 'Granting access to a directory outside the allowed roots needs a confirmation this client cannot show. ' +\n 'Call list_roots and use a path under one of the roots it returns.',\n};\n\n/**\n * Fail early, and legibly, when the client cannot answer an embedded request.\n * The SDK checks each `inputRequests` entry against the declared client\n * capabilities and rejects the whole call with `-32021` before anything reaches\n * the wire — a protocol error the model never sees. Throwing `FsError` here\n * instead lands in the tool executor's catch and reaches the model as an\n * `isError` result carrying the workaround.\n *\n * `undefined` capabilities mean the connection cannot report them, NOT that the\n * client has none: proceed and let the SDK decide, exactly as before this check\n * existed.\n */\nfunction assertCanElicit(op: PendingOp, capabilities: ClientCapabilities | undefined): void {\n if (capabilities === undefined) return;\n if (capabilities.elicitation !== undefined) return;\n throw new FsError(ErrorCode.INVALID_INPUT, `${op}: ${NO_ELICITATION_HINT[op]}`);\n}\n\nexport async function pendingRoundTrip(\n opts: PendingRoundTripOpts,\n): Promise<InputRequiredResult | undefined> {\n const state = opts.requestState?.();\n // No verified state yet, OR the verified state belongs to a different\n // flow (e.g. an access-grant round's state is still the retried request's\n // requestState after the grant was applied, and this call is now the\n // destructive-confirmation round for the SAME tool call) — either way,\n // this op has not yet had its own round-trip, so mint a fresh\n // input_required rather than treating a foreign-but-valid state as a\n // tamper/mismatch error.\n if (state?.op !== opts.op) {\n assertCanElicit(opts.op, opts.clientCapabilities);\n return buildInputRequired({ op: opts.op, paths: opts.pending }, opts.buildInputs(opts.pending));\n }\n // Retry for THIS op (R9): the verified state must bind the same pending set.\n if (!pathsEqual(state.paths, opts.pending)) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n `${opts.op}: confirmation does not match the requested paths`,\n );\n }\n return undefined;\n}\n\n// Response shapes handed to the SDK's schema-aware `acceptedContent` overload:\n// it returns `undefined` for a missing key, a decline/cancel, a non-elicit\n// response, AND a payload that fails validation — one call covers every refusal\n// case the readers below used to hand-check.\nconst ConfirmContent = z.object({ confirm: z.boolean() });\nconst ChoiceContent = z.object({ choice: z.string() });\nconst MultiChoiceContent = z.object({ choice: z.array(z.string()) });\n\n/**\n * Read one pending item's boolean confirmation from a retried request's\n * `inputResponses`. Returns `true` only when the client explicitly accepted AND\n * the `confirm` field is `true`; every other outcome (decline, cancel, missing\n * key, accept-without-confirm) returns `false`, which the caller reports as\n * `CANCELLED` (R3 proceed, R4/R5 cancelled).\n */\nexport function readAcceptedConfirm(\n responses: Record<string, unknown> | undefined,\n key: string,\n): boolean {\n return acceptedContent(responses, key, ConfirmContent)?.confirm === true;\n}\n\n/**\n * Read one pending item's enum selection from a retried request's\n * `inputResponses`. Returns the chosen `value` only when the client explicitly\n * accepted AND the `choice` field is a string; every other outcome (decline,\n * cancel, missing key, accept-without-choice) returns `undefined`, which the\n * caller reports as `CANCELLED` — same contract as the boolean reader.\n *\n * The shape is SDK-validated, but the returned value is NOT checked for\n * membership in the `choices` offered in the request schema. Callers must\n * compare against the expected values (e.g. `choice === 'overwrite'`) before\n * acting — never echo the string back into a path or trust it as an enum\n * member.\n */\nexport function readAcceptedChoice(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n return acceptedContent(responses, key, ChoiceContent)?.choice;\n}\n\n/**\n * Read one pending item's multi-select enum selection from a retried request's\n * `inputResponses`. Returns the accepted `value`s only when the client\n * explicitly accepted AND `choice` is a string array of strings; every other\n * outcome (decline, cancel, missing key, accept-without-choice, non-array\n * `choice`, non-string elements) returns `undefined`, which the caller reports\n * as `CANCELLED` — same contract as the single-select reader.\n *\n * As with `readAcceptedChoice`, the returned values are NOT checked for\n * membership in the offered `choices`; callers must compare against the\n * expected set before acting.\n */\nexport function readAcceptedMultiChoice(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string[] | undefined {\n return acceptedContent(responses, key, MultiChoiceContent)?.choice;\n}\n\n/**\n * Order-independent equality of two sorted, de-duplicated path lists. Used to\n * compare a recomputed pending set against the `requestState`-bound set (R9):\n * both are sorted by construction, so a straight element-wise compare settles\n * it without allocating.\n */\nfunction pathsEqual(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n"]}
1
+ {"version":3,"file":"input-required.js","sourceRoot":"","sources":["../../src/core/input-required.ts"],"names":[],"mappings":"AAmBA,OAAO,EACL,eAAe,EACf,uBAAuB,EACvB,aAAa,GACd,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAmC5C;;;;;;;GAOG;AACH,SAAS,yBAAyB;IAChC,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IAChD,IAAI,GAAG,EAAE,CAAC;QACR,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QACvC,IAAI,KAAK,CAAC,MAAM,IAAI,EAAE;YAAE,OAAO,KAAK,CAAC;QACrC,MAAM,CAA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AoB,EAAE,CAAoB;IAC5D,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACxC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAAE,OAAO,KAAK,CAAC;IACnE,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["// Shared infrastructure for the SEP-2577 `input_required` multi-round-trip\n// destructive-confirmation flows (recursive delete, move overwrite, out-of-root\n// access grant). A handler returns `inputRequired(...)` instead of the deprecated\n// push-style server-to-client elicitation request; the client retries the same\n// `tools/call` carrying `inputResponses`, and the handler re-enters from the top\n// reading the verified `requestState` and the accepted responses.\n//\n// `requestState` round-trips through the client (attacker-controlled on\n// re-entry), so it is sealed with the SDK's HMAC-SHA256 codec. The payload binds\n// each confirmation to its operation kind and sorted target-path set (spec R9,\n// R10); the handler additionally rejects any retry whose decoded paths do not\n// match the retried request's parameters (the codec only proves the state was\n// not tampered — it cannot see the current args).\nimport type {\n ClientCapabilities,\n InputRequest,\n InputRequiredResult,\n RequestStateCodec,\n} from '@modelcontextprotocol/server';\nimport {\n acceptedContent,\n createRequestStateCodec,\n inputRequired,\n} from '@modelcontextprotocol/server';\n\nimport { randomBytes } from 'node:crypto';\n\nimport * as z from 'zod/v4';\n\nimport { ErrorCode, FsError } from './errors.js';\nimport { Logger } from './observability.js';\n\n/** The destructive operation a pending confirmation authorizes. */\ntype PendingOp = 'delete' | 'move' | 'copy' | 'grant';\n\n/**\n * Integrity-protected state minted into an `input_required` result and echoed\n * back by the client on retry. `paths` is the sorted canonical set of target\n * paths the confirmation covers; the handler compares it to the retried\n * request's parameters and rejects a mismatch (R9).\n */\nexport interface PendingState {\n readonly op: PendingOp;\n readonly paths: readonly string[];\n}\n\n/** One embedded form-mode confirmation, keyed within the call. */\ninterface PendingInput {\n /** Server-assigned key, unique within the `tools/call`. */\n readonly key: string;\n /** Human-readable prompt for this item. */\n readonly message: string;\n /**\n * When set, the form offers a titled single-select enum (`choice` field)\n * instead of a boolean `confirm`. Each entry is a `{ value, title }` pair.\n */\n readonly choices?: readonly { value: string; title: string }[];\n /**\n * When set with `choices`, the form offers a multi-select enum: `choice` is\n * a string array (`MultiSelectEnumSchema` shape) and the caller reads the\n * accepted set with `readAcceptedMultiChoice`. Single-select otherwise.\n */\n readonly multi?: boolean;\n}\n\n/**\n * HMAC key for the requestState codec. Read once from\n * `FS_REQUEST_STATE_KEY` (UTF-8, must be >=32 bytes); a random\n * 32-byte key is generated at boot when the env var is unset or too short. A\n * per-process key is correct for stdio and the single-node HTTP leg (decision\n * record 11). A server restart invalidates in-flight tokens; the client\n * re-requests, which is fail-closed and safe.\n */\nfunction configuredRequestStateKey(): Uint8Array | undefined {\n const env = process.env['FS_REQUEST_STATE_KEY'];\n if (env) {\n const bytes = Buffer.from(env, 'utf8');\n if (bytes.length >= 32) return bytes;\n Logger.warn(\n `FS_REQUEST_STATE_KEY is ${String(bytes.length)} bytes; 32 are required. Falling back to a random per-boot key — in-flight input_required rounds will not survive a restart.`,\n );\n }\n return undefined;\n}\n\n// Built on first use, not at module load, so an unset env var costs nothing at\n// import and the random per-boot fallback is minted only once something needs it.\nlet codec: RequestStateCodec<PendingState> | undefined;\n\nfunction getRequestStateCodec(): RequestStateCodec<PendingState> {\n codec ??= createRequestStateCodec<PendingState>({\n key: configuredRequestStateKey() ?? randomBytes(32),\n });\n return codec;\n}\n\n/**\n * The codec: `mint` seals a `PendingState` into the opaque wire string a\n * handler returns from `inputRequired({ requestState })`; `verify` drops into\n * `ServerOptions.requestState.verify` and throws on tamper, expiry, or bind\n * mismatch (the seam answers with the frozen `-32602`).\n */\nexport const requestStateCodec: RequestStateCodec<PendingState> = {\n mint: (payload, ctx) => getRequestStateCodec().mint(payload, ctx),\n verify: (state, ctx) => getRequestStateCodec().verify(state, ctx),\n};\n\n/**\n * Build a single-select enum confirmation input. The form renders a `choice`\n * field whose options are the titled `choices`; the caller reads the selection\n * with `readAcceptedChoice`.\n */\nexport function choiceInput(\n key: string,\n message: string,\n choices: readonly { value: string; title: string }[],\n): PendingInput {\n return { key, message, choices };\n}\n\n/**\n * Build a multi-select enum confirmation input. Like `choiceInput` but the\n * form renders `choice` as a string array (`MultiSelectEnumSchema` shape), so\n * the client may accept a subset; the caller reads the accepted set with\n * `readAcceptedMultiChoice`.\n */\nexport function multiSelectInput(\n key: string,\n message: string,\n choices: readonly { value: string; title: string }[],\n): PendingInput {\n return {\n key,\n message,\n choices,\n multi: true,\n };\n}\n\n/**\n * Build an `input_required` result carrying one boolean confirmation per pending\n * item, plus the integrity-protected `requestState` sealing the operation kind\n * and sorted target paths. `mint` is async (HMAC + base64url).\n */\nexport async function buildInputRequired(\n pending: PendingState,\n inputs: readonly PendingInput[],\n): Promise<InputRequiredResult> {\n const inputRequests: Record<string, InputRequest> = {};\n for (const input of inputs) {\n const requestedSchema = input.choices\n ? input.multi\n ? {\n // Multi-select enum (matches MultiSelectEnumSchema): `choice` is a\n // string array; the client may accept a subset of the offered dirs.\n type: 'object' as const,\n properties: {\n choice: {\n type: 'array' as const,\n items: {\n anyOf: input.choices.map((c) => ({ const: c.value, title: c.title })),\n },\n },\n },\n required: ['choice'],\n }\n : {\n type: 'object' as const,\n properties: {\n choice: {\n type: 'string' as const,\n oneOf: input.choices.map((c) => ({ const: c.value, title: c.title })),\n },\n },\n required: ['choice'],\n }\n : {\n type: 'object' as const,\n properties: { confirm: { type: 'boolean' as const, title: 'Confirm' } },\n required: ['confirm'],\n };\n inputRequests[input.key] = inputRequired.elicit({\n message: input.message,\n requestedSchema,\n });\n }\n const requestState = await requestStateCodec.mint({\n op: pending.op,\n paths: [...pending.paths].sort(),\n });\n return inputRequired({ inputRequests, requestState });\n}\n\n/**\n * The shared read-state → `buildInputRequired` → mismatch-throw flow used by\n * every destructive-confirmation handler (delete, move, grant). No verified\n * state, OR a verified state belonging to a different `op` (e.g. a chained\n * call's grant round already resolved and this is now that same call's own\n * delete/move confirmation round), mints a fresh `input_required` for this\n * op. A retry whose verified state matches this op but not the pending path\n * set throws `FsError(INVALID_INPUT)` (R9) — uniformly surfaced as an\n * `isError` tool result by the handler's catch. Returns `undefined` on a\n * matching same-op retry so the caller proceeds.\n *\n * One home for the R9 binding check means a future fix cannot miss two of three\n * sites. The caller supplies `buildInputs` so only the prompt text varies.\n */\ninterface PendingRoundTripOpts {\n readonly op: PendingOp;\n readonly pending: readonly string[];\n readonly requestState: (() => PendingState | undefined) | undefined;\n /**\n * What the client declared it can do, or `undefined` when this connection\n * cannot say. Only a positively-absent `elicitation` short-circuits; see\n * {@link assertCanElicit}.\n */\n readonly clientCapabilities?: ClientCapabilities | undefined;\n readonly buildInputs: (pending: readonly string[]) => readonly PendingInput[];\n}\n\n/**\n * What to tell the model when the round-trip cannot happen. Each names the way\n * forward that does not need a confirmation, or says plainly that there is\n * none — a dead end the model can report is worth more than a retry loop.\n */\nconst NO_ELICITATION_HINT: Readonly<Record<PendingOp, string>> = {\n delete:\n 'Deleting a non-empty directory needs a confirmation this client cannot show. ' +\n 'Delete the entries inside it individually, or connect a client that declares the elicitation capability.',\n move:\n 'Overwriting an existing destination needs a confirmation this client cannot show. ' +\n 'Delete the destination first, or move to a path that does not exist yet.',\n copy:\n 'Overwriting an existing destination needs a confirmation this client cannot show. ' +\n 'Pass overwrite=true to replace it without confirming, or copy to a path that does not exist yet.',\n grant:\n 'Granting access to a directory outside the allowed roots needs a confirmation this client cannot show. ' +\n 'Call list_roots and use a path under one of the roots it returns.',\n};\n\n/**\n * Fail early, and legibly, when the client cannot answer an embedded request.\n * The SDK checks each `inputRequests` entry against the declared client\n * capabilities and rejects the whole call with `-32021` before anything reaches\n * the wire — a protocol error the model never sees. Throwing `FsError` here\n * instead lands in the tool executor's catch and reaches the model as an\n * `isError` result carrying the workaround.\n *\n * `undefined` capabilities mean the connection cannot report them, NOT that the\n * client has none: proceed and let the SDK decide, exactly as before this check\n * existed.\n */\nfunction assertCanElicit(op: PendingOp, capabilities: ClientCapabilities | undefined): void {\n if (capabilities === undefined) return;\n if (capabilities.elicitation !== undefined) return;\n throw new FsError(ErrorCode.INVALID_INPUT, `${op}: ${NO_ELICITATION_HINT[op]}`);\n}\n\nexport async function pendingRoundTrip(\n opts: PendingRoundTripOpts,\n): Promise<InputRequiredResult | undefined> {\n const state = opts.requestState?.();\n // No verified state yet, OR the verified state belongs to a different\n // flow (e.g. an access-grant round's state is still the retried request's\n // requestState after the grant was applied, and this call is now the\n // destructive-confirmation round for the SAME tool call) — either way,\n // this op has not yet had its own round-trip, so mint a fresh\n // input_required rather than treating a foreign-but-valid state as a\n // tamper/mismatch error.\n if (state?.op !== opts.op) {\n assertCanElicit(opts.op, opts.clientCapabilities);\n return buildInputRequired({ op: opts.op, paths: opts.pending }, opts.buildInputs(opts.pending));\n }\n // Retry for THIS op (R9): the verified state must bind the same pending set.\n if (!pathsEqual(state.paths, opts.pending)) {\n throw new FsError(\n ErrorCode.INVALID_INPUT,\n `${opts.op}: confirmation does not match the requested paths`,\n );\n }\n return undefined;\n}\n\n// Response shapes handed to the SDK's schema-aware `acceptedContent` overload:\n// it returns `undefined` for a missing key, a decline/cancel, a non-elicit\n// response, AND a payload that fails validation — one call covers every refusal\n// case the readers below used to hand-check.\nconst ConfirmContent = z.object({ confirm: z.boolean() });\nconst ChoiceContent = z.object({ choice: z.string() });\nconst MultiChoiceContent = z.object({ choice: z.array(z.string()) });\n\n/**\n * Round-trip key for `pendingSorted[index]` — the single home of the\n * `confirm_${i}` convention. The build side mints it with the map index; the\n * read side re-derives it from the same sorted pending set the requestState\n * binds (R9), so a format change lands here once instead of at six call\n * sites.\n */\nexport function confirmKey(index: number): string {\n return `confirm_${index}`;\n}\n\n/**\n * Read one pending item's boolean confirmation from a retried request's\n * `inputResponses`. Returns `true` only when the client explicitly accepted AND\n * the `confirm` field is `true`; every other outcome (decline, cancel, missing\n * key, accept-without-confirm) returns `false`, which the caller reports as\n * `CANCELLED` (R3 proceed, R4/R5 cancelled).\n */\nexport function readAcceptedConfirm(\n responses: Record<string, unknown> | undefined,\n key: string,\n): boolean {\n return acceptedContent(responses, key, ConfirmContent)?.confirm === true;\n}\n\n/**\n * Read one pending item's enum selection from a retried request's\n * `inputResponses`. Returns the chosen `value` only when the client explicitly\n * accepted AND the `choice` field is a string; every other outcome (decline,\n * cancel, missing key, accept-without-choice) returns `undefined`, which the\n * caller reports as `CANCELLED` — same contract as the boolean reader.\n *\n * The shape is SDK-validated, but the returned value is NOT checked for\n * membership in the `choices` offered in the request schema. Callers must\n * compare against the expected values (e.g. `choice === 'overwrite'`) before\n * acting — never echo the string back into a path or trust it as an enum\n * member.\n */\nexport function readAcceptedChoice(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string | undefined {\n return acceptedContent(responses, key, ChoiceContent)?.choice;\n}\n\n/**\n * Read one pending item's multi-select enum selection from a retried request's\n * `inputResponses`. Returns the accepted `value`s only when the client\n * explicitly accepted AND `choice` is a string array of strings; every other\n * outcome (decline, cancel, missing key, accept-without-choice, non-array\n * `choice`, non-string elements) returns `undefined`, which the caller reports\n * as `CANCELLED` — same contract as the single-select reader.\n *\n * As with `readAcceptedChoice`, the returned values are NOT checked for\n * membership in the offered `choices`; callers must compare against the\n * expected set before acting.\n */\nexport function readAcceptedMultiChoice(\n responses: Record<string, unknown> | undefined,\n key: string,\n): string[] | undefined {\n return acceptedContent(responses, key, MultiChoiceContent)?.choice;\n}\n\n/**\n * Order-independent equality of two sorted, de-duplicated path lists. Used to\n * compare a recomputed pending set against the `requestState`-bound set (R9):\n * both are sorted by construction, so a straight element-wise compare settles\n * it without allocating.\n */\nfunction pathsEqual(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"observability.d.ts","sourceRoot":"","sources":["../../src/core/observability.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,YAAY,GACtB,OAAO,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,OAAO,GAAG,UAAU,GAAG,OAAO,GAAG,WAAW,CAAC;AA6DzF,eAAO,MAAM,MAAM;kBACH,YAAY,WAAW,MAAM;oBAG3B,MAAM,WAAW,OAAO,EAAE;oBAG1B,MAAM,WAAW,OAAO,EAAE;qBAGzB,MAAM,WAAW,OAAO,EAAE;qBAG1B,MAAM,WAAW,OAAO,EAAE;CAG5C,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAEjG"}
1
+ {"version":3,"file":"observability.d.ts","sourceRoot":"","sources":["../../src/core/observability.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,YAAY,GACtB,OAAO,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,OAAO,GAAG,UAAU,GAAG,OAAO,GAAG,WAAW,CAAC;AA2DzF,eAAO,MAAM,MAAM;kBACH,YAAY,WAAW,MAAM;oBAG3B,MAAM,WAAW,OAAO,EAAE;oBAG1B,MAAM,WAAW,OAAO,EAAE;qBAGzB,MAAM,WAAW,OAAO,EAAE;qBAG1B,MAAM,WAAW,OAAO,EAAE;CAG5C,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAEjG"}
@@ -1,4 +1,5 @@
1
1
  import { cli } from './config.js';
2
+ import { warnInvalidSetting } from './primitives.js';
2
3
  // RFC 5424 severities, most severe first. A message is emitted when its
3
4
  // severity is at least as high as the configured minimum.
4
5
  const LEVEL_ORDER = [
@@ -22,7 +23,7 @@ function parseLogLevel(raw) {
22
23
  return 'warning';
23
24
  if (isLoggingLevel(raw))
24
25
  return raw;
25
- console.error(`[warning] Invalid FS_LOG_LEVEL value: ${raw} (must be ${LEVEL_ORDER.join('|')}). Using default: info`);
26
+ warnInvalidSetting('FS_LOG_LEVEL', raw, LEVEL_ORDER.join('|'), 'info');
26
27
  return 'info';
27
28
  }
28
29
  // Seeded to the value `parseLogLevel(undefined)` returns, so an unset
@@ -1 +1 @@
1
- {"version":3,"file":"observability.js","sourceRoot":"","sources":["../../src/core/observability.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAKlC,wEAAwE;AACxE,0DAA0D;AAC1D,MAAM,WAAW,GAA4B;IAC3C,WAAW;IACX,OAAO;IACP,UAAU;IACV,OAAO;IACP,SAAS;IACT,QAAQ;IACR,MAAM;IACN,OAAO;CACR,CAAC;AAEF,SAAS,cAAc,CAAC,KAAa;IACnC,OAAQ,WAAiC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,aAAa,CAAC,GAAuB;IAC5C,IAAI,CAAC,GAAG;QAAE,OAAO,MAAM,CAAC;IACxB,8EAA8E;IAC9E,IAAI,GAAG,KAAK,MAAM;QAAE,OAAO,SAAS,CAAC;IACrC,IAAI,cAAc,CAAC,GAAG,CAAC;QAAE,OAAO,GAAG,CAAC;IACpC,OAAO,CAAC,KAAK,CACX,yCAAyC,GAAG,aAAa,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,wBAAwB,CACvG,CAAC;IACF,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,sEAAsE;AACtE,0EAA0E;AAC1E,IAAI,SAA6B,CAAC;AAClC,IAAI,WAAW,GAAiB,MAAM,CAAC;AAEvC;;;;;GAKG;AACH,SAAS,WAAW;IAClB,MAAM,GAAG,GAAG,CAAC,GAAG,CAAC,QAAQ,IAAI,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,EAAE,IAAI,EA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,GAAG,IAAe,EAAE,EAAE;QAC7C,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;CACF,CAAC;AAEF,MAAM,UAAU,iBAAiB,CAAC,EAAU,EAAE,KAAa,EAAE,MAAc,EAAE,KAAc;IACzF,KAAK,CAAC,OAAO,EAAE,oBAAoB,EAAE,KAAK,KAAK,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AACzE,CAAC","sourcesContent":["import { cli } from './config.js';\n\nexport type LoggingLevel =\n 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency';\n\n// RFC 5424 severities, most severe first. A message is emitted when its\n// severity is at least as high as the configured minimum.\nconst LEVEL_ORDER: readonly LoggingLevel[] = [\n 'emergency',\n 'alert',\n 'critical',\n 'error',\n 'warning',\n 'notice',\n 'info',\n 'debug',\n];\n\nfunction isLoggingLevel(value: string): value is LoggingLevel {\n return (LEVEL_ORDER as readonly string[]).includes(value);\n}\n\nfunction parseLogLevel(raw: string | undefined): LoggingLevel {\n if (!raw) return 'info';\n // `warn` is the common short form; the canonical RFC 5424 level is `warning`.\n if (raw === 'warn') return 'warning';\n if (isLoggingLevel(raw)) return raw;\n console.error(\n `[warning] Invalid FS_LOG_LEVEL value: ${raw} (must be ${LEVEL_ORDER.join('|')}). Using default: info`,\n );\n return 'info';\n}\n\n// Seeded to the value `parseLogLevel(undefined)` returns, so an unset\n// LOG_LEVEL — the initial `cachedRaw` — needs no first-call special case.\nlet cachedRaw: string | undefined;\nlet cachedLevel: LoggingLevel = 'info';\n\n/**\n * Minimum severity that reaches stderr, from `FS_LOG_LEVEL` / `--log-level`.\n * Memoized on the raw value, not resolved once: `cli.logLevel` lands after\n * `parseArgs`, and writes happen before that. Keying on the raw string keeps it\n * live while the invalid-value warning fires once per setting, not per line.\n */\nfunction getLogLevel(): LoggingLevel {\n const raw = (cli.logLevel ?? process.env['FS_LOG_LEVEL'])?.trim().toLowerCase();\n if (raw !== cachedRaw) {\n cachedRaw = raw;\n cachedLevel = parseLogLevel(raw);\n }\n return cachedLevel;\n}\n\n/** True when `level` is at least as severe as the configured minimum. */\nfunction isLevelEnabled(level: LoggingLevel, minimum: LoggingLevel = getLogLevel()): boolean {\n return LEVEL_ORDER.indexOf(level) <= LEVEL_ORDER.indexOf(minimum);\n}\n\nfunction write(level: LoggingLevel, message: string, args: readonly unknown[]): void {\n if (!isLevelEnabled(level)) return;\n const prefix = `[${level}]`;\n console.error(`${prefix} ${message}`, ...args);\n}\n\nexport const Logger = {\n emit: (level: LoggingLevel, message: string) => {\n write(level, message, []);\n },\n info: (message: string, ...args: unknown[]) => {\n write('info', message, args);\n },\n warn: (message: string, ...args: unknown[]) => {\n write('warning', message, args);\n },\n error: (message: string, ...args: unknown[]) => {\n write('error', message, args);\n },\n debug: (message: string, ...args: unknown[]) => {\n write('debug', message, args);\n },\n};\n\nexport function logRuntimeFailure(id: string, scope: string, method: string, error: unknown): void {\n write('error', `Runtime failure: ${id} [${scope}.${method}]`, [error]);\n}\n"]}
1
+ {"version":3,"file":"observability.js","sourceRoot":"","sources":["../../src/core/observability.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAClC,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAKrD,wEAAwE;AACxE,0DAA0D;AAC1D,MAAM,WAAW,GAA4B;IAC3C,WAAW;IACX,OAAO;IACP,UAAU;IACV,OAAO;IACP,SAAS;IACT,QAAQ;IACR,MAAM;IACN,OAAO;CACR,CAAC;AAEF,SAAS,cAAc,CAAC,KAAa;IACnC,OAAQ,WAAiC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAC5D,CAAC;AAED,SAAS,aAAa,CAAC,GAAuB;IAC5C,IAAI,CAAC,GAAG;QAAE,OAAO,MAAM,CAAC;IACxB,8EAA8E;IAC9E,IAAI,GAAG,KAAK,MAAM;QAAE,O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AAC,CAAC;IAC5B,CAAC;IACD,IAAI,EAAE,CAAC,OAAe,EAAE,GAAG,IAAe,EAAE,EAAE;QAC5C,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC/B,CAAC;IACD,IAAI,EAAE,CAAC,OAAe,EAAE,GAAG,IAAe,EAAE,EAAE;QAC5C,KAAK,CAAC,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAClC,CAAC;IACD,KAAK,EAAE,CAAC,OAAe,EAAE,GAAG,IAAe,EAAE,EAAE;QAC7C,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;IACD,KAAK,EAAE,CAAC,OAAe,EAAE,GAAG,IAAe,EAAE,EAAE;QAC7C,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAChC,CAAC;CACF,CAAC;AAEF,MAAM,UAAU,iBAAiB,CAAC,EAAU,EAAE,KAAa,EAAE,MAAc,EAAE,KAAc;IACzF,KAAK,CAAC,OAAO,EAAE,oBAAoB,EAAE,KAAK,KAAK,IAAI,MAAM,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AACzE,CAAC","sourcesContent":["import { cli } from './config.js';\nimport { warnInvalidSetting } from './primitives.js';\n\nexport type LoggingLevel =\n 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency';\n\n// RFC 5424 severities, most severe first. A message is emitted when its\n// severity is at least as high as the configured minimum.\nconst LEVEL_ORDER: readonly LoggingLevel[] = [\n 'emergency',\n 'alert',\n 'critical',\n 'error',\n 'warning',\n 'notice',\n 'info',\n 'debug',\n];\n\nfunction isLoggingLevel(value: string): value is LoggingLevel {\n return (LEVEL_ORDER as readonly string[]).includes(value);\n}\n\nfunction parseLogLevel(raw: string | undefined): LoggingLevel {\n if (!raw) return 'info';\n // `warn` is the common short form; the canonical RFC 5424 level is `warning`.\n if (raw === 'warn') return 'warning';\n if (isLoggingLevel(raw)) return raw;\n warnInvalidSetting('FS_LOG_LEVEL', raw, LEVEL_ORDER.join('|'), 'info');\n return 'info';\n}\n\n// Seeded to the value `parseLogLevel(undefined)` returns, so an unset\n// LOG_LEVEL — the initial `cachedRaw` — needs no first-call special case.\nlet cachedRaw: string | undefined;\nlet cachedLevel: LoggingLevel = 'info';\n\n/**\n * Minimum severity that reaches stderr, from `FS_LOG_LEVEL` / `--log-level`.\n * Memoized on the raw value, not resolved once: `cli.logLevel` lands after\n * `parseArgs`, and writes happen before that. Keying on the raw string keeps it\n * live while the invalid-value warning fires once per setting, not per line.\n */\nfunction getLogLevel(): LoggingLevel {\n const raw = (cli.logLevel ?? process.env['FS_LOG_LEVEL'])?.trim().toLowerCase();\n if (raw !== cachedRaw) {\n cachedRaw = raw;\n cachedLevel = parseLogLevel(raw);\n }\n return cachedLevel;\n}\n\n/** True when `level` is at least as severe as the configured minimum. */\nfunction isLevelEnabled(level: LoggingLevel, minimum: LoggingLevel = getLogLevel()): boolean {\n return LEVEL_ORDER.indexOf(level) <= LEVEL_ORDER.indexOf(minimum);\n}\n\nfunction write(level: LoggingLevel, message: string, args: readonly unknown[]): void {\n if (!isLevelEnabled(level)) return;\n const prefix = `[${level}]`;\n console.error(`${prefix} ${message}`, ...args);\n}\n\nexport const Logger = {\n emit: (level: LoggingLevel, message: string) => {\n write(level, message, []);\n },\n info: (message: string, ...args: unknown[]) => {\n write('info', message, args);\n },\n warn: (message: string, ...args: unknown[]) => {\n write('warning', message, args);\n },\n error: (message: string, ...args: unknown[]) => {\n write('error', message, args);\n },\n debug: (message: string, ...args: unknown[]) => {\n write('debug', message, args);\n },\n};\n\nexport function logRuntimeFailure(id: string, scope: string, method: string, error: unknown): void {\n write('error', `Runtime failure: ${id} [${scope}.${method}]`, [error]);\n}\n"]}
@@ -12,6 +12,13 @@ export interface DirentLike {
12
12
  isSymbolicLink(): boolean;
13
13
  }
14
14
  export declare function resolveEntryType(dirent: DirentLike): EntryType;
15
+ /**
16
+ * Warn once per (setting, value) that a configured value was rejected, and say
17
+ * what was used instead. console.error, not Logger: this module stays
18
+ * dependency-free to avoid import cycles, and a startup misconfiguration is
19
+ * worth printing even when the operator asked for errors only.
20
+ */
21
+ export declare function warnInvalidSetting(name: string, value: string, expected: string, fallback: string | number | boolean): void;
15
22
  /**
16
23
  * Parse a boolean env flag: `true`/`1` enable, `false`/`0`/empty disable.
17
24
  * Any other value warns once per var (when `name` is given) and reads as
@@ -1 +1 @@
1
- {"version":3,"file":"primitives.d.ts","sourceRoot":"","sources":["../../src/core/primitives.ts"],"names":[],"mappings":"AAEA;;;GAGG;AAEH,2EAA2E;AAC3E,eAAO,MAAM,WAAW,oDAAqD,CAAC;AAC9E,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;AAErD,4FAA4F;AAC5F,MAAM,WAAW,UAAU;IACzB,WAAW,IAAI,OAAO,CAAC;IACvB,MAAM,IAAI,OAAO,CAAC;IAClB,cAAc,IAAI,OAAO,CAAC;CAC3B;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,SAAS,CAK9D;AAID;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAgBlF;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,EAAE,CAM9D;AAID,eAAO,MAAM,UAAU,SAA+B,CAAC;AAEvD,eAAO,MAAM,OAAO,GAAI,MAAM,MAAM,KAAG,OAAqC,CAAC;AAE7E,eAAO,MAAM,OAAO,GAAI,MAAM,MAAM,KAAG,OACoB,CAAC;AAE5D,eAAO,MAAM,WAAW,GAAI,OAAO,MAAM,KAAG,MAAqC,CAAC"}
1
+ {"version":3,"file":"primitives.d.ts","sourceRoot":"","sources":["../../src/core/primitives.ts"],"names":[],"mappings":"AAEA;;;GAGG;AAEH,2EAA2E;AAC3E,eAAO,MAAM,WAAW,oDAAqD,CAAC;AAC9E,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;AAErD,4FAA4F;AAC5F,MAAM,WAAW,UAAU;IACzB,WAAW,IAAI,OAAO,CAAC;IACvB,MAAM,IAAI,OAAO,CAAC;IAClB,cAAc,IAAI,OAAO,CAAC;CAC3B;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,UAAU,GAAG,SAAS,CAK9D;AAID;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAClC,IAAI,CAON;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAQlF;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,EAAE,CAM9D;AAID,eAAO,MAAM,UAAU,SAA+B,CAAC;AAEvD,eAAO,MAAM,OAAO,GAAI,MAAM,MAAM,KAAG,OAAqC,CAAC;AAE7E,eAAO,MAAM,OAAO,GAAI,MAAM,MAAM,KAAG,OACoB,CAAC;AAE5D,eAAO,MAAM,WAAW,GAAI,OAAO,MAAM,KAAG,MAAqC,CAAC"}
@@ -14,7 +14,20 @@ export function resolveEntryType(dirent) {
14
14
  return 'symlink';
15
15
  return 'other';
16
16
  }
17
- const warnedFlagValues = new Set();
17
+ const warnedSettings = new Set();
18
+ /**
19
+ * Warn once per (setting, value) that a configured value was rejected, and say
20
+ * what was used instead. console.error, not Logger: this module stays
21
+ * dependency-free to avoid import cycles, and a startup misconfiguration is
22
+ * worth printing even when the operator asked for errors only.
23
+ */
24
+ export function warnInvalidSetting(name, value, expected, fallback) {
25
+ const key = `${name}:${value}`;
26
+ if (warnedSettings.has(key))
27
+ return;
28
+ warnedSettings.add(key);
29
+ console.error(`[warning] Invalid ${name} value: ${value} (must be ${expected}). Using default: ${String(fallback)}`);
30
+ }
18
31
  /**
19
32
  * Parse a boolean env flag: `true`/`1` enable, `false`/`0`/empty disable.
20
33
  * Any other value warns once per var (when `name` is given) and reads as
@@ -27,13 +40,7 @@ export function parseTrueEnvFlag(value, name) {
27
40
  if (trimmed === 'true' || trimmed === '1')
28
41
  return true;
29
42
  if (name && trimmed !== '' && trimmed !== 'false' && trimmed !== '0') {
30
- const key = `${name}:${trimmed}`;
31
- if (!warnedFlagValues.has(key)) {
32
- warnedFlagValues.add(key);
33
- // console.error, not Logger: this module stays dependency-free to avoid
34
- // import cycles (same precedent as parseLogLevel in observability.ts).
35
- console.error(`[warning] Invalid ${name} value: ${value} (must be "true" or "1"). Using default: false`);
36
- }
43
+ warnInvalidSetting(name, value, '"true" or "1"', false);
37
44
  }
38
45
  return false;
39
46
  }