@evobug_com/safe-ts-skill 0.4.0 → 0.5.1

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,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
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,
3
+ // (the idiomatic rules see `x.tag === ...`, `if (isErr(x)) return x`,
4
4
  // `'key' in` on a union, casts in tests, `unwrapOr(x, undefined)`, `JsonNull` in app state),
5
5
  // the hand-rolled patterns no rule reports (loading/error/data trios, sentinels, string
6
6
  // if-chains, boolean flag sets, raw fetch, try/catch, casts, ...), the escape hatches
@@ -20,13 +20,57 @@
20
20
  //
21
21
  // The patterns are regular expressions over the text, so they are a map of where to look,
22
22
  // not findings: read each place before changing it. Comment lines are skipped, except for
23
- // `safe-ts-ignore` comments, which are counted.
23
+ // `safe-ts-ignore` comments, which are counted. The skill's own folder isn't scanned.
24
+ //
25
+ // This file runs before SAFE-TS is installed, so it can't import std: each call that can fail
26
+ // goes through `orExit`, which names what failed and exits 2, and dictionaries are `Map`s. It
27
+ // passes oxlint with the SAFE-TS preset, so a project that lints every file needn't exclude it.
24
28
  import { execFileSync, spawnSync } from "node:child_process";
25
29
  import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
26
- import { extname, join, relative, resolve, sep } from "node:path";
30
+ import { dirname, extname, join, relative, resolve, sep } from "node:path";
31
+ import { fileURLToPath } from "node:url";
27
32
 
28
33
  import { findSafeTs } from "./safe-ts.mjs";
29
34
 
35
+ /**
36
+ * Runs `step` and returns its value; when it throws, prints `census: <what>: <why>` and exits 2.
37
+ * @template T
38
+ * @param {string} what
39
+ * @param {() => T} step
40
+ * @returns {T}
41
+ */
42
+ function orExit(what, step) {
43
+ try {
44
+ return step();
45
+ } catch (error) {
46
+ console.error(`census: ${what}: ${error instanceof Error ? error.message : String(error)}`);
47
+ process.exit(2);
48
+ }
49
+ }
50
+
51
+ /** A regular expression built from this file's own pattern text. */
52
+ const regex = (source) => orExit("a pattern of this script doesn't compile", () => new RegExp(source));
53
+ const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
54
+ /** A count per key (file, directory, rule, ...). */
55
+ class Counts extends Map {
56
+ /** Adds `n` to `key`'s count. */
57
+ add(key, n = 1) {
58
+ this.set(key, (this.get(key) ?? 0) + n);
59
+ return this;
60
+ }
61
+ }
62
+ /** A `Map` as a plain object for the JSON report (`fromEntries` defines each key, so `__proto__` is safe). */
63
+ const toObject = (map, value = (v) => v) => Object.fromEntries([...map].map(([key, v]) => [key, value(v)]));
64
+ /** A plain object read from JSON (a baseline) as a `Map`. */
65
+ const toMap = (object) => new Map(object !== null && typeof object === "object" ? Object.entries(object) : []);
66
+ /** A count read from a baseline: 0 when absent; anything but a whole number stops the gate. */
67
+ const countOf = (value, where) => {
68
+ if (value === undefined) return 0;
69
+ if (Number.isInteger(value) && value >= 0) return value;
70
+ console.error(`census: the baseline's ${where} is ${String(value)}, not a count; write it again with --write-baseline`);
71
+ process.exit(2);
72
+ };
73
+
30
74
  // ---- options -----------------------------------------------------------------------------
31
75
 
32
76
  const args = process.argv.slice(2);
@@ -41,19 +85,40 @@ const depth = Number(option("--depth") ?? 2);
41
85
  const root = process.cwd();
42
86
  const EXTENSIONS = new Set([".ts", ".tsx", ".mts", ".cts", ".vue", ".jsx"]);
43
87
  const SKIPPED_DIRS = new Set(["node_modules", ".git", "dist", "build", "coverage", "target", ".output", ".nuxt", ".next", ".cache", ".safe-ts"]);
88
+ // This skill's folder (when the script runs from it), so a copy in `.claude/skills/` is never
89
+ // counted. A copy of the scripts in the project's `scripts/` has no SKILL.md beside it.
90
+ const SKILL_DIR = (() => {
91
+ const dir = dirname(dirname(fileURLToPath(import.meta.url)));
92
+ return existsSync(join(dir, "SKILL.md")) ? dir : undefined;
93
+ })();
94
+
95
+ /** A test file, as the checker sees one: `*.test.*` / `*.spec.*`, a test directory, or a test runner imported. */
96
+ const TEST_NAME = /(?:^|\/)(?:test|tests|__tests__|__mocks__)\/|\.(?:test|spec)\.[^/]*$/;
97
+ const TEST_RUNNER = /\bfrom\s*["'](?:vitest|node:test|bun:test|@jest\/globals|vite-plus\/test|mocha)["']/;
44
98
 
45
99
  // ---- the patterns ------------------------------------------------------------------------
46
100
 
47
101
  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
102
  const ERROR_NAME = String.raw`\w*(?:[Ee]rror|[Ee]rr|[Ff]ailure|[Ff]ailed|[Pp]roblem)\w*`;
103
+ // `<E>`, `<Option<E>>`: type arguments, one level of nesting.
104
+ const TYPE_ARGS = String.raw`(?:<(?:[^<>]|<[^<>]*>)*>)?`;
49
105
  const BOOL_STATE = String.raw`(?:ref|shallowRef|useState)(?:<boolean>)?\(\s*(?:true|false)\s*\)`;
50
106
 
51
107
  // `x as T`: a value, then `as`, then something that starts a type (a capitalised name, an
52
108
  // object, tuple or function type, or a built-in type keyword), so English text in a template
53
109
  // ("saved as draft") doesn't count. `as const` isn't a cast.
54
110
  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.
111
+ // `import { a as b }`, `export * as ns from`, `export { a as b }`: renames, not casts. The
112
+ // lines inside a list that spans several lines (` type Building as SimBuilding,`) are skipped
113
+ // too (see `renameLines`).
56
114
  const REEXPORT = /^\s*(?:import\b|export\s*(?:\*|\{|type\s*\{))/;
115
+ // The start of an import or export list left open on its line: `import {`, `import type {`,
116
+ // `import React, {`, `export {`, `export type {`. Not `export const x = {`.
117
+ const OPEN_LIST = /^\s*(?:import\b[^'"`]*\{|export\s+(?:type\s+)?\{)[^}]*$/;
118
+ // A mapped type's key remapping, `[K in Keys as NewKey]`: the `as` renames keys, it isn't a cast.
119
+ const KEY_REMAP = /(\[\s*[\w$]+\s+in\s+(?:[^[\]\n]|\[[^\]\n]*\])*?)\s+as\s+/g;
120
+ /** The line with what only looks like a cast taken out: mapped-type key remapping. */
121
+ const withoutRenames = (text) => text.replaceAll(KEY_REMAP, "$1 ");
57
122
 
58
123
  /**
59
124
  * Each pattern: what it finds, where the catalogue says what to write instead, and whether
@@ -66,19 +131,26 @@ const PATTERNS = [
66
131
  what: "a boolean loading/busy flag (ref, useState or let)",
67
132
  see: "patterns-vue.md#a-loading-error-data-trio / patterns-react.md#a-loading-error-data-trio",
68
133
  gate: true,
69
- line: new RegExp(
134
+ line: regex(
70
135
  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
136
  ),
72
137
  },
73
138
  {
74
139
  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",
140
+ what: "an error kept in its own state: ref('')/ref(null)/ref<E>()/shallowRef<Option<E>>()/useState('') named error, failed, ...",
141
+ see: "patterns-vue.md#a-loading-error-data-trio / patterns-vue.md#a-result-returned-to-vue",
77
142
  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*\))`,
143
+ line: regex(
144
+ String.raw`(?:\b(?:const|let)\s+${ERROR_NAME}\s*=\s*(?:ref|shallowRef)${TYPE_ARGS}\(\s*(?:''|""|null|undefined)?\s*\))|(?:\bconst\s*\[\s*${ERROR_NAME}\s*,\s*\w+\s*\]\s*=\s*useState${TYPE_ARGS}\(\s*(?:''|""|null|undefined)?\s*\))`,
80
145
  ),
81
146
  },
147
+ {
148
+ id: "error-or-undefined",
149
+ what: "a state set to `isErr(r) ? r.error : undefined`: its undefined means both \"not tried yet\" and \"it worked\"; one Enum names every state",
150
+ see: "patterns-vue.md#a-result-returned-to-vue / patterns-react.md#a-result-returned-to-react",
151
+ gate: true,
152
+ line: /\bisErr\((\w+)\)\s*\?\s*\1\.error\s*:\s*undefined\b/,
153
+ },
82
154
  {
83
155
  id: "empty-string-sentinel",
84
156
  what: "'' compared or returned: check whether it means \"none\" or \"no error\"",
@@ -88,10 +160,14 @@ const PATTERNS = [
88
160
  },
89
161
  {
90
162
  id: "minus-one-sentinel",
91
- what: "-1 compared, returned or assigned (often \"not found\" or \"none selected\")",
163
+ what: "-1 compared, returned or assigned (often \"not found\" or \"none selected\"); a named constant (`const NONE = -1`) counts once, at its declaration",
92
164
  see: "patterns-core.md#a-sentinel-value",
93
165
  gate: true,
166
+ // A literal -1 only: `x === NONE`, `.fill(NONE)` aren't counted, so a sentinel the project
167
+ // names once (in typed arrays or a file format, where `Option` can't go) is one entry, its
168
+ // declaration, which `NAMED_SENTINEL` also counts when it ends in `as const` or a type.
94
169
  line: /(?:[!=]==?\s*-1\b)|(?:\breturn\s+-1\b)|(?:[^=!<>]=\s*-1\s*[;,)]?\s*$)|(?:\(\s*-1\s*\))/,
170
+ or: /^\s*(?:export\s+)?(?:const|(?:(?:private|protected|public)\s+)?static\s+readonly)\s+[A-Z][A-Z0-9_]*\s*(?::\s*[^=]+)?=\s*-1\b/,
95
171
  },
96
172
  {
97
173
  id: "zero-sentinel",
@@ -105,7 +181,7 @@ const PATTERNS = [
105
181
  what: "a boolean state (ref, useState); 3 or more in a file are listed under boolean-flag-files",
106
182
  see: "patterns-core.md#a-set-of-boolean-flags",
107
183
  gate: false,
108
- line: new RegExp(String.raw`\b(?:const|let)\s+(?:\[\s*)?\w+(?:\s*,\s*\w+\s*\])?\s*=\s*${BOOL_STATE}`),
184
+ line: regex(String.raw`\b(?:const|let)\s+(?:\[\s*)?\w+(?:\s*,\s*\w+\s*\])?\s*=\s*${BOOL_STATE}`),
109
185
  },
110
186
  {
111
187
  id: "raw-fetch",
@@ -135,6 +211,7 @@ const PATTERNS = [
135
211
  gate: true,
136
212
  line: CAST,
137
213
  skip: REEXPORT,
214
+ renames: true,
138
215
  },
139
216
  {
140
217
  id: "double-cast",
@@ -143,6 +220,7 @@ const PATTERNS = [
143
220
  gate: true,
144
221
  line: /\bas\s+(?:unknown\s+as|never|any)\b/,
145
222
  skip: REEXPORT,
223
+ renames: true,
146
224
  },
147
225
  {
148
226
  id: "json-parse",
@@ -219,11 +297,13 @@ const PATTERNS = [
219
297
  },
220
298
  {
221
299
  id: "module-let",
222
- what: "a `let` at the top of a .ts module (module state)",
300
+ what: "a `let` at the top of a .ts module (module state); not in test files",
223
301
  see: "patterns-vue.md#module-state / patterns-react.md#module-state",
224
302
  gate: true,
225
303
  line: /^(?:export\s+)?let\s+[\w$]/,
226
- only: (file) => !file.endsWith(".vue"),
304
+ // A test file's `let errors: string[]` that `beforeEach` resets is the runner's idiom, not
305
+ // app state: each test file is its own module. `no-mutable-global` still sees them.
306
+ only: (file, test) => !file.endsWith(".vue") && !test,
227
307
  },
228
308
  ];
229
309
 
@@ -231,38 +311,105 @@ const PATTERNS = [
231
311
  * Rules whose findings have a catalogue entry: the idiomatic rules a checker-driven migration
232
312
  * trips over, and the ones its first census is full of. The report names the entry.
233
313
  */
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
- };
314
+ const RULE_SEE = new Map([
315
+ ["prefer-is-over-tag", "patterns-core.md#reading-an-enum-one-style"],
316
+ ["prefer-constructor-tag", "patterns-core.md#reading-an-enum-one-style"],
317
+ ["prefer-q", "patterns-core.md#passing-an-error-up"],
318
+ ["prefer-map-err", "patterns-core.md#passing-an-error-up"],
319
+ ["q-undeclared-error", "patterns-core.md#passing-an-error-up"],
320
+ ["key-presence-union", "patterns-core.md#a-union-told-apart-by-keys"],
321
+ ["no-type-predicate", "patterns-core.md#a-hand-written-type-guard"],
322
+ ["undeclared-return-type", "patterns-core.md#a-function-result-the-checker-cannot-read"],
323
+ ["unused-code", "patterns-core.md#code-nothing-reaches"],
324
+ ["unused-private", "patterns-core.md#code-nothing-reaches"],
325
+ ["unreachable-code", "patterns-core.md#code-nothing-reaches"],
326
+ ["unknown-event", "patterns-core.md#event-names-at-both-ends"],
327
+ ["unmatched-event", "patterns-core.md#event-names-at-both-ends"],
328
+ ["no-overload", "patterns-core.md#a-hand-written-type-guard"],
329
+ ["cast-in-test", "patterns-core.md#casts-in-tests"],
330
+ ["no-swallowed-error", "patterns-core.md#a-failure-turned-into-undefined"],
331
+ ["sentinel-error", "patterns-core.md#a-sentinel-value"],
332
+ ["strict-truthiness", "patterns-core.md#a-sentinel-value"],
333
+ ["compare-misses-undefined", "patterns-core.md#a-sentinel-value"],
334
+ ["no-ts-suppression", "escape-hatches.md#when-each-is-allowed"],
335
+ ["no-lint-suppression", "escape-hatches.md#when-each-is-allowed"],
336
+ ["unlisted-marker", "escape-hatches.md#when-each-is-allowed"],
337
+ ["no-unchecked-declare", "escape-hatches.md#when-each-is-allowed"],
338
+ ["no-method-signature", "patterns-core.md#a-method-in-an-interface"],
339
+ ["override-parameter", "patterns-core.md#an-override-that-asks-for-more"],
340
+ ["implicit-propagation", "patterns-core.md#a-method-the-language-calls-for-you"],
341
+ ["missing-mut", "patterns-core.md#a-parameter-the-function-changes"],
342
+ ["aliased-mut", "patterns-core.md#a-parameter-the-function-changes"],
343
+ ["mutating-getter", "patterns-core.md#a-parameter-the-function-changes"],
344
+ ["covariant-alias", "patterns-core.md#a-parameter-the-function-changes"],
345
+ ["union-tag-write", "patterns-core.md#a-parameter-the-function-changes"],
346
+ ["readonly-dropped", "patterns-core.md#a-parameter-the-function-changes"],
347
+ ["unbounded-spread", "patterns-core.md#a-list-spread-into-mathmax-or-push"],
348
+ ["not-found-index", "patterns-core.md#a-not-found-answer-used-as-a-value"],
349
+ ["divide-by-length", "patterns-core.md#a-not-found-answer-used-as-a-value"],
350
+ ["sparse-array-write", "patterns-core.md#a-not-found-answer-used-as-a-value"],
351
+ ["number-parse-nan", "patterns-core.md#a-not-found-answer-used-as-a-value"],
352
+ ["regex-last-index", "patterns-core.md#a-regex-with-the-g-flag-tested-again"],
353
+ ["promise-as-value", "patterns-core.md#a-promise-used-as-its-value"],
354
+ ["floating-promise", "patterns-core.md#a-promise-used-as-its-value"],
355
+ ["use-after-consume", "patterns-core.md#a-value-used-after-it-was-used-up"],
356
+ ["stale-across-await", "patterns-core.md#state-across-an-await"],
357
+ ["late-listener", "patterns-core.md#what-happened-during-an-await"],
358
+ ["unused-answer", "patterns-core.md#an-answer-nobody-reads"],
359
+ ["misplaced-argument", "patterns-core.md#an-answer-nobody-reads"],
360
+ ["superseded-task-write", "patterns-core.md#what-happened-during-an-await"],
361
+ ["promise-never-settles", "patterns-core.md#a-promise-that-never-settles-a-resource-kept"],
362
+ ["unreleased-resource", "patterns-core.md#a-promise-that-never-settles-a-resource-kept"],
363
+ ["unbalanced-update", "patterns-core.md#a-change-left-behind-a-test-already-decided"],
364
+ ["decided-test", "patterns-core.md#a-change-left-behind-a-test-already-decided"],
365
+ ["test-without-assertion", "patterns-core.md#a-test-that-cannot-fail"],
366
+ ["assertion-cannot-fail", "patterns-core.md#a-test-that-cannot-fail"],
367
+ ["deferred-assertion", "patterns-core.md#a-test-that-cannot-fail"],
368
+ ["swallowed-assertion", "patterns-core.md#a-test-that-cannot-fail"],
369
+ ["focused-test", "patterns-core.md#a-test-that-cannot-fail"],
370
+ ["skipped-test", "patterns-core.md#a-test-that-cannot-fail"],
371
+ ["duplicate-test-name", "patterns-core.md#a-test-that-cannot-fail"],
372
+ ["empty-test-suite", "patterns-core.md#a-test-that-cannot-fail"],
373
+ ["constructor-calls-override", "patterns-core.md#a-constructor-that-calls-an-overridable-method"],
374
+ ["no-optional-field", "patterns-core.md#an-optional-key"],
375
+ ["brand-constructor", "patterns-core.md#a-cast"],
376
+ ["markup-sink", "patterns-core.md#text-given-to-a-sink"],
377
+ ["url-sink", "patterns-core.md#text-given-to-a-sink"],
378
+ ["code-sink", "patterns-core.md#text-given-to-a-sink"],
379
+ ["command-sink", "patterns-core.md#text-given-to-a-sink"],
380
+ ["path-sink", "patterns-core.md#text-given-to-a-sink"],
381
+ ["pattern-sink", "patterns-core.md#text-given-to-a-sink"],
382
+ ["sql-sink", "patterns-core.md#text-given-to-a-sink"],
383
+ ["brand-sink", "patterns-core.md#text-given-to-a-sink"],
384
+ ["json-null-in-app", "patterns-core.md#an-api-that-sends-null"],
385
+ ["undefined-to-null", "patterns-core.md#an-api-that-sends-null"],
386
+ ["catch-on-result", "patterns-core.md#try-and-catch-around-your-own-code"],
387
+ ["misplaced-axios-check", "patterns-core.md#requests-return-a-result"],
388
+ ["unsafe-project-call", "patterns-core.md#a-bug-inside-a-result-returning-call"],
389
+ ["panic-on-loading", "patterns-core.md#panic-on-a-loading-state"],
390
+ ["latest-wins-counter", "patterns-vue.md#module-state"],
391
+ ["unused-task-signal", "patterns-vue.md#a-loading-error-data-trio"],
392
+ ["no-throw", "patterns-core.md#a-function-that-throws"],
393
+ ["failure-contract", "patterns-core.md#a-failure-behind-an-interface"],
394
+ ["fetch-signal", "patterns-core.md#requests-return-a-result"],
395
+ ["no-unchecked-cast", "patterns-core.md#a-cast"],
396
+ ["no-hidden-any", "patterns-core.md#json-and-storage"],
397
+ ["unbound-method", "patterns-core.md#a-method-handed-over-by-name"],
398
+ ["no-object-dictionary", "patterns-core.md#a-table-keyed-by-server-data"],
399
+ ["json-type", "patterns-core.md#a-cast"],
400
+ ["no-mutable-global", "patterns-vue.md#module-state / patterns-react.md#module-state"],
401
+ ["vue-split-state", "patterns-vue.md#a-loading-error-data-trio"],
402
+ ["vue-async-race", "patterns-vue.md#a-loading-error-data-trio"],
403
+ ["vue-ref-without-value", "patterns-vue.md#a-ref-filled-after-mount"],
404
+ ["vue-template-ref", "patterns-vue.md#a-template-ref"],
405
+ ["vue-v-html", "patterns-vue.md#v-html-and-bound-urls"],
406
+ ["vue-unsafe-url", "patterns-vue.md#v-html-and-bound-urls"],
407
+ ["exhaustive-dispatch", "patterns-core.md#a-closed-set-of-states"],
408
+ ["string-dispatch", "patterns-core.md#a-closed-set-of-states"],
409
+ ["negative-member-guard", "patterns-core.md#a-closed-set-of-states"],
410
+ ["code-range-compare", "patterns-core.md#a-closed-set-of-states"],
411
+ ["inline-member-set", "patterns-core.md#a-closed-set-of-states"],
412
+ ]);
266
413
 
267
414
  /** SAFE-TS features: how often the code uses each (for the final pass). */
268
415
  const FEATURES = [
@@ -304,32 +451,39 @@ function sourceFiles() {
304
451
  console.error(`census: not found: ${target}`);
305
452
  process.exit(2);
306
453
  }
307
- if (statSync(absolute).isFile()) {
308
- files.add(relative(root, absolute));
454
+ if (orExit(`can't read ${target}`, () => statSync(absolute)).isFile()) {
455
+ files.add(absolute);
309
456
  continue;
310
457
  }
311
- for (const file of gitFiles(absolute) ?? walk(absolute)) files.add(relative(root, file));
458
+ for (const file of gitFiles(absolute) ?? walk(absolute)) files.add(file);
312
459
  }
313
- return [...files].filter((f) => EXTENSIONS.has(extname(f)) && !/\.d\.[cm]?ts$/.test(f)).map((f) => f.split(sep).join("/")).sort();
460
+ const ownFile = (file) => SKILL_DIR !== undefined && (file === SKILL_DIR || file.startsWith(SKILL_DIR + sep));
461
+ return [...files]
462
+ .filter((f) => !ownFile(f) && EXTENSIONS.has(extname(f)) && !/\.d\.[cm]?ts$/.test(f))
463
+ .map((f) => relative(root, f).split(sep).join("/"))
464
+ .sort(byText);
314
465
  }
315
466
 
316
467
  /** Tracked and untracked-but-not-ignored files, when the directory is in a git repository. */
317
468
  function gitFiles(dir) {
469
+ let out;
318
470
  try {
319
- const out = execFileSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", "."], {
471
+ out = execFileSync("git", ["ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", "."], {
320
472
  cwd: dir,
321
473
  encoding: "utf8",
322
474
  maxBuffer: 256 * 1024 * 1024,
323
475
  stdio: ["ignore", "pipe", "ignore"],
324
476
  });
325
- return out.split("\0").filter((f) => f !== "").map((f) => join(dir, f)).filter((f) => existsSync(f));
326
477
  } catch {
478
+ // Not a git repository, or no git: walk the folder instead.
327
479
  return undefined;
328
480
  }
481
+ return out.split("\0").filter((f) => f !== "").map((f) => join(dir, f)).filter((f) => existsSync(f));
329
482
  }
330
483
 
331
484
  function walk(dir) {
332
- return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
485
+ const entries = orExit(`can't list ${relative(root, dir) || "."}`, () => readdirSync(dir, { withFileTypes: true }));
486
+ return entries.flatMap((entry) => {
333
487
  if (entry.isDirectory()) return SKIPPED_DIRS.has(entry.name) ? [] : walk(join(dir, entry.name));
334
488
  return entry.isFile() ? [join(dir, entry.name)] : [];
335
489
  });
@@ -362,57 +516,77 @@ function codeLines(text) {
362
516
  return lines;
363
517
  }
364
518
 
365
- const hasComment = (lines, index) => {
366
- const { text } = lines[index];
367
- if (/\/\/|\/\*/.test(text)) return true;
368
- return false;
369
- };
519
+ /**
520
+ * The numbers of the lines inside an import or export list that spans several lines, from the
521
+ * `import {` line to the `} from` line: their `a as b` are renames.
522
+ */
523
+ function renameLines(lines) {
524
+ const inside = new Set();
525
+ let open = false;
526
+ for (const { number, text } of lines) {
527
+ if (!open && OPEN_LIST.test(text)) open = true;
528
+ if (open) inside.add(number);
529
+ if (open && text.includes("}")) open = false;
530
+ }
531
+ return inside;
532
+ }
533
+
534
+ const hasComment = (text) => /\/\/|\/\*/.test(text);
535
+
536
+ /** One pattern's counts: in total, per file (a `Map`), and every place. */
537
+ const tally = (what, see, gate) => ({ what, see, gate, count: 0, byFile: new Counts(), places: [] });
370
538
 
371
539
  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]));
540
+ const patterns = new Map(PATTERNS.map((p) => [p.id, tally(p.what, p.see, p.gate)]));
541
+ patterns.set("boolean-flag-files", tally("files with 3 or more boolean states", "patterns-core.md#a-set-of-boolean-flags", true));
542
+ patterns.set("trio-files", tally("files with both a loading flag and an error state: a loading/error/data trio", "patterns-vue.md#a-loading-error-data-trio", true));
543
+ patterns.set("string-if-chain", tally("a value compared with 3 or more string literals in one file (a closed set handled by if-chains)", "patterns-core.md#a-closed-set-of-states", true));
544
+ const counted = (id, file) => patterns.get(id)?.byFile.get(file) ?? 0;
545
+ const features = new Counts(FEATURES.map(([name]) => [name, 0]));
377
546
  const legacy = [];
378
547
  const std = [];
379
548
  let cacheMarks = 0;
380
- const kinds = {};
549
+ const kinds = new Counts();
381
550
 
382
551
  for (const file of files) {
383
- const text = readFileSync(join(root, file), "utf8");
384
- kinds[extname(file)] = (kinds[extname(file)] ?? 0) + 1;
552
+ const text = orExit(`can't read ${file}`, () => readFileSync(join(root, file), "utf8"));
553
+ kinds.add(extname(file));
554
+ const test = TEST_NAME.test(file) || TEST_RUNNER.test(text);
385
555
  // `// @safe-ts legacy`, or `<!-- @safe-ts legacy -->` in a component.
386
556
  if (/(?:\/\/|<!--)\s*@safe-ts legacy\b/.test(text)) legacy.push(file);
387
557
  if (/\/\/\s*@safe-ts std\b/.test(text)) std.push(file);
388
558
  cacheMarks += (text.match(/\/\*\*\s*@cache\s*\*\//g) ?? []).length;
389
559
  const raw = text.split(/\r?\n/);
390
560
  const lines = codeLines(text);
561
+ const renames = renameLines(lines);
391
562
  const hit = (id, line) => {
392
- const p = patterns[id];
563
+ const p = patterns.get(id);
564
+ if (p === undefined) return;
393
565
  p.count += 1;
394
- p.byFile[file] = (p.byFile[file] ?? 0) + 1;
566
+ p.byFile.add(file);
395
567
  p.places.push(`${file}:${line.number}: ${line.text.trim().slice(0, 140)}`);
396
568
  };
397
569
  raw.forEach((line, i) => {
398
570
  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 });
571
+ if (pattern.comment && (!pattern.only || pattern.only(file, test)) && pattern.line.test(line)) hit(pattern.id, { number: i + 1, text: line });
400
572
  }
401
573
  });
402
574
  const comparisons = new Map();
403
- lines.forEach((line, index) => {
575
+ for (const line of lines) {
404
576
  for (const pattern of PATTERNS) {
405
577
  if (pattern.comment) continue;
406
- if (pattern.only && !pattern.only(file)) continue;
578
+ if (pattern.only && !pattern.only(file, test)) continue;
407
579
  if (pattern.skip?.test(line.text)) continue;
408
- if (!pattern.line.test(line.text)) continue;
580
+ if (pattern.renames && renames.has(line.number)) continue;
581
+ const seen = pattern.renames ? withoutRenames(line.text) : line.text;
582
+ if (!pattern.line.test(seen) && !pattern.or?.test(seen)) continue;
409
583
  if (pattern.needsReason) {
410
584
  const above = raw[line.number - 2] ?? "";
411
- if (hasComment(lines, index) || /^\s*(?:\/\/|\*|\/\*)/.test(above)) continue;
585
+ if (hasComment(line.text) || /^\s*(?:\/\/|\*|\/\*)/.test(above)) continue;
412
586
  }
413
587
  hit(pattern.id, line);
414
588
  }
415
- for (const [name, re] of FEATURES) if (re.test(line.text)) features[name] += 1;
589
+ for (const [name, re] of FEATURES) if (re.test(line.text)) features.add(name);
416
590
  for (const m of line.text.matchAll(/([\w$][\w$.?]*)\s*[!=]==\s*(['"])([^'"\n]+)\2/g)) {
417
591
  const subject = m[1];
418
592
  if (subject.endsWith(".tag") || subject === "typeof" || /^(?:process\.env|import\.meta)/.test(subject)) continue;
@@ -420,13 +594,13 @@ function scan(files) {
420
594
  seen.literals.add(m[3]);
421
595
  comparisons.set(subject, seen);
422
596
  }
423
- });
597
+ }
424
598
  for (const [subject, { literals, first }] of comparisons) {
425
599
  if (literals.size >= 3) hit("string-if-chain", { number: first.number, text: `${subject}: ${[...literals].map((l) => `'${l}'`).join(", ")}` });
426
600
  }
427
- const booleans = patterns["boolean-state"].byFile[file] ?? 0;
601
+ const booleans = counted("boolean-state", file);
428
602
  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) {
603
+ if (counted("loading-flag", file) > 0 && counted("error-state", file) > 0) {
430
604
  hit("trio-files", { number: 1, text: "loading flag and error state in one file" });
431
605
  }
432
606
  }
@@ -446,7 +620,7 @@ function runChecker(files) {
446
620
  // left out, while the patterns count them.
447
621
  const entries = given.length > 0 ? given : files;
448
622
  // 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.
623
+ // `'key' in` on a union, ...): count them whether or not package.json turns the layer on yet.
450
624
  const flags = args.includes("--no-idiomatic") ? ["--json"] : ["--json", "--idiomatic"];
451
625
  const chunks = [];
452
626
  // Keep each command line well under Windows' 32k characters.
@@ -471,6 +645,7 @@ function runChecker(files) {
471
645
  try {
472
646
  parsed = JSON.parse(run.stdout);
473
647
  } catch {
648
+ // Not JSON: the checker failed before it could report. Say so in the report.
474
649
  return { skipped: `safe-ts check failed (exit ${run.status}): ${(run.stderr || run.stdout).trim().split("\n").slice(0, 5).join(" | ")}` };
475
650
  }
476
651
  for (const d of parsed) {
@@ -485,22 +660,23 @@ function runChecker(files) {
485
660
  }
486
661
 
487
662
  function summarizeFindings(diagnostics) {
488
- const byRule = {};
489
- const byDir = {};
490
- const origins = {};
663
+ const byRule = new Map();
664
+ const byDir = new Counts();
665
+ const origins = new Counts();
491
666
  let warnings = 0;
492
667
  for (const d of diagnostics) {
493
668
  const file = d.file.split(sep).join("/");
494
669
  const dir = directoryOf(file);
495
- const rule = (byRule[d.rule] ??= { total: 0, severity: d.severity ?? "error", byDir: {}, byFile: {} });
670
+ const rule = byRule.get(d.rule) ?? { total: 0, severity: d.severity ?? "error", byDir: new Counts(), byFile: new Counts() };
671
+ byRule.set(d.rule, rule);
496
672
  rule.total += 1;
497
673
  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;
674
+ rule.byDir.add(dir);
675
+ rule.byFile.add(file);
676
+ byDir.add(dir);
677
+ if (d.origin) origins.add(d.origin);
502
678
  }
503
- const topOrigins = Object.entries(origins).filter(([, n]) => n >= 3).sort((a, b) => b[1] - a[1]).slice(0, 15);
679
+ const topOrigins = [...origins].filter(([, n]) => n >= 3).sort((a, b) => b[1] - a[1]).slice(0, 15);
504
680
  return {
505
681
  total: diagnostics.length,
506
682
  errors: diagnostics.length - warnings,
@@ -518,47 +694,59 @@ const scanned = scan(files);
518
694
  const checker = runChecker(files);
519
695
  const findings = checker.diagnostics ? summarizeFindings(checker.diagnostics) : undefined;
520
696
  const byDir = (byFile) => {
521
- const out = {};
522
- for (const [file, n] of Object.entries(byFile)) out[directoryOf(file)] = (out[directoryOf(file)] ?? 0) + n;
697
+ const out = new Counts();
698
+ for (const [file, n] of byFile) out.add(directoryOf(file), n);
523
699
  return out;
524
700
  };
701
+ const pattern = (id) => scanned.patterns.get(id)?.count ?? 0;
525
702
 
703
+ /** The report, with plain objects, as `--json` prints it. */
526
704
  const report = {
527
705
  generated: new Date().toISOString(),
528
706
  root,
529
- files: { total: files.length, byExtension: scanned.kinds, legacy: scanned.legacy.length, std: scanned.std },
707
+ files: { total: files.length, byExtension: toObject(scanned.kinds), legacy: scanned.legacy.length, std: scanned.std },
530
708
  checker: checker.diagnostics
531
709
  ? { binary: checker.binary, version: checker.version, idiomatic: checker.idiomatic, entries: checker.entries }
532
710
  : { skipped: checker.skipped },
533
- findings,
711
+ findings: findings && {
712
+ ...findings,
713
+ byRule: toObject(findings.byRule, (x) => ({ ...x, byDir: toObject(x.byDir), byFile: toObject(x.byFile) })),
714
+ byDir: toObject(findings.byDir),
715
+ },
534
716
  escapeHatches: {
535
717
  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,
718
+ unsafe: pattern("unsafe"),
719
+ unsafeAsync: pattern("unsafe-async"),
720
+ unexplainedUnsafe: pattern("unexplained-unsafe"),
721
+ panic: pattern("panic"),
722
+ trust: pattern("trust"),
723
+ legacyNull: pattern("legacy-null"),
724
+ safeTsIgnore: pattern("safe-ts-ignore"),
725
+ void: pattern("void-call"),
544
726
  cacheMarks: scanned.cacheMarks,
545
727
  stdFiles: scanned.std.length,
546
- casts: scanned.patterns["as-cast"].count,
728
+ casts: pattern("as-cast"),
547
729
  },
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,
730
+ patterns: toObject(scanned.patterns, (p) => ({
731
+ what: p.what,
732
+ see: p.see,
733
+ gate: p.gate,
734
+ count: p.count,
735
+ files: p.byFile.size,
736
+ byDir: toObject(byDir(p.byFile)),
737
+ byFile: toObject(p.byFile),
738
+ })),
739
+ features: toObject(scanned.features),
552
740
  };
553
741
 
554
742
  const show = option("--show");
555
743
  if (show !== undefined) {
556
- const pattern = scanned.patterns[show];
744
+ const places = scanned.patterns.get(show)?.places;
557
745
  const rule = checker.diagnostics?.filter((d) => d.rule === show);
558
- if (pattern) for (const place of pattern.places) console.log(place);
746
+ if (places) for (const place of places) console.log(place);
559
747
  else if (rule && rule.length > 0) for (const d of rule) console.log(`${d.file}:${d.line}:${d.column}: ${d.message}`);
560
748
  else {
561
- console.error(`census: no pattern or reported rule named "${show}"; patterns: ${Object.keys(scanned.patterns).join(", ")}`);
749
+ console.error(`census: no pattern or reported rule named "${show}"; patterns: ${[...scanned.patterns.keys()].join(", ")}`);
562
750
  process.exit(2);
563
751
  }
564
752
  process.exit(0);
@@ -566,35 +754,43 @@ if (show !== undefined) {
566
754
 
567
755
  const written = option("--write-baseline");
568
756
  if (written !== undefined) {
569
- writeFileSync(written, `${JSON.stringify(baselineOf(report), null, 2)}\n`);
757
+ const text = orExit("can't serialize the baseline", () => JSON.stringify(baselineOf(), null, 2));
758
+ orExit(`can't write ${written}`, () => writeFileSync(written, `${text}\n`));
570
759
  console.error(`census: baseline written to ${written}`);
571
760
  }
572
761
 
573
762
  const baseline = option("--baseline");
574
- if (baseline !== undefined) process.exit(gate(JSON.parse(readFileSync(baseline, "utf8")), baselineOf(report)));
763
+ if (baseline !== undefined) {
764
+ const text = orExit(`can't read the baseline ${baseline}`, () => readFileSync(baseline, "utf8"));
765
+ const before = orExit(`the baseline ${baseline} isn't JSON`, () => JSON.parse(text));
766
+ process.exit(gate(before));
767
+ }
575
768
 
576
- if (args.includes("--json")) console.log(JSON.stringify(report, null, 2));
577
- else if (written === undefined) printReport(report);
769
+ if (args.includes("--json")) console.log(orExit("can't serialize the report", () => JSON.stringify(report, null, 2)));
770
+ else if (written === undefined) printReport();
578
771
 
579
772
  /** 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 };
773
+ function baselineOf() {
774
+ const gated = [...scanned.patterns].filter(([, p]) => p.gate).map(([id, p]) => [id, toObject(p.byFile)]);
775
+ const rules = [...(findings?.byRule ?? [])].map(([rule, x]) => [rule, toObject(x.byFile)]);
776
+ return { generated: report.generated, patterns: Object.fromEntries(gated), rules: Object.fromEntries(rules), legacyFiles: scanned.legacy.length };
584
777
  }
585
778
 
586
779
  /** The architecture gate: 1 when a count rose in any file, with the files named. */
587
- function gate(before, now) {
780
+ function gate(before) {
588
781
  const rises = [];
589
- const compare = (kind, id, old = {}, current = {}) => {
590
- for (const [file, n] of Object.entries(current)) {
591
- const was = old[file] ?? 0;
782
+ const oldPatterns = toMap(before?.patterns);
783
+ const oldRules = toMap(before?.rules);
784
+ const compare = (kind, id, old, current) => {
785
+ for (const [file, n] of current) {
786
+ const was = countOf(old.get(file), `${kind} ${id} ${file}`);
592
787
  if (n > was) rises.push(`${kind} ${id}: ${file} ${was} -> ${n}`);
593
788
  }
594
789
  };
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}`);
790
+ for (const [id, p] of scanned.patterns) if (p.gate) compare("pattern", id, toMap(oldPatterns.get(id)), p.byFile);
791
+ if (findings) for (const [rule, x] of findings.byRule) compare("rule", rule, toMap(oldRules.get(rule)), x.byFile);
792
+ const legacyBefore = countOf(before?.legacyFiles, "legacyFiles");
793
+ if (scanned.legacy.length > legacyBefore) rises.push(`legacy files: ${legacyBefore} -> ${scanned.legacy.length}`);
598
794
  if (rises.length === 0) {
599
795
  console.log("census gate: no count rose against the baseline");
600
796
  return 0;
@@ -605,43 +801,44 @@ function gate(before, now) {
605
801
  return 1;
606
802
  }
607
803
 
608
- function printReport(r) {
804
+ function printReport() {
609
805
  const n = (x) => x.toLocaleString("en-US");
610
806
  const pad = (s, w) => String(s).padEnd(w);
611
807
  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`);
808
+ const top = (dirs, k = 3) => [...dirs].sort((a, b) => b[1] - a[1]).slice(0, k).map(([d, c]) => `${d} (${n(c)})`).join(", ");
809
+ const kinds = [...scanned.kinds].map(([e, c]) => `${n(c)} ${e}`).join(", ");
810
+ console.log(`SAFE-TS census: ${n(files.length)} files (${kinds}), ${n(scanned.legacy.length)} marked legacy\n`);
615
811
 
616
- if (r.findings) {
617
- const how = `safe-ts ${r.checker.version ?? ""} check --json${r.checker.idiomatic ? " --idiomatic" : ""}`.replace(" ", " ");
812
+ if (findings) {
813
+ const how = `safe-ts ${checker.version ?? ""} check --json${checker.idiomatic ? " --idiomatic" : ""}`.replace(" ", " ");
618
814
  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)`,
815
+ `Checker findings (${how}, ${n(checker.entries)} entries): ${n(findings.total)} ` +
816
+ `(${n(findings.errors)} errors, ${n(findings.warnings)} warnings)`,
621
817
  );
622
- const rules = Object.entries(r.findings.byRule).sort((a, b) => b[1].total - a[1].total);
818
+ const rules = [...findings.byRule].sort((a, b) => b[1].total - a[1].total);
623
819
  for (const [rule, x] of rules) {
624
820
  const level = x.severity === "warning" ? " (warn)" : "";
625
821
  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]}`);
822
+ const see = RULE_SEE.get(rule);
823
+ if (see) console.log(` ${pad("", 30)} ${" ".repeat(7)} see references/${see}`);
627
824
  }
628
- if (r.findings.origins.length > 0) {
825
+ if (findings.origins.length > 0) {
629
826
  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}`);
827
+ for (const { origin, count } of findings.origins) console.log(` ${lpad(n(count), 7)} ${origin}`);
631
828
  }
632
- if (r.files.legacy > 0) console.log("\n Legacy files report nothing; remove a marker to see that file's findings.");
829
+ if (scanned.legacy.length > 0) console.log("\n Legacy files report nothing; remove a marker to see that file's findings.");
633
830
  } else {
634
- console.log(`Checker not run: ${r.checker.skipped}`);
831
+ console.log(`Checker not run: ${checker.skipped}`);
635
832
  }
636
833
 
637
834
  console.log("\nPatterns the checker doesn't report (heuristic: read each place):");
638
- for (const [id, p] of Object.entries(r.patterns)) {
835
+ for (const [id, p] of scanned.patterns) {
639
836
  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)}`);
837
+ console.log(` ${pad(id, 24)} ${lpad(n(p.count), 6)} in ${lpad(n(p.byFile.size), 4)} files ${top(byDir(p.byFile), 2)}`);
641
838
  console.log(` ${pad("", 24)} ${p.what}; see references/${p.see}`);
642
839
  }
643
840
 
644
- const h = r.escapeHatches;
841
+ const h = report.escapeHatches;
645
842
  console.log(
646
843
  `\nEscape hatches: ${n(h.legacyFiles)} legacy file(s), ${n(h.unsafe)} unsafe(), ${n(h.unsafeAsync)} unsafeAsync(), ` +
647
844
  `${n(h.unexplainedUnsafe)} without a reason comment, ${n(h.panic)} panic(), ${n(h.trust)} trust(), ` +
@@ -650,18 +847,20 @@ function printReport(r) {
650
847
  );
651
848
 
652
849
  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(" · ")}`);
850
+ console.log(` ${[...scanned.features].map(([f, c]) => `${f} ${n(c)}`).join(" · ")}`);
654
851
 
655
- const dirs = new Set([...Object.keys(r.findings?.byDir ?? {}), ...files.map(directoryOf)]);
852
+ const dirs = new Set([...(findings?.byDir.keys() ?? []), ...files.map(directoryOf)]);
853
+ const patternsByDir = [...scanned.patterns]
854
+ .filter(([id]) => !["boolean-state", "unsafe", "unexplained-unsafe"].includes(id))
855
+ .map(([id, p]) => [id, byDir(p.byFile)]);
656
856
  console.log(`\nPer directory (depth ${depth}): findings, then the most frequent patterns`);
657
857
  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])
858
+ const patterns = patternsByDir
859
+ .map(([id, counts]) => [id, counts.get(dir) ?? 0])
661
860
  .filter(([, c]) => c > 0)
662
861
  .sort((a, b) => b[1] - a[1])
663
862
  .slice(0, 4);
664
- return { dir, findings: r.findings?.byDir[dir] ?? 0, patterns };
863
+ return { dir, findings: findings?.byDir.get(dir) ?? 0, patterns };
665
864
  });
666
865
  rows.sort((a, b) => b.findings - a.findings || a.dir.localeCompare(b.dir));
667
866
  for (const row of rows) {