@hublo/sentinel 1.7.0-alpha.3 → 1.7.0-alpha.5

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.
@@ -1,3 +1,12 @@
1
+ import {
2
+ LEGACY_ENTRY,
3
+ appliedOptions,
4
+ diffConfigs,
5
+ extendsList,
6
+ isBaseEntry,
7
+ isStackPresetEntry,
8
+ remainder
9
+ } from "./chunk-ZZMYV576.js";
1
10
  import {
2
11
  binFromOwnInstall,
3
12
  resolveBin,
@@ -14,93 +23,8 @@ import { createRequire } from "node:module";
14
23
  import { dirname as dirname2, join, relative as relative2, resolve as resolve2 } from "node:path";
15
24
  import { stripComments } from "jsonc-parser";
16
25
 
17
- // src/roles/typescript/migrate/compare.ts
18
- var STRICT_FAMILY = [
19
- "alwaysStrict",
20
- "noImplicitAny",
21
- "noImplicitThis",
22
- "strictBindCallApply",
23
- "strictBuiltinIteratorReturn",
24
- "strictFunctionTypes",
25
- "strictNullChecks",
26
- "strictPropertyInitialization",
27
- "useUnknownInCatchVariables"
28
- ];
29
- var CASE_INSENSITIVE = /* @__PURE__ */ new Set([
30
- "jsx",
31
- "lib",
32
- "module",
33
- "moduleDetection",
34
- "moduleResolution",
35
- "target"
36
- ]);
37
- function targetYear(target) {
38
- const name = typeof target === "string" ? target.toLowerCase() : "es5";
39
- if (name === "esnext") return Number.MAX_SAFE_INTEGER;
40
- const year = Number(name.replace(/^es/, ""));
41
- return Number.isFinite(year) ? year : 5;
42
- }
43
- function comparable(key, value) {
44
- const json = JSON.stringify(value) ?? "undefined";
45
- return CASE_INSENSITIVE.has(key) ? json.toLowerCase() : json;
46
- }
47
- function appliedOptions(config) {
48
- const options = new Map(Object.entries(config.compilerOptions ?? {}));
49
- options.delete("paths");
50
- const derive = (key, value) => {
51
- if (!options.has(key)) options.set(key, value);
52
- };
53
- if (options.get("strict") === true) for (const key of STRICT_FAMILY) derive(key, true);
54
- derive("allowJs", false);
55
- if (options.get("esModuleInterop") === true) derive("allowSyntheticDefaultImports", true);
56
- if (options.get("verbatimModuleSyntax") === true) derive("isolatedModules", true);
57
- if (options.get("isolatedModules") === true) derive("preserveConstEnums", true);
58
- derive("useDefineForClassFields", targetYear(options.get("target")) >= 2022);
59
- return new Map([...options].map(([key, value]) => [key, comparable(key, value)]));
60
- }
61
- function diffConfigs(before, after) {
62
- const was = appliedOptions(before);
63
- const now = appliedOptions(after);
64
- const differences = [];
65
- for (const key of /* @__PURE__ */ new Set([...was.keys(), ...now.keys()])) {
66
- if (was.get(key) !== now.get(key)) {
67
- differences.push({ key: `compilerOptions.${key}`, before: was.get(key), after: now.get(key) });
68
- }
69
- }
70
- for (const key of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])) {
71
- if (key === "compilerOptions") continue;
72
- const left = JSON.stringify(before[key]);
73
- const right = JSON.stringify(after[key]);
74
- if (left !== right) differences.push({ key, before: left, after: right });
75
- }
76
- return differences;
77
- }
78
- function remainder(effective, layers, ownKeys) {
79
- const applied = appliedOptions(effective);
80
- const given = appliedOptions(layers);
81
- const written = [];
82
- for (const [key, value] of applied) {
83
- if (ownKeys.has(key) || given.get(key) === value) continue;
84
- written.push({ key, value: effective.compilerOptions?.[key] ?? JSON.parse(value) });
85
- }
86
- return written;
87
- }
88
-
89
26
  // src/roles/typescript/migrate/detach.ts
90
27
  import { dirname, posix, relative, resolve, sep } from "node:path";
91
- var BASE_FILE = "tsconfig.base.json";
92
- var LEGACY_ENTRY = "@hublo/sentinel/typescript/legacy";
93
- function isBaseEntry(entry) {
94
- return entry === BASE_FILE || entry.endsWith(`/${BASE_FILE}`);
95
- }
96
- function isStackPresetEntry(entry) {
97
- return /^@hublo\/sentinel\/(?:typescript|tsconfig)\/(?!legacy$)[a-z-]+$/.test(entry);
98
- }
99
- function extendsList(config) {
100
- const value = config.extends;
101
- if (typeof value === "string") return [value];
102
- return Array.isArray(value) ? value.filter((entry) => typeof entry === "string") : [];
103
- }
104
28
  function rebaseTarget(target, pathsRoot, directory) {
105
29
  const moved = relative(directory, resolve(pathsRoot, target)).split(sep).join(posix.sep);
106
30
  const kept = target.endsWith("/") && !moved.endsWith("/") ? `${moved}/` : moved;
@@ -155,7 +79,7 @@ function parseTrace(text) {
155
79
  const patterns = /* @__PURE__ */ new Set();
156
80
  let open;
157
81
  let afterPathsLine = false;
158
- for (const line of text.split("\n")) {
82
+ for (const line of text.split(/\r?\n/)) {
159
83
  const isPathsMatch = afterPathsLine;
160
84
  afterPathsLine = line.startsWith("'paths' option is specified");
161
85
  const resolving = RESOLVING_MODULE.exec(line) ?? RESOLVING_TYPE.exec(line);
@@ -186,9 +110,10 @@ function diffResolutions(before, after) {
186
110
  for (const key of /* @__PURE__ */ new Set([...before.keys(), ...after.keys()])) {
187
111
  const was = before.get(key);
188
112
  const now = after.get(key);
189
- if (was === now) continue;
113
+ if (was === now && before.has(key) === after.has(key)) continue;
190
114
  const [from, name] = key.split("\0");
191
- lines.push(`${from ?? ""}: '${name ?? ""}' ${was ?? "unresolved"} -> ${now ?? "unresolved"}`);
115
+ const say = (side, value) => side.has(key) ? value ?? "unresolved" : "absent";
116
+ lines.push(`${from ?? ""}: '${name ?? ""}' ${say(before, was)} -> ${say(after, now)}`);
192
117
  }
193
118
  return lines;
194
119
  }
@@ -204,25 +129,32 @@ function readTsconfig(file) {
204
129
  function tscFor(directory) {
205
130
  return resolveBin(directory, "tsc") ?? binFromOwnInstall("typescript", "tsc") ?? "tsc";
206
131
  }
132
+ var TSC_OUTPUT_LIMIT = 512 * 1024 * 1024;
207
133
  function tsc(directory, tsconfig, extra) {
208
- try {
209
- return execFileSync(tscFor(directory), ["-p", tsconfig, ...extra], {
210
- cwd: directory,
211
- encoding: "utf8",
212
- maxBuffer: 2 ** 31 - 1,
213
- stdio: ["ignore", "pipe", "pipe"]
214
- });
215
- } catch (error) {
216
- const failure = error;
217
- if (typeof failure.stdout === "string" && failure.stdout.length > 0) return failure.stdout;
218
- const said = typeof failure.stderr === "string" && failure.stderr !== "" ? failure.stderr : failure.message;
219
- throw new Error(`tsc -p ${tsconfig} ${extra.join(" ")}: ${String(said).trim()}`, {
220
- cause: error
221
- });
222
- }
134
+ const command = `tsc -p ${tsconfig} ${extra.join(" ")}`;
135
+ const run = spawnSync(tscFor(directory), ["-p", tsconfig, ...extra], {
136
+ cwd: directory,
137
+ encoding: "utf8",
138
+ maxBuffer: TSC_OUTPUT_LIMIT,
139
+ stdio: ["ignore", "pipe", "pipe"]
140
+ });
141
+ if (run.error !== void 0)
142
+ throw new Error(`${command}: ${run.error.message}`, { cause: run.error });
143
+ if (run.signal !== null) throw new Error(`${command}: killed by ${run.signal}`);
144
+ const completed = run.status === 0 || run.status === 1 || run.status === 2;
145
+ if (completed && run.stdout.length > 0) return run.stdout;
146
+ const said = run.stderr.trim() || run.stdout.trim() || `exit ${String(run.status)}, no output`;
147
+ throw new Error(`${command}: ${said}`);
223
148
  }
224
149
  function showConfig(directory, tsconfig) {
225
- return JSON.parse(tsc(directory, tsconfig, ["--showConfig"]));
150
+ const printed = tsc(directory, tsconfig, ["--showConfig"]);
151
+ try {
152
+ return JSON.parse(printed);
153
+ } catch {
154
+ throw new Error(
155
+ `tsc --showConfig on ${join(directory, tsconfig)} did not print a config: ${printed.trim().slice(0, 300)}`
156
+ );
157
+ }
226
158
  }
227
159
  function withProbe(directory, config, use) {
228
160
  writeFileSync(join(directory, PROBE), JSON.stringify(config));
@@ -254,20 +186,27 @@ function owner(file, directory) {
254
186
  }
255
187
  return directory;
256
188
  }
257
- function trackedFiles(directory) {
189
+ function moduleFiles(directory) {
190
+ let listed;
258
191
  try {
259
- return execFileSync("git", ["ls-files", "--cached"], { cwd: directory, encoding: "utf8" }).split("\n").filter(Boolean);
192
+ listed = execFileSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard"], {
193
+ cwd: directory,
194
+ encoding: "utf8"
195
+ });
260
196
  } catch {
261
197
  return void 0;
262
198
  }
199
+ return [...new Set(listed.split("\0").filter(Boolean))].filter(
200
+ (name) => existsSync(join(directory, name))
201
+ );
263
202
  }
264
- function outsidePrograms(directory, chained, tracked) {
203
+ function outsidePrograms(directory, chained, files) {
265
204
  const listed = new Set(
266
205
  chained.flatMap(
267
206
  (name) => tsc(directory, name, ["--listFilesOnly"]).split("\n").map((line) => line.trim()).filter(Boolean)
268
207
  )
269
208
  );
270
- return tracked.filter((name) => SOURCE.test(name) && !name.endsWith(".d.ts")).map((name) => join(directory, name)).filter((file) => existsSync(file) && !listed.has(file) && owner(file, directory) === directory);
209
+ return files.filter((name) => SOURCE.test(name) && !name.endsWith(".d.ts")).map((name) => join(directory, name)).filter((file) => existsSync(file) && !listed.has(file) && owner(file, directory) === directory);
271
210
  }
272
211
  function trace(directory, name) {
273
212
  return parseTrace(tsc(directory, name, ["--noEmit", "--traceResolution"]));
@@ -302,29 +241,44 @@ function sentinelInstalls(directory, presets) {
302
241
  if (legacy === void 0) return "no-legacy";
303
242
  return presets.every((preset) => packageRoot(preset) === legacy) ? "one" : "several";
304
243
  }
305
- function migrateTsconfig(directory, target, names, options) {
306
- const file = join(directory, target);
307
- const shown = relative2(options.workspaceRoot, file);
308
- const original = readFileSync(file, "utf8");
244
+ function refused(file, refusal, reason) {
245
+ return { file, kept: false, refusal, reason };
246
+ }
247
+ function refuseEarly(directory, shown, original, chain) {
309
248
  if (stripComments(original) !== original) {
310
- return { file: shown, kept: false, reason: "it has comments a rewrite would drop; left as is" };
249
+ return refused(shown, "comments", "it has comments a rewrite would drop; left as is");
311
250
  }
312
- const config = readTsconfig(file);
313
- const chain = extendsList(config);
314
- const baseEntry = chain.find(isBaseEntry);
315
- if (baseEntry === void 0)
316
- return { file: shown, kept: false, reason: "it does not extend the base" };
317
- const baseFile = resolve2(directory, baseEntry);
318
- const base = readTsconfig(baseFile);
319
- const basePaths = base.compilerOptions?.paths ?? {};
251
+ const installs = sentinelInstalls(directory, chain.filter(isStackPresetEntry));
252
+ if (installs === "no-legacy") {
253
+ return refused(
254
+ shown,
255
+ "no-legacy",
256
+ `${LEGACY_ENTRY} does not resolve from this module: bump its @hublo/sentinel to the version running this command, run \`pnpm install\`, and run it again`
257
+ );
258
+ }
259
+ if (installs === "several") {
260
+ return refused(
261
+ shown,
262
+ "several-installs",
263
+ `${LEGACY_ENTRY} and the stack preset resolve from two different @hublo/sentinel installs here; give this module one sentinel version and run \`pnpm install\``
264
+ );
265
+ }
266
+ return void 0;
267
+ }
268
+ function baseline(directory, target, names, files) {
320
269
  const chained = inheritors(directory, names, target).filter(
321
270
  (name) => compilesFiles(readTsconfig(join(directory, name)))
322
271
  );
323
272
  const before = new Map(names.map((name) => [name, showConfig(directory, name)]));
324
273
  const traces = new Map(chained.map((name) => [name, trace(directory, name)]));
325
- const tracked = trackedFiles(directory);
326
- const outside = tracked === void 0 ? [] : outsidePrograms(directory, chained, tracked);
274
+ const outside = files === void 0 ? [] : outsidePrograms(directory, chained, files);
327
275
  if (outside.length > 0) traces.set(OUTSIDE, traceOutside(directory, target, outside));
276
+ return { before, traces, outside };
277
+ }
278
+ function planDetach(directory, config, chain, effective, traces) {
279
+ const baseFile = resolve2(directory, chain.find(isBaseEntry) ?? "");
280
+ const base = readTsconfig(baseFile);
281
+ const basePaths = base.compilerOptions?.paths ?? {};
328
282
  const matched = new Set([...traces.values()].flatMap((one) => [...one.patterns]));
329
283
  const paths = pickPaths(
330
284
  basePaths,
@@ -332,21 +286,11 @@ function migrateTsconfig(directory, target, names, options) {
332
286
  pathsRootOf(baseFile, base.compilerOptions?.baseUrl),
333
287
  directory
334
288
  );
335
- const effective = before.get(target) ?? {};
336
- const withoutBase = chain.filter((entry) => !isBaseEntry(entry));
337
289
  const inputs = Object.fromEntries(
338
290
  ["files", "include", "references"].filter((key) => key in config).map((key) => [key, config[key]])
339
291
  );
340
292
  const layers = (entries) => withProbe(directory, { extends: entries, ...inputs }, (probe) => showConfig(directory, probe));
341
- const installs = sentinelInstalls(directory, chain.filter(isStackPresetEntry));
342
- if (installs !== "one") {
343
- return {
344
- file: shown,
345
- kept: false,
346
- reason: installs === "no-legacy" ? `${LEGACY_ENTRY} does not resolve from this module: bump its @hublo/sentinel to the version running this command, run \`pnpm install\`, and run it again` : `${LEGACY_ENTRY} and the stack preset resolve from two different @hublo/sentinel installs here; give this module one sentinel version and run \`pnpm install\``
347
- };
348
- }
349
- const stack = layers(withoutBase);
293
+ const stack = layers(chain.filter((entry) => !isBaseEntry(entry)));
350
294
  const withLegacy = layers(chain.map((entry) => isBaseEntry(entry) ? LEGACY_ENTRY : entry));
351
295
  const stackApplied = appliedOptions(stack);
352
296
  const legacyKeys = new Set(
@@ -359,22 +303,14 @@ function migrateTsconfig(directory, target, names, options) {
359
303
  ({ key }) => key !== "paths"
360
304
  );
361
305
  const exclude = config.exclude === void 0 ? effective.exclude : void 0;
362
- const report = {
363
- file: shown,
364
- legacy,
365
- aliases: { kept: Object.keys(paths).length, of: Object.keys(basePaths).length },
366
- written: copied.map(({ key }) => key),
367
- resolutions: [...traces.values()].reduce((sum, one) => sum + one.resolutions.size, 0),
368
- outsidePrograms: outside.map((path) => relative2(directory, path))
369
- };
370
- let kept = false;
306
+ return { paths, legacy, copied, exclude, aliasesOfBase: Object.keys(basePaths).length };
307
+ }
308
+ function proveRewrite(directory, target, names, contents, { before, traces, outside }) {
309
+ const file = join(directory, target);
310
+ const original = readFileSync(file, "utf8");
371
311
  writeFileSync(`${file}${ORIGINAL}`, original);
372
312
  try {
373
- writeFileSync(
374
- file,
375
- `${JSON.stringify(detachedConfig({ config, legacy, copied, paths, exclude }), null, 2)}
376
- `
377
- );
313
+ writeFileSync(file, contents);
378
314
  const configDifferences = names.flatMap(
379
315
  (name) => diffConfigs(before.get(name) ?? {}, showConfig(directory, name)).map((difference) => ({
380
316
  ...difference,
@@ -387,24 +323,65 @@ function migrateTsconfig(directory, target, names, options) {
387
323
  (name === OUTSIDE ? traceOutside(directory, target, outside) : trace(directory, name)).resolutions
388
324
  ).map((line) => `${name}: ${line}`)
389
325
  );
390
- const proved = configDifferences.length === 0 && resolutionDifferences.length === 0;
391
- kept = proved && options.write;
392
- return {
393
- ...report,
394
- kept,
395
- ...proved ? {} : { reason: "tsc does not agree before and after; restored" },
396
- configDifferences,
397
- resolutionDifferences
398
- };
326
+ return { configDifferences, resolutionDifferences };
399
327
  } finally {
400
- if (!kept) writeFileSync(file, original);
328
+ writeFileSync(file, original);
401
329
  unlinkSync(`${file}${ORIGINAL}`);
402
330
  }
403
331
  }
404
- function restoreInterrupted(moduleRoot, tracked, notes, workspaceRoot) {
332
+ function proveTsconfig(directory, target, names, files, workspaceRoot) {
333
+ const file = join(directory, target);
334
+ const shown = relative2(workspaceRoot, file);
335
+ const original = readFileSync(file, "utf8");
336
+ const config = readTsconfig(file);
337
+ const chain = extendsList(config);
338
+ const early = refuseEarly(directory, shown, original, chain);
339
+ if (early !== void 0) return { result: early };
340
+ const known = baseline(directory, target, names, files);
341
+ const empty = [...known.traces].filter(
342
+ ([name, one]) => name !== OUTSIDE && one.resolutions.size === 0
343
+ );
344
+ if (empty.length > 0) {
345
+ return {
346
+ result: refused(
347
+ shown,
348
+ "no-trace",
349
+ `tsc --traceResolution printed no resolution sentinel could read for ${empty.map(([name]) => name).join(", ")}; nothing can be proved`
350
+ )
351
+ };
352
+ }
353
+ const plan = planDetach(directory, config, chain, known.before.get(target) ?? {}, known.traces);
354
+ const contents = `${JSON.stringify(
355
+ detachedConfig({
356
+ config,
357
+ legacy: plan.legacy,
358
+ copied: plan.copied,
359
+ paths: plan.paths,
360
+ exclude: plan.exclude
361
+ }),
362
+ null,
363
+ 2
364
+ )}
365
+ `;
366
+ const differences = proveRewrite(directory, target, names, contents, known);
367
+ const agrees = differences.configDifferences.length === 0 && differences.resolutionDifferences.length === 0;
368
+ const result = {
369
+ file: shown,
370
+ kept: false,
371
+ ...agrees ? {} : { refusal: "disagrees", reason: "tsc does not agree before and after; restored" },
372
+ legacy: plan.legacy,
373
+ aliases: { kept: Object.keys(plan.paths).length, of: plan.aliasesOfBase },
374
+ written: plan.copied.map(({ key }) => key),
375
+ resolutions: [...known.traces.values()].reduce((sum, one) => sum + one.resolutions.size, 0),
376
+ outsidePrograms: known.outside.map((path) => relative2(directory, path)),
377
+ ...differences
378
+ };
379
+ return agrees ? { result, contents } : { result };
380
+ }
381
+ function restoreInterrupted(moduleRoot, files, notes, workspaceRoot) {
405
382
  const folders = /* @__PURE__ */ new Set([
406
383
  moduleRoot,
407
- ...(tracked ?? []).filter((name) => TSCONFIG_NAME.test(name.slice(name.lastIndexOf("/") + 1))).map((name) => join(moduleRoot, dirname2(name)))
384
+ ...(files ?? []).filter((name) => TSCONFIG_NAME.test(name.slice(name.lastIndexOf("/") + 1))).map((name) => join(moduleRoot, dirname2(name)))
408
385
  ]);
409
386
  for (const folder of folders) {
410
387
  for (const name of readdirSync(folder).filter((entry) => entry.endsWith(ORIGINAL))) {
@@ -417,9 +394,7 @@ function restoreInterrupted(moduleRoot, tracked, notes, workspaceRoot) {
417
394
  }
418
395
  }
419
396
  function formatWritten(moduleRoot, files, notes, options) {
420
- const proved = files.filter(
421
- (one) => options.write ? one.kept : one.configDifferences?.length === 0 && one.resolutionDifferences?.length === 0
422
- );
397
+ const proved = files.filter((one) => options.write ? one.kept : one.refusal === void 0);
423
398
  if (proved.length === 0) return;
424
399
  const formatter = writtenFileFormatter(moduleRoot);
425
400
  if (formatter === void 0) {
@@ -444,10 +419,10 @@ function formatWritten(moduleRoot, files, notes, options) {
444
419
  function isOwnModule(folder) {
445
420
  return existsSync(join(folder, "package.json")) || existsSync(join(folder, "project.json"));
446
421
  }
447
- function foldersToMigrate(moduleRoot, tracked, notes) {
422
+ function foldersToMigrate(moduleRoot, files, notes) {
448
423
  const nested = [
449
424
  ...new Set(
450
- (tracked ?? []).filter(
425
+ (files ?? []).filter(
451
426
  (name) => TSCONFIG_NAME.test(name.slice(name.lastIndexOf("/") + 1)) && name.includes("/")
452
427
  ).map((name) => join(moduleRoot, dirname2(name)))
453
428
  )
@@ -466,14 +441,83 @@ function foldersToMigrate(moduleRoot, tracked, notes) {
466
441
  (folder) => readdirSync(folder).filter((name) => TSCONFIG_NAME.test(name) && name !== PROBE).some((name) => extendsList(readTsconfig(join(folder, name))).some(isBaseEntry))
467
442
  );
468
443
  }
444
+ function removeLeftProbe(folder, notes, workspaceRoot) {
445
+ if (!existsSync(join(folder, PROBE))) return;
446
+ unlinkSync(join(folder, PROBE));
447
+ notes.push(`removed ${relative2(workspaceRoot, join(folder, PROBE))}, left by an interrupted run`);
448
+ }
449
+ function proveFolder(folder, files, workspaceRoot) {
450
+ const names = readdirSync(folder).filter((name) => TSCONFIG_NAME.test(name) && name !== PROBE);
451
+ const targets = names.filter(
452
+ (name) => extendsList(readTsconfig(join(folder, name))).some(isBaseEntry)
453
+ );
454
+ return targets.map((target) => {
455
+ const shown = relative2(workspaceRoot, join(folder, target));
456
+ if (!extendsList(readTsconfig(join(folder, target))).some(isStackPresetEntry)) {
457
+ return {
458
+ result: refused(
459
+ shown,
460
+ "not-adopted",
461
+ "it extends the base but no sentinel preset: only an adopted module is detached. Run `sentinel --init --typescript` first"
462
+ )
463
+ };
464
+ }
465
+ try {
466
+ return proveTsconfig(folder, target, names, files, workspaceRoot);
467
+ } catch (error) {
468
+ return { result: refused(shown, "error", error.message) };
469
+ }
470
+ });
471
+ }
472
+ function markPartlyAdopted(proved) {
473
+ const adopted = proved.filter(({ result }) => result.refusal !== "not-adopted");
474
+ if (adopted.length === 0) return;
475
+ for (const one of proved) {
476
+ if (one.result.refusal !== "not-adopted") continue;
477
+ const name = one.result.file.slice(one.result.file.lastIndexOf("/") + 1);
478
+ one.result = {
479
+ ...one.result,
480
+ refusal: "partly-adopted",
481
+ reason: `${name} extends the base without a sentinel preset, while this module's other tsconfigs are adopted: add the module's stack preset to its \`extends\` (or make it extend the adopted tsconfig), then run again`
482
+ };
483
+ }
484
+ }
485
+ function summarize(results, write) {
486
+ const plural = (count) => `${count} tsconfig${count === 1 ? "" : "s"}`;
487
+ if (results.every((one) => one.refusal === "not-adopted")) {
488
+ return {
489
+ outcome: "blocked",
490
+ message: "this module is not adopted: run `sentinel --init --typescript` first. Nothing was written"
491
+ };
492
+ }
493
+ const refusals = results.filter((one) => one.refusal !== void 0);
494
+ if (refusals.length === 0) {
495
+ return write ? {
496
+ outcome: "migrated",
497
+ message: `detached ${plural(results.length)} from tsconfig.base.json`
498
+ } : {
499
+ outcome: "proved",
500
+ message: "dry run: tsc agrees before and after on every tsconfig; nothing was written"
501
+ };
502
+ }
503
+ const disagreeing = refusals.filter((one) => one.refusal === "disagrees").length;
504
+ const unproved = refusals.length - disagreeing;
505
+ const why = [
506
+ ...disagreeing > 0 ? [`tsc does not agree on ${plural(disagreeing)}`] : [],
507
+ ...unproved > 0 ? [`${plural(unproved)} could not be proved`] : []
508
+ ].join(", ");
509
+ return { outcome: "failed", message: `${write ? "" : "dry run: "}${why}; nothing was written` };
510
+ }
469
511
  function migrateModule(moduleRoot, options) {
470
512
  const notes = [];
471
- const tracked = trackedFiles(moduleRoot);
472
- if (tracked === void 0) {
473
- notes.push("not a git checkout: the files outside every program were not traced");
513
+ const files = moduleFiles(moduleRoot);
514
+ if (files === void 0) {
515
+ notes.push(
516
+ "not a git checkout: the files outside every program were not traced, and only the module's own folder was checked for nested tsconfigs and for a run left interrupted"
517
+ );
474
518
  }
475
- restoreInterrupted(moduleRoot, tracked, notes, options.workspaceRoot);
476
- const folders = foldersToMigrate(moduleRoot, tracked, notes);
519
+ restoreInterrupted(moduleRoot, files, notes, options.workspaceRoot);
520
+ const folders = foldersToMigrate(moduleRoot, files, notes);
477
521
  if (folders.length === 0) {
478
522
  return {
479
523
  outcome: "skipped",
@@ -482,60 +526,22 @@ function migrateModule(moduleRoot, options) {
482
526
  notes
483
527
  };
484
528
  }
485
- const files = [];
529
+ const proved = [];
486
530
  for (const folder of folders) {
487
- if (existsSync(join(folder, PROBE))) {
488
- unlinkSync(join(folder, PROBE));
489
- notes.push(
490
- `removed ${relative2(options.workspaceRoot, join(folder, PROBE))}, left by an interrupted run`
491
- );
492
- }
493
- const names = readdirSync(folder).filter((name) => TSCONFIG_NAME.test(name) && name !== PROBE);
494
- const targets = names.filter(
495
- (name) => extendsList(readTsconfig(join(folder, name))).some(isBaseEntry)
496
- );
497
- for (const target of targets) {
498
- const chain = extendsList(readTsconfig(join(folder, target)));
499
- if (!chain.some(isStackPresetEntry)) {
500
- files.push({
501
- file: relative2(options.workspaceRoot, join(folder, target)),
502
- kept: false,
503
- reason: "it extends the base but no sentinel preset: only an adopted module is detached. Run `sentinel --init --typescript` first"
504
- });
505
- continue;
506
- }
507
- files.push(migrateTsconfig(folder, target, names, options));
508
- }
531
+ removeLeftProbe(folder, notes, options.workspaceRoot);
532
+ proved.push(...proveFolder(folder, files, options.workspaceRoot));
509
533
  }
510
- formatWritten(moduleRoot, files, notes, options);
511
- const refused = files.filter((one) => !one.kept);
512
- const notAdopted = files.every((one) => one.reason?.includes("no sentinel preset") === true);
513
- if (notAdopted) {
514
- return {
515
- outcome: "blocked",
516
- message: "this module is not adopted: run `sentinel --init --typescript` first. Nothing was written",
517
- files,
518
- notes
519
- };
520
- }
521
- const unproved = files.filter((one) => one.configDifferences === void 0);
522
- if (!options.write) {
523
- const proved = files.every(
524
- (one) => one.configDifferences?.length === 0 && one.resolutionDifferences?.length === 0
525
- );
526
- return {
527
- outcome: proved ? "proved" : "failed",
528
- message: proved ? "dry run: tsc agrees before and after on every tsconfig; nothing was written" : unproved.length > 0 ? `dry run: ${unproved.length} tsconfig${unproved.length === 1 ? "" : "s"} could not be proved; nothing was written` : "dry run: tsc does not agree on every tsconfig; nothing was written",
529
- files,
530
- notes
531
- };
534
+ markPartlyAdopted(proved);
535
+ const allHold = proved.every(({ result }) => result.refusal === void 0);
536
+ const write = options.write && allHold;
537
+ if (write) {
538
+ for (const { result, contents } of proved) {
539
+ writeFileSync(resolve2(options.workspaceRoot, result.file), contents ?? "");
540
+ }
532
541
  }
533
- return {
534
- outcome: refused.length === 0 ? "migrated" : "failed",
535
- message: refused.length === 0 ? `detached ${files.length} tsconfig${files.length === 1 ? "" : "s"} from tsconfig.base.json` : `${refused.length} of ${files.length} tsconfig${files.length === 1 ? "" : "s"} kept as they were`,
536
- files,
537
- notes
538
- };
542
+ const results = proved.map(({ result }) => ({ ...result, kept: write }));
543
+ formatWritten(moduleRoot, results, notes, options);
544
+ return { ...summarize(results, options.write), files: results, notes };
539
545
  }
540
546
  export {
541
547
  ORIGINAL,
@@ -72,21 +72,49 @@ and the `paths` entries tsc reports having MATCHED (`--traceResolution`), the se
72
72
  files no tsconfig compiles included. Measured on 113 modules (sentinel#147), that is all that is
73
73
  left once the presets carry the base's standards.
74
74
 
75
- It keeps nothing unless tsc agrees, and restores the file otherwise:
75
+ It is all or nothing. Every tsconfig of the module that extends the base is proved first, each
76
+ rewritten and put back in turn, and the module's files are written only when tsc agrees on every
77
+ one of them, on both:
76
78
 
77
79
  - `--showConfig` of every tsconfig of the folder applies the same options, `paths` aside. Applied,
78
80
  not printed: the base printed `alwaysStrict`, `allowJs: false` and `isolatedModules`, and the
79
81
  presets leave them to `strict`, the default and `verbatimModuleSyntax`. Same compilation,
80
82
  different output, so the comparison derives those options the way tsc does
81
- (`src/roles/typescript/migrate/compare.ts`);
83
+ (`src/roles/typescript/compare.ts`);
82
84
  - every module and type reference tsc resolves, file by file, lands on the same file.
83
85
 
84
86
  A kept tsconfig is then formatted with the style the module states (its `.oxfmtrc.json`, else
85
87
  the workspace's Prettier), the same rule `--init --test` follows: whitespace only, after tsc agreed.
86
88
 
87
- It refuses, and writes nothing, for a module not adopted yet (run `--init --typescript` first), a
88
- tsconfig with comments, and a module whose installed sentinel has no `legacy`. A nested folder
89
- that is a module of its own is named and left to its own run.
89
+ It refuses, and writes nothing, for:
90
+
91
+ - a module not adopted yet (run `--init --typescript` first);
92
+ - a module with one tsconfig that extends the base without a sentinel preset, even when the others
93
+ are proved (`partly-adopted`). On the monorepo that is `tsconfig.acceptance.json` in `contract`
94
+ and `network`. Detaching the rest would leave the module compiling two ways, still on the base.
95
+ `--init` adopts the main tsconfig only, so the fix is to add the stack preset to that file's
96
+ `extends`, or to make it extend the adopted tsconfig;
97
+ - a tsconfig with comments;
98
+ - a module whose installed sentinel has no `legacy`, or resolves it from another install than its
99
+ stack preset;
100
+ - a tsconfig tsc cannot read (`error`, naming what tsc said), or a program that compiles files and
101
+ whose trace yields no resolution at all (`no-trace`): every program resolves at least its type
102
+ references, the smallest of the monorepo's 111 traces 447, so none means the trace was not read.
103
+
104
+ A nested folder that is a module of its own is named and left to its own run. Each refusal carries a
105
+ `refusal` code in `--json` (`not-adopted`, `partly-adopted`, `comments`, `no-legacy`,
106
+ `several-installs`, `no-trace`, `disagrees`, `error`).
107
+
108
+ `--dry-run` writes nothing either, but each tsconfig is rewritten on disk for the time of its proof.
109
+ A watcher (the Nx daemon, tsserver, a dev server) can see it come and go.
110
+
111
+ Once migrated, `--inspect` lists the compromises the module takes from `legacy` under
112
+ `inherited compromises (debt to remove)`: the options the stack preset does not set and the module
113
+ does not set itself, the ones that apply, each against the value the standard would apply
114
+ (`noImplicitAny — false, where the standard says true, inherited from …/legacy`). `--json` carries
115
+ the same lists as data: `standardOverrides` and `legacyCompromises`, each item with `rule`,
116
+ `value` and `standard`. The debt left the base, and stays
117
+ visible module by module until the module removes the `legacy` line.
90
118
 
91
119
  What it does not prove is tsc's view only: the Nx project graph still reads the root base's
92
120
  `paths`, and esbuild and Vite resolve each file through its nearest tsconfig. The base stays
@@ -117,7 +145,7 @@ sentinel --inspect --typescript # adoption + conformity coverage
117
145
  | `--ci` | from the root, only affected modules; non-zero exit on failure |
118
146
  | `--json` | machine-readable envelope on stdout, for every verb; progress goes to stderr |
119
147
  | `--max-diagnostics <n>` | cap the diagnostics embedded per module in `--run --json` (`0` = no cap) |
120
- | `--dry-run` | preview what `--init` would write, or prove `--migrate` and restore, changing nothing |
148
+ | `--dry-run` | preview what `--init` would write, or prove `--migrate` and write nothing (see above) |
121
149
  | `--rehearse` | with `--dry-run`: run the autofix passes in a copy and name the source they rewrite |
122
150
  | `--runner <tool>` | override the default runner |
123
151
  | `-- <tool options>` | `--run` only, one type named: everything after `--` goes to tsc itself (see below) |
@@ -225,3 +253,12 @@ it would hand it to the workspace tsconfig this module extends
225
253
  ```
226
254
 
227
255
  It is not reported as drift by `--inspect` either, so a module that legitimately overrides the base does not read as non-conformant forever.
256
+
257
+ Not drift, but not hidden either: `--inspect` lists it under `differs from the repo standard`,
258
+ with both values. An option a preset took over from the base (`fromBase`) and that the module
259
+ sets to another value is this module departing from the standard, and that is worth seeing:
260
+
261
+ ```
262
+ differs from the repo standard (kept by --init, not drift):
263
+ • verbatimModuleSyntax — false, where the nest preset says true
264
+ ```