@vibe-agent-toolkit/utils 0.2.0-rc.2 → 0.2.0-rc.3

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 (102) hide show
  1. package/README.md +6 -3
  2. package/dist/compare-code-units.d.ts +28 -0
  3. package/dist/compare-code-units.d.ts.map +1 -0
  4. package/dist/compare-code-units.js +33 -0
  5. package/dist/compare-code-units.js.map +1 -0
  6. package/dist/crawl-timing.d.ts +680 -0
  7. package/dist/crawl-timing.d.ts.map +1 -0
  8. package/dist/crawl-timing.js +809 -0
  9. package/dist/crawl-timing.js.map +1 -0
  10. package/dist/file-crawler.d.ts +22 -0
  11. package/dist/file-crawler.d.ts.map +1 -1
  12. package/dist/file-crawler.js +31 -7
  13. package/dist/file-crawler.js.map +1 -1
  14. package/dist/fs-utils.d.ts +17 -0
  15. package/dist/fs-utils.d.ts.map +1 -1
  16. package/dist/fs-utils.js +69 -0
  17. package/dist/fs-utils.js.map +1 -1
  18. package/dist/fs.d.ts +3 -1
  19. package/dist/fs.d.ts.map +1 -1
  20. package/dist/fs.js +5 -1
  21. package/dist/fs.js.map +1 -1
  22. package/dist/git-run.d.ts +167 -0
  23. package/dist/git-run.d.ts.map +1 -0
  24. package/dist/git-run.js +154 -0
  25. package/dist/git-run.js.map +1 -0
  26. package/dist/git-snapshot.d.ts +181 -0
  27. package/dist/git-snapshot.d.ts.map +1 -0
  28. package/dist/git-snapshot.js +232 -0
  29. package/dist/git-snapshot.js.map +1 -0
  30. package/dist/git-tracker.d.ts +94 -1
  31. package/dist/git-tracker.d.ts.map +1 -1
  32. package/dist/git-tracker.js +135 -3
  33. package/dist/git-tracker.js.map +1 -1
  34. package/dist/git-utils.d.ts +38 -0
  35. package/dist/git-utils.d.ts.map +1 -1
  36. package/dist/git-utils.js +103 -80
  37. package/dist/git-utils.js.map +1 -1
  38. package/dist/git.d.ts +2 -1
  39. package/dist/git.d.ts.map +1 -1
  40. package/dist/git.js +2 -1
  41. package/dist/git.js.map +1 -1
  42. package/dist/gitignore-checker.d.ts.map +1 -1
  43. package/dist/gitignore-checker.js +6 -3
  44. package/dist/gitignore-checker.js.map +1 -1
  45. package/dist/index.d.ts +8 -1
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +42 -1
  48. package/dist/index.js.map +1 -1
  49. package/dist/link-auth/expand-macro.d.ts.map +1 -1
  50. package/dist/link-auth/expand-macro.js +7 -1
  51. package/dist/link-auth/expand-macro.js.map +1 -1
  52. package/dist/link-auth/resolve-token.d.ts.map +1 -1
  53. package/dist/link-auth/resolve-token.js +15 -1
  54. package/dist/link-auth/resolve-token.js.map +1 -1
  55. package/dist/path-core.d.ts +1 -1
  56. package/dist/path-core.js +1 -1
  57. package/dist/project-utils.d.ts.map +1 -1
  58. package/dist/project-utils.js +6 -3
  59. package/dist/project-utils.js.map +1 -1
  60. package/dist/safe-exec.d.ts +38 -10
  61. package/dist/safe-exec.d.ts.map +1 -1
  62. package/dist/safe-exec.js +88 -19
  63. package/dist/safe-exec.js.map +1 -1
  64. package/dist/skill-test/index.d.ts +1 -1
  65. package/dist/skill-test/index.d.ts.map +1 -1
  66. package/dist/skill-test/index.js +1 -1
  67. package/dist/skill-test/index.js.map +1 -1
  68. package/dist/skill-test/spawn-claude.d.ts +28 -0
  69. package/dist/skill-test/spawn-claude.d.ts.map +1 -1
  70. package/dist/skill-test/spawn-claude.js +51 -2
  71. package/dist/skill-test/spawn-claude.js.map +1 -1
  72. package/dist/skill-test/transcript.d.ts +41 -2
  73. package/dist/skill-test/transcript.d.ts.map +1 -1
  74. package/dist/skill-test/transcript.js +47 -3
  75. package/dist/skill-test/transcript.js.map +1 -1
  76. package/dist/test-helpers.d.ts +185 -13
  77. package/dist/test-helpers.d.ts.map +1 -1
  78. package/dist/test-helpers.js +274 -27
  79. package/dist/test-helpers.js.map +1 -1
  80. package/dist/text-content.d.ts +197 -0
  81. package/dist/text-content.d.ts.map +1 -0
  82. package/dist/text-content.js +348 -0
  83. package/dist/text-content.js.map +1 -0
  84. package/dist/text-file.d.ts +45 -0
  85. package/dist/text-file.d.ts.map +1 -0
  86. package/dist/text-file.js +53 -0
  87. package/dist/text-file.js.map +1 -0
  88. package/dist/text.d.ts +16 -0
  89. package/dist/text.d.ts.map +1 -0
  90. package/dist/text.js +16 -0
  91. package/dist/text.js.map +1 -0
  92. package/dist/timing-dump.d.ts +119 -0
  93. package/dist/timing-dump.d.ts.map +1 -0
  94. package/dist/timing-dump.js +164 -0
  95. package/dist/timing-dump.js.map +1 -0
  96. package/eslint/README.md +105 -3
  97. package/eslint/index.cjs +41 -0
  98. package/eslint/index.d.cts +7 -4
  99. package/eslint/rules/no-bare-symlink-in-tests.cjs +200 -0
  100. package/eslint/rules/no-raw-text-decode.cjs +296 -0
  101. package/eslint/rules/no-self-package-import.cjs +157 -0
  102. package/package.json +9 -2
@@ -0,0 +1,197 @@
1
+ /**
2
+ * **The one way VAT turns file bytes into text.**
3
+ *
4
+ * `local/no-raw-text-decode` enforces that — but only where it is registered,
5
+ * which today is `packages/utils/src` and `packages/resources/src`. Those two
6
+ * own the seam and every corpus-document read; the rest of the repo is a
7
+ * migration ledger, not a covered claim, and `eslint.config.js` carries it in
8
+ * cost order. Do not read this docstring as "nothing else in the repo decodes".
9
+ *
10
+ * ## Where this lives, and why it is a `utils` primitive
11
+ *
12
+ * Bytes-to-text is a pure function of its argument. It knows nothing about
13
+ * content keys, parse caches or the projection — `readContentWithKey` in
14
+ * `@vibe-agent-toolkit/resources` *composes* this with a raw-bytes content key,
15
+ * and the key is the projection concept, not the decode.
16
+ *
17
+ * It has to live here for a harder reason than tidiness. `resources` depends on
18
+ * `utils` and `utils` must never depend on `resources`, so a seam in `resources`
19
+ * with a lint rule shipped from `utils` would flag `utils`' own reads
20
+ * (`gitignore-checker.ts` reads an adopter's `.gitignore`; `project-utils.ts`
21
+ * reads an adopter's `package.json`) while giving them no legal way to comply.
22
+ * The rule would then be widened with exemptions until it meant nothing. Placing
23
+ * the primitive at the bottom of the arrow is what makes the guardrail
24
+ * enforceable.
25
+ *
26
+ * `./text` is also deliberately **pure** — no `node:*` import at all — so bytes
27
+ * from a git blob, an HTTP body or a zip entry decode through the same function
28
+ * as bytes from disk. The file-reading half is in `./fs` (`readTextContent`),
29
+ * where everything that touches `node:fs` lives.
30
+ *
31
+ * ## The defect this exists for
32
+ *
33
+ * `readContentWithKey` (in `@vibe-agent-toolkit/resources`) used to call
34
+ * `bytes.toString('utf-8')` unconditionally. Measured end to end, on a real
35
+ * `working-tree-encoding=UTF-16` checkout (see `resources`'
36
+ * `test/system/git-hostile-config.system.test.ts`):
37
+ *
38
+ * ```text
39
+ * bytes on disk 40 B, BOM fe ff, UTF-16BE
40
+ * decoded "��# \0D\0o\0c\0…" NUL-interleaved mojibake
41
+ * looksBinary true — the decoded string carries NULs
42
+ * projection BLOB_NOT_TEXT, no blob row, 0 sections, 0 references
43
+ * the same doc 1 heading, 1 link, from its UTF-8 bytes
44
+ * ```
45
+ *
46
+ * So VAT could not read a UTF-16 document *at all*, and the reason it matters is
47
+ * not exotic: **PowerShell 5.1's `Out-File` and `>` write UTF-16LE by default**,
48
+ * so a Windows-authored document lands squarely in that hole.
49
+ *
50
+ * ## What is a fact here, and what is an assumption
51
+ *
52
+ * The distinction is carried in the result ({@link TextProvenance.encodingSource})
53
+ * rather than left to prose, because the two are not the same kind of claim:
54
+ *
55
+ * | input | encoding | encodingSource | why |
56
+ * |---|---|---|---|
57
+ * | leading `ef bb bf` | `utf-8` | `bom` | the bytes say so |
58
+ * | leading `ff fe` (not `ff fe 00 00`) | `utf-16le` | `bom` | the bytes say so |
59
+ * | leading `fe ff` | `utf-16be` | `bom` | the bytes say so |
60
+ * | leading `ff fe 00 00` | `utf-32le` | `bom` | the bytes say so |
61
+ * | leading `00 00 fe ff` | `utf-32be` | `bom` | the bytes say so |
62
+ * | anything else | `utf-8` | `assumed` | the defensible default |
63
+ *
64
+ * ## And what proves the assumption WRONG
65
+ *
66
+ * `encoding` says what was guessed; {@link TextProvenance.replacementCharacters}
67
+ * is what the guess cost. A malformed sequence decodes to U+FFFD instead of
68
+ * throwing, so a mis-decoded document arrives as a well-formed JS string full of
69
+ * garbage — and a byte-level BPE tokenizer has no out-of-vocabulary concept, so
70
+ * it embeds and indexes that garbage without erroring anywhere. Counting the
71
+ * substitutions is what turns "we assumed UTF-8" into "we assumed UTF-8 and were
72
+ * demonstrably wrong 3,200 times in this file".
73
+ *
74
+ * It is counted **without paying for it on the clean path**. Every decode runs
75
+ * first through a `fatal: true` decoder, which throws on the first malformed
76
+ * sequence rather than substituting; a file that decodes cleanly — nearly every
77
+ * file — costs exactly one decode and no scan at all. Only a file that actually
78
+ * threw is decoded a second time in substituting mode and scanned for U+FFFD, so
79
+ * the O(n) scan is charged entirely to broken input.
80
+ *
81
+ * That ordering also buys a correctness property a scan alone cannot have: a
82
+ * document that *legitimately contains* U+FFFD is valid input, so the fatal
83
+ * decoder does not throw and it is reported as **0** replacements rather than
84
+ * accused of a bad decode. A bare scan would count its own content against it.
85
+ *
86
+ * 🪤 **The UTF-32LE BOM starts with the UTF-16LE BOM.** `ff fe 00 00` matches
87
+ * `ff fe`, so a table tested shortest-first decodes every UTF-32LE document as
88
+ * NUL-interleaved UTF-16 — the same bug this module exists to fix, one encoding
89
+ * further down. {@link BOMS} is therefore ordered longest-first and the test
90
+ * suite pins that ordering directly.
91
+ *
92
+ * ## The two limitations, recorded rather than guessed around
93
+ *
94
+ * - **BOM-less UTF-16 is not detected.** It is undecidable from bytes alone: the
95
+ * same byte string is a legal, different UTF-8 document. A NUL-density
96
+ * heuristic would decide it *usually* correctly and silently wrongly the rest
97
+ * of the time, and "silently wrongly" is the failure class this whole module
98
+ * is a reaction to. BOM-less input is UTF-8.
99
+ * - **Latin charsets are not detected either, and there is no windows-1252
100
+ * fallback.** "These bytes are not valid UTF-8" is a fact; "therefore they are
101
+ * latin-1" is a guess, and it is equally consistent with a UTF-8 document
102
+ * carrying one corrupt byte. Malformed input gets U+FFFD. In practice the
103
+ * Latin family costs little: every ASCII byte string is valid UTF-8 and
104
+ * decodes correctly, so only high bytes are affected.
105
+ *
106
+ * Both are pinned as tests that state what is given up, so adding a heuristic
107
+ * later has to edit an assertion rather than quietly widen a claim.
108
+ *
109
+ * ## Why `TextDecoder` for three encodings and hand-rolled code for two
110
+ *
111
+ * `TextDecoder` implements the WHATWG Encoding Standard, which **deliberately
112
+ * omits UTF-32** — no engine offers it. Node's `Buffer` is narrower still:
113
+ * `utf8`, `utf16le`/`ucs2`, `latin1`, `ascii` and the binary-to-text codecs, with
114
+ * **no UTF-16BE at all** (the encoding a round trip through git's
115
+ * `working-tree-encoding=UTF-16` actually produces). So `TextDecoder` carries
116
+ * utf-8/utf-16le/utf-16be, and UTF-32 is converted here.
117
+ *
118
+ * Refusing UTF-32 loudly was the alternative, and it was rejected for one
119
+ * reason: the BOM has to be *recognised* regardless (see the trap above), so the
120
+ * choice was never "detect it or not" — only "having detected it, decode it or
121
+ * throw". Decoding is ~20 lines and leaves no hole.
122
+ *
123
+ * ## The BOM is stripped, and that is load-bearing in both directions
124
+ *
125
+ * A surviving leading U+FEFF stops `# Heading` from parsing as a heading. And
126
+ * every offset downstream is a **character** offset over this decoded string —
127
+ * `lineStartOffsets` in `resources`' `projection/blob-sections.ts` derives them
128
+ * from `content.split('\n')`, and `parseMarkdownContent` takes remark's own
129
+ * character positions — so stripping shifts all of them consistently. What must
130
+ * NOT shift is the content key, which is computed over the raw bytes; see
131
+ * `resources`' `content-key.ts`.
132
+ */
133
+ /** An encoding this module can decode. */
134
+ export type TextEncoding = 'utf-8' | 'utf-16le' | 'utf-16be' | 'utf-32le' | 'utf-32be';
135
+ /**
136
+ * How the encoding was arrived at.
137
+ *
138
+ * `'bom'` is a fact about the bytes. `'assumed'` is a default, and the honest
139
+ * name for it: BOM-less UTF-16 and BOM-less latin-1 both land here and both
140
+ * decode as UTF-8.
141
+ */
142
+ export type EncodingSource = 'bom' | 'assumed';
143
+ /**
144
+ * Everything the decode knew, guessed, and lost — the text itself excluded.
145
+ *
146
+ * Split out from {@link DecodedText} so a consumer that must carry the decode's
147
+ * provenance alongside *other* facts about the same bytes — `KeyedContent` in
148
+ * `@vibe-agent-toolkit/resources` carries it beside a content key and a byte
149
+ * length — can hold exactly these three fields without also re-holding the
150
+ * content, and without restating them one by one at every layer they cross.
151
+ */
152
+ export interface TextProvenance {
153
+ /** The encoding used. */
154
+ readonly encoding: TextEncoding;
155
+ /** Whether {@link encoding} was read off a BOM or assumed. */
156
+ readonly encodingSource: EncodingSource;
157
+ /**
158
+ * How many U+FFFD REPLACEMENT CHARACTERs the decode produced.
159
+ *
160
+ * Zero for a document that decodes cleanly, **including one whose own content
161
+ * legitimately contains U+FFFD** — see the module docstring for why the
162
+ * fatal-first ordering is what makes those two cases distinguishable. A
163
+ * non-zero value is proof, not suspicion: these bytes are not valid in the
164
+ * encoding they were read as.
165
+ */
166
+ readonly replacementCharacters: number;
167
+ }
168
+ /** Text decoded from bytes, and what it was decoded as. */
169
+ export interface DecodedText extends TextProvenance {
170
+ /** The decoded content, BOM removed, exactly as a parser should receive it. */
171
+ readonly text: string;
172
+ }
173
+ /**
174
+ * **The canonical content-decoding seam.** Turn file bytes into the text a
175
+ * parser should see.
176
+ *
177
+ * Takes bytes rather than a path so that a caller which must also key, hash or
178
+ * measure the raw bytes reads the file exactly once — `readContentWithKey` in
179
+ * `@vibe-agent-toolkit/resources` is that caller, and its key must stay over the
180
+ * raw byte preimage whatever this function decides the characters are. For the
181
+ * ordinary "read a file, give me its text" case use `readTextContent` from
182
+ * `@vibe-agent-toolkit/utils/fs`.
183
+ *
184
+ * @param bytes - The exact bytes read from disk
185
+ * @returns The decoded text, the encoding used, whether that was a fact, and how
186
+ * many characters the decode had to replace
187
+ *
188
+ * @example
189
+ * ```typescript
190
+ * const bytes = await readFile(path);
191
+ * const { text, encoding, encodingSource, replacementCharacters } = decodeTextContent(bytes);
192
+ * // UTF-16BE file: encoding 'utf-16be', encodingSource 'bom', 0 replacements,
193
+ * // text with no BOM and no NULs
194
+ * ```
195
+ */
196
+ export declare function decodeTextContent(bytes: Uint8Array): DecodedText;
197
+ //# sourceMappingURL=text-content.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text-content.d.ts","sourceRoot":"","sources":["../src/text-content.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmIG;AAEH,0CAA0C;AAC1C,MAAM,MAAM,YAAY,GAAG,OAAO,GAAG,UAAU,GAAG,UAAU,GAAG,UAAU,GAAG,UAAU,CAAC;AAEvF;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG,KAAK,GAAG,SAAS,CAAC;AAE/C;;;;;;;;GAQG;AACH,MAAM,WAAW,cAAc;IAC7B,yBAAyB;IACzB,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;IAChC,8DAA8D;IAC9D,QAAQ,CAAC,cAAc,EAAE,cAAc,CAAC;IACxC;;;;;;;;OAQG;IACH,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC;CACxC;AAED,2DAA2D;AAC3D,MAAM,WAAW,WAAY,SAAQ,cAAc;IACjD,+EAA+E;IAC/E,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACvB;AAkLD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,UAAU,GAAG,WAAW,CA4BhE"}
@@ -0,0 +1,348 @@
1
+ /**
2
+ * **The one way VAT turns file bytes into text.**
3
+ *
4
+ * `local/no-raw-text-decode` enforces that — but only where it is registered,
5
+ * which today is `packages/utils/src` and `packages/resources/src`. Those two
6
+ * own the seam and every corpus-document read; the rest of the repo is a
7
+ * migration ledger, not a covered claim, and `eslint.config.js` carries it in
8
+ * cost order. Do not read this docstring as "nothing else in the repo decodes".
9
+ *
10
+ * ## Where this lives, and why it is a `utils` primitive
11
+ *
12
+ * Bytes-to-text is a pure function of its argument. It knows nothing about
13
+ * content keys, parse caches or the projection — `readContentWithKey` in
14
+ * `@vibe-agent-toolkit/resources` *composes* this with a raw-bytes content key,
15
+ * and the key is the projection concept, not the decode.
16
+ *
17
+ * It has to live here for a harder reason than tidiness. `resources` depends on
18
+ * `utils` and `utils` must never depend on `resources`, so a seam in `resources`
19
+ * with a lint rule shipped from `utils` would flag `utils`' own reads
20
+ * (`gitignore-checker.ts` reads an adopter's `.gitignore`; `project-utils.ts`
21
+ * reads an adopter's `package.json`) while giving them no legal way to comply.
22
+ * The rule would then be widened with exemptions until it meant nothing. Placing
23
+ * the primitive at the bottom of the arrow is what makes the guardrail
24
+ * enforceable.
25
+ *
26
+ * `./text` is also deliberately **pure** — no `node:*` import at all — so bytes
27
+ * from a git blob, an HTTP body or a zip entry decode through the same function
28
+ * as bytes from disk. The file-reading half is in `./fs` (`readTextContent`),
29
+ * where everything that touches `node:fs` lives.
30
+ *
31
+ * ## The defect this exists for
32
+ *
33
+ * `readContentWithKey` (in `@vibe-agent-toolkit/resources`) used to call
34
+ * `bytes.toString('utf-8')` unconditionally. Measured end to end, on a real
35
+ * `working-tree-encoding=UTF-16` checkout (see `resources`'
36
+ * `test/system/git-hostile-config.system.test.ts`):
37
+ *
38
+ * ```text
39
+ * bytes on disk 40 B, BOM fe ff, UTF-16BE
40
+ * decoded "��# \0D\0o\0c\0…" NUL-interleaved mojibake
41
+ * looksBinary true — the decoded string carries NULs
42
+ * projection BLOB_NOT_TEXT, no blob row, 0 sections, 0 references
43
+ * the same doc 1 heading, 1 link, from its UTF-8 bytes
44
+ * ```
45
+ *
46
+ * So VAT could not read a UTF-16 document *at all*, and the reason it matters is
47
+ * not exotic: **PowerShell 5.1's `Out-File` and `>` write UTF-16LE by default**,
48
+ * so a Windows-authored document lands squarely in that hole.
49
+ *
50
+ * ## What is a fact here, and what is an assumption
51
+ *
52
+ * The distinction is carried in the result ({@link TextProvenance.encodingSource})
53
+ * rather than left to prose, because the two are not the same kind of claim:
54
+ *
55
+ * | input | encoding | encodingSource | why |
56
+ * |---|---|---|---|
57
+ * | leading `ef bb bf` | `utf-8` | `bom` | the bytes say so |
58
+ * | leading `ff fe` (not `ff fe 00 00`) | `utf-16le` | `bom` | the bytes say so |
59
+ * | leading `fe ff` | `utf-16be` | `bom` | the bytes say so |
60
+ * | leading `ff fe 00 00` | `utf-32le` | `bom` | the bytes say so |
61
+ * | leading `00 00 fe ff` | `utf-32be` | `bom` | the bytes say so |
62
+ * | anything else | `utf-8` | `assumed` | the defensible default |
63
+ *
64
+ * ## And what proves the assumption WRONG
65
+ *
66
+ * `encoding` says what was guessed; {@link TextProvenance.replacementCharacters}
67
+ * is what the guess cost. A malformed sequence decodes to U+FFFD instead of
68
+ * throwing, so a mis-decoded document arrives as a well-formed JS string full of
69
+ * garbage — and a byte-level BPE tokenizer has no out-of-vocabulary concept, so
70
+ * it embeds and indexes that garbage without erroring anywhere. Counting the
71
+ * substitutions is what turns "we assumed UTF-8" into "we assumed UTF-8 and were
72
+ * demonstrably wrong 3,200 times in this file".
73
+ *
74
+ * It is counted **without paying for it on the clean path**. Every decode runs
75
+ * first through a `fatal: true` decoder, which throws on the first malformed
76
+ * sequence rather than substituting; a file that decodes cleanly — nearly every
77
+ * file — costs exactly one decode and no scan at all. Only a file that actually
78
+ * threw is decoded a second time in substituting mode and scanned for U+FFFD, so
79
+ * the O(n) scan is charged entirely to broken input.
80
+ *
81
+ * That ordering also buys a correctness property a scan alone cannot have: a
82
+ * document that *legitimately contains* U+FFFD is valid input, so the fatal
83
+ * decoder does not throw and it is reported as **0** replacements rather than
84
+ * accused of a bad decode. A bare scan would count its own content against it.
85
+ *
86
+ * 🪤 **The UTF-32LE BOM starts with the UTF-16LE BOM.** `ff fe 00 00` matches
87
+ * `ff fe`, so a table tested shortest-first decodes every UTF-32LE document as
88
+ * NUL-interleaved UTF-16 — the same bug this module exists to fix, one encoding
89
+ * further down. {@link BOMS} is therefore ordered longest-first and the test
90
+ * suite pins that ordering directly.
91
+ *
92
+ * ## The two limitations, recorded rather than guessed around
93
+ *
94
+ * - **BOM-less UTF-16 is not detected.** It is undecidable from bytes alone: the
95
+ * same byte string is a legal, different UTF-8 document. A NUL-density
96
+ * heuristic would decide it *usually* correctly and silently wrongly the rest
97
+ * of the time, and "silently wrongly" is the failure class this whole module
98
+ * is a reaction to. BOM-less input is UTF-8.
99
+ * - **Latin charsets are not detected either, and there is no windows-1252
100
+ * fallback.** "These bytes are not valid UTF-8" is a fact; "therefore they are
101
+ * latin-1" is a guess, and it is equally consistent with a UTF-8 document
102
+ * carrying one corrupt byte. Malformed input gets U+FFFD. In practice the
103
+ * Latin family costs little: every ASCII byte string is valid UTF-8 and
104
+ * decodes correctly, so only high bytes are affected.
105
+ *
106
+ * Both are pinned as tests that state what is given up, so adding a heuristic
107
+ * later has to edit an assertion rather than quietly widen a claim.
108
+ *
109
+ * ## Why `TextDecoder` for three encodings and hand-rolled code for two
110
+ *
111
+ * `TextDecoder` implements the WHATWG Encoding Standard, which **deliberately
112
+ * omits UTF-32** — no engine offers it. Node's `Buffer` is narrower still:
113
+ * `utf8`, `utf16le`/`ucs2`, `latin1`, `ascii` and the binary-to-text codecs, with
114
+ * **no UTF-16BE at all** (the encoding a round trip through git's
115
+ * `working-tree-encoding=UTF-16` actually produces). So `TextDecoder` carries
116
+ * utf-8/utf-16le/utf-16be, and UTF-32 is converted here.
117
+ *
118
+ * Refusing UTF-32 loudly was the alternative, and it was rejected for one
119
+ * reason: the BOM has to be *recognised* regardless (see the trap above), so the
120
+ * choice was never "detect it or not" — only "having detected it, decode it or
121
+ * throw". Decoding is ~20 lines and leaves no hole.
122
+ *
123
+ * ## The BOM is stripped, and that is load-bearing in both directions
124
+ *
125
+ * A surviving leading U+FEFF stops `# Heading` from parsing as a heading. And
126
+ * every offset downstream is a **character** offset over this decoded string —
127
+ * `lineStartOffsets` in `resources`' `projection/blob-sections.ts` derives them
128
+ * from `content.split('\n')`, and `parseMarkdownContent` takes remark's own
129
+ * character positions — so stripping shifts all of them consistently. What must
130
+ * NOT shift is the content key, which is computed over the raw bytes; see
131
+ * `resources`' `content-key.ts`.
132
+ */
133
+ /**
134
+ * Byte-order marks, **longest first**.
135
+ *
136
+ * The ordering is the correctness property, not a formatting choice — see the
137
+ * module docstring's trap. Frozen so a caller cannot reorder it in place.
138
+ */
139
+ const BOMS = Object.freeze([
140
+ { bytes: [0xff, 0xfe, 0x00, 0x00], encoding: 'utf-32le' },
141
+ { bytes: [0x00, 0x00, 0xfe, 0xff], encoding: 'utf-32be' },
142
+ { bytes: [0xef, 0xbb, 0xbf], encoding: 'utf-8' },
143
+ { bytes: [0xff, 0xfe], encoding: 'utf-16le' },
144
+ { bytes: [0xfe, 0xff], encoding: 'utf-16be' },
145
+ ]);
146
+ /**
147
+ * One `TextDecoder` per encoding, built once.
148
+ *
149
+ * Constructing a decoder per call is measurable on a corpus of thousands of
150
+ * files, and these are stateless when `stream: false` (the default for
151
+ * `decode()`), so one instance is safe to share.
152
+ *
153
+ * `ignoreBOM: true` on purpose: this module has already removed the BOM by the
154
+ * time a decoder sees the bytes, and leaving the option at its default would put
155
+ * a second, silent BOM-stripping step behind the deliberate one — so a document
156
+ * whose *content* legitimately begins with U+FEFF would lose a character that
157
+ * nothing here decided to remove.
158
+ */
159
+ const DECODERS = new Map([
160
+ // No `eslint-disable` needed: this file is the `exemptFiles` entry for
161
+ // `local/no-raw-text-decode` in the repo's `eslint.config.js`. If the rule
162
+ // starts firing here, that entry has drifted from this path.
163
+ ['utf-8', new TextDecoder('utf-8', { ignoreBOM: true })],
164
+ ['utf-16le', new TextDecoder('utf-16le', { ignoreBOM: true })],
165
+ ['utf-16be', new TextDecoder('utf-16be', { ignoreBOM: true })],
166
+ ]);
167
+ /**
168
+ * The same three encodings in **fatal** mode — throw rather than substitute.
169
+ *
170
+ * This is the whole cost model for {@link TextProvenance.replacementCharacters}.
171
+ * A substituting decoder cannot tell a caller whether it substituted, so the only
172
+ * other way to know is to scan every decoded string for U+FFFD — an O(n) pass
173
+ * over every file in a corpus to learn that almost none of them needed it. A
174
+ * fatal decoder answers the same question by *not throwing*, at no extra cost on
175
+ * the clean path, and the expensive route is taken only where there is genuinely
176
+ * something to count.
177
+ *
178
+ * Same `ignoreBOM: true` as their substituting twins, for the same reason: the
179
+ * BOM is already gone by the time either sees the bytes.
180
+ */
181
+ const FATAL_DECODERS = new Map([
182
+ ['utf-8', new TextDecoder('utf-8', { ignoreBOM: true, fatal: true })],
183
+ ['utf-16le', new TextDecoder('utf-16le', { ignoreBOM: true, fatal: true })],
184
+ ['utf-16be', new TextDecoder('utf-16be', { ignoreBOM: true, fatal: true })],
185
+ ]);
186
+ /** How many code points to spread into one `String.fromCodePoint` call. */
187
+ const CODE_POINT_CHUNK = 4096;
188
+ /** The last Unicode code point. */
189
+ const MAX_CODE_POINT = 0x10_ff_ff;
190
+ /** First and last UTF-16 surrogate — never a scalar value on their own. */
191
+ const SURROGATE_FIRST = 0xd8_00;
192
+ const SURROGATE_LAST = 0xdf_ff;
193
+ /** U+FFFD REPLACEMENT CHARACTER, what a malformed unit becomes. */
194
+ const REPLACEMENT_CODE_POINT = 0xff_fd;
195
+ /** Does `bytes` begin with `prefix`? */
196
+ function startsWith(bytes, prefix) {
197
+ if (bytes.length < prefix.length)
198
+ return false;
199
+ return prefix.every((byte, index) => bytes[index] === byte);
200
+ }
201
+ /**
202
+ * The encoding a BOM announces, and how many bytes it occupies.
203
+ *
204
+ * @param bytes - Raw bytes, from the start of the file
205
+ * @returns The BOM's encoding and length, or `null` when there is no BOM
206
+ */
207
+ function bomAt(bytes) {
208
+ for (const bom of BOMS) {
209
+ if (startsWith(bytes, bom.bytes)) {
210
+ return { encoding: bom.encoding, length: bom.bytes.length };
211
+ }
212
+ }
213
+ return null;
214
+ }
215
+ /**
216
+ * Is `codePoint` something `String.fromCodePoint` will accept?
217
+ *
218
+ * A lone surrogate and anything past U+10FFFF both throw, and a corrupt document
219
+ * must not surface as an exception out of a decoder.
220
+ */
221
+ function isScalarValue(codePoint) {
222
+ if (codePoint > MAX_CODE_POINT)
223
+ return false;
224
+ return codePoint < SURROGATE_FIRST || codePoint > SURROGATE_LAST;
225
+ }
226
+ /**
227
+ * Build a string from code points, in chunks.
228
+ *
229
+ * `String.fromCodePoint(...points)` blows the engine's argument limit somewhere
230
+ * in the tens of thousands, which a real document reaches — so the spread is
231
+ * bounded rather than whole-array.
232
+ */
233
+ function fromCodePoints(points) {
234
+ if (points.length <= CODE_POINT_CHUNK)
235
+ return String.fromCodePoint(...points);
236
+ const parts = [];
237
+ for (let start = 0; start < points.length; start += CODE_POINT_CHUNK) {
238
+ parts.push(String.fromCodePoint(...points.slice(start, start + CODE_POINT_CHUNK)));
239
+ }
240
+ return parts.join('');
241
+ }
242
+ /**
243
+ * Decode UTF-32, by hand, because no engine does.
244
+ *
245
+ * Every 4-byte unit that is not a Unicode scalar value becomes U+FFFD, as does a
246
+ * trailing run of 1–3 bytes that cannot form a unit. That mirrors what
247
+ * `TextDecoder` does with malformed input, so the two paths fail the same way.
248
+ *
249
+ * There is no fatal-first pass here and none is needed: this loop *decides* each
250
+ * substitution, so it can count them as it makes them — free, and exact. The
251
+ * fatal-decoder trick exists only because `TextDecoder` refuses to say.
252
+ *
253
+ * @param bytes - The content bytes, BOM already removed
254
+ * @param littleEndian - Byte order the BOM announced
255
+ * @returns The decoded string and how many units were replaced
256
+ */
257
+ function decodeUtf32(bytes, littleEndian) {
258
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
259
+ const whole = bytes.byteLength - (bytes.byteLength % 4);
260
+ const points = [];
261
+ let replacementCharacters = 0;
262
+ for (let offset = 0; offset < whole; offset += 4) {
263
+ const codePoint = view.getUint32(offset, littleEndian);
264
+ if (isScalarValue(codePoint)) {
265
+ points.push(codePoint);
266
+ }
267
+ else {
268
+ points.push(REPLACEMENT_CODE_POINT);
269
+ replacementCharacters += 1;
270
+ }
271
+ }
272
+ if (whole !== bytes.byteLength) {
273
+ points.push(REPLACEMENT_CODE_POINT);
274
+ replacementCharacters += 1;
275
+ }
276
+ return { text: fromCodePoints(points), replacementCharacters };
277
+ }
278
+ /**
279
+ * Count the U+FFFD in a string that a fatal decode already refused.
280
+ *
281
+ * Only ever called on input known to be malformed, which is what keeps the O(n)
282
+ * scan off the common path. A scan rather than a regex or a split: it allocates
283
+ * nothing on a string that may be megabytes long. U+FFFD is a BMP character, so
284
+ * the comparison is exact whether the index lands on it or on a surrogate half.
285
+ *
286
+ * @param text - The substituting decoder's output
287
+ * @returns How many replacement characters it contains
288
+ */
289
+ function countReplacementCharacters(text) {
290
+ let count = 0;
291
+ for (let index = 0; index < text.length; index += 1) {
292
+ if (text.codePointAt(index) === REPLACEMENT_CODE_POINT)
293
+ count += 1;
294
+ }
295
+ return count;
296
+ }
297
+ /**
298
+ * **The canonical content-decoding seam.** Turn file bytes into the text a
299
+ * parser should see.
300
+ *
301
+ * Takes bytes rather than a path so that a caller which must also key, hash or
302
+ * measure the raw bytes reads the file exactly once — `readContentWithKey` in
303
+ * `@vibe-agent-toolkit/resources` is that caller, and its key must stay over the
304
+ * raw byte preimage whatever this function decides the characters are. For the
305
+ * ordinary "read a file, give me its text" case use `readTextContent` from
306
+ * `@vibe-agent-toolkit/utils/fs`.
307
+ *
308
+ * @param bytes - The exact bytes read from disk
309
+ * @returns The decoded text, the encoding used, whether that was a fact, and how
310
+ * many characters the decode had to replace
311
+ *
312
+ * @example
313
+ * ```typescript
314
+ * const bytes = await readFile(path);
315
+ * const { text, encoding, encodingSource, replacementCharacters } = decodeTextContent(bytes);
316
+ * // UTF-16BE file: encoding 'utf-16be', encodingSource 'bom', 0 replacements,
317
+ * // text with no BOM and no NULs
318
+ * ```
319
+ */
320
+ export function decodeTextContent(bytes) {
321
+ const bom = bomAt(bytes);
322
+ const encoding = bom?.encoding ?? 'utf-8';
323
+ const body = bom === null ? bytes : bytes.subarray(bom.length);
324
+ const encodingSource = bom === null ? 'assumed' : 'bom';
325
+ if (encoding === 'utf-32le' || encoding === 'utf-32be') {
326
+ return { ...decodeUtf32(body, encoding === 'utf-32le'), encoding, encodingSource };
327
+ }
328
+ const decoder = DECODERS.get(encoding);
329
+ const fatalDecoder = FATAL_DECODERS.get(encoding);
330
+ if (decoder === undefined || fatalDecoder === undefined) {
331
+ // Unreachable: BOMS, DECODERS and FATAL_DECODERS cover the same five
332
+ // encodings between them. Thrown rather than defaulted, because a silent fall
333
+ // back to UTF-8 here would reproduce the exact defect this module was written
334
+ // to remove.
335
+ throw new Error(`no decoder for encoding "${encoding}"`);
336
+ }
337
+ try {
338
+ // The clean path, and the only one nearly every file takes: one decode, no
339
+ // scan. A throw here is the ONLY evidence that a substitution happened —
340
+ // see FATAL_DECODERS.
341
+ return { text: fatalDecoder.decode(body), encoding, encodingSource, replacementCharacters: 0 };
342
+ }
343
+ catch {
344
+ const text = decoder.decode(body);
345
+ return { text, encoding, encodingSource, replacementCharacters: countReplacementCharacters(text) };
346
+ }
347
+ }
348
+ //# sourceMappingURL=text-content.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text-content.js","sourceRoot":"","sources":["../src/text-content.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmIG;AA8CH;;;;;GAKG;AACH,MAAM,IAAI,GACR,MAAM,CAAC,MAAM,CAAC;IACZ,EAAE,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE;IACzD,EAAE,KAAK,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IA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C;QACxD,qEAAqE;QACrE,8EAA8E;QAC9E,8EAA8E;QAC9E,aAAa;QACb,MAAM,IAAI,KAAK,CAAC,4BAA4B,QAAQ,GAAG,CAAC,CAAC;IAC3D,CAAC;IAED,IAAI,CAAC;QACH,2EAA2E;QAC3E,yEAAyE;QACzE,sBAAsB;QACtB,OAAO,EAAE,IAAI,EAAE,YAAY,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,cAAc,EAAE,qBAAqB,EAAE,CAAC,EAAE,CAAC;IACjG,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAClC,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,cAAc,EAAE,qBAAqB,EAAE,0BAA0B,CAAC,IAAI,CAAC,EAAE,CAAC;IACrG,CAAC;AACH,CAAC"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Read a file and decode it through the one content-decoding seam.
3
+ *
4
+ * The replacement for `readFile(path, 'utf-8')`, which decodes inside `fs` with
5
+ * no byte-order-mark handling and no way to express UTF-16BE at all. The
6
+ * *decision* about what the bytes say lives in `text-content.ts`, which is pure
7
+ * and reaches no `node:*` module; this file is only the two lines that get the
8
+ * bytes off disk, and it lives on the `./fs` entry with everything else here
9
+ * that touches the filesystem.
10
+ *
11
+ * Two functions rather than one, because the callers genuinely differ: an
12
+ * enumeration or parse lane is asynchronous throughout, while a manifest or
13
+ * config probe on a startup path is not, and handing the latter a Promise makes
14
+ * it worse rather than more consistent.
15
+ *
16
+ * A caller that needs the RAW bytes as well as the text — to hash them, key
17
+ * them, or report `stat().size` — must not use these: read the bytes once itself
18
+ * and call `decodeTextContent` on them, so the digest and the characters come
19
+ * from the same read. `readContentWithKey` in `@vibe-agent-toolkit/resources` is
20
+ * that caller and is shaped exactly that way.
21
+ */
22
+ import { type DecodedText } from './text-content.js';
23
+ /**
24
+ * Read a file and decode it through {@link decodeTextContent}.
25
+ *
26
+ * @param filePath - Path to read
27
+ * @returns The decoded text, the encoding used, whether that was a fact, and the replacement-character count
28
+ * @throws Whatever `readFile` throws — callers decide whether that is fatal
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * const { text, encoding } = await readTextContent(docPath);
33
+ * // A PowerShell-written document: encoding 'utf-16le', text with no BOM
34
+ * ```
35
+ */
36
+ export declare function readTextContent(filePath: string): Promise<DecodedText>;
37
+ /**
38
+ * {@link readTextContent}, synchronously.
39
+ *
40
+ * @param filePath - Path to read
41
+ * @returns The decoded text, the encoding used, whether that was a fact, and the replacement-character count
42
+ * @throws Whatever `readFileSync` throws
43
+ */
44
+ export declare function readTextContentSync(filePath: string): DecodedText;
45
+ //# sourceMappingURL=text-file.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text-file.d.ts","sourceRoot":"","sources":["../src/text-file.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAKH,OAAO,EAAqB,KAAK,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAExE;;;;;;;;;;;;GAYG;AACH,wBAAsB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAG5E;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW,CAGjE"}
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Read a file and decode it through the one content-decoding seam.
3
+ *
4
+ * The replacement for `readFile(path, 'utf-8')`, which decodes inside `fs` with
5
+ * no byte-order-mark handling and no way to express UTF-16BE at all. The
6
+ * *decision* about what the bytes say lives in `text-content.ts`, which is pure
7
+ * and reaches no `node:*` module; this file is only the two lines that get the
8
+ * bytes off disk, and it lives on the `./fs` entry with everything else here
9
+ * that touches the filesystem.
10
+ *
11
+ * Two functions rather than one, because the callers genuinely differ: an
12
+ * enumeration or parse lane is asynchronous throughout, while a manifest or
13
+ * config probe on a startup path is not, and handing the latter a Promise makes
14
+ * it worse rather than more consistent.
15
+ *
16
+ * A caller that needs the RAW bytes as well as the text — to hash them, key
17
+ * them, or report `stat().size` — must not use these: read the bytes once itself
18
+ * and call `decodeTextContent` on them, so the digest and the characters come
19
+ * from the same read. `readContentWithKey` in `@vibe-agent-toolkit/resources` is
20
+ * that caller and is shaped exactly that way.
21
+ */
22
+ import { readFileSync } from 'node:fs';
23
+ import { readFile } from 'node:fs/promises';
24
+ import { decodeTextContent } from './text-content.js';
25
+ /**
26
+ * Read a file and decode it through {@link decodeTextContent}.
27
+ *
28
+ * @param filePath - Path to read
29
+ * @returns The decoded text, the encoding used, whether that was a fact, and the replacement-character count
30
+ * @throws Whatever `readFile` throws — callers decide whether that is fatal
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * const { text, encoding } = await readTextContent(docPath);
35
+ * // A PowerShell-written document: encoding 'utf-16le', text with no BOM
36
+ * ```
37
+ */
38
+ export async function readTextContent(filePath) {
39
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- caller-supplied path, same trust level as the parsers this feeds
40
+ return decodeTextContent(await readFile(filePath));
41
+ }
42
+ /**
43
+ * {@link readTextContent}, synchronously.
44
+ *
45
+ * @param filePath - Path to read
46
+ * @returns The decoded text, the encoding used, whether that was a fact, and the replacement-character count
47
+ * @throws Whatever `readFileSync` throws
48
+ */
49
+ export function readTextContentSync(filePath) {
50
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- caller-supplied path, same trust level as the parsers this feeds
51
+ return decodeTextContent(readFileSync(filePath));
52
+ }
53
+ //# sourceMappingURL=text-file.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"text-file.js","sourceRoot":"","sources":["../src/text-file.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C,OAAO,EAAE,iBAAiB,EAAoB,MAAM,mBAAmB,CAAC;AAExE;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,QAAgB;IACpD,uIAAuI;IACvI,OAAO,iBAAiB,CAAC,MAAM,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC;AACrD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,mBAAmB,CAAC,QAAgB;IAClD,uIAAuI;IACvI,OAAO,iBAAiB,CAAC,YAAY,CAAC,QAAQ,CAAC,CAAC,CAAC;AACnD,CAAC"}