@evobug_com/safe-ts-skill 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,671 @@
1
+ #!/usr/bin/env node
2
+ // The migration census: what `safe-ts check --idiomatic` reports, per rule and per directory
3
+ // (the idiomatic rules see `x.tag === ...`, `if (isErr(x)) return x`, partial type guards,
4
+ // `'key' in` on a union, casts in tests, `unwrapOr(x, undefined)`, `JsonNull` in app state),
5
+ // the hand-rolled patterns no rule reports (loading/error/data trios, sentinels, string
6
+ // if-chains, boolean flag sets, raw fetch, try/catch, casts, ...), the escape hatches
7
+ // (`unsafe`, `panic`, `trust`, `LegacyNull`, `safe-ts-ignore`, legacy markers, ...), and which
8
+ // SAFE-TS features the code already uses.
9
+ //
10
+ // node census.mjs [dirs or files...] a report (default: the current directory)
11
+ // node census.mjs --json > census.json the same as JSON
12
+ // node census.mjs --show loading-flag every place one pattern was found
13
+ // node census.mjs --write-baseline census-baseline.json
14
+ // node census.mjs --baseline census-baseline.json exit 1 if any count rose (a gate)
15
+ //
16
+ // Options: --depth <n> (directory grouping, default 2), --no-check (patterns only),
17
+ // --no-idiomatic (leave the idiomatic rules out), --entry <file> (check only from these
18
+ // entries; repeatable; default: every scanned file, so tests, scripts and files nothing
19
+ // imports are counted like the patterns are).
20
+ //
21
+ // The patterns are regular expressions over the text, so they are a map of where to look,
22
+ // not findings: read each place before changing it. Comment lines are skipped, except for
23
+ // `safe-ts-ignore` comments, which are counted.
24
+ import { execFileSync, spawnSync } from "node:child_process";
25
+ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
26
+ import { extname, join, relative, resolve, sep } from "node:path";
27
+
28
+ import { findSafeTs } from "./safe-ts.mjs";
29
+
30
+ // ---- options -----------------------------------------------------------------------------
31
+
32
+ const args = process.argv.slice(2);
33
+ const option = (name) => {
34
+ const i = args.indexOf(name);
35
+ return i === -1 ? undefined : args[i + 1];
36
+ };
37
+ const repeated = (name) => args.flatMap((a, i) => (a === name && args[i + 1] !== undefined ? [args[i + 1]] : []));
38
+ const VALUED = new Set(["--depth", "--show", "--baseline", "--write-baseline", "--entry"]);
39
+ const targets = args.filter((a, i) => !a.startsWith("--") && !VALUED.has(args[i - 1]));
40
+ const depth = Number(option("--depth") ?? 2);
41
+ const root = process.cwd();
42
+ const EXTENSIONS = new Set([".ts", ".tsx", ".mts", ".cts", ".vue", ".jsx"]);
43
+ const SKIPPED_DIRS = new Set(["node_modules", ".git", "dist", "build", "coverage", "target", ".output", ".nuxt", ".next", ".cache", ".safe-ts"]);
44
+
45
+ // ---- the patterns ------------------------------------------------------------------------
46
+
47
+ const LOADING_NAME = String.raw`(?:is|set)?(?:[Ll]oading|[Bb]usy|[Pp]ending|[Ff]etching|[Ss]aving|[Ss]ubmitting|[Rr]efreshing|[Ww]orking|[Ii]nFlight)\w*`;
48
+ const ERROR_NAME = String.raw`\w*(?:[Ee]rror|[Ee]rr|[Ff]ailure|[Ff]ailed|[Pp]roblem)\w*`;
49
+ const BOOL_STATE = String.raw`(?:ref|shallowRef|useState)(?:<boolean>)?\(\s*(?:true|false)\s*\)`;
50
+
51
+ // `x as T`: a value, then `as`, then something that starts a type (a capitalised name, an
52
+ // object, tuple or function type, or a built-in type keyword), so English text in a template
53
+ // ("saved as draft") doesn't count. `as const` isn't a cast.
54
+ const CAST = /(?:[\w$)\]}>'"`]|\?\.)\s+as\s+(?:[A-Z{[(]|(?:string|number|boolean|bigint|symbol|object|unknown|never|any|undefined|readonly|keyof|typeof)\b)/;
55
+ // `import { a as b }`, `export * as ns from`, `export { a as b }`: renames, not casts.
56
+ const REEXPORT = /^\s*(?:import\b|export\s*(?:\*|\{|type\s*\{))/;
57
+
58
+ /**
59
+ * Each pattern: what it finds, where the catalogue says what to write instead, and whether
60
+ * the architecture gate holds it down (`gate`: its count may only fall).
61
+ * `line` is tested on each line that isn't a comment (`comment`: on each comment line instead).
62
+ */
63
+ const PATTERNS = [
64
+ {
65
+ id: "loading-flag",
66
+ what: "a boolean loading/busy flag (ref, useState or let)",
67
+ see: "patterns-vue.md#a-loading-error-data-trio / patterns-react.md#a-loading-error-data-trio",
68
+ gate: true,
69
+ line: new RegExp(
70
+ String.raw`(?:\b(?:const|let)\s+${LOADING_NAME}\s*=\s*${BOOL_STATE})|(?:\bconst\s*\[\s*${LOADING_NAME}\s*,\s*\w+\s*\]\s*=\s*${BOOL_STATE})|(?:\blet\s+${LOADING_NAME}\s*=\s*(?:true|false)\b)`,
71
+ ),
72
+ },
73
+ {
74
+ id: "error-state",
75
+ what: "an error kept in its own state: ref('')/ref(null)/ref<E>()/useState('') named error, failed, ...",
76
+ see: "patterns-vue.md#a-loading-error-data-trio",
77
+ gate: true,
78
+ line: new RegExp(
79
+ String.raw`(?:\b(?:const|let)\s+${ERROR_NAME}\s*=\s*(?:ref|shallowRef)(?:<[^>]*>)?\(\s*(?:''|""|null|undefined)?\s*\))|(?:\bconst\s*\[\s*${ERROR_NAME}\s*,\s*\w+\s*\]\s*=\s*useState(?:<[^>]*>)?\(\s*(?:''|""|null|undefined)?\s*\))`,
80
+ ),
81
+ },
82
+ {
83
+ id: "empty-string-sentinel",
84
+ what: "'' compared or returned: check whether it means \"none\" or \"no error\"",
85
+ see: "patterns-core.md#a-sentinel-value",
86
+ gate: true,
87
+ line: /(?:[!=]==?\s*(?:''|""))|(?:(?:''|"")\s*[!=]==?)|(?:\breturn\s+(?:''|"")\s*;?\s*$)/,
88
+ },
89
+ {
90
+ id: "minus-one-sentinel",
91
+ what: "-1 compared, returned or assigned (often \"not found\" or \"none selected\")",
92
+ see: "patterns-core.md#a-sentinel-value",
93
+ gate: true,
94
+ line: /(?:[!=]==?\s*-1\b)|(?:\breturn\s+-1\b)|(?:[^=!<>]=\s*-1\s*[;,)]?\s*$)|(?:\(\s*-1\s*\))/,
95
+ },
96
+ {
97
+ id: "zero-sentinel",
98
+ what: "an id or index that starts at 0 (check whether 0 means \"none\")",
99
+ see: "patterns-core.md#a-sentinel-value",
100
+ gate: false,
101
+ line: /\b(?:const|let)\s+\w*(?:[Ii]d|[Ii]ndex|[Ss]elected|[Aa]ctive|[Cc]urrent)\s*=\s*(?:(?:ref|shallowRef|useState)(?:<number>)?\(\s*0\s*\)|0\s*;?\s*$)/,
102
+ },
103
+ {
104
+ id: "boolean-state",
105
+ what: "a boolean state (ref, useState); 3 or more in a file are listed under boolean-flag-files",
106
+ see: "patterns-core.md#a-set-of-boolean-flags",
107
+ gate: false,
108
+ line: new RegExp(String.raw`\b(?:const|let)\s+(?:\[\s*)?\w+(?:\s*,\s*\w+\s*\])?\s*=\s*${BOOL_STATE}`),
109
+ },
110
+ {
111
+ id: "raw-fetch",
112
+ what: "fetch(...) or an HTTP client called directly (axios, XMLHttpRequest)",
113
+ see: "patterns-core.md#requests-return-a-result",
114
+ gate: true,
115
+ line: /(?:(?<![.\w$])fetch\s*\()|(?:\baxios(?:\.\w+)?\s*\()|(?:\bnew\s+XMLHttpRequest\b)/,
116
+ },
117
+ {
118
+ id: "try-catch",
119
+ what: "a try block (around your own code, a Result is the answer; around a library, unsafe or a safe version)",
120
+ see: "patterns-core.md#try-and-catch-around-your-own-code",
121
+ gate: true,
122
+ line: /\btry\s*\{/,
123
+ },
124
+ {
125
+ id: "promise-catch",
126
+ what: ".catch(...) on a promise (a promise of a Result can't reject; a .catch on it hides that)",
127
+ see: "patterns-core.md#try-and-catch-around-your-own-code",
128
+ gate: true,
129
+ line: /\.catch\s*\(/,
130
+ },
131
+ {
132
+ id: "as-cast",
133
+ what: "an `as` cast (as const excluded)",
134
+ see: "patterns-core.md#a-cast",
135
+ gate: true,
136
+ line: CAST,
137
+ skip: REEXPORT,
138
+ },
139
+ {
140
+ id: "double-cast",
141
+ what: "as unknown as / as never / as any",
142
+ see: "patterns-core.md#a-cast",
143
+ gate: true,
144
+ line: /\bas\s+(?:unknown\s+as|never|any)\b/,
145
+ skip: REEXPORT,
146
+ },
147
+ {
148
+ id: "json-parse",
149
+ what: "JSON.parse(...) (parseJson<T> checks the shape)",
150
+ see: "patterns-core.md#json-and-storage",
151
+ gate: true,
152
+ line: /\bJSON\.parse\s*\(/,
153
+ },
154
+ {
155
+ id: "raw-storage",
156
+ what: "localStorage / sessionStorage called directly",
157
+ see: "patterns-core.md#json-and-storage",
158
+ gate: true,
159
+ line: /\b(?:localStorage|sessionStorage)\.(?:getItem|setItem|removeItem|key)\s*\(/,
160
+ },
161
+ {
162
+ id: "unsafe-async",
163
+ what: "unsafeAsync(...) (around your own Result-returning code, pass Panic)",
164
+ see: "escape-hatches.md",
165
+ gate: true,
166
+ line: /\bunsafeAsync\s*\(/,
167
+ },
168
+ {
169
+ id: "unsafe",
170
+ what: "unsafe(...)",
171
+ see: "escape-hatches.md",
172
+ gate: true,
173
+ line: /(?<![\w$.])unsafe\s*\(/,
174
+ },
175
+ {
176
+ id: "unexplained-unsafe",
177
+ what: "unsafe(...)/unsafeAsync(...) with no comment on its line or the line above",
178
+ see: "escape-hatches.md",
179
+ gate: true,
180
+ line: /(?<![\w$.])unsafe(?:Async)?\s*\(/,
181
+ needsReason: true,
182
+ },
183
+ {
184
+ id: "panic",
185
+ what: "panic(...) (only for invariants; never for loading or server data)",
186
+ see: "escape-hatches.md",
187
+ gate: true,
188
+ line: /(?<![\w$.])panic\s*\(/,
189
+ },
190
+ {
191
+ id: "void-call",
192
+ what: "void f(...): a Result or promise dropped on purpose",
193
+ see: "escape-hatches.md",
194
+ gate: true,
195
+ line: /\bvoid\s+[\w$.]+\s*\(/,
196
+ },
197
+ {
198
+ id: "trust",
199
+ what: "trust<T>(value): a trusted boundary, typed without a check",
200
+ see: "escape-hatches.md",
201
+ gate: true,
202
+ line: /(?<![\w$.])trust\s*(?:<[^>]*>\s*)?\(/,
203
+ },
204
+ {
205
+ id: "legacy-null",
206
+ what: "LegacyNull: strict code still taking null from callers not migrated yet (a bridge, meant to go)",
207
+ see: "escape-hatches.md",
208
+ gate: true,
209
+ line: /\bLegacyNull\b/,
210
+ skip: /^\s*import\b/,
211
+ },
212
+ {
213
+ id: "safe-ts-ignore",
214
+ what: "// safe-ts-ignore <rule>: <reason> (and -file, and <!-- --> in templates): a finding silenced",
215
+ see: "escape-hatches.md",
216
+ gate: true,
217
+ comment: true,
218
+ line: /^\s*(?:\/\/|\/\*|<!--)\s*safe-ts-ignore(?:-file)?\b/,
219
+ },
220
+ {
221
+ id: "module-let",
222
+ what: "a `let` at the top of a .ts module (module state)",
223
+ see: "patterns-vue.md#module-state / patterns-react.md#module-state",
224
+ gate: true,
225
+ line: /^(?:export\s+)?let\s+[\w$]/,
226
+ only: (file) => !file.endsWith(".vue"),
227
+ },
228
+ ];
229
+
230
+ /**
231
+ * Rules whose findings have a catalogue entry: the idiomatic rules a checker-driven migration
232
+ * trips over, and the ones its first census is full of. The report names the entry.
233
+ */
234
+ const RULE_SEE = {
235
+ "prefer-is-over-tag": "patterns-core.md#reading-an-enum-one-style",
236
+ "prefer-q": "patterns-core.md#passing-an-error-up",
237
+ "prefer-map-err": "patterns-core.md#passing-an-error-up",
238
+ "key-presence-union": "patterns-core.md#a-union-told-apart-by-keys",
239
+ "partial-type-guard": "patterns-core.md#a-hand-written-type-guard",
240
+ "cast-in-test": "patterns-core.md#casts-in-tests",
241
+ "no-swallowed-error": "patterns-core.md#a-failure-turned-into-undefined",
242
+ "sentinel-error": "patterns-core.md#a-sentinel-value",
243
+ "strict-truthiness": "patterns-core.md#a-sentinel-value",
244
+ "brand-constructor": "patterns-core.md#a-cast",
245
+ "json-null-in-app": "patterns-core.md#an-api-that-sends-null",
246
+ "undefined-to-null": "patterns-core.md#an-api-that-sends-null",
247
+ "catch-on-result": "patterns-core.md#try-and-catch-around-your-own-code",
248
+ "misplaced-axios-check": "patterns-core.md#requests-return-a-result",
249
+ "unsafe-project-call": "patterns-core.md#a-bug-inside-a-result-returning-call",
250
+ "panic-on-loading": "patterns-core.md#panic-on-a-loading-state",
251
+ "latest-wins-counter": "patterns-vue.md#module-state",
252
+ "unused-task-signal": "patterns-vue.md#a-loading-error-data-trio",
253
+ "no-throw": "patterns-core.md#a-function-that-throws",
254
+ "fetch-signal": "patterns-core.md#requests-return-a-result",
255
+ "no-unchecked-cast": "patterns-core.md#a-cast",
256
+ "no-object-dictionary": "patterns-core.md#a-table-keyed-by-server-data",
257
+ "json-type": "patterns-core.md#a-cast",
258
+ "no-mutable-global": "patterns-vue.md#module-state / patterns-react.md#module-state",
259
+ "vue-split-state": "patterns-vue.md#a-loading-error-data-trio",
260
+ "vue-async-race": "patterns-vue.md#a-loading-error-data-trio",
261
+ "vue-ref-without-value": "patterns-vue.md#a-ref-filled-after-mount",
262
+ "vue-template-ref": "patterns-vue.md#a-template-ref",
263
+ "vue-v-html": "patterns-vue.md#v-html-and-bound-urls",
264
+ "vue-unsafe-url": "patterns-vue.md#v-html-and-bound-urls",
265
+ };
266
+
267
+ /** SAFE-TS features: how often the code uses each (for the final pass). */
268
+ const FEATURES = [
269
+ ["useTask", /\buseTask\s*\(/],
270
+ ["reset()", /\.reset\s*\(\s*\)|\breset\s*\(\s*\)/],
271
+ ["AsyncState", /\bAsyncState\b/],
272
+ ["Enum<", /\bEnum\s*</],
273
+ ["constructors<", /\bconstructors\s*</],
274
+ ["match(", /(?<![\w$.])match\s*\(/],
275
+ ["<Match>", /<Match\b/],
276
+ ["is(", /(?<![\w$.])is\s*\(/],
277
+ ["variant(", /(?<![\w$.])variant\s*\(/],
278
+ ["q(", /(?<![\w$.])q\s*\(/],
279
+ ["mapErr(", /\bmapErr\s*\(/],
280
+ ["Option<", /\bOption\s*</],
281
+ ["parseJson<", /\bparseJson\s*</],
282
+ ["validate<", /\bvalidate\s*</],
283
+ ["useElement", /\buse(?:Optional)?Elements?\s*</],
284
+ ["safeHref(", /\bsafeHref\s*\(/],
285
+ ["PropagateError", /\bPropagateError\b/],
286
+ ["getOwn(", /\bgetOwn\s*\(/],
287
+ ["Open<", /\bOpen\s*</],
288
+ ["lookup(", /(?<![\w$.])lookup\s*\(/],
289
+ ["Patch<", /\bPatch\s*</],
290
+ ["defineSanitizer(", /\bdefineSanitizer\s*\(/],
291
+ ["Html/SafeUrl", /\b(?:Html|SafeUrl)\b/],
292
+ ["toBase64/fromBase64", /\b(?:toBase64|fromBase64(?:Bytes)?)\s*\(/],
293
+ ["fixture/testDouble", /\b(?:fixture|testDouble)\s*</],
294
+ ];
295
+
296
+ // ---- files -------------------------------------------------------------------------------
297
+
298
+ function sourceFiles() {
299
+ const roots = targets.length === 0 ? ["."] : targets;
300
+ const files = new Set();
301
+ for (const target of roots) {
302
+ const absolute = resolve(root, target);
303
+ if (!existsSync(absolute)) {
304
+ console.error(`census: not found: ${target}`);
305
+ process.exit(2);
306
+ }
307
+ if (statSync(absolute).isFile()) {
308
+ files.add(relative(root, absolute));
309
+ continue;
310
+ }
311
+ for (const file of gitFiles(absolute) ?? walk(absolute)) files.add(relative(root, file));
312
+ }
313
+ return [...files].filter((f) => EXTENSIONS.has(extname(f)) && !/\.d\.[cm]?ts$/.test(f)).map((f) => f.split(sep).join("/")).sort();
314
+ }
315
+
316
+ /** Tracked and untracked-but-not-ignored files, when the directory is in a git repository. */
317
+ function gitFiles(dir) {
318
+ try {
319
+ const out = execFileSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", "."], {
320
+ cwd: dir,
321
+ encoding: "utf8",
322
+ maxBuffer: 256 * 1024 * 1024,
323
+ stdio: ["ignore", "pipe", "ignore"],
324
+ });
325
+ return out.split("\0").filter((f) => f !== "").map((f) => join(dir, f)).filter((f) => existsSync(f));
326
+ } catch {
327
+ return undefined;
328
+ }
329
+ }
330
+
331
+ function walk(dir) {
332
+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
333
+ if (entry.isDirectory()) return SKIPPED_DIRS.has(entry.name) ? [] : walk(join(dir, entry.name));
334
+ return entry.isFile() ? [join(dir, entry.name)] : [];
335
+ });
336
+ }
337
+
338
+ const directoryOf = (file) => {
339
+ const parts = file.split("/").slice(0, -1);
340
+ return parts.length === 0 ? "." : parts.slice(0, depth).join("/");
341
+ };
342
+
343
+ // ---- scanning ----------------------------------------------------------------------------
344
+
345
+ /** The lines of a file that aren't comments, with their numbers (block comments followed roughly). */
346
+ function codeLines(text) {
347
+ const lines = [];
348
+ let inBlock = false;
349
+ text.split(/\r?\n/).forEach((raw, i) => {
350
+ const line = raw.trim();
351
+ if (inBlock) {
352
+ if (line.includes("*/")) inBlock = false;
353
+ return;
354
+ }
355
+ if (line.startsWith("/*") || line.startsWith("<!--")) {
356
+ if (!line.includes("*/") && !line.includes("-->")) inBlock = line.startsWith("/*");
357
+ return;
358
+ }
359
+ if (line.startsWith("//") || line.startsWith("*")) return;
360
+ lines.push({ number: i + 1, text: raw });
361
+ });
362
+ return lines;
363
+ }
364
+
365
+ const hasComment = (lines, index) => {
366
+ const { text } = lines[index];
367
+ if (/\/\/|\/\*/.test(text)) return true;
368
+ return false;
369
+ };
370
+
371
+ function scan(files) {
372
+ const patterns = Object.fromEntries(PATTERNS.map((p) => [p.id, { what: p.what, see: p.see, gate: p.gate, count: 0, byFile: {}, places: [] }]));
373
+ patterns["boolean-flag-files"] = { what: "files with 3 or more boolean states", see: "patterns-core.md#a-set-of-boolean-flags", gate: true, count: 0, byFile: {}, places: [] };
374
+ patterns["trio-files"] = { what: "files with both a loading flag and an error state: a loading/error/data trio", see: "patterns-vue.md#a-loading-error-data-trio", gate: true, count: 0, byFile: {}, places: [] };
375
+ patterns["string-if-chain"] = { what: "a value compared with 3 or more string literals in one file (a closed set handled by if-chains)", see: "patterns-core.md#a-closed-set-of-states", gate: true, count: 0, byFile: {}, places: [] };
376
+ const features = Object.fromEntries(FEATURES.map(([name]) => [name, 0]));
377
+ const legacy = [];
378
+ const std = [];
379
+ let cacheMarks = 0;
380
+ const kinds = {};
381
+
382
+ for (const file of files) {
383
+ const text = readFileSync(join(root, file), "utf8");
384
+ kinds[extname(file)] = (kinds[extname(file)] ?? 0) + 1;
385
+ // `// @safe-ts legacy`, or `<!-- @safe-ts legacy -->` in a component.
386
+ if (/(?:\/\/|<!--)\s*@safe-ts legacy\b/.test(text)) legacy.push(file);
387
+ if (/\/\/\s*@safe-ts std\b/.test(text)) std.push(file);
388
+ cacheMarks += (text.match(/\/\*\*\s*@cache\s*\*\//g) ?? []).length;
389
+ const raw = text.split(/\r?\n/);
390
+ const lines = codeLines(text);
391
+ const hit = (id, line) => {
392
+ const p = patterns[id];
393
+ p.count += 1;
394
+ p.byFile[file] = (p.byFile[file] ?? 0) + 1;
395
+ p.places.push(`${file}:${line.number}: ${line.text.trim().slice(0, 140)}`);
396
+ };
397
+ raw.forEach((line, i) => {
398
+ for (const pattern of PATTERNS) {
399
+ if (pattern.comment && (!pattern.only || pattern.only(file)) && pattern.line.test(line)) hit(pattern.id, { number: i + 1, text: line });
400
+ }
401
+ });
402
+ const comparisons = new Map();
403
+ lines.forEach((line, index) => {
404
+ for (const pattern of PATTERNS) {
405
+ if (pattern.comment) continue;
406
+ if (pattern.only && !pattern.only(file)) continue;
407
+ if (pattern.skip?.test(line.text)) continue;
408
+ if (!pattern.line.test(line.text)) continue;
409
+ if (pattern.needsReason) {
410
+ const above = raw[line.number - 2] ?? "";
411
+ if (hasComment(lines, index) || /^\s*(?:\/\/|\*|\/\*)/.test(above)) continue;
412
+ }
413
+ hit(pattern.id, line);
414
+ }
415
+ for (const [name, re] of FEATURES) if (re.test(line.text)) features[name] += 1;
416
+ for (const m of line.text.matchAll(/([\w$][\w$.?]*)\s*[!=]==\s*(['"])([^'"\n]+)\2/g)) {
417
+ const subject = m[1];
418
+ if (subject.endsWith(".tag") || subject === "typeof" || /^(?:process\.env|import\.meta)/.test(subject)) continue;
419
+ const seen = comparisons.get(subject) ?? { literals: new Set(), first: line };
420
+ seen.literals.add(m[3]);
421
+ comparisons.set(subject, seen);
422
+ }
423
+ });
424
+ for (const [subject, { literals, first }] of comparisons) {
425
+ if (literals.size >= 3) hit("string-if-chain", { number: first.number, text: `${subject}: ${[...literals].map((l) => `'${l}'`).join(", ")}` });
426
+ }
427
+ const booleans = patterns["boolean-state"].byFile[file] ?? 0;
428
+ if (booleans >= 3) hit("boolean-flag-files", { number: 1, text: `${booleans} boolean states` });
429
+ if ((patterns["loading-flag"].byFile[file] ?? 0) > 0 && (patterns["error-state"].byFile[file] ?? 0) > 0) {
430
+ hit("trio-files", { number: 1, text: "loading flag and error state in one file" });
431
+ }
432
+ }
433
+ return { patterns, features, legacy, std, cacheMarks, kinds };
434
+ }
435
+
436
+ // ---- the checker -------------------------------------------------------------------------
437
+
438
+ function runChecker(files) {
439
+ if (args.includes("--no-check")) return { skipped: "--no-check" };
440
+ const binary = findSafeTs(root);
441
+ if (binary === undefined) return { skipped: "no safe-ts binary found (install @evobug_com/safe-ts-transform, or set SAFE_TS_BIN)" };
442
+ const given = repeated("--entry");
443
+ // Every scanned file as an entry. `check` follows imports (relative, tsconfig `paths`,
444
+ // workspace packages) from its entries, so the app's entry points would reach the app; but
445
+ // tests, scripts, workers whose path is built at runtime and files nothing imports would be
446
+ // left out, while the patterns count them.
447
+ const entries = given.length > 0 ? given : files;
448
+ // The idiomatic rules see several hand-rolled forms (raw tag reads, `if (isErr(x)) return x`,
449
+ // partial guards, ...): count them whether or not package.json turns the layer on yet.
450
+ const flags = args.includes("--no-idiomatic") ? ["--json"] : ["--json", "--idiomatic"];
451
+ const chunks = [];
452
+ // Keep each command line well under Windows' 32k characters.
453
+ let chunk = [];
454
+ let length = 0;
455
+ for (const entry of entries) {
456
+ if (chunk.length > 0 && length + entry.length > 24_000) {
457
+ chunks.push(chunk);
458
+ chunk = [];
459
+ length = 0;
460
+ }
461
+ chunk.push(entry);
462
+ length += entry.length + 1;
463
+ }
464
+ if (chunk.length > 0) chunks.push(chunk);
465
+ const seen = new Set();
466
+ const diagnostics = [];
467
+ for (const part of chunks) {
468
+ const run = spawnSync(binary, ["check", ...part, ...flags], { cwd: root, encoding: "utf8", maxBuffer: 1024 * 1024 * 1024 });
469
+ if (run.error) return { skipped: `could not run ${binary}: ${run.error.message}` };
470
+ let parsed;
471
+ try {
472
+ parsed = JSON.parse(run.stdout);
473
+ } catch {
474
+ return { skipped: `safe-ts check failed (exit ${run.status}): ${(run.stderr || run.stdout).trim().split("\n").slice(0, 5).join(" | ")}` };
475
+ }
476
+ for (const d of parsed) {
477
+ const key = `${d.file}:${d.line}:${d.column}:${d.rule}:${d.message}`;
478
+ if (seen.has(key)) continue;
479
+ seen.add(key);
480
+ diagnostics.push(d);
481
+ }
482
+ }
483
+ const version = spawnSync(binary, ["--version"], { encoding: "utf8" }).stdout?.trim().replace(/^safe-ts /, "");
484
+ return { binary, version, idiomatic: flags.includes("--idiomatic"), entries: entries.length, diagnostics };
485
+ }
486
+
487
+ function summarizeFindings(diagnostics) {
488
+ const byRule = {};
489
+ const byDir = {};
490
+ const origins = {};
491
+ let warnings = 0;
492
+ for (const d of diagnostics) {
493
+ const file = d.file.split(sep).join("/");
494
+ const dir = directoryOf(file);
495
+ const rule = (byRule[d.rule] ??= { total: 0, severity: d.severity ?? "error", byDir: {}, byFile: {} });
496
+ rule.total += 1;
497
+ if (d.severity === "warning") warnings += 1;
498
+ rule.byDir[dir] = (rule.byDir[dir] ?? 0) + 1;
499
+ rule.byFile[file] = (rule.byFile[file] ?? 0) + 1;
500
+ byDir[dir] = (byDir[dir] ?? 0) + 1;
501
+ if (d.origin) origins[d.origin] = (origins[d.origin] ?? 0) + 1;
502
+ }
503
+ const topOrigins = Object.entries(origins).filter(([, n]) => n >= 3).sort((a, b) => b[1] - a[1]).slice(0, 15);
504
+ return {
505
+ total: diagnostics.length,
506
+ errors: diagnostics.length - warnings,
507
+ warnings,
508
+ byRule,
509
+ byDir,
510
+ origins: topOrigins.map(([origin, count]) => ({ origin, count })),
511
+ };
512
+ }
513
+
514
+ // ---- report ------------------------------------------------------------------------------
515
+
516
+ const files = sourceFiles();
517
+ const scanned = scan(files);
518
+ const checker = runChecker(files);
519
+ const findings = checker.diagnostics ? summarizeFindings(checker.diagnostics) : undefined;
520
+ const byDir = (byFile) => {
521
+ const out = {};
522
+ for (const [file, n] of Object.entries(byFile)) out[directoryOf(file)] = (out[directoryOf(file)] ?? 0) + n;
523
+ return out;
524
+ };
525
+
526
+ const report = {
527
+ generated: new Date().toISOString(),
528
+ root,
529
+ files: { total: files.length, byExtension: scanned.kinds, legacy: scanned.legacy.length, std: scanned.std },
530
+ checker: checker.diagnostics
531
+ ? { binary: checker.binary, version: checker.version, idiomatic: checker.idiomatic, entries: checker.entries }
532
+ : { skipped: checker.skipped },
533
+ findings,
534
+ escapeHatches: {
535
+ legacyFiles: scanned.legacy.length,
536
+ unsafe: scanned.patterns.unsafe.count,
537
+ unsafeAsync: scanned.patterns["unsafe-async"].count,
538
+ unexplainedUnsafe: scanned.patterns["unexplained-unsafe"].count,
539
+ panic: scanned.patterns.panic.count,
540
+ trust: scanned.patterns.trust.count,
541
+ legacyNull: scanned.patterns["legacy-null"].count,
542
+ safeTsIgnore: scanned.patterns["safe-ts-ignore"].count,
543
+ void: scanned.patterns["void-call"].count,
544
+ cacheMarks: scanned.cacheMarks,
545
+ stdFiles: scanned.std.length,
546
+ casts: scanned.patterns["as-cast"].count,
547
+ },
548
+ patterns: Object.fromEntries(
549
+ Object.entries(scanned.patterns).map(([id, p]) => [id, { what: p.what, see: p.see, gate: p.gate, count: p.count, files: Object.keys(p.byFile).length, byDir: byDir(p.byFile), byFile: p.byFile }]),
550
+ ),
551
+ features: scanned.features,
552
+ };
553
+
554
+ const show = option("--show");
555
+ if (show !== undefined) {
556
+ const pattern = scanned.patterns[show];
557
+ const rule = checker.diagnostics?.filter((d) => d.rule === show);
558
+ if (pattern) for (const place of pattern.places) console.log(place);
559
+ else if (rule && rule.length > 0) for (const d of rule) console.log(`${d.file}:${d.line}:${d.column}: ${d.message}`);
560
+ else {
561
+ console.error(`census: no pattern or reported rule named "${show}"; patterns: ${Object.keys(scanned.patterns).join(", ")}`);
562
+ process.exit(2);
563
+ }
564
+ process.exit(0);
565
+ }
566
+
567
+ const written = option("--write-baseline");
568
+ if (written !== undefined) {
569
+ writeFileSync(written, `${JSON.stringify(baselineOf(report), null, 2)}\n`);
570
+ console.error(`census: baseline written to ${written}`);
571
+ }
572
+
573
+ const baseline = option("--baseline");
574
+ if (baseline !== undefined) process.exit(gate(JSON.parse(readFileSync(baseline, "utf8")), baselineOf(report)));
575
+
576
+ if (args.includes("--json")) console.log(JSON.stringify(report, null, 2));
577
+ else if (written === undefined) printReport(report);
578
+
579
+ /** What a baseline keeps: per gated pattern and per rule, the count in each file. */
580
+ function baselineOf(r) {
581
+ const gated = Object.fromEntries(Object.entries(r.patterns).filter(([, p]) => p.gate).map(([id, p]) => [id, p.byFile]));
582
+ const rules = Object.fromEntries(Object.entries(r.findings?.byRule ?? {}).map(([rule, x]) => [rule, x.byFile]));
583
+ return { generated: r.generated, patterns: gated, rules, legacyFiles: r.files.legacy };
584
+ }
585
+
586
+ /** The architecture gate: 1 when a count rose in any file, with the files named. */
587
+ function gate(before, now) {
588
+ const rises = [];
589
+ const compare = (kind, id, old = {}, current = {}) => {
590
+ for (const [file, n] of Object.entries(current)) {
591
+ const was = old[file] ?? 0;
592
+ if (n > was) rises.push(`${kind} ${id}: ${file} ${was} -> ${n}`);
593
+ }
594
+ };
595
+ for (const [id, current] of Object.entries(now.patterns)) compare("pattern", id, before.patterns?.[id], current);
596
+ if (checker.diagnostics) for (const [rule, current] of Object.entries(now.rules)) compare("rule", rule, before.rules?.[rule], current);
597
+ if (now.legacyFiles > (before.legacyFiles ?? 0)) rises.push(`legacy files: ${before.legacyFiles ?? 0} -> ${now.legacyFiles}`);
598
+ if (rises.length === 0) {
599
+ console.log("census gate: no count rose against the baseline");
600
+ return 0;
601
+ }
602
+ console.log(`census gate: ${rises.length} count(s) rose against the baseline`);
603
+ for (const rise of rises) console.log(` ${rise}`);
604
+ console.log("Fix them, or (for a reviewed exception) write a new baseline with --write-baseline.");
605
+ return 1;
606
+ }
607
+
608
+ function printReport(r) {
609
+ const n = (x) => x.toLocaleString("en-US");
610
+ const pad = (s, w) => String(s).padEnd(w);
611
+ const lpad = (s, w) => String(s).padStart(w);
612
+ const top = (dirs, k = 3) => Object.entries(dirs).sort((a, b) => b[1] - a[1]).slice(0, k).map(([d, c]) => `${d} (${n(c)})`).join(", ");
613
+ const kinds = Object.entries(r.files.byExtension).map(([e, c]) => `${n(c)} ${e}`).join(", ");
614
+ console.log(`SAFE-TS census: ${n(r.files.total)} files (${kinds}), ${n(r.files.legacy)} marked legacy\n`);
615
+
616
+ if (r.findings) {
617
+ const how = `safe-ts ${r.checker.version ?? ""} check --json${r.checker.idiomatic ? " --idiomatic" : ""}`.replace(" ", " ");
618
+ console.log(
619
+ `Checker findings (${how}, ${n(r.checker.entries)} entries): ${n(r.findings.total)} ` +
620
+ `(${n(r.findings.errors)} errors, ${n(r.findings.warnings)} warnings)`,
621
+ );
622
+ const rules = Object.entries(r.findings.byRule).sort((a, b) => b[1].total - a[1].total);
623
+ for (const [rule, x] of rules) {
624
+ const level = x.severity === "warning" ? " (warn)" : "";
625
+ console.log(` ${pad(rule + level, 30)} ${lpad(n(x.total), 7)} ${top(x.byDir)}`);
626
+ if (RULE_SEE[rule]) console.log(` ${pad("", 30)} ${" ".repeat(7)} see references/${RULE_SEE[rule]}`);
627
+ }
628
+ if (r.findings.origins.length > 0) {
629
+ console.log("\n Root causes (one origin, 3 or more findings):");
630
+ for (const { origin, count } of r.findings.origins) console.log(` ${lpad(n(count), 7)} ${origin}`);
631
+ }
632
+ if (r.files.legacy > 0) console.log("\n Legacy files report nothing; remove a marker to see that file's findings.");
633
+ } else {
634
+ console.log(`Checker not run: ${r.checker.skipped}`);
635
+ }
636
+
637
+ console.log("\nPatterns the checker doesn't report (heuristic: read each place):");
638
+ for (const [id, p] of Object.entries(r.patterns)) {
639
+ if (p.count === 0) continue;
640
+ console.log(` ${pad(id, 24)} ${lpad(n(p.count), 6)} in ${lpad(n(p.files), 4)} files ${top(p.byDir, 2)}`);
641
+ console.log(` ${pad("", 24)} ${p.what}; see references/${p.see}`);
642
+ }
643
+
644
+ const h = r.escapeHatches;
645
+ console.log(
646
+ `\nEscape hatches: ${n(h.legacyFiles)} legacy file(s), ${n(h.unsafe)} unsafe(), ${n(h.unsafeAsync)} unsafeAsync(), ` +
647
+ `${n(h.unexplainedUnsafe)} without a reason comment, ${n(h.panic)} panic(), ${n(h.trust)} trust(), ` +
648
+ `${n(h.legacyNull)} LegacyNull, ${n(h.safeTsIgnore)} safe-ts-ignore, ${n(h.void)} void calls, ` +
649
+ `${n(h.casts)} as-casts, ${n(h.cacheMarks)} @cache, ${n(h.stdFiles)} std file(s)`,
650
+ );
651
+
652
+ console.log("\nSAFE-TS features in use (for the final pass):");
653
+ console.log(` ${Object.entries(r.features).map(([f, c]) => `${f} ${n(c)}`).join(" · ")}`);
654
+
655
+ const dirs = new Set([...Object.keys(r.findings?.byDir ?? {}), ...files.map(directoryOf)]);
656
+ console.log(`\nPer directory (depth ${depth}): findings, then the most frequent patterns`);
657
+ const rows = [...dirs].map((dir) => {
658
+ const patterns = Object.entries(r.patterns)
659
+ .filter(([id]) => !["boolean-state", "unsafe", "unexplained-unsafe"].includes(id))
660
+ .map(([id, p]) => [id, p.byDir[dir] ?? 0])
661
+ .filter(([, c]) => c > 0)
662
+ .sort((a, b) => b[1] - a[1])
663
+ .slice(0, 4);
664
+ return { dir, findings: r.findings?.byDir[dir] ?? 0, patterns };
665
+ });
666
+ rows.sort((a, b) => b.findings - a.findings || a.dir.localeCompare(b.dir));
667
+ for (const row of rows) {
668
+ console.log(` ${pad(row.dir, 40)} ${lpad(n(row.findings), 6)} ${row.patterns.map(([id, c]) => `${id} ${n(c)}`).join(", ")}`);
669
+ }
670
+ console.log("\n`--show <pattern or rule>` lists every place; `--json` gives all of it.");
671
+ }