pi-charset 0.1.6 → 0.1.7

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 (42) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/CHANGELOG.zh-CN.md +18 -0
  3. package/dist/config.js +943 -0
  4. package/dist/edit/apply-patch-core.js +274 -0
  5. package/dist/edit/diagnostics.js +46 -0
  6. package/dist/edit/hashline.js +400 -0
  7. package/dist/edit/patch.js +634 -0
  8. package/dist/edit/paths.js +48 -0
  9. package/dist/edit/plan.js +90 -0
  10. package/dist/encoding/classify.js +430 -0
  11. package/dist/encoding/common-scripts.js +58 -0
  12. package/dist/encoding/converter.js +311 -0
  13. package/dist/encoding/fast-codec.js +476 -0
  14. package/dist/encoding/file-stamp.js +32 -0
  15. package/dist/encoding/line-endings.js +118 -0
  16. package/dist/encoding/mime.js +88 -0
  17. package/dist/encoding/stream-transcode.js +287 -0
  18. package/dist/grep-core.js +730 -0
  19. package/dist/journal.js +494 -0
  20. package/dist/maintenance.js +333 -0
  21. package/dist/mcp/server.js +866 -0
  22. package/dist/notify.js +60 -0
  23. package/dist/operations.js +1021 -0
  24. package/dist/path-key.js +10 -0
  25. package/dist/read-view.js +927 -0
  26. package/dist/resolve.js +325 -0
  27. package/dist/version.js +2 -0
  28. package/docs/MCP-AND-MULTI-AGENT.md +27 -19
  29. package/docs/zh-CN/MCP-AND-MULTI-AGENT.md +27 -19
  30. package/package.json +14 -2
  31. package/src/edit/apply-patch-core.ts +32 -3
  32. package/src/grep-core.ts +50 -8
  33. package/src/grep.ts +9 -1
  34. package/src/index.ts +8 -5
  35. package/src/journal.ts +167 -42
  36. package/src/mcp/server.ts +435 -163
  37. package/src/operations.ts +197 -68
  38. package/src/read-view.ts +111 -8
  39. package/src/shell-guard.ts +38 -1
  40. package/src/version.ts +1 -1
  41. package/tools/pi-charset-cli.mjs +453 -167
  42. package/tools/pi-charset-mcp.mjs +78 -41
package/dist/config.js ADDED
@@ -0,0 +1,943 @@
1
+ // Configuration loader, validator, and zero-config sibling inference (.pi-charset.json).
2
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
3
+ import { readdir, readFile, stat } from "node:fs/promises";
4
+ import * as os from "node:os";
5
+ import * as path from "node:path";
6
+ import micromatch from "micromatch";
7
+ import { normalizePathKey } from "./path-key.js";
8
+ import { isGBEncoding, isSingleByteEncoding, isStatefulEncoding, isSupportedEncoding, normalizeEncoding, } from "./encoding/converter.js";
9
+ import { classifyBuffer, decideFamilyFromBuffers, DEFAULT_AUTO_CANDIDATES, exactRoundTrip, familyOf, preferFamily, quickKind } from "./encoding/classify.js";
10
+ import { fileStampKey, sameFileStamp, stampFromStat } from "./encoding/file-stamp.js";
11
+ import { detectLineEndingKind } from "./encoding/line-endings.js";
12
+ export const CONFIG_FILENAME = ".pi-charset.json";
13
+ function resolveConfigPathSync(dir) {
14
+ const p = path.join(dir, CONFIG_FILENAME);
15
+ try {
16
+ return { path: p, stamp: stampFromStat(statSync(p)) };
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ }
22
+ async function resolveConfigPath(dir) {
23
+ const p = path.join(dir, CONFIG_FILENAME);
24
+ try {
25
+ return { path: p, stamp: stampFromStat(await stat(p)) };
26
+ }
27
+ catch {
28
+ return null;
29
+ }
30
+ }
31
+ /** Resolve active diagnostic/UI locale ("en" or "zh-CN"). Defaults to "zh-CN" unless configured or PI_CHARSET_LOCALE=en. */
32
+ export function resolveLocale(locale) {
33
+ if (locale === "en" || locale === "zh-CN")
34
+ return locale;
35
+ const env = (process.env.PI_CHARSET_LOCALE ?? "").trim().toLowerCase();
36
+ if (env === "en" || env.startsWith("en-") || env.startsWith("en_"))
37
+ return "en";
38
+ if (env === "zh" || env.startsWith("zh-") || env.startsWith("zh_"))
39
+ return "zh-CN";
40
+ return "zh-CN";
41
+ }
42
+ function normalizeNewFileLineEnding(raw, where, warnings) {
43
+ if (raw === undefined)
44
+ return undefined;
45
+ if (raw === "CRLF" || raw === "LF")
46
+ return raw;
47
+ warnings.push(`${where}: newFileLineEnding 只接受 "CRLF"/"LF",收到 ${JSON.stringify(raw)},已忽略`);
48
+ return undefined;
49
+ }
50
+ const DEFAULTS = {
51
+ sourceEncoding: "GB18030",
52
+ readStrategy: "auto",
53
+ unmappable: "error",
54
+ verifyWrite: true,
55
+ protectUtf8: true,
56
+ autoCandidates: [...DEFAULT_AUTO_CANDIDATES],
57
+ transcodeBash: false,
58
+ bashFileDump: true,
59
+ autoCommit: false,
60
+ hashlines: false,
61
+ shellGuard: "block",
62
+ };
63
+ const NARROW_CJK_ORDER = ["GBK", "Big5", "Shift_JIS", "EUC-KR", "EUC-JP", "GB18030"];
64
+ const BINARY_SKIP_EXT = new Set([
65
+ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".ico", ".pdf",
66
+ ".zip", ".gz", ".7z", ".rar", ".jar", ".war", ".class", ".exe", ".dll", ".so", ".bin", ".o", ".obj", ".axf", ".elf",
67
+ ]);
68
+ const dirCache = new Map();
69
+ const MAX_DIR_CACHE = 2000;
70
+ let _configGen = 0;
71
+ function setDirCache(key, value) {
72
+ const prev = dirCache.get(key);
73
+ const changed = prev !== undefined &&
74
+ ((prev === null) !== (value === null) ||
75
+ (prev !== null && value !== null && (prev.configPath !== value.configPath || !sameFileStamp(prev.stamp, value.stamp))));
76
+ if (dirCache.size >= MAX_DIR_CACHE && !dirCache.has(key))
77
+ dirCache.clear();
78
+ dirCache.set(key, value);
79
+ if (changed) {
80
+ siblingInference.clear();
81
+ _configGen++;
82
+ }
83
+ }
84
+ let runtimeDefaults = null;
85
+ /**
86
+ * Configure process-level defaults (used by `pi-charset-mcp` CLI flags and `PI_CHARSET_*` env vars)
87
+ * so users can run or pin encoding policies with zero `.pi-charset.json` files on disk.
88
+ */
89
+ export function setRuntimeDefaults(defaults) {
90
+ if (!defaults || Object.values(defaults).every((v) => v === undefined)) {
91
+ runtimeDefaults = null;
92
+ }
93
+ else {
94
+ const clean = {};
95
+ if (defaults.sourceEncoding)
96
+ clean.sourceEncoding = normalizeEncoding(defaults.sourceEncoding);
97
+ if (defaults.writeEncoding)
98
+ clean.writeEncoding = normalizeEncoding(defaults.writeEncoding);
99
+ if (defaults.newFileLineEnding === "CRLF" || defaults.newFileLineEnding === "LF") {
100
+ clean.newFileLineEnding = defaults.newFileLineEnding;
101
+ }
102
+ if (typeof defaults.preferSourceOverUtf8 === "boolean")
103
+ clean.preferSourceOverUtf8 = defaults.preferSourceOverUtf8;
104
+ if (typeof defaults.protectUtf8 === "boolean")
105
+ clean.protectUtf8 = defaults.protectUtf8;
106
+ if (defaults.unmappable === "error" || defaults.unmappable === "escape" || defaults.unmappable === "drop-to-gb18030") {
107
+ clean.unmappable = defaults.unmappable;
108
+ }
109
+ if (typeof defaults.hashlines === "boolean")
110
+ clean.hashlines = defaults.hashlines;
111
+ if (typeof defaults.autoCommit === "boolean")
112
+ clean.autoCommit = defaults.autoCommit;
113
+ if (defaults.locale === "auto" || defaults.locale === "en" || defaults.locale === "zh-CN") {
114
+ clean.locale = defaults.locale;
115
+ }
116
+ runtimeDefaults = Object.keys(clean).length > 0 ? clean : null;
117
+ }
118
+ _configGen++;
119
+ }
120
+ export function getRuntimeDefaults() {
121
+ return runtimeDefaults;
122
+ }
123
+ function runtimeFoundConfig(startDir) {
124
+ if (!runtimeDefaults?.sourceEncoding)
125
+ return null;
126
+ const config = {
127
+ ...DEFAULTS,
128
+ sourceEncoding: runtimeDefaults.sourceEncoding,
129
+ ...(runtimeDefaults.writeEncoding ? { writeEncoding: runtimeDefaults.writeEncoding } : { writeEncoding: runtimeDefaults.sourceEncoding }),
130
+ ...(runtimeDefaults.newFileLineEnding ? { newFileLineEnding: runtimeDefaults.newFileLineEnding } : {}),
131
+ ...(runtimeDefaults.preferSourceOverUtf8 !== undefined ? { preferSourceOverUtf8: runtimeDefaults.preferSourceOverUtf8 } : {}),
132
+ ...(runtimeDefaults.protectUtf8 !== undefined ? { protectUtf8: runtimeDefaults.protectUtf8 } : {}),
133
+ ...(runtimeDefaults.unmappable ? { unmappable: runtimeDefaults.unmappable } : {}),
134
+ ...(runtimeDefaults.hashlines !== undefined ? { hashlines: runtimeDefaults.hashlines } : {}),
135
+ ...(runtimeDefaults.autoCommit !== undefined ? { autoCommit: runtimeDefaults.autoCommit } : {}),
136
+ ...(runtimeDefaults.locale ? { locale: runtimeDefaults.locale } : {}),
137
+ };
138
+ return { config, configDir: path.resolve(startDir), configPath: "(runtime CLI/env flags)", warnings: [] };
139
+ }
140
+ export function configGeneration() {
141
+ return _configGen;
142
+ }
143
+ export function clearConfigCache() {
144
+ dirCache.clear();
145
+ siblingInference.clear();
146
+ projectHintsCache.clear();
147
+ _configGen++;
148
+ }
149
+ /** Invalidate cached zero-config sibling inference for one directory after any file mutation inside it. */
150
+ export function invalidateSiblingInference(dir) {
151
+ const prefix = normalizePathKey(path.resolve(dir)) + "\u0000";
152
+ for (const key of [...siblingInference.keys()]) {
153
+ if (key.startsWith(prefix))
154
+ siblingInference.delete(key);
155
+ }
156
+ }
157
+ /** Pick the narrowest encoding from NARROW_CJK_ORDER that appears in candidates (e.g. GBK over GB18030 when 2-byte clean). */
158
+ export function pickNarrowestCandidate(candidates, fallback = "GB18030") {
159
+ for (const pref of NARROW_CJK_ORDER) {
160
+ if (candidates.includes(pref))
161
+ return pref;
162
+ }
163
+ return candidates[0] ?? fallback;
164
+ }
165
+ function sameExtGroup(extA, extB) {
166
+ if (extA === extB)
167
+ return true;
168
+ const cFamily = new Set([".c", ".h", ".cpp", ".hpp", ".cc", ".hh", ".cxx", ".hxx", ".s", ".asm", ".inc"]);
169
+ return cFamily.has(extA) && cFamily.has(extB);
170
+ }
171
+ // Inference over a directory repeats for every read of an ASCII file and every new-file write, so it is
172
+ // cached per (directory, extension group, target name) and revalidated against the selected siblings'
173
+ // unified FileStamp (dev, ino, size, mtimeMs, ctimeMs).
174
+ const siblingInference = new Map();
175
+ function selectSiblingEntries(entries, targetExt, excludeBase) {
176
+ return entries
177
+ .filter((e) => e.isFile() && e.name !== excludeBase && !e.name.startsWith(".") && !BINARY_SKIP_EXT.has(path.extname(e.name).toLowerCase()))
178
+ .sort((a, b) => {
179
+ const aMatch = sameExtGroup(path.extname(a.name).toLowerCase(), targetExt) ? 0 : 1;
180
+ const bMatch = sameExtGroup(path.extname(b.name).toLowerCase(), targetExt) ? 0 : 1;
181
+ return aMatch - bMatch || a.name.localeCompare(b.name);
182
+ })
183
+ .slice(0, 16);
184
+ }
185
+ function scoreSiblingBuffers(buffers) {
186
+ let cjkCount = 0;
187
+ let utf8Count = 0;
188
+ let crlfCount = 0;
189
+ let lfCount = 0;
190
+ let pending = [];
191
+ let legacyTotal = 0;
192
+ for (const buf of buffers) {
193
+ const quick = quickKind(buf);
194
+ if (quick) {
195
+ if (quick.kind === "binary" || quick.kind === "unknown")
196
+ continue;
197
+ const eol = detectLineEndingKind(buf);
198
+ if (eol === "CRLF")
199
+ crlfCount++;
200
+ else if (eol === "LF")
201
+ lfCount++;
202
+ if (quick.kind === "utf8" || quick.kind === "utf8-bom")
203
+ utf8Count++;
204
+ continue;
205
+ }
206
+ const eol = detectLineEndingKind(buf);
207
+ if (eol === "CRLF")
208
+ crlfCount++;
209
+ else if (eol === "LF")
210
+ lfCount++;
211
+ pending.push(buf);
212
+ legacyTotal++;
213
+ }
214
+ // Candidates outside NARROW_CJK_ORDER still get tested, after the narrow ones, in their default order.
215
+ const candidates = [...NARROW_CJK_ORDER, ...DEFAULT_AUTO_CANDIDATES.filter((c) => !NARROW_CJK_ORDER.includes(c))];
216
+ // Score each sibling from its own first non-ASCII byte without concatenating raw multi-byte buffers.
217
+ const decision = pending.length
218
+ ? decideFamilyFromBuffers(pending, new Set(candidates.map(familyOf)), 4096)
219
+ : { family: null, confident: false };
220
+ const ordered = decision.confident ? preferFamily(candidates, decision.family) : candidates;
221
+ let common = null;
222
+ for (const enc of ordered) {
223
+ if (!pending.length)
224
+ break;
225
+ const remaining = [];
226
+ for (const buf of pending) {
227
+ if (exactRoundTrip(buf, enc))
228
+ common = enc;
229
+ else
230
+ remaining.push(buf);
231
+ }
232
+ pending = remaining;
233
+ }
234
+ // Legacy siblings still pending after every candidate are undecodable and ignored, as before.
235
+ cjkCount = legacyTotal - pending.length;
236
+ const dominantEol = crlfCount > lfCount ? "CRLF" : lfCount > crlfCount ? "LF" : null;
237
+ if (cjkCount === 0 && utf8Count === 0)
238
+ return { encoding: "UTF-8", eol: null, hasSignal: false };
239
+ // Line endings are inherited only from legacy-encoded siblings; UTF-8 trees keep the host default.
240
+ return cjkCount > 0 && cjkCount >= utf8Count
241
+ ? { encoding: common ?? "GB18030", eol: dominantEol, hasSignal: true }
242
+ : { encoding: "UTF-8", eol: null, hasSignal: true };
243
+ }
244
+ function siblingSignature(selected) {
245
+ return selected.map((s) => `${s.name}:${fileStampKey(s.stamp)}`).join("|");
246
+ }
247
+ function storeSiblingInference(cacheKey, signature, result) {
248
+ if (siblingInference.size > 2000)
249
+ siblingInference.clear();
250
+ siblingInference.set(cacheKey, { signature, encoding: result.encoding, eol: result.eol });
251
+ }
252
+ const MAX_PARENT_SIBLING_DEPTH = 3;
253
+ const NORMALIZED_TMPDIR = normalizePathKey(path.resolve(os.tmpdir()));
254
+ function isBoundaryDir(dir) {
255
+ return normalizePathKey(path.resolve(dir)) === NORMALIZED_TMPDIR;
256
+ }
257
+ function hasGitRoot(dir) {
258
+ try {
259
+ return existsSync(path.join(dir, ".git"));
260
+ }
261
+ catch {
262
+ return false;
263
+ }
264
+ }
265
+ const HINT_FILES = [".editorconfig", ".gitattributes", "pom.xml", "CMakeLists.txt"];
266
+ const projectHintsCache = new Map();
267
+ /**
268
+ * Inspect .editorconfig, .gitattributes, pom.xml, and CMakeLists.txt in `dir` for declared encoding/EOL conventions.
269
+ * Stamp-validated cache avoids re-reading or re-parsing unchanged hint files across repeated zero-config lookups.
270
+ */
271
+ export function detectProjectHints(dir) {
272
+ const absDir = path.resolve(dir);
273
+ const key = normalizePathKey(absDir);
274
+ const stamps = HINT_FILES.map((name) => {
275
+ try {
276
+ const st = statSync(path.join(absDir, name));
277
+ return st.isFile() && st.size <= 256 * 1024 ? stampFromStat(st) : null;
278
+ }
279
+ catch {
280
+ return null;
281
+ }
282
+ });
283
+ const sig = stamps.map((s) => (s ? fileStampKey(s) : "-")).join("|");
284
+ const cached = projectHintsCache.get(key);
285
+ if (cached && cached.sig === sig)
286
+ return cached.hints;
287
+ const readHint = (idx) => {
288
+ if (!stamps[idx])
289
+ return null;
290
+ try {
291
+ return readFileSync(path.join(absDir, HINT_FILES[idx]), "utf8");
292
+ }
293
+ catch {
294
+ return null;
295
+ }
296
+ };
297
+ const normSupported = (raw) => {
298
+ if (!raw)
299
+ return undefined;
300
+ const clean = raw.toLowerCase() === "utf-8-bom" ? "UTF-8" : raw;
301
+ return isSupportedEncoding(clean) ? normalizeEncoding(clean) : undefined;
302
+ };
303
+ const hints = [];
304
+ const ec = readHint(0);
305
+ if (ec) {
306
+ const cm = /^\s*charset\s*=\s*([^\s#;]+)/im.exec(ec);
307
+ const em = /^\s*end_of_line\s*=\s*(crlf|lf)\b/im.exec(ec);
308
+ if (cm || em) {
309
+ const rawCharset = cm?.[1]?.trim();
310
+ const encoding = normSupported(rawCharset);
311
+ const lineEnding = em ? em[1].toUpperCase() : undefined;
312
+ hints.push({
313
+ source: ".editorconfig",
314
+ ...(encoding ? { encoding } : {}),
315
+ ...(lineEnding ? { lineEnding } : {}),
316
+ detail: [rawCharset ? `charset=${rawCharset}` : "", lineEnding ? `end_of_line=${lineEnding.toLowerCase()}` : ""].filter(Boolean).join(", "),
317
+ });
318
+ }
319
+ }
320
+ const ga = readHint(1);
321
+ if (ga) {
322
+ const wm = /working-tree-encoding=([^\s#]+)/i.exec(ga);
323
+ const em = /\beol=(crlf|lf)\b/i.exec(ga);
324
+ if (wm || em) {
325
+ const encoding = normSupported(wm?.[1]);
326
+ const lineEnding = em ? em[1].toUpperCase() : undefined;
327
+ hints.push({
328
+ source: ".gitattributes",
329
+ ...(encoding ? { encoding } : {}),
330
+ ...(lineEnding ? { lineEnding } : {}),
331
+ detail: [wm ? `working-tree-encoding=${wm[1]}` : "", em ? `eol=${em[1].toLowerCase()}` : ""].filter(Boolean).join(", "),
332
+ });
333
+ }
334
+ }
335
+ const pom = readHint(2);
336
+ const pm = pom && /<project\.build\.sourceEncoding>\s*([^<\s]+)\s*<\/project\.build\.sourceEncoding>/i.exec(pom);
337
+ if (pm) {
338
+ const encoding = normSupported(pm[1]);
339
+ if (encoding)
340
+ hints.push({ source: "pom.xml", encoding, detail: `project.build.sourceEncoding=${pm[1]}` });
341
+ }
342
+ const cmk = readHint(3);
343
+ const cm = cmk && /(?:\/source-charset:|-finput-charset=)([A-Za-z0-9._-]+)/i.exec(cmk);
344
+ if (cm) {
345
+ const encoding = normSupported(cm[1]);
346
+ if (encoding)
347
+ hints.push({ source: "CMakeLists.txt", encoding, detail: cm[0] });
348
+ }
349
+ if (projectHintsCache.size > MAX_DIR_CACHE)
350
+ projectHintsCache.clear();
351
+ projectHintsCache.set(key, { sig, hints });
352
+ return hints;
353
+ }
354
+ /**
355
+ * Zero-config fallback: inspect existing project declaration files in `dir` and up to 3 parent directories
356
+ * so users never need to duplicate existing team encoding/EOL settings into .pi-charset.json.
357
+ */
358
+ function inferFromProjectFiles(dir) {
359
+ let cur = path.resolve(dir);
360
+ for (let depth = 0; depth <= MAX_PARENT_SIBLING_DEPTH; depth++) {
361
+ if (depth > 0 && isBoundaryDir(cur))
362
+ break;
363
+ let enc = null;
364
+ let eol = null;
365
+ for (const h of detectProjectHints(cur)) {
366
+ if (!enc && h.encoding && !isSingleByteEncoding(h.encoding) && !isStatefulEncoding(h.encoding))
367
+ enc = h.encoding;
368
+ if (!eol && h.lineEnding)
369
+ eol = h.lineEnding;
370
+ }
371
+ if (enc || eol)
372
+ return { encoding: enc ?? "UTF-8", eol };
373
+ if (hasGitRoot(cur))
374
+ break;
375
+ const parent = path.dirname(cur);
376
+ if (parent === cur)
377
+ break;
378
+ cur = parent;
379
+ }
380
+ return null;
381
+ }
382
+ function finalizeSiblingBuffers(cacheKey, signature, buffers, origDir) {
383
+ const result = scoreSiblingBuffers(buffers);
384
+ const resolved = result.hasSignal
385
+ ? { encoding: result.encoding, eol: result.eol }
386
+ : (inferFromProjectFiles(origDir) ?? { encoding: "UTF-8", eol: null });
387
+ storeSiblingInference(cacheKey, signature, resolved);
388
+ return resolved;
389
+ }
390
+ function siblingCacheLookup(cur, targetExt, excludeBase, selected) {
391
+ const signature = siblingSignature(selected);
392
+ const cacheKey = `${normalizePathKey(cur)}\u0000${targetExt}\u0000${excludeBase}`;
393
+ const cached = siblingInference.get(cacheKey);
394
+ return {
395
+ cacheKey,
396
+ signature,
397
+ hit: cached && cached.signature === signature ? { encoding: cached.encoding, eol: cached.eol } : null,
398
+ };
399
+ }
400
+ function nextParentDir(cur) {
401
+ if (hasGitRoot(cur))
402
+ return null;
403
+ const parent = path.dirname(cur);
404
+ return parent === cur ? null : parent;
405
+ }
406
+ /**
407
+ * Scan up to 16 sibling text files in `dir` (falling back up to 3 parent dirs for newly created/empty subdirectories)
408
+ * to infer the dominant encoding and line-ending style when creating a new file or adding non-ASCII text to a pure-ASCII file.
409
+ */
410
+ function inferFromSiblings(dir, targetExt, excludeBase) {
411
+ let cur = path.resolve(dir);
412
+ for (let depth = 0; cur && depth <= MAX_PARENT_SIBLING_DEPTH; depth++) {
413
+ if (depth > 0 && isBoundaryDir(cur))
414
+ break;
415
+ let entries = null;
416
+ try {
417
+ entries = readdirSync(cur, { withFileTypes: true });
418
+ }
419
+ catch {
420
+ entries = null;
421
+ }
422
+ if (entries) {
423
+ const excl = depth === 0 ? excludeBase : "";
424
+ const selected = [];
425
+ for (const f of selectSiblingEntries(entries, targetExt, excl)) {
426
+ const abs = path.join(cur, f.name);
427
+ try {
428
+ const st = statSync(abs);
429
+ if (st.size > 0 && st.size <= 256 * 1024)
430
+ selected.push({ name: f.name, abs, stamp: stampFromStat(st) });
431
+ }
432
+ catch { /* unreadable sibling */ }
433
+ }
434
+ if (selected.length > 0) {
435
+ const { cacheKey, signature, hit } = siblingCacheLookup(cur, targetExt, excl, selected);
436
+ if (hit)
437
+ return hit;
438
+ const buffers = [];
439
+ for (const s of selected) {
440
+ try {
441
+ buffers.push(readFileSync(s.abs));
442
+ }
443
+ catch { /* unreadable sibling */ }
444
+ }
445
+ return finalizeSiblingBuffers(cacheKey, signature, buffers, dir);
446
+ }
447
+ }
448
+ cur = nextParentDir(cur);
449
+ }
450
+ return inferFromProjectFiles(dir) ?? { encoding: "UTF-8", eol: null };
451
+ }
452
+ /** Non-blocking sibling inference (with parent & project-file fallback for empty/new subdirectories) used on async hot paths. */
453
+ async function inferFromSiblingsAsync(dir, targetExt, excludeBase) {
454
+ let cur = path.resolve(dir);
455
+ for (let depth = 0; cur && depth <= MAX_PARENT_SIBLING_DEPTH; depth++) {
456
+ if (depth > 0 && isBoundaryDir(cur))
457
+ break;
458
+ const entries = await readdir(cur, { withFileTypes: true }).catch(() => null);
459
+ if (entries) {
460
+ const excl = depth === 0 ? excludeBase : "";
461
+ const statResults = await Promise.all(selectSiblingEntries(entries, targetExt, excl).map(async (f) => {
462
+ const abs = path.join(cur, f.name);
463
+ const st = await stat(abs).catch(() => null);
464
+ return st && st.size > 0 && st.size <= 256 * 1024 ? { name: f.name, abs, stamp: stampFromStat(st) } : null;
465
+ }));
466
+ const selected = statResults.filter((s) => s !== null);
467
+ if (selected.length > 0) {
468
+ const { cacheKey, signature, hit } = siblingCacheLookup(cur, targetExt, excl, selected);
469
+ if (hit)
470
+ return hit;
471
+ const buffers = (await Promise.all(selected.map((s) => readFile(s.abs).catch(() => null)))).filter((b) => b !== null);
472
+ return finalizeSiblingBuffers(cacheKey, signature, buffers, dir);
473
+ }
474
+ }
475
+ cur = nextParentDir(cur);
476
+ }
477
+ return inferFromProjectFiles(dir) ?? { encoding: "UTF-8", eol: null };
478
+ }
479
+ // The verdict behind an adaptive rule, keyed by the very buffer it classified, so the read plan that
480
+ // immediately follows can reuse it instead of classifying the same bytes again under the inferred rule.
481
+ const adaptiveVerdicts = new WeakMap();
482
+ export function adaptiveVerdictFor(raw) {
483
+ return adaptiveVerdicts.get(raw);
484
+ }
485
+ function makeAdaptiveRule(dir, encoding, newFileLineEnding = null) {
486
+ const rd = runtimeDefaults;
487
+ return {
488
+ configDir: dir,
489
+ sourceEncoding: encoding,
490
+ writeEncoding: encoding,
491
+ writeIntent: null,
492
+ readStrategy: "auto",
493
+ unmappable: rd?.unmappable ?? "error",
494
+ verifyWrite: true,
495
+ protectUtf8: rd?.protectUtf8 ?? true,
496
+ preferSourceOverUtf8: rd?.preferSourceOverUtf8 ?? false,
497
+ autoCandidates: [...DEFAULT_AUTO_CANDIDATES],
498
+ force: false,
499
+ autoCommit: rd?.autoCommit ?? false,
500
+ hashlines: rd?.hashlines ?? false,
501
+ locale: rd?.locale,
502
+ newFileLineEnding: newFileLineEnding ?? rd?.newFileLineEnding ?? null,
503
+ matchedPattern: null,
504
+ warnings: [],
505
+ adaptive: true,
506
+ };
507
+ }
508
+ function adaptiveRuleFromBytes(dir, raw) {
509
+ if (!raw || raw.length === 0)
510
+ return null;
511
+ // Narrowest-first with an early stop: the verdict's encoding is the narrowest candidate that
512
+ // round-trips, which is what pickNarrowestCandidate would select from the exhaustive list.
513
+ const v = classifyBuffer(raw, null, { exhaustive: false, candidateOrder: NARROW_CJK_ORDER });
514
+ adaptiveVerdicts.set(raw, v);
515
+ if (v.kind === "cjk" || v.kind === "utf16le" || v.kind === "utf16be")
516
+ return makeAdaptiveRule(dir, v.encoding);
517
+ if (v.kind === "utf8" || v.kind === "utf8-bom" || v.kind === "binary" || v.kind === "unknown")
518
+ return makeAdaptiveRule(dir, "UTF-8");
519
+ return null;
520
+ }
521
+ /**
522
+ * Synthesize a self-adaptive ResolvedConfig when no .pi-charset.json file is present:
523
+ * - Existing non-ASCII files use their own byte-classified encoding.
524
+ * - New files and pure-ASCII files inherit the dominant encoding and line ending of sibling files in the same directory (defaulting to UTF-8).
525
+ */
526
+ export function inferAdaptiveRule(absFilePath, rawBytes) {
527
+ const dir = path.dirname(absFilePath);
528
+ let raw = rawBytes;
529
+ if (raw === undefined) {
530
+ try {
531
+ raw = readFileSync(absFilePath);
532
+ }
533
+ catch {
534
+ raw = null;
535
+ }
536
+ }
537
+ const direct = adaptiveRuleFromBytes(dir, raw);
538
+ if (direct)
539
+ return direct;
540
+ // Target file is either new or pure ASCII: infer from sibling files in the same directory.
541
+ const sib = inferFromSiblings(dir, path.extname(absFilePath).toLowerCase(), path.basename(absFilePath));
542
+ return makeAdaptiveRule(dir, sib.encoding, sib.eol);
543
+ }
544
+ /** Non-blocking counterpart to inferAdaptiveRule used on async read/write/edit paths. */
545
+ export async function inferAdaptiveRuleAsync(absFilePath, rawBytes) {
546
+ const dir = path.dirname(absFilePath);
547
+ const raw = rawBytes !== undefined ? rawBytes : await readFile(absFilePath).catch(() => null);
548
+ const direct = adaptiveRuleFromBytes(dir, raw);
549
+ if (direct)
550
+ return direct;
551
+ const sib = await inferFromSiblingsAsync(dir, path.extname(absFilePath).toLowerCase(), path.basename(absFilePath));
552
+ return makeAdaptiveRule(dir, sib.encoding, sib.eol);
553
+ }
554
+ function parseAndCacheConfig(cKey, p, stamp, text) {
555
+ let parsed;
556
+ try {
557
+ parsed = JSON.parse(stripJsonComments(text));
558
+ }
559
+ catch (e) {
560
+ // Fall back to default configuration with a warning if the JSON file is malformed, avoiding raw UTF-8 passthrough.
561
+ const entry = {
562
+ config: { ...DEFAULTS },
563
+ configPath: p,
564
+ warnings: [`${p} 不是合法 JSON(${e.message});本次按默认值处理,请修正该文件`],
565
+ stamp,
566
+ };
567
+ setDirCache(cKey, entry);
568
+ return entry;
569
+ }
570
+ const { config, warnings } = validateConfig((parsed ?? {}), p);
571
+ const entry = { config, configPath: p, warnings, stamp };
572
+ setDirCache(cKey, entry);
573
+ return entry;
574
+ }
575
+ function loadConfigInDirSync(dir) {
576
+ const cKey = normalizePathKey(dir);
577
+ const cached = dirCache.get(cKey);
578
+ const found = resolveConfigPathSync(dir);
579
+ if (!found) {
580
+ setDirCache(cKey, null);
581
+ return null;
582
+ }
583
+ const { path: p, stamp } = found;
584
+ if (cached && cached.configPath === p && sameFileStamp(cached.stamp, stamp))
585
+ return cached;
586
+ try {
587
+ return parseAndCacheConfig(cKey, p, stamp, readFileSync(p, "utf-8"));
588
+ }
589
+ catch {
590
+ setDirCache(cKey, null);
591
+ return null;
592
+ }
593
+ }
594
+ export function findNearestConfigSync(startDir) {
595
+ let cur = path.resolve(startDir);
596
+ const warnings = [];
597
+ while (true) {
598
+ const entry = loadConfigInDirSync(cur);
599
+ if (entry) {
600
+ if (entry.warnings.length)
601
+ warnings.push(...entry.warnings);
602
+ return { config: entry.config, configDir: cur, configPath: entry.configPath, warnings };
603
+ }
604
+ const parent = path.dirname(cur);
605
+ if (parent === cur)
606
+ return runtimeFoundConfig(startDir);
607
+ cur = parent;
608
+ }
609
+ }
610
+ /** Strip // line comments and /* *\/ block comments from JSONC while preserving string literals. */
611
+ export function stripJsonComments(src) {
612
+ let out = "";
613
+ let inStr = false;
614
+ let quote = "";
615
+ for (let i = 0; i < src.length; i++) {
616
+ const c = src[i];
617
+ const n = src[i + 1];
618
+ if (inStr) {
619
+ out += c;
620
+ if (c === "\\") {
621
+ out += n ?? "";
622
+ i++;
623
+ continue;
624
+ }
625
+ if (c === quote)
626
+ inStr = false;
627
+ continue;
628
+ }
629
+ if (c === '"' || c === "'") {
630
+ inStr = true;
631
+ quote = c;
632
+ out += c;
633
+ continue;
634
+ }
635
+ if (c === "/" && n === "/") {
636
+ while (i < src.length && src[i] !== "\n")
637
+ i++;
638
+ out += "\n";
639
+ continue;
640
+ }
641
+ if (c === "/" && n === "*") {
642
+ i += 2;
643
+ while (i < src.length && !(src[i] === "*" && src[i + 1] === "/"))
644
+ i++;
645
+ i++;
646
+ continue;
647
+ }
648
+ out += c;
649
+ }
650
+ return out;
651
+ }
652
+ export function normalizeBashMode(raw, where, warnings) {
653
+ if (raw === undefined || raw === false || raw === "false" || raw === "off")
654
+ return false;
655
+ if (raw === true || raw === "auto" || raw === "on")
656
+ return "auto";
657
+ if (typeof raw === "string") {
658
+ try {
659
+ const n = normalizeEncoding(raw);
660
+ if (n === "UTF-8") {
661
+ warnings.push(`${where}: transcodeBash="${raw}" 目标已是 UTF-8,按 false 处理`);
662
+ return false;
663
+ }
664
+ if (isStatefulEncoding(n)) {
665
+ warnings.push(`${where}: transcodeBash="${raw}" 为状态转义编码,无法做流式判定,改用 "auto"`);
666
+ return "auto";
667
+ }
668
+ return n;
669
+ }
670
+ catch {
671
+ warnings.push(`${where}: transcodeBash="${raw}" 不是可用编码名,改用 "auto"`);
672
+ return "auto";
673
+ }
674
+ }
675
+ warnings.push(`${where}: transcodeBash 只接受 false/"auto"/编码名,收到 ${JSON.stringify(raw)},按 false 处理`);
676
+ return false;
677
+ }
678
+ function validateConfig(parsed, where) {
679
+ const warnings = [];
680
+ const merged = { ...DEFAULTS, ...(parsed ?? {}) };
681
+ try {
682
+ merged.sourceEncoding = normalizeEncoding(String(merged.sourceEncoding ?? "GB18030"));
683
+ }
684
+ catch (e) {
685
+ warnings.push(`${where}: sourceEncoding "${merged.sourceEncoding}" 不可用(${e.message}),按 GB18030 处理`);
686
+ merged.sourceEncoding = "GB18030";
687
+ }
688
+ if (merged.writeEncoding) {
689
+ try {
690
+ merged.writeEncoding = normalizeEncoding(String(merged.writeEncoding));
691
+ }
692
+ catch {
693
+ warnings.push(`${where}: writeEncoding "${merged.writeEncoding}" 不可用,回退至 sourceEncoding`);
694
+ merged.writeEncoding = merged.sourceEncoding;
695
+ }
696
+ }
697
+ if (merged.readStrategy !== "auto" && merged.readStrategy !== "config") {
698
+ warnings.push(`${where}: readStrategy "${merged.readStrategy}" 非法,已回退为 "auto"`);
699
+ merged.readStrategy = "auto";
700
+ }
701
+ if (merged.unmappable !== "error" && merged.unmappable !== "escape" && merged.unmappable !== "drop-to-gb18030") {
702
+ warnings.push(`${where}: unmappable "${merged.unmappable}" 非法,已回退为 "error"`);
703
+ merged.unmappable = "error";
704
+ }
705
+ if (typeof merged.verifyWrite !== "boolean")
706
+ merged.verifyWrite = true;
707
+ if (typeof merged.protectUtf8 !== "boolean")
708
+ merged.protectUtf8 = true;
709
+ if (!Array.isArray(merged.autoCandidates) || merged.autoCandidates.length === 0) {
710
+ merged.autoCandidates = [...DEFAULT_AUTO_CANDIDATES];
711
+ }
712
+ else {
713
+ const kept = [];
714
+ for (const c of merged.autoCandidates) {
715
+ let n;
716
+ try {
717
+ n = normalizeEncoding(String(c));
718
+ }
719
+ catch {
720
+ warnings.push(`${where}: autoCandidates 中的 "${c}" 不是可用编码,已忽略(支持列表:${DEFAULT_AUTO_CANDIDATES.join("/")})`);
721
+ continue;
722
+ }
723
+ if (isSingleByteEncoding(n) || isStatefulEncoding(n)) {
724
+ warnings.push(`${where}: autoCandidates 不支持单字节或转义序列编码 "${n}",需在 overrides 中通过 "force": true 指定`);
725
+ continue;
726
+ }
727
+ kept.push(n);
728
+ }
729
+ if (kept.length === 0) {
730
+ warnings.push(`${where}: autoCandidates 全部无效,已回退默认候选链`);
731
+ merged.autoCandidates = [...DEFAULT_AUTO_CANDIDATES];
732
+ }
733
+ else
734
+ merged.autoCandidates = kept;
735
+ }
736
+ const checkBool = (field, val, def) => {
737
+ if (val === undefined)
738
+ return def;
739
+ if (typeof val === "boolean")
740
+ return val;
741
+ warnings.push(`${where}: ${field} 只接受 true/false,收到 ${JSON.stringify(val)},按 ${def} 处理`);
742
+ return def;
743
+ };
744
+ const checkEnum = (field, val, allowed, def) => {
745
+ if (val === undefined)
746
+ return def;
747
+ if (typeof val === "string" && allowed.includes(val))
748
+ return val;
749
+ warnings.push(`${where}: ${field} 只接受 ${allowed.map((x) => `"${x}"`).join("/")},收到 ${JSON.stringify(val)},已回退为 "${def}"`);
750
+ return def;
751
+ };
752
+ merged.transcodeBash = normalizeBashMode(parsed.transcodeBash, where, warnings);
753
+ merged.autoCommit = checkBool("autoCommit", parsed.autoCommit, false);
754
+ merged.hashlines = checkBool("hashlines", parsed.hashlines, false);
755
+ merged.preferSourceOverUtf8 = checkBool("preferSourceOverUtf8", parsed.preferSourceOverUtf8, false);
756
+ merged.shellGuard = checkEnum("shellGuard", parsed.shellGuard, ["block", "warn", "off"], DEFAULTS.shellGuard);
757
+ merged.locale = parsed.locale === undefined ? undefined : checkEnum("locale", parsed.locale, ["auto", "en", "zh-CN"], "auto");
758
+ merged.newFileLineEnding = normalizeNewFileLineEnding(parsed.newFileLineEnding, where, warnings);
759
+ merged.bashFileDump = checkBool("bashFileDump", parsed.bashFileDump, DEFAULTS.bashFileDump);
760
+ if (merged.overrides) {
761
+ merged.overrides = merged.overrides.map((r) => {
762
+ const rule = { ...r };
763
+ const label = r.encoding;
764
+ if (!label) {
765
+ warnings.push(`${where}: override "${r.pattern}" 缺少 encoding,已忽略`);
766
+ return rule;
767
+ }
768
+ try {
769
+ const n = normalizeEncoding(String(label));
770
+ rule.encoding = n;
771
+ if ((isSingleByteEncoding(n) || isStatefulEncoding(n)) && rule.force !== true) {
772
+ warnings.push(`${where}: override "${r.pattern}" 的编码 ${n} 为单字节或转义序列编码,需设置 "force": true 才会生效`);
773
+ }
774
+ }
775
+ catch (e) {
776
+ warnings.push(`${where}: override "${r.pattern}" 的编码 "${label}" 不可用(${e.message})`);
777
+ }
778
+ if (rule.writeEncoding) {
779
+ try {
780
+ rule.writeEncoding = normalizeEncoding(rule.writeEncoding);
781
+ }
782
+ catch {
783
+ warnings.push(`${where}: override "${r.pattern}" 的 writeEncoding 不可用,已回退`);
784
+ rule.writeEncoding = undefined;
785
+ }
786
+ }
787
+ rule.newFileLineEnding = normalizeNewFileLineEnding(r.newFileLineEnding, `${where}: override "${r.pattern}"`, warnings);
788
+ return rule;
789
+ });
790
+ }
791
+ return { config: merged, warnings };
792
+ }
793
+ async function loadConfigInDir(dir, fresh = false) {
794
+ const cKey = normalizePathKey(dir);
795
+ const cached = dirCache.get(cKey);
796
+ const found = await resolveConfigPath(dir);
797
+ if (!found) {
798
+ setDirCache(cKey, null);
799
+ return null;
800
+ }
801
+ const { path: p, stamp } = found;
802
+ if (!fresh && cached && cached.configPath === p && sameFileStamp(cached.stamp, stamp))
803
+ return cached;
804
+ try {
805
+ return parseAndCacheConfig(cKey, p, stamp, await readFile(p, "utf-8"));
806
+ }
807
+ catch {
808
+ setDirCache(cKey, null);
809
+ return null;
810
+ }
811
+ }
812
+ export async function findNearestConfig(startDir, fresh = false) {
813
+ let cur = path.resolve(startDir);
814
+ const warnings = [];
815
+ while (true) {
816
+ const entry = await loadConfigInDir(cur, fresh);
817
+ if (entry) {
818
+ if (entry.warnings.length)
819
+ warnings.push(...entry.warnings);
820
+ return { config: entry.config, configDir: cur, configPath: entry.configPath, warnings };
821
+ }
822
+ const parent = path.dirname(cur);
823
+ if (parent === cur)
824
+ return runtimeFoundConfig(startDir);
825
+ cur = parent;
826
+ }
827
+ }
828
+ function scoreSpecificity(pattern) {
829
+ if (!pattern)
830
+ return 0;
831
+ let score = 0;
832
+ for (const seg of pattern.split("/")) {
833
+ if (seg === "**")
834
+ score += 1;
835
+ else if (seg === "*")
836
+ score += 2;
837
+ else if (seg.includes("*") || seg.includes("?"))
838
+ score += 5;
839
+ else
840
+ score += 10;
841
+ }
842
+ return score;
843
+ }
844
+ function ruleMatches(rel, pattern) {
845
+ if (!pattern)
846
+ return false;
847
+ const isBare = !pattern.includes("/");
848
+ return micromatch.isMatch(rel, pattern, isBare ? { matchBase: true } : undefined);
849
+ }
850
+ function pickOverride(absFilePath, found) {
851
+ const { config, configDir } = found;
852
+ if (!config.overrides?.length)
853
+ return { rule: null, score: 0 };
854
+ const rel = path.relative(configDir, absFilePath).replace(/\\/g, "/");
855
+ const matched = config.overrides
856
+ .map((rule, index) => ({ rule, score: scoreSpecificity(rule.pattern), index }))
857
+ .filter((it) => ruleMatches(rel, it.rule.pattern))
858
+ .sort((a, b) => b.score - a.score || a.index - b.index);
859
+ const best = matched[0];
860
+ return best ? { rule: best.rule, score: best.score } : { rule: null, score: 0 };
861
+ }
862
+ export function resolveFileRule(absFilePath, found) {
863
+ const { config, configDir } = found;
864
+ const { rule } = pickOverride(absFilePath, found);
865
+ const warnings = [...(found.warnings ?? [])];
866
+ const overrideRead = normalizeRuleLabel(rule?.encoding);
867
+ const sourceEncoding = overrideRead ?? config.sourceEncoding;
868
+ const rootWrite = normalizeRuleLabel(config.writeEncoding);
869
+ const rootSource = normalizeRuleLabel(config.sourceEncoding);
870
+ const migrationIntent = !!rootWrite && !!rootSource && rootWrite !== rootSource;
871
+ // When an override specifies only encoding and the root config has no migration intent, writeEncoding follows the override.
872
+ const writeEncoding = normalizeRuleLabel(rule?.writeEncoding) ??
873
+ (overrideRead && !migrationIntent ? overrideRead : rootWrite ?? sourceEncoding);
874
+ if (migrationIntent && overrideRead && rootWrite && overrideRead !== rootWrite && !rule?.writeEncoding) {
875
+ warnings.push(`${configDir}: 根配置带迁移意图(sourceEncoding=${rootSource} -> writeEncoding=${rootWrite}),` +
876
+ `override "${rule?.pattern}" 仅声明了读编码 ${overrideRead},该目录下新建与纯 ASCII 文件仍按 ${rootWrite} 写入;` +
877
+ `若需按 ${overrideRead} 写入,请在该 override 中显式设置 "writeEncoding": "${overrideRead}"。`);
878
+ }
879
+ if (rule?.writeEncoding && rule.encoding === undefined) {
880
+ warnings.push(`${configDir}: override "${rule.pattern}" 仅设置了 writeEncoding,读编码沿用 ${sourceEncoding}`);
881
+ }
882
+ const force = rule?.force ?? false;
883
+ const writeIntent = normalizeEncoding(writeEncoding) !== normalizeEncoding(sourceEncoding) ? writeEncoding : null;
884
+ if (isGBEncoding(writeEncoding) && isGBEncoding(sourceEncoding) && writeEncoding !== sourceEncoding) {
885
+ if (writeEncoding.toUpperCase() === "GBK" && sourceEncoding.toUpperCase() === "GB18030") {
886
+ warnings.push(`${configDir}: writeEncoding=GBK 而 sourceEncoding=GB18030,文件中的 4 字节扩展区字符在写出时将被闸门 1 拦截`);
887
+ }
888
+ }
889
+ return {
890
+ configDir,
891
+ sourceEncoding,
892
+ writeEncoding,
893
+ writeIntent,
894
+ readStrategy: rule?.readStrategy ?? config.readStrategy ?? DEFAULTS.readStrategy,
895
+ unmappable: rule?.unmappable ?? config.unmappable ?? DEFAULTS.unmappable,
896
+ verifyWrite: rule?.verifyWrite ?? config.verifyWrite ?? DEFAULTS.verifyWrite,
897
+ protectUtf8: rule?.protectUtf8 ?? config.protectUtf8 ?? DEFAULTS.protectUtf8,
898
+ preferSourceOverUtf8: rule?.preferSourceOverUtf8 ?? config.preferSourceOverUtf8 ?? false,
899
+ autoCandidates: rule?.autoCandidates?.length
900
+ ? rule.autoCandidates.map((c) => safeNormalize(String(c))).filter(Boolean)
901
+ : config.autoCandidates ?? DEFAULTS.autoCandidates,
902
+ force,
903
+ matchedPattern: rule?.pattern ?? null,
904
+ newFileLineEnding: rule?.newFileLineEnding ?? config.newFileLineEnding ?? null,
905
+ autoCommit: config.autoCommit === true,
906
+ hashlines: config.hashlines === true,
907
+ locale: config.locale,
908
+ warnings,
909
+ };
910
+ }
911
+ function safeNormalize(label) {
912
+ try {
913
+ return normalizeEncoding(label);
914
+ }
915
+ catch {
916
+ return null;
917
+ }
918
+ }
919
+ function normalizeRuleLabel(label) {
920
+ if (!label)
921
+ return null;
922
+ return safeNormalize(label);
923
+ }
924
+ export function resolveOverrideEncoding(absFilePath, found) {
925
+ return resolveFileRule(absFilePath, found).sourceEncoding;
926
+ }
927
+ export function shellRuleFor(startDir) {
928
+ const found = findNearestConfigSync(startDir);
929
+ if (!found)
930
+ return null;
931
+ const warnings = [...(found.warnings ?? [])];
932
+ const mode = normalizeBashMode(found.config.transcodeBash, found.configDir, warnings);
933
+ if (mode === false)
934
+ return null;
935
+ return {
936
+ mode,
937
+ fileDump: found.config.bashFileDump !== false,
938
+ sourceEncoding: found.config.sourceEncoding,
939
+ autoCandidates: found.config.autoCandidates ?? [...DEFAULT_AUTO_CANDIDATES],
940
+ configDir: found.configDir,
941
+ warnings,
942
+ };
943
+ }