@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.
- package/install.mjs +31 -7
- package/package.json +1 -1
- package/safe-ts-migrate/SKILL.md +80 -13
- package/safe-ts-migrate/references/architecture.md +10 -3
- package/safe-ts-migrate/references/census.md +31 -9
- package/safe-ts-migrate/references/escape-hatches.md +19 -9
- package/safe-ts-migrate/references/final-pass.md +7 -5
- package/safe-ts-migrate/references/fix-the-design.md +87 -0
- package/safe-ts-migrate/references/order-and-gates.md +9 -4
- package/safe-ts-migrate/references/patterns-core.md +1240 -85
- package/safe-ts-migrate/references/patterns-react.md +52 -16
- package/safe-ts-migrate/references/patterns-vue.md +98 -21
- package/safe-ts-migrate/references/review-checklist.md +7 -0
- package/safe-ts-migrate/references/templates.md +46 -21
- package/safe-ts-migrate/references/tool-gaps.md +284 -14
- package/safe-ts-migrate/scripts/census.mjs +343 -144
package/install.mjs
CHANGED
|
@@ -6,11 +6,33 @@
|
|
|
6
6
|
// npx @evobug_com/safe-ts-skill --force replace a copy that differs
|
|
7
7
|
//
|
|
8
8
|
// Use the version that matches the project's other @evobug_com packages
|
|
9
|
-
// (`npx @evobug_com/safe-ts-skill@0.
|
|
9
|
+
// (`npx @evobug_com/safe-ts-skill@0.5.1`): the skill describes that version's APIs.
|
|
10
|
+
//
|
|
11
|
+
// It runs before SAFE-TS is installed, so it can't import std: each call that can fail goes
|
|
12
|
+
// through `orExit`, which names what failed and exits 2. It passes oxlint with the SAFE-TS
|
|
13
|
+
// preset, like the skill's scripts.
|
|
10
14
|
import { cpSync, existsSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
11
15
|
import { dirname, join, relative, resolve } from "node:path";
|
|
12
16
|
import { fileURLToPath } from "node:url";
|
|
13
17
|
|
|
18
|
+
/**
|
|
19
|
+
* Runs `step` and returns its value; when it throws, prints `safe-ts-skill: <what>: <why>` and exits 2.
|
|
20
|
+
* @template T
|
|
21
|
+
* @param {string} what
|
|
22
|
+
* @param {() => T} step
|
|
23
|
+
* @returns {T}
|
|
24
|
+
*/
|
|
25
|
+
function orExit(what, step) {
|
|
26
|
+
try {
|
|
27
|
+
return step();
|
|
28
|
+
} catch (error) {
|
|
29
|
+
console.error(`safe-ts-skill: ${what}: ${error instanceof Error ? error.message : String(error)}`);
|
|
30
|
+
process.exit(2);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const byText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
35
|
+
|
|
14
36
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
15
37
|
// Published: next to this file. In the SAFE-TS repository: skills/ at the root.
|
|
16
38
|
const source = [join(here, "safe-ts-migrate"), join(here, "..", "..", "skills", "safe-ts-migrate")].find((dir) =>
|
|
@@ -34,16 +56,18 @@ if (source === undefined) {
|
|
|
34
56
|
|
|
35
57
|
/** Every file under `dir`, relative to it. */
|
|
36
58
|
function files(dir) {
|
|
37
|
-
return readdirSync(dir, { recursive: true })
|
|
59
|
+
return orExit(`can't list ${dir}`, () => readdirSync(dir, { recursive: true }))
|
|
38
60
|
.map(String)
|
|
39
|
-
.filter((f) => statSync(join(dir, f)).isFile())
|
|
40
|
-
.sort();
|
|
61
|
+
.filter((f) => orExit(`can't read ${join(dir, f)}`, () => statSync(join(dir, f))).isFile())
|
|
62
|
+
.sort(byText);
|
|
41
63
|
}
|
|
42
64
|
|
|
65
|
+
const bytes = (file) => orExit(`can't read ${file}`, () => readFileSync(file));
|
|
66
|
+
|
|
43
67
|
const same = (a, b) => {
|
|
44
68
|
const left = files(a);
|
|
45
69
|
const right = files(b);
|
|
46
|
-
return left.length === right.length && left.every((f, i) => f === right[i] &&
|
|
70
|
+
return left.length === right.length && left.every((f, i) => f === right[i] && bytes(join(a, f)).equals(bytes(join(b, f))));
|
|
47
71
|
};
|
|
48
72
|
|
|
49
73
|
if (existsSync(target)) {
|
|
@@ -55,8 +79,8 @@ if (existsSync(target)) {
|
|
|
55
79
|
console.error(`safe-ts-skill: ${shown} exists and differs (another version, or edited). --force replaces it; edits there are lost.`);
|
|
56
80
|
process.exit(1);
|
|
57
81
|
}
|
|
58
|
-
rmSync(target, { recursive: true, force: true });
|
|
82
|
+
orExit(`can't remove the old ${shown}`, () => rmSync(target, { recursive: true, force: true }));
|
|
59
83
|
}
|
|
60
|
-
cpSync(source, target, { recursive: true });
|
|
84
|
+
orExit(`can't copy the skill to ${shown}`, () => cpSync(source, target, { recursive: true }));
|
|
61
85
|
console.log(`safe-ts-skill: installed ${shown}`);
|
|
62
86
|
console.log("Ask your agent to migrate the project to SAFE-TS; it reads SKILL.md first.");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@evobug_com/safe-ts-skill",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "An agent skill (Claude Code / Agent Skills format) for migrating an existing project to SAFE-TS: the target architecture first, a census script, a pattern catalogue with before and after, gates, behaviour checks and a review checklist. `npx @evobug_com/safe-ts-skill` copies it into .claude/skills/.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"safe-ts",
|
package/safe-ts-migrate/SKILL.md
CHANGED
|
@@ -1,25 +1,31 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: safe-ts-migrate
|
|
3
|
-
description: Migrate an existing TypeScript, Vue or React project to SAFE-TS (the @evobug_com/safe-ts-* packages) toward its target architecture, not only a passing checker. Use when asked to adopt SAFE-TS in a code base, plan or run a SAFE-TS migration, convert an area or remove `// @safe-ts legacy` markers, take a census of what is left,
|
|
3
|
+
description: Migrate an existing TypeScript, Vue or React project to SAFE-TS (the @evobug_com/safe-ts-* packages) toward its target architecture, not only a passing checker. Use when asked to adopt SAFE-TS in a code base, plan or run a SAFE-TS migration, convert an area or remove `// @safe-ts legacy` markers, take a census of what is left, review a SAFE-TS migration change, or upgrade a project already on SAFE-TS to a newer version.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Migrating a project to SAFE-TS
|
|
7
7
|
|
|
8
|
-
Written for SAFE-TS 0.
|
|
8
|
+
Written for SAFE-TS 0.5.1. Check the installed version (`npx safe-ts --version`); if it is
|
|
9
9
|
newer, read its CHANGELOG entries first and prefer what they say over
|
|
10
10
|
[references/tool-gaps.md](references/tool-gaps.md).
|
|
11
11
|
|
|
12
12
|
**The goal is the target architecture, and the checker is one gate among several.** Without the
|
|
13
13
|
idiomatic layer, `safe-ts check` accepts a `.tag === 'Ready'` chain, an `if (isErr(x)) return
|
|
14
|
-
x
|
|
15
|
-
|
|
16
|
-
beside an `Enum`, a `''` that means "none" and a string if-chain. A migration that aims at "no
|
|
14
|
+
x` and an `unwrapOr(x, undefined)`; with it, they are warnings, and a run with only warnings
|
|
15
|
+
still exits 0. Even then it accepts a boolean flag set beside an `Enum`, a `''` that means "none" and a string if-chain. A migration that aims at "no
|
|
17
16
|
findings" converts `null` and `throw` and stops there. This skill aims at the architecture
|
|
18
17
|
SAFE-TS is built for: `Result` for failures, `Option` for absence, `useTask` and `AsyncState` for
|
|
19
18
|
async work, `Enum` and `match` for closed sets, validated boundaries, no module state.
|
|
20
19
|
|
|
21
20
|
## Rules for the whole migration
|
|
22
21
|
|
|
22
|
+
- **Fix the design, not the finding.** A finding points at a line, but the bug is in the
|
|
23
|
+
design that let it be written: a type that admits a bad value, a closed set that exists only
|
|
24
|
+
in `if` chains, state with two owners. Group the findings by cause, change the representation
|
|
25
|
+
so the class of bug can't be written, and let the compiler list the places that follow, the
|
|
26
|
+
way a Rust borrow error is fixed by changing ownership, not by moving a variable. A guard, a
|
|
27
|
+
default or a branch added at the reported line is a patch; it needs a reason in the hand-off
|
|
28
|
+
report ([references/fix-the-design.md](references/fix-the-design.md)).
|
|
23
29
|
- **Only real APIs.** Every function, rule, option and command you write must exist in the
|
|
24
30
|
installed packages (read the `.d.ts` files in `node_modules/@evobug_com/`) or the guide
|
|
25
31
|
(https://safe-ts.evobug-pages.com). Don't invent wrappers around std; the architecture
|
|
@@ -28,11 +34,14 @@ async work, `Enum` and `match` for closed sets, validated boundaries, no module
|
|
|
28
34
|
bodies, same messages in the same places. Static gates don't prove it
|
|
29
35
|
([references/behaviour.md](references/behaviour.md)).
|
|
30
36
|
- **A gate is never fixed by weakening it**: no new legacy marker, `safe-ts-ignore` comment,
|
|
31
|
-
rule set to `"off"` or `"warn"`, cast, `trust`, `void` or baseline rewrite
|
|
32
|
-
the architecture document's exception list.
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
37
|
+
`@ts-expect-error`, rule set to `"off"` or `"warn"`, cast, `trust`, `void` or baseline rewrite
|
|
38
|
+
without a line in the architecture document's exception list. Never `@ts-ignore` or
|
|
39
|
+
`@ts-nocheck`.
|
|
40
|
+
- **"The checker passes" means `safe-ts check <dirs or entries> --deny-warnings` exits 0**,
|
|
41
|
+
with `"idiomatic": true` in package.json. Warnings alone exit 0, and the idiomatic rules are
|
|
42
|
+
warnings: never read a plain `check` run's exit code as done. With `--deny-warnings`, a file
|
|
43
|
+
the entries don't reach, an import that resolves to nothing and a `warning:` line about the
|
|
44
|
+
setup (no strict-lib in the tsconfig, a pack not installed) fail it too. Run it this way in your own loop,
|
|
36
45
|
not only in CI.
|
|
37
46
|
- **The CLI is the `safe-ts` command** (`npx safe-ts check src/main.ts`, `npx safe-ts migrate
|
|
38
47
|
throw-to-result src/`, `safe-ts ...` in package.json scripts). It comes with the transform and
|
|
@@ -57,16 +66,23 @@ async work, `Enum` and `match` for closed sets, validated boundaries, no module
|
|
|
57
66
|
absence policy, errors and requests, state, async work, closed sets, boundaries, tooling,
|
|
58
67
|
escape-hatch budget, sanctioned helpers, exceptions, areas and order. Get it approved.
|
|
59
68
|
4. **Set up** ([references/templates.md](references/templates.md)): packages, tsconfig flags
|
|
60
|
-
(`strict`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`
|
|
69
|
+
(`strict`, `noUncheckedIndexedAccess`, `exactOptionalPropertyTypes`: `safe-ts check` warns
|
|
70
|
+
for each one left off) and std's strict-lib in
|
|
71
|
+
`"types"` (lib's `any` from `JSON.parse`, `response.json()`, ... as `unknown`), the oxlint preset,
|
|
61
72
|
the Vite plugin (or the Bun plugin), the loader for Node, `"idiomatic": true`, the feature
|
|
62
73
|
packs, `"requestFunctions"` for the project's request wrapper, the scripts, the CI job, the
|
|
63
74
|
conventions section in `CLAUDE.md` / `AGENTS.md`. Mark the files that don't pass yet with
|
|
64
|
-
`// @safe-ts legacy
|
|
65
|
-
|
|
75
|
+
`// @safe-ts legacy` and list them under `"legacyFiles"` in package.json (`safe-ts check`
|
|
76
|
+
prints the lines), then write the census baseline (`--write-baseline safe-ts-census.json`)
|
|
77
|
+
and the checker's (`safe-ts check src --write-baseline safe-ts-baseline.json`): from here the
|
|
78
|
+
counts may only fall.
|
|
66
79
|
5. **Migrate in order** ([references/order-and-gates.md](references/order-and-gates.md)): the
|
|
67
80
|
shared foundation (transport, requests, error types, stores), then utilities and the component
|
|
68
81
|
library, then the feature areas in parallel by dependency, then the removal of bridges and the
|
|
69
82
|
last markers. For each change:
|
|
83
|
+
- group the area's findings by cause and name, for each group, the design that rules it out
|
|
84
|
+
([references/fix-the-design.md](references/fix-the-design.md#the-procedure)); change that
|
|
85
|
+
first, then the call sites;
|
|
70
86
|
- rewrite with the catalogue: [references/patterns-core.md](references/patterns-core.md),
|
|
71
87
|
[references/patterns-vue.md](references/patterns-vue.md),
|
|
72
88
|
[references/patterns-react.md](references/patterns-react.md). For the repetitive part,
|
|
@@ -83,6 +99,56 @@ async work, `Enum` and `match` for closed sets, validated boundaries, no module
|
|
|
83
99
|
and the escape-hatch counts ([references/escape-hatches.md](references/escape-hatches.md)):
|
|
84
100
|
census before and after, what remains, and why.
|
|
85
101
|
|
|
102
|
+
## Upgrading between versions
|
|
103
|
+
|
|
104
|
+
For a project already on SAFE-TS that moves to a newer release (0.3.0 to 0.4.0, say). Read
|
|
105
|
+
the CHANGELOG sections in between first: **Added** lists the new rules, and **Changed** the
|
|
106
|
+
rules that now report more.
|
|
107
|
+
|
|
108
|
+
1. **Bump every `@evobug_com` package together, then take the census.** They are released with
|
|
109
|
+
one version, and each package's peer range is its own minor (`^0.4.0`, which npm reads as
|
|
110
|
+
`>=0.4.0 <0.5.0` for a 0.x version), so a mix of versions doesn't install. Changing the pins
|
|
111
|
+
in package.json and running `npm install` can stop with `ERESOLVE` when the lockfile still
|
|
112
|
+
holds an old one (`safe-ts-vue@0.3.0` while the new `safe-ts-feature-browser` peers
|
|
113
|
+
`safe-ts-std@^0.4.0`). Either name them all in one command, which keeps each in the field
|
|
114
|
+
it is in:
|
|
115
|
+
|
|
116
|
+
```sh
|
|
117
|
+
npm install @evobug_com/safe-ts-std@0.4.0 @evobug_com/safe-ts-vue@0.4.0 \
|
|
118
|
+
@evobug_com/safe-ts-transform@0.4.0 @evobug_com/oxlint-plugin-safe-ts@0.4.0 ...
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
or change the pins, delete the `node_modules/@evobug_com/...` entries from
|
|
122
|
+
`package-lock.json`, and run `npm install`. Then run the census against the baseline
|
|
123
|
+
(`--baseline safe-ts-census.json`): the new rules' findings show as rises, by file.
|
|
124
|
+
2. **Apply the new rules' fixes one rule at a time, and review each before the next.** The
|
|
125
|
+
census's `--show <rule>` lists every place of a rule; apply the editor's quick fixes (or, if
|
|
126
|
+
your version has it, `safe-ts fix <rule>`), read the diff, run the tests. Take most care
|
|
127
|
+
with `strict-truthiness`: on a value that may be `undefined`, `if (x)` meant "set and not
|
|
128
|
+
empty", and a fix that writes `x !== ''` is true for `undefined`. A 0.4.0 quick fix did
|
|
129
|
+
exactly that for an `x?: string`. Write `x !== undefined && x !== ''`, or whichever of the
|
|
130
|
+
two the code means.
|
|
131
|
+
3. **Audit the comparisons with `''` or `0` whose operand can be `undefined`**, the fixes' and
|
|
132
|
+
the code's own: `x !== ''`, `x === 0`, `x !== 0`. `--show empty-string-sentinel` lists
|
|
133
|
+
the `''` ones, and `rg -n '[!=]==?\s*0\b' src` the `0` ones. Where the operand's type
|
|
134
|
+
includes `undefined`, the comparison is true (or false) for it too: check that this is meant.
|
|
135
|
+
4. **Past the release that made `Mut<T>` a type of its own: lend every `Mut` with `mut(...)`.** Since then
|
|
136
|
+
`tsc` refuses every value passed to a `Mut` parameter without `mut(value)`. Run
|
|
137
|
+
`npx safe-ts migrate mut <your source dirs> --write` once over the whole program (all of
|
|
138
|
+
`apps` and `packages` together, so calls across packages resolve), review the diff, then
|
|
139
|
+
work through its "Needs a decision" list and what `tsc` (or `vue-tsc`) still refuses: a
|
|
140
|
+
function taking `Mut<T>` passed as a callback that only lends to read, a `Dog[]` lent as
|
|
141
|
+
`Mut<Animal[]>`, a union lent as one member (take `Mut<A> | Mut<B>`), a list of `Mut`
|
|
142
|
+
elements built by a call, a call the migration couldn't follow (patterns-core.md, "A
|
|
143
|
+
parameter the function changes"). Then the census: new
|
|
144
|
+
`aliased-mut` findings are calls that lend a value and pass a part of it too.
|
|
145
|
+
5. **Reinstall the skill with `--force`**: `npx @evobug_com/safe-ts-skill@0.4.0 --force`. It
|
|
146
|
+
replaces the copy in `.claude/skills/`, edits included, so keep project notes in the
|
|
147
|
+
architecture document.
|
|
148
|
+
|
|
149
|
+
Once the new rules' findings are fixed or recorded as exceptions, write the baseline again in a
|
|
150
|
+
commit that names the upgrade.
|
|
151
|
+
|
|
86
152
|
## When several agents migrate at once
|
|
87
153
|
|
|
88
154
|
Give each builder this skill, the approved architecture document, and the foundation's exported
|
|
@@ -96,6 +162,7 @@ a `Result` through store members and factories, not through parameters, class fi
|
|
|
96
162
|
| File | Holds |
|
|
97
163
|
|---|---|
|
|
98
164
|
| [architecture.md](references/architecture.md) | the target architecture document, section by section, with SAFE-TS's defaults |
|
|
165
|
+
| [fix-the-design.md](references/fix-the-design.md) | fixing the cause, not the finding: the procedure, how to tell a patch from a design fix, examples |
|
|
99
166
|
| [census.md](references/census.md) | running and reading `scripts/census.mjs`; the pattern table; the baseline gate |
|
|
100
167
|
| [patterns-core.md](references/patterns-core.md) | before and after for TypeScript idioms: throws, requests, sentinels, enums, casts, JSON, null on the wire, optional keys, `Patch`, `Open`, base64 and `Ascii`, `trust`, `LegacyNull`, `parseArgs`, IndexedDB |
|
|
101
168
|
| [patterns-vue.md](references/patterns-vue.md) | Vue: the loading trio, `useTask`, `<Match>`, `useElement`, stores, props, `v-html` and `Html`, URLs and `SafeUrl` |
|
|
@@ -74,6 +74,12 @@ accepts most of what this document rules out.
|
|
|
74
74
|
- One style for reading an enum: `match`, `is`, `variant` in TypeScript; `<Match :value>`, or an
|
|
75
75
|
exhaustive `v-if` chain of `is(...)`, in templates. `prefer-is-over-tag` (idiomatic) holds it:
|
|
76
76
|
no raw `.tag` anywhere.
|
|
77
|
+
- What a screen or a flow is doing is one `Enum` that names every state it can be in, the
|
|
78
|
+
first one included: `Editing | Rejected { error } | Published`, the way `useTask`'s
|
|
79
|
+
`AsyncState` is `Idle | Loading | Ready | Failed`. Not an `Option` of the error, where
|
|
80
|
+
`undefined` stands for "not tried yet" and for "it worked" alike, so success leaves no
|
|
81
|
+
trace and the template can't say it. `Option<T>` is for a value that is there or not (the
|
|
82
|
+
selected item, the signed-in user), not for the outcome of a step.
|
|
77
83
|
- Sets of booleans of which at most one is true are one `Enum`. Unions told apart by key
|
|
78
84
|
presence (`'k' in o`) get a tag.
|
|
79
85
|
- A string the server fills from a list it may extend (a status, a type) is an `Open<K>`, read
|
|
@@ -84,8 +90,8 @@ accepts most of what this document rules out.
|
|
|
84
90
|
- Every value from outside (responses, storage, `postMessage`, URL and query parameters,
|
|
85
91
|
`history.state`, server-rendered data in the page) is read with `validate<T>` /
|
|
86
92
|
`parseJson<T>` or a pack's safe version.
|
|
87
|
-
- No `as` on such values,
|
|
88
|
-
|
|
93
|
+
- No `as` on such values, no hand-written `value is T` guard or assertion signature
|
|
94
|
+
(`no-type-predicate`) and no overload over a looser implementation (`no-overload`). A trusted boundary that can't be validated (a worker's message
|
|
89
95
|
of the same build, a type `validate` refuses) is a `trust<T>(value)` call, listed here by name
|
|
90
96
|
with the reason.
|
|
91
97
|
- Types that `validate<T>` reads are declared in the project: project files, namespaces of
|
|
@@ -102,7 +108,8 @@ accepts most of what this document rules out.
|
|
|
102
108
|
## 7. Tooling
|
|
103
109
|
|
|
104
110
|
- `tsconfig.json`: `strict`, `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` on from
|
|
105
|
-
the first step, in the tsconfig every tool reads (tsc, vue-tsc, type-aware oxlint)
|
|
111
|
+
the first step, in the tsconfig every tool reads (tsc, vue-tsc, type-aware oxlint), with
|
|
112
|
+
`"@evobug_com/safe-ts-std/strict-lib"` in `"types"`.
|
|
106
113
|
- `"safe-ts": { "idiomatic": true }` in package.json from the first step, the feature packs the
|
|
107
114
|
code needs (`"features": [...]`), and the project's request wrappers (`"requestFunctions"`).
|
|
108
115
|
- `safe-ts check` runs with `--deny-warnings` wherever a gate reads its exit code, CI and the
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
1. what `safe-ts check --json --idiomatic` reports, errors and warnings, with the idiomatic
|
|
6
6
|
rules on whether or not package.json turns them on yet: several of them (`prefer-is-over-tag`,
|
|
7
|
-
`prefer-q`, `
|
|
7
|
+
`prefer-q`, `key-presence-union`, `no-swallowed-error`,
|
|
8
8
|
`json-null-in-app`, `cast-in-test`, ...) report the hand-rolled forms a checker-driven
|
|
9
9
|
migration leaves behind;
|
|
10
10
|
2. the hand-rolled patterns no rule reports, found by regular expressions over the source
|
|
@@ -27,7 +27,11 @@ node .claude/skills/safe-ts-migrate/scripts/census.mjs --json > census.json
|
|
|
27
27
|
|
|
28
28
|
- Files: `.ts`, `.tsx`, `.mts`, `.cts`, `.vue`, `.jsx`, from `git ls-files` (so `.gitignore`
|
|
29
29
|
applies), without `.d.ts` files. Outside git, `node_modules`, `dist`, `build` and the like
|
|
30
|
-
are skipped.
|
|
30
|
+
are skipped. The skill's own folder is never scanned.
|
|
31
|
+
- The scripts run before SAFE-TS is installed, so they don't import std. They pass oxlint with
|
|
32
|
+
the SAFE-TS preset (and the Node pack): a project that lints every file needn't exclude
|
|
33
|
+
`.claude/`. When a step fails (a file it can't read, a baseline that isn't JSON), the census
|
|
34
|
+
prints `census: <what failed>: <why>` and exits 2.
|
|
31
35
|
- The checker: the `safe-ts` binary from the project's `node_modules` (`SAFE_TS_BIN=<path>`
|
|
32
36
|
overrides it; `--no-check` skips it, `--no-idiomatic` leaves the idiomatic rules out). Every
|
|
33
37
|
scanned file is passed as an entry, so tests, scripts and files nothing imports are counted
|
|
@@ -58,36 +62,54 @@ node .claude/skills/safe-ts-migrate/scripts/census.mjs --json > census.json
|
|
|
58
62
|
| Pattern | Finds | Target |
|
|
59
63
|
|---|---|---|
|
|
60
64
|
| `loading-flag` | `const loading = ref(false)`, `useState(false)`, `let busy = false` (names like loading, busy, pending, saving, submitting) | `useTask` |
|
|
61
|
-
| `error-state` | an error kept in its own state: `ref('')`, `ref(null)`, `ref<E>()`, `useState('')` named error, failed, problem | `useTask`'s `Failed`, or
|
|
65
|
+
| `error-state` | an error kept in its own state: `ref('')`, `ref(null)`, `ref<E>()`, `shallowRef<Option<E>>()`, `useState('')` named error, failed, problem | `useTask`'s `Failed`, or one state `Enum` with a failed variant |
|
|
66
|
+
| `error-or-undefined` | a state set to `isErr(r) ? r.error : undefined`: `undefined` is both "not tried yet" and "it worked" | one state `Enum` that names every state (`Editing \| Rejected \| Published`) |
|
|
62
67
|
| `trio-files` | files with a loading flag and an error state | `useTask` + `<Match>` |
|
|
63
68
|
| `empty-string-sentinel` | `=== ''`, `!== ''`, `return ''` | `Option<string>`, `Result<void, E>` |
|
|
64
|
-
| `minus-one-sentinel` | `=== -1`, `return -1`, `= -1` | `Option<T>`, `indexIn` |
|
|
69
|
+
| `minus-one-sentinel` | `=== -1`, `return -1`, `= -1`; a named constant (`const NONE = -1`) once, at its declaration ([below](#a-named-sentinel)) | `Option<T>`, `indexIn` |
|
|
65
70
|
| `zero-sentinel` | an id or index that starts at `0` | `Option<T>` |
|
|
66
|
-
| `string-if-chain` | one value compared with 3 or more string literals in a file | `Enum` + `match` |
|
|
71
|
+
| `string-if-chain` | one value compared with 3 or more string literals in a file | `Enum` + `match`, or a union parsed once ([patterns-core.md](patterns-core.md#a-closed-set-of-states)); the checker's rules: `string-dispatch` (a plain `string`, idiomatic), `exhaustive-dispatch` and `exhaustive-switch` (a closed set) |
|
|
67
72
|
| `boolean-state`, `boolean-flag-files` | boolean refs/states; files with 3 or more | one `Enum` |
|
|
68
73
|
| `raw-fetch` | `fetch(`, `axios(`/`axios.get(`, `new XMLHttpRequest` | a request function returning a `Result` |
|
|
69
74
|
| `try-catch`, `promise-catch` | `try {`, `.catch(` | a `Result`; `unsafe` for code that throws |
|
|
70
|
-
| `as-cast`, `double-cast` | `x as T` (not `as const`), `as unknown as`, `as never`, `as any` | `validate<T>`, an annotation, `satisfies` |
|
|
75
|
+
| `as-cast`, `double-cast` | `x as T` (not `as const`), `as unknown as`, `as never`, `as any`; not the renames in import and export lists (`type Building as SimBuilding,` on a line of its own too) or a mapped type's `[E in Events as E['type']]` | `validate<T>`, an annotation, `satisfies` |
|
|
71
76
|
| `json-parse`, `raw-storage` | `JSON.parse(`, `localStorage.getItem(` and friends | `parseJson<T>`, the browser pack's `getItem` / `setItem` |
|
|
72
77
|
| `unsafe`, `unsafe-async`, `unexplained-unsafe`, `panic`, `void-call` | escape hatches; `unsafe(` without a comment on its line or the line above | [escape-hatches.md](escape-hatches.md) |
|
|
73
78
|
| `trust`, `legacy-null`, `safe-ts-ignore` | `trust<T>(...)`, `LegacyNull`, `// safe-ts-ignore` (and `-file`, `<!-- -->`) comments | [escape-hatches.md](escape-hatches.md) |
|
|
74
|
-
| `module-let` | a `let` at the top of a `.ts` module | a store, a context |
|
|
79
|
+
| `module-let` | a `let` at the top of a `.ts` module, not in a test file | a store, a context |
|
|
75
80
|
|
|
76
81
|
Comment lines are skipped (except for `safe-ts-ignore`); strings are not, so a pattern inside a
|
|
77
82
|
string literal counts.
|
|
78
83
|
|
|
84
|
+
`module-let` skips test files, the ones the checker calls test files: named `*.test.*` or
|
|
85
|
+
`*.spec.*`, in a `test`, `tests`, `__tests__` or `__mocks__` folder, or importing a test runner
|
|
86
|
+
(`vitest`, `node:test`, `bun:test`, `@jest/globals`, `mocha`). A test file's `let errors:
|
|
87
|
+
string[]` that `beforeEach` resets is the runner's idiom: each test file is its own module, so
|
|
88
|
+
it isn't state the app shares. The checker's `no-mutable-global` still reports it, when the
|
|
89
|
+
project lints tests.
|
|
90
|
+
|
|
91
|
+
### A named sentinel
|
|
92
|
+
|
|
93
|
+
Not every `-1` means "not found". An index that typed arrays or a file format store can't be
|
|
94
|
+
`undefined`, so a project names it once: `const NONE = -1`. The census counts that
|
|
95
|
+
declaration (also `export const`, `static readonly`, with a type or `as const`), and not the
|
|
96
|
+
comparisons or arguments that use the name (`=== NONE`, `.fill(NONE)`), so the sentinel is one
|
|
97
|
+
entry, not one per use. To mark one, write every use with its name: a literal `-1` that means
|
|
98
|
+
the same thing still counts, and is the place to replace. Record the sentinel in the
|
|
99
|
+
architecture document's exceptions, with why `Option` can't hold it.
|
|
100
|
+
|
|
79
101
|
The forms the idiomatic rules see are counted as their findings, not as patterns:
|
|
80
102
|
|
|
81
103
|
| Rule (idiomatic) | Finds | Target |
|
|
82
104
|
|---|---|---|
|
|
83
105
|
| `prefer-is-over-tag` | `x.tag === '...'`, `switch (x.tag)`, in code and templates | `is`, `variant`, `match`, `<Match>` |
|
|
106
|
+
| `prefer-constructor-tag` | `is(x, "Published")` where the enum has constructors in scope | `is(x, Status.Published)` |
|
|
84
107
|
| `prefer-q`, `prefer-map-err` | `if (isErr(x)) return x`, an error re-wrapped by hand | `q(x)`, `q(x, map)`, `mapErr` |
|
|
85
108
|
| `key-presence-union` | `'key' in x` telling a project union's members apart | a tagged `Enum` |
|
|
86
|
-
| `partial-type-guard` | a `value is T` guard that tests part of `T` | `validate<T>` |
|
|
87
109
|
| `no-swallowed-error` | `unwrapOr(x, undefined)`, `.catch(() => {})`, helpers around them | the `Result` itself |
|
|
88
110
|
| `json-null-in-app` | `JsonNull` as app state (`Ref<T \| JsonNull>`, `Option<T \| JsonNull>`) | `Option`, an `Enum`, `AsyncState<Option<T>, E>` |
|
|
89
111
|
| `catch-on-result` | `.catch` / `try` around calls that return a `Result` | the `Result` checked |
|
|
90
|
-
| `latest-wins-counter`, `unused-task-signal` | a hand-written "latest run wins" ticket; a task that ignores its `signal` | `useTask
|
|
112
|
+
| `latest-wins-counter`, `unused-task-signal` | a hand-written "latest run wins" ticket; a task that ignores its `signal` | `useTask` (outside components, std's `latest`), the `signal` passed on |
|
|
91
113
|
| `cast-in-test` | `as unknown as T`, `as never` in tests where `no-unchecked-cast` is off for them (otherwise that rule reports the cast) | `fixture`, `testDouble`, `unchecked` |
|
|
92
114
|
| `panic-on-loading` | `panic` under a loading flag | a state the page shows |
|
|
93
115
|
|
|
@@ -2,15 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
Every escape hatch is allowed somewhere, and each one is visible and counted. The policy says
|
|
4
4
|
where; the budget says how many; the hand-off report says how many are left. `safe-ts check`
|
|
5
|
-
counts most of them after each run
|
|
5
|
+
counts most of them after each run, and names what package.json weakens below the defaults
|
|
6
|
+
(rule levels, `infer`, `infer.exclude`, `testRunners`, `vue.sanitizers`):
|
|
6
7
|
|
|
7
8
|
```text
|
|
8
|
-
escape hatches: 2 unsafe() block(s), 0 panic() call(s), 1 trust() call(s), 3 LegacyNull use(s), 0 @cache mark(s), 1 safe-ts-ignore comment(s), 0 legacy file(s), 1 std file(s) (src/protocol/trusted.ts)
|
|
9
|
+
escape hatches: 2 unsafe() block(s), 0 panic() call(s), 1 trust() call(s), 3 LegacyNull use(s), 0 @cache mark(s), 1 safe-ts-ignore comment(s), 0 legacy file(s), 1 std file(s) (src/protocol/trusted.ts), 0 @ts-ignore, 1 @ts-expect-error (and 12 in test files), 0 @ts-nocheck comment(s)
|
|
10
|
+
weakened below the defaults: no-mutable-global off for src/stores/** (package.json)
|
|
9
11
|
```
|
|
10
12
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
13
|
+
`safe-ts check --baseline safe-ts-baseline.json` fails when any of those counts rose, something
|
|
14
|
+
was newly weakened, a setting got weaker than the baseline recorded (`"idiomatic"` off, a pack
|
|
15
|
+
out of `"features"`, an entry out of `"emitters"` or `"requestFunctions"`, Vue SSR off), or the
|
|
16
|
+
files not checked, the unresolved imports or the warnings of a rule rose (`--write-baseline`
|
|
17
|
+
records them). The census counts the rest (`unsafeAsync`, `void` calls,
|
|
18
|
+
casts, `unsafe` without a reason comment), per file, and its baseline keeps each count from
|
|
19
|
+
rising. Treat a rising count as a review question, the way Rust projects treat a new `unsafe`
|
|
20
|
+
block.
|
|
14
21
|
|
|
15
22
|
## When each is allowed
|
|
16
23
|
|
|
@@ -24,14 +31,17 @@ as a review question, the way Rust projects treat a new `unsafe` block.
|
|
|
24
31
|
| `LegacyNull` | strict code whose legacy callers still pass `null`, until they are migrated | a `null` that means something on the wire (`JsonNull`); the end state |
|
|
25
32
|
| `// safe-ts-ignore <rule>: <reason>` | one line in a migrated file that is right as it is, or that the rule gets wrong (a package's type that tells `null` from `undefined`) | a file that isn't migrated yet (the legacy marker); a finding the code should fix |
|
|
26
33
|
| `// safe-ts-ignore-file <rule>: <reason>` | a generated file the project can't change | hand-written code |
|
|
27
|
-
| `"off"` / `"warn"` in package.json `"rules"` / `"overrides"` | a directory whose code the rule doesn't fit (generated types), decided in the architecture document | silencing an area's findings to pass a gate: the census baseline ratchets them instead |
|
|
34
|
+
| `"off"` / `"warn"` in package.json `"rules"` / `"overrides"` | a directory whose code the rule doesn't fit (generated types), decided in the architecture document | silencing an area's findings to pass a gate: the census baseline ratchets them instead. `check` names each one, and its `--baseline` fails on a new one |
|
|
35
|
+
| `// @ts-expect-error <reason>` | one line TypeScript can't type yet (a package's wrong declaration), with the reason; a compile-time test's "this must not compile" | data from outside (`validate<T>`); `@ts-ignore` and `@ts-nocheck`, which `no-ts-suppression` reports, like a `@ts-expect-error` without a reason |
|
|
28
36
|
| `void f()` | a `Result` or promise whose failure really doesn't matter (best-effort telemetry) | anything the user started, or any write |
|
|
29
|
-
| `// @safe-ts legacy` | a file that waits its turn in the burn-down | the end state; a file that "doesn't fit" |
|
|
30
|
-
| `// @safe-ts std` | low-level helpers like the std library itself, reviewed line by line | application code |
|
|
37
|
+
| `// @safe-ts legacy` | a file that waits its turn in the burn-down, listed under `"legacyFiles"` in package.json (`unlisted-marker` reports the marker anywhere else, and the file is checked) | the end state; a file that "doesn't fit"; a marker without the list entry |
|
|
38
|
+
| `// @safe-ts std` | low-level helpers like the std library itself, reviewed line by line, listed under `"trustedFiles"` | application code |
|
|
39
|
+
| `// eslint-disable-next-line <rule> -- <reason>` | another linter's rule that is wrong on this line, named | a blanket `eslint-disable` / `oxlint-disable`, or one naming a `safe-ts/` rule: `no-lint-suppression` reports them; write `// safe-ts-ignore <rule>: <reason>` |
|
|
40
|
+
| `declare const X: unknown` (validated where read), `declare module "*.svg" { ... }`, a global the project sets typed `Option<T>`, optional members added to a library's interface | a constant a bundler injects, an asset module, an expando field the project writes itself | `declare const X: Config`, `declare function`, `declare module "pkg" { export function ... }`, a `declare module "virtual:x"` with a typed value (export it `unknown` and `trust<T>` it once in a wrapper module), a required member added to `Window`, a class field `declare x: T`: `no-unchecked-declare` reports them, a cast with no `as` |
|
|
31
41
|
| `/** @cache */` | a memo that can be thrown away and computed again | state |
|
|
32
42
|
| `safeTs({ exclude })` | vendored or generated code the build should leave alone entirely | the project's own code waiting its turn (it loses its prelude imports): the legacy marker |
|
|
33
43
|
| `as T`, `x!` | nowhere on outside data. `x[i]!` under a bound the checker accepts; `as const` | data from a request, storage, a message, the DOM; a brand (`as Html`, `as SafeUrl` are `brand-constructor` errors) |
|
|
34
|
-
| An overload over a loose implementation, a `value is T` guard |
|
|
44
|
+
| An overload over a loose implementation, a `value is T` guard, `asserts value is T` | nowhere: `no-overload` and `no-type-predicate` report them. A guard whose body is one test drops its annotation (TypeScript infers it); overloads that only narrow the implementation (same result, each parameter a member of its union) and `asserts ok` with exactly `if (!ok) throw` are allowed. A claim no check can make is `trust<T>(value)` | a way around `validate<T>` |
|
|
35
45
|
| A catch-all `catch` | a harness boundary that runs independent units of work and reports each failure | anywhere below it |
|
|
36
46
|
|
|
37
47
|
## The reason
|
|
@@ -14,25 +14,27 @@ node scripts/census.mjs --show string-if-chain
|
|
|
14
14
|
|
|
15
15
|
| Look for | Census (pattern or rule) | Replace with |
|
|
16
16
|
|---|---|---|
|
|
17
|
-
| loading / error / data state, a lone busy flag, an error string | `trio-files`, `loading-flag`, `error-state`, `vue-split-state` | `useTask` + `<Match :value>` (or `match` in a `computed`) |
|
|
18
|
-
| hand-written `AsyncState` assignments, latest-wins counters, tasks that ignore their signal | `latest-wins-counter`, `unused-task-signal`, a search for `AsyncState.` outside `useTask` | `useTask`, in the component or the setup store |
|
|
17
|
+
| loading / error / data state, a lone busy flag, an error string | `trio-files`, `loading-flag`, `error-state`, `error-or-undefined`, `vue-split-state` | `useTask` + `<Match :value>` (or `match` in a `computed`) |
|
|
18
|
+
| hand-written `AsyncState` assignments, latest-wins counters, tasks that ignore their signal | `latest-wins-counter`, `unused-task-signal`, a search for `AsyncState.` outside `useTask` | `useTask`, in the component or the setup store; std's `latest` outside Vue and React |
|
|
19
19
|
| an answer or error the user dismisses by hand | a search for `dismissed`, `clearError` | `useTask`'s `reset()` |
|
|
20
20
|
| a blank `Idle` after a bug | `<Match>` without `#Idle` / `#_` | a slot that reads the task's `panic` |
|
|
21
|
-
| string unions in if-chains, boolean sets, unions told apart by keys | `string-if-chain`, `boolean-flag-files`, `key-presence-union` | `Enum` + `constructors` + `match
|
|
21
|
+
| string unions in if-chains, boolean sets, unions told apart by keys | `string-if-chain`, `exhaustive-dispatch`, `string-dispatch`, `boolean-flag-files`, `key-presence-union` | `Enum` + `constructors` + `match`; a string parsed once into a union |
|
|
22
22
|
| raw tag reads | `prefer-is-over-tag` | `is`, `variant`, `match`, `<Match>` |
|
|
23
|
+
| variants named by strings where the enum has constructors | `prefer-constructor-tag` | `is(x, Status.Published)` |
|
|
23
24
|
| `if (isErr(x)) return x`, hand re-wraps of an error | `prefer-q`, `prefer-map-err` | `q(x)`, `q(x, map)`, `mapErr` |
|
|
24
25
|
| `.catch` or `try` around calls that return a `Result` | `catch-on-result`, `promise-catch`, `try-catch` | the `Result` checked |
|
|
25
26
|
| `''`, `-1`, `0` sentinels | `empty-string-sentinel`, `minus-one-sentinel`, `zero-sentinel`, `sentinel-error` | `Option<T>`, `indexIn`, an `Enum` variant |
|
|
26
27
|
| `unwrapOr(x, undefined)` and helpers around it | `no-swallowed-error` | the `Result`; `Result<Option<T>, E>` |
|
|
27
28
|
| `JsonNull` as app state, every `undefined` written as `null` | `json-null-in-app`, `undefined-to-null` | `Option`, an `Enum`, `AsyncState<Option<T>, E>`; `jsonNull` only where a body needs it |
|
|
28
|
-
| `JSON.parse`, direct storage, casts and
|
|
29
|
+
| `JSON.parse`, direct storage, casts, guards and overloads on outside data | `json-parse`, `raw-storage`, `as-cast`, `no-type-predicate`, `no-overload` | `parseJson<T>`, `validate<T>`, the browser pack |
|
|
29
30
|
| `btoa` / `atob` of text | `unhandled-failure` | `toBase64`, `fromBase64` |
|
|
30
31
|
| `ref<HTMLElement \| null>(null)` | (checker: `no-null`) | `useElement` / `useOptionalElement` / `useElements` |
|
|
31
32
|
| `addEventListener` / `setInterval` in components | (checker: `listener-cleanup`) | `useListener`, `useInterval` (Vue); `listen` elsewhere |
|
|
32
33
|
| tables indexed by wire data | `no-object-dictionary`, a search for `[` on `Record` constants | `getOwn(table, key, fallback)`; for a server field from a list, `Open<K>` + `lookup` |
|
|
33
34
|
| `null` in request bodies, `undefined` turned into `null` on the way out | `json-null-in-app`, `undefined-to-null`, a search for `jsonNull` | `Patch<T>` with `keep` / `clear` |
|
|
34
35
|
| markup and URLs passed around as `string` | `vue-v-html`, `vue-unsafe-url`, `Html/SafeUrl` in the features | `defineSanitizer`, props typed `Html` / `SafeUrl` |
|
|
35
|
-
| numbers and strings tested for truth | `strict-truthiness` | `> 0`, `!== ""`,
|
|
36
|
+
| numbers and strings tested for truth | `strict-truthiness`, `compare-misses-undefined` | `> 0`, `!== ""` on a value that can't be `undefined`; on one that can (`x?: string`, `Option<string>`, `a?.b`, `map.get(k)`) both halves, `x !== undefined && x !== ""`, or `x !== undefined` alone; never a lone `x !== ""` |
|
|
37
|
+
| codes numbered by hand, lists kept sorted by a comment | `duplicate-code-value`, `list-invariant` | codes derived from an append-only list of names (the `codesOf` pattern of the JSON guide); `/** @sorted */`, `/** @unique */` |
|
|
36
38
|
| casts in tests | `no-unchecked-cast` in test files (`cast-in-test` where that is off for tests) | `fixture`, `testDouble`, `unchecked`, `expectPresent` |
|
|
37
39
|
| bridges left from the migration | `legacy-null`, `trust`, `safe-ts-ignore` | gone, or each one in the exception list with its reason |
|
|
38
40
|
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# Fix the design, not the finding
|
|
2
|
+
|
|
3
|
+
A finding is a symptom. It points at one line, but the bug it stands for is a property of the
|
|
4
|
+
design: a type that lets a bad value exist, a set of cases that lives only in `if` chains, state
|
|
5
|
+
that two places own. Patching the line clears the finding and keeps the design that produced
|
|
6
|
+
it, so the same bug comes back at the next line someone writes, where no rule looks.
|
|
7
|
+
|
|
8
|
+
Rust works the same way. A borrow-checker error is rarely fixed by moving a variable or adding a
|
|
9
|
+
`clone()` until it compiles. The fix is a different ownership: who holds the data, who may change
|
|
10
|
+
it, how long it lives. Migrate to SAFE-TS the same way. For each group of findings, ask which
|
|
11
|
+
design would make that class of bug impossible to write, change the design, and let the
|
|
12
|
+
compiler list the places that have to follow.
|
|
13
|
+
|
|
14
|
+
## The procedure
|
|
15
|
+
|
|
16
|
+
1. **Group before you edit.** Take the census for the area (`--show <rule>`) and group the
|
|
17
|
+
findings by cause, not by file. Twenty `unhandled-failure` findings behind one throwing helper
|
|
18
|
+
are one cause. So are fourteen `strict-truthiness` findings on ids that may be `''`. A
|
|
19
|
+
`string-if-chain` in five files on the same field is one closed set without a type.
|
|
20
|
+
2. **Name the class of bug.** Write one sentence about what can go wrong at runtime, not which
|
|
21
|
+
rule fired: "a phase added later is silently treated as idle", "an empty id passes as a
|
|
22
|
+
real one", "a failure is shown as an empty list".
|
|
23
|
+
3. **Find the representation that rules it out.** Usually it is one of:
|
|
24
|
+
- a type that can't hold the bad value: `Option<T>` instead of a `''` or `-1` sentinel, an
|
|
25
|
+
`Enum` instead of three booleans, a brand that only its constructor makes;
|
|
26
|
+
- a closed set with one definition, handled by `match` or a `Record<Key, …>` table, so a new
|
|
27
|
+
member fails to compile everywhere it is handled;
|
|
28
|
+
- a boundary that parses once: outside data becomes a typed value in one place
|
|
29
|
+
(`validate<T>`, a `parseX(raw): Option<X>`), and the code behind it never re-checks the
|
|
30
|
+
raw form;
|
|
31
|
+
- one owner for each piece of state (a store, a context made at startup), and data passed
|
|
32
|
+
to the code that needs it, not read from wherever it happens to be;
|
|
33
|
+
- a failure in the return type (`Result`) at its origin, not handled at each caller.
|
|
34
|
+
4. **Change the representation first, then follow the compiler.** Change the type, the
|
|
35
|
+
definition of the set, or the owner, and let `tsc` and `safe-ts check` list the call sites.
|
|
36
|
+
Fix each one with the new design. A long error list at this step is the design change
|
|
37
|
+
working: each entry is a place that depended on the bad representation.
|
|
38
|
+
5. **Record the cause, not the lines.** The hand-off report lists each cause removed, the design
|
|
39
|
+
that replaced it, and the findings it cleared ([templates.md](templates.md#hand-off-report-per-area)).
|
|
40
|
+
|
|
41
|
+
## Patch or design?
|
|
42
|
+
|
|
43
|
+
A change is a patch, not a design fix, when it:
|
|
44
|
+
|
|
45
|
+
- adds a guard, a `??` default, a `!` or an early return at the line the finding names, while
|
|
46
|
+
the type still lets the bad value reach the next caller;
|
|
47
|
+
- adds the missing branch to one `if` chain while other chains on the same value stay as they
|
|
48
|
+
are;
|
|
49
|
+
- adds `!== ''` or `!== 0` next to a value that can also be `undefined`, or tests one half of
|
|
50
|
+
an `Option`;
|
|
51
|
+
- copies a check into a second place instead of moving it to where the value is made;
|
|
52
|
+
- wraps the failing call in `unsafe` at every caller instead of returning a `Result` from the
|
|
53
|
+
function that fails;
|
|
54
|
+
- moves code, splits a function, or renames something until the checker stops following it;
|
|
55
|
+
- adds a comment explaining why this case can't happen, where a type could say it;
|
|
56
|
+
- adds a cast, `trust`, `void`, `safe-ts-ignore` or a rule level (these also need the exception
|
|
57
|
+
list: [escape-hatches.md](escape-hatches.md)).
|
|
58
|
+
|
|
59
|
+
A local fix is right when the cause really is local: one function's own logic, a value parsed
|
|
60
|
+
once at its boundary, a message to reword. Say so in the hand-off report. "It was the fastest"
|
|
61
|
+
is not a reason.
|
|
62
|
+
|
|
63
|
+
## Examples
|
|
64
|
+
|
|
65
|
+
| Finding or bug | The patch | The design fix |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| A phase added to a code table (`codesOf([...])`) is missing from two `if`/`else if` chains and falls to `: 0` | add the branch to the two chains | `match` on an `Enum`, or a `Record<PhaseName, …>` table, so the next phase fails to compile in every place that handles phases |
|
|
68
|
+
| `strict-truthiness` on `unitId` (`string \| undefined`) | `unitId !== ''` (forgets `undefined`) | decide what absence is: `Option<UnitId>` with a brand whose constructor refuses `''`, then test `!== undefined` only |
|
|
69
|
+
| `unhandled-failure` at 20 callers of a helper that throws | `unsafe(...)` at each caller | the helper returns a `Result`; callers pass it on with `q` |
|
|
70
|
+
| `string-if-chain`: a command word compared with `'open'`, `'urls'`, `'help'`, `'?'` | a `switch` | a `parseCommand(word): Option<Command>` table at the boundary (aliases included) and `match` on `Command`; help text made from the same table |
|
|
71
|
+
| `loading` and `error` refs beside the data | rename them, add a reset | `useTask`, shown with `<Match>` |
|
|
72
|
+
| an admin "reset" built on the loader that fails for broken records | catch the load failure in reset | the repair path takes the stored row, not the loaded aggregate: what must work on broken data doesn't depend on the code that refuses it |
|
|
73
|
+
| a rectangle in world coordinates passed where local ones are expected | subtract the offset at the call site | a `LocalRect` brand made only by `toLocal(rect, origin)`, so the wrong frame doesn't compile |
|
|
74
|
+
| `no-mutable-global` on a cache several modules write | turn the `let` into a `const` object and mutate its fields | one owner: a store or a context made at startup, passed to the code that uses it |
|
|
75
|
+
|
|
76
|
+
The first row is a real bug that reached production after a checker-clean migration: the code
|
|
77
|
+
had no finding, because the chains compared numeric codes, which no rule checks. Look for the
|
|
78
|
+
design problem even where the checker is silent. The census's patterns
|
|
79
|
+
([census.md](census.md#the-patterns)) are where to start.
|
|
80
|
+
|
|
81
|
+
## In the architecture document
|
|
82
|
+
|
|
83
|
+
Each section of the architecture document ([architecture.md](architecture.md)) is a design
|
|
84
|
+
decision of this kind, made once for the whole project: what absence is, where failures are
|
|
85
|
+
returned, who owns state, where outside data is parsed, how closed sets are defined. When a
|
|
86
|
+
group of findings doesn't fit any of them, the document is missing a decision. Add it there and
|
|
87
|
+
get it approved, instead of deciding it again in each area.
|
|
@@ -35,7 +35,11 @@
|
|
|
35
35
|
`// @safe-ts legacy` (first lines of a `.ts` file; in a `.vue` file, the first line inside either
|
|
36
36
|
`<script>` block, or `<!-- @safe-ts legacy -->` at the top) lets the build stay green while a
|
|
37
37
|
file waits its turn. A marker anywhere else in a component marks nothing and is reported
|
|
38
|
-
(`vue-sfc`).
|
|
38
|
+
(`vue-sfc`). The file must also be listed under `"legacyFiles"` in the package.json
|
|
39
|
+
(`"safe-ts": { "legacyFiles": ["src/old/report.ts"] }`): a marker in a file the list doesn't name
|
|
40
|
+
is reported (`unlisted-marker`) and the file checked, and `safe-ts check` prints the lines that
|
|
41
|
+
list every marked file. List each file by name rather than a directory, so the list shrinks with
|
|
42
|
+
the burn-down. It is never the end state:
|
|
39
43
|
|
|
40
44
|
- The census counts the marked files; the baseline holds the count, so no new file gets one.
|
|
41
45
|
The count per week or per release is the burn-down.
|
|
@@ -76,9 +80,9 @@ architecture document's exception list gains a line for it.
|
|
|
76
80
|
|
|
77
81
|
| Gate | Command (adapt to the project) | Passes when |
|
|
78
82
|
|---|---|---|
|
|
79
|
-
| Types | `tsc --noEmit`, or `vue-tsc --noEmit` for Vue, with `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` on | no errors |
|
|
83
|
+
| Types | `tsc --noEmit`, or `vue-tsc --noEmit` for Vue, with `strict`, `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` on and std's strict-lib in `"types"` | no errors |
|
|
80
84
|
| Lint | `oxlint --deny-warnings` (add `--type-aware` if the project uses it) with the SAFE-TS preset | no warnings or errors |
|
|
81
|
-
| SAFE-TS | `safe-ts check <entries> --deny-warnings`: the app's entry points
|
|
85
|
+
| SAFE-TS | `safe-ts check <dirs or entries> --deny-warnings --baseline safe-ts-baseline.json`: the source directories (each file an entry), or the app's entry points plus the tests, scripts and workers nothing imports | exit 0: no findings, no `could not resolve` warning, no file not checked, no setup warning (all four fail `--deny-warnings`), no escape hatch or weakened rule added (legacy files report nothing) |
|
|
82
86
|
| Architecture | `node scripts/census.mjs --baseline safe-ts-census.json` | no count rose in any file |
|
|
83
87
|
| Tests | the project's runner; Node processes with `--import @evobug_com/safe-ts-transform/register` | pass |
|
|
84
88
|
| Build | `vite build` with `safeTs({ check: "error" })` (fails on errors; warnings are the SAFE-TS gate's) | succeeds, and its last line says `safe-ts: N files checked, ...` |
|
|
@@ -89,7 +93,8 @@ architecture patterns and the idiomatic rules' findings are at zero, or each rem
|
|
|
89
93
|
an entry in the exception list. The hand-off report ([templates.md](templates.md)) says which.
|
|
90
94
|
|
|
91
95
|
Run the SAFE-TS gate in your own loop the way CI runs it, with `--deny-warnings`: a plain
|
|
92
|
-
`safe-ts check` exits 0 with every idiomatic finding still there
|
|
96
|
+
`safe-ts check` exits 0 with every idiomatic finding still there, and with files it never
|
|
97
|
+
read. `--max-warnings <n>`, with `n`
|
|
93
98
|
the area's current count, lets a burn-down land in steps without letting the count rise.
|
|
94
99
|
|
|
95
100
|
Before a gate's fix text or a project rule names a replacement, check the replacement against
|