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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,235 @@
1
+ # Templates
2
+
3
+ Adapt the paths and the package manager (`npm`, `pnpm`, `bun`, `yarn`) to the project. The
4
+ setup itself is in the guide: Adopting SAFE-TS, and the Vue or React Setup page.
5
+
6
+ ## Packages
7
+
8
+ ```sh
9
+ npm install -D @evobug_com/safe-ts-transform @evobug_com/oxlint-plugin-safe-ts @evobug_com/safe-ts-prelude oxlint
10
+ npm install -D @evobug_com/safe-ts-native # pnpm only: puts the `safe-ts` command on the PATH
11
+ npm install @evobug_com/safe-ts-std
12
+ npm install @evobug_com/safe-ts-vue # Vue 3.5+
13
+ npm install @evobug_com/safe-ts-react # React 18+
14
+ npm install @evobug_com/safe-ts-feature-browser # browser code: fetch, storage, DOM lookups, IndexedDB
15
+ npm install @evobug_com/safe-ts-feature-node # Node code: fs, child_process, util.parseArgs, ...
16
+ ```
17
+
18
+ Every `@evobug_com/*` package has the same version; keep them in step (`npx safe-ts --version`
19
+ prints it).
20
+
21
+ ## tsconfig.json
22
+
23
+ ```jsonc
24
+ {
25
+ "compilerOptions": {
26
+ "strict": true,
27
+ "noUncheckedIndexedAccess": true,
28
+ "exactOptionalPropertyTypes": true,
29
+ // The prelude: Result, Option, q, match, ... without imports. Keep the entries the project
30
+ // already lists ("node", "vite/client"). With "typeRoots" set, add "node_modules" to it, or
31
+ // TypeScript can't find the prelude (TS2688).
32
+ "types": ["@evobug_com/safe-ts-prelude"]
33
+ }
34
+ }
35
+ ```
36
+
37
+ Both flags go in from the first step, in the tsconfig that tsc, vue-tsc and a type-aware oxlint
38
+ all read. Measure their error count first (`tsc --noEmit` with each flag), and fix those errors
39
+ as part of the setup or the foundation step.
40
+
41
+ ## package.json
42
+
43
+ ```jsonc
44
+ {
45
+ "scripts": {
46
+ "check:safe-ts": "safe-ts check src/main.ts --deny-warnings",
47
+ "check:safe-ts:summary": "safe-ts check src/main.ts --summary",
48
+ "check:architecture": "node scripts/census.mjs --baseline safe-ts-census.json",
49
+ "census": "node scripts/census.mjs"
50
+ },
51
+ "safe-ts": {
52
+ "idiomatic": true,
53
+ "features": ["@evobug_com/safe-ts-feature-browser"],
54
+ "requestFunctions": ["api"]
55
+ }
56
+ }
57
+ ```
58
+
59
+ - `safe-ts` is the command of `@evobug_com/safe-ts-native`, which the transform and the oxlint
60
+ plugin bring. Give `check` the app's entry points (it follows relative imports, tsconfig
61
+ `paths` aliases, workspace packages, workers and `import()`), and the files nothing imports:
62
+ tests, scripts, workers whose path is built at runtime
63
+ (`safe-ts check src/main.ts src/workers/*.ts scripts/*.ts --deny-warnings`). Several apps in a
64
+ monorepo: all their entries in one run.
65
+ - `--deny-warnings` makes warnings fail the run: the idiomatic rules and the cost rules are
66
+ warnings, and without it a run with only warnings exits 0. While an area burns a count down,
67
+ `--max-warnings <n>` holds it at `n`.
68
+ - `"idiomatic": true` turns the idiomatic rules on for every tool (check, editor, Vite, oxlint).
69
+ - `"requestFunctions"` names the project's own request wrapper or axios instance, so
70
+ `fetch-signal` reports a call of it without a `signal` or `timeout`, like a bare `fetch`.
71
+ - `scripts/census.mjs` and `scripts/safe-ts.mjs` are this skill's `scripts/`, copied into the
72
+ project (they import each other by relative path).
73
+ - Rule levels: `"rules": { "stable-shape": "error" }` and `"overrides": [{ "files":
74
+ ["src/generated/**"], "rules": { "no-null": "off" } }]`. Each `"off"` or `"warn"` is an
75
+ exception in the architecture document; a count to burn down is ratcheted by the census
76
+ instead.
77
+ - Feature packs: the browser pack for browser code, `@evobug_com/safe-ts-feature-node` for Node,
78
+ and the packs for the libraries the code uses (Libraries and feature packs). A pack turns
79
+ each unhandled call of its library into a finding, so an existing app gains findings when one
80
+ is enabled: enable it in the setup step, before the first census.
81
+
82
+ ## .oxlintrc.json
83
+
84
+ ```jsonc
85
+ {
86
+ "extends": ["./node_modules/@evobug_com/oxlint-plugin-safe-ts/recommended.json"]
87
+ }
88
+ ```
89
+
90
+ Run it as `oxlint --deny-warnings` (add `--type-aware` if the project uses type-aware rules).
91
+ The plugin checks `.vue` components too, template included. The project's own `rules` win over
92
+ the preset's: while files are legacy, downgrade the preset's oxlint rules that report in them
93
+ (`"no-empty": "warn"`, `"unicorn/prefer-at": "off"`), with a line in the exception list, and
94
+ remove those lines at the end. oxlint takes the level of a `safe-ts/*` finding from this file;
95
+ an `"off"` in package.json's `"safe-ts"` wins in both.
96
+
97
+ ## vite.config.ts
98
+
99
+ ```ts
100
+ import { safeTs } from "@evobug_com/safe-ts-transform";
101
+ import vue from "@vitejs/plugin-vue"; // or: import react from "@vitejs/plugin-react";
102
+ import { defineConfig } from "vite";
103
+
104
+ // safeTs before the framework's plugin: it rewrites q(...), match(...), parseJson<T> and
105
+ // <Match> before the framework compiles the file. `exclude` is for vendored or generated code
106
+ // only: an excluded file isn't checked or transformed, and gets no prelude imports.
107
+ export default defineConfig({ plugins: [safeTs({ check: "error", exclude: ["src/vendor/**"] }), vue()] });
108
+ ```
109
+
110
+ `check: "warn"` (the default) prints findings in the dev server; `"error"` shows the overlay and
111
+ fails the build on errors (warnings are printed). `vite build` ends with
112
+ `safe-ts: N files checked, M legacy, K problems`: if that line is missing, the plugin didn't run. What `vite.config.ts` imports runs without the plugin: keep the prelude and
113
+ `q(...)` out of it, or load those modules with `loadTransformed` (Adopting SAFE-TS, "The Vite
114
+ config").
115
+
116
+ Node processes that run TypeScript directly (scripts, `node --test`, workers) need the loader:
117
+ `node --import @evobug_com/safe-ts-transform/register <file>.ts`.
118
+
119
+ ## Bun
120
+
121
+ `bun run` and `bun test` get the transform from the Bun plugin, not the Node loader:
122
+
123
+ ```toml
124
+ # bunfig.toml
125
+ preload = ["@evobug_com/safe-ts-transform/bun"]
126
+
127
+ [test]
128
+ preload = ["@evobug_com/safe-ts-transform/bun"]
129
+ ```
130
+
131
+ The `bun build` command takes no plugins. Bundle with a script (`bun build.ts`):
132
+
133
+ ```ts
134
+ import { safeTsBun } from "@evobug_com/safe-ts-transform";
135
+
136
+ const result = await Bun.build({ entrypoints: ["src/main.ts"], outdir: "dist", target: "bun", plugins: [safeTsBun({ check: "error" })] });
137
+ if (!result.success) process.exit(1);
138
+ ```
139
+
140
+ A Vite app run with Bun (`bunx --bun vite`) uses the Vite plugin as above.
141
+
142
+ ## CI job
143
+
144
+ GitHub Actions syntax (Forgejo Actions reads the same):
145
+
146
+ ```yaml
147
+ name: checks
148
+ on: [push, pull_request]
149
+ jobs:
150
+ checks:
151
+ runs-on: ubuntu-latest
152
+ steps:
153
+ - uses: actions/checkout@v4
154
+ - uses: actions/setup-node@v4
155
+ with:
156
+ node-version: lts/*
157
+ - run: npm ci
158
+ - run: npx safe-ts --version # the checker's version in the log
159
+ - run: npx vue-tsc --noEmit # or: npx tsc --noEmit
160
+ - run: npx oxlint --deny-warnings
161
+ - run: npm run check:safe-ts # safe-ts check ... --deny-warnings
162
+ - run: npm run check:architecture
163
+ - run: npm test
164
+ - run: npx vite build # ends with "safe-ts: N files checked, ..."
165
+ ```
166
+
167
+ ## Conventions section for CLAUDE.md / AGENTS.md
168
+
169
+ ```markdown
170
+ ## SAFE-TS
171
+
172
+ This project follows SAFE-TS. The decisions are in docs/safe-ts-architecture.md; read it before
173
+ changing code, and follow it over habits from other projects.
174
+
175
+ - A function that can fail returns `Result<T, E>`; pass errors up with `q(...)` (with a mapping
176
+ or `mapErr` when the error type changes). No `throw new Error`. No `try`/`catch` around our
177
+ own code.
178
+ - Absence is `undefined` (`Option<T>`). No `null`; `jsonNull` only in request bodies that clear a
179
+ field. "Not loaded" is an `AsyncState`, "none" an `Option` or an `Enum` variant.
180
+ - Async work goes through `useTask` and is shown with `<Match>` / `match`. No `loading`,
181
+ `error` or `data` refs. Every request takes the task's `signal`.
182
+ - Closed sets are `Enum`s with `constructors`; read them with `match`, `is`, `variant` (and
183
+ `<Match :value="...">` in templates). No raw `.tag ===`. No `''`, `-1` or `0` meaning "none".
184
+ - Outside data goes through `validate<T>` / `parseJson<T>` or a feature pack's safe version. No
185
+ `as` and no hand-written `value is T` guards on it. A trusted boundary inside the program is
186
+ `trust<T>(value)`, listed in the architecture document.
187
+ - Wire-keyed tables: `getOwn(table, key, fallback)`; a server field from a list that can grow is
188
+ `Open<K>`, read with `match` and `lookup`. Base64: `toBase64` / `fromBase64` (`btoa` only of
189
+ an `Ascii`).
190
+ - Request bodies that change a record are `Patch<T>` (`keep`, `clear`, a value).
191
+ - Markup is `Html` (from the sanitizer declared with `defineSanitizer` in <module>), URLs are
192
+ `SafeUrl` (from `safeHref`); never `as Html`. Test numbers and strings explicitly
193
+ (`count > 0`, `name !== ""`), not for truth.
194
+ - Optional keys under `exactOptionalPropertyTypes`: `...(x === undefined ? {} : { x })`.
195
+ - No module state: Pinia setup stores (Vue) or provided contexts.
196
+ - Escape hatches (`unsafe`, `unsafeAsync`, `panic`, `trust`, `LegacyNull`, `void`, casts,
197
+ `safe-ts-ignore`, legacy markers, rule levels) follow docs/safe-ts-architecture.md, each with
198
+ a reason. A line that must stay as it is: `// safe-ts-ignore <rule>: <reason>`. A file not
199
+ migrated yet: `// @safe-ts legacy`. Never a new one without a line in the exception list.
200
+ - Tests use `fixture`, `testDouble`, `unchecked` and `expectPresent` from
201
+ `@evobug_com/safe-ts-std/testing`, not casts.
202
+ - Before a change is done: `npm run check:safe-ts` (`--deny-warnings`: warnings count),
203
+ `npm run check:architecture`, the type check, `oxlint --deny-warnings`, the tests and the
204
+ build pass.
205
+ ```
206
+
207
+ ## Hand-off report, per area
208
+
209
+ ```markdown
210
+ # <area>: SAFE-TS migration
211
+
212
+ ## Gates
213
+ - types / lint / safe-ts (`--deny-warnings`) / architecture / tests / build: pass (paste the
214
+ summary lines, and `safe-ts --version`)
215
+
216
+ ## Census, before → after (this area's directories)
217
+ - checker findings: <n> → <n>
218
+ - legacy files: <n> → 0
219
+ - patterns: trio-files <n> → <n>, loading-flag ..., string-if-chain ..., as-cast ..., ...
220
+ - features: useTask <n> → <n>, Enum ..., match ..., <Match> ..., q ...
221
+ - idiomatic findings: prefer-is-over-tag <n> → <n>, prefer-q ..., no-swallowed-error ..., ...
222
+ - escape hatches: unsafe <n> (each with its reason), panic <n>, trust <n>, LegacyNull <n>,
223
+ safe-ts-ignore <n>, void <n>, casts <n>
224
+
225
+ ## Changed signatures (callers in other areas must be checked)
226
+ - `useIssueStore().rename`: now `Promise<Result<void, RequestError>>` (was rejecting)
227
+ - `formatDue(due)`: takes `Option<string>` (was `string | null`)
228
+
229
+ ## Behaviour
230
+ - bodies compared for: <flows>; differences: <none / intended: ...>
231
+ - smoke: <pages>, failure paths: <which>; findings: <none / ...>
232
+
233
+ ## Remaining exceptions
234
+ - <file:line>: <what>, <why>, <until when> (also in the architecture document)
235
+ ```
@@ -0,0 +1,124 @@
1
+ # Known tool gaps and their workarounds
2
+
3
+ Limits of the SAFE-TS version this skill was written for that a migration runs into, so it
4
+ doesn't rediscover them. Each entry says what happens, what to do, and where the docs cover it
5
+ (guide pages on https://safe-ts.evobug-pages.com). Newer versions fix some of these: read the
6
+ CHANGELOG (`safe-ts --version` prints the installed version) and drop the workarounds that are
7
+ no longer needed.
8
+
9
+ ## The CLI
10
+
11
+ - **pnpm doesn't link the `safe-ts` command** of a package that isn't a direct dependency. npm
12
+ and bun put it on the PATH of package.json scripts once the transform or the oxlint plugin is
13
+ installed; with pnpm, `pnpm add -D @evobug_com/safe-ts-native` (Adopting SAFE-TS, "Setup").
14
+ - **`npx safe-ts` in a folder where it isn't installed** downloads an unrelated npm package
15
+ named `safe-ts`. Run it from the project, or name the package:
16
+ `npx -p @evobug_com/safe-ts-native safe-ts check ...`.
17
+ - **A run with only warnings exits 0.** The idiomatic rules and the cost rules (`stable-shape`,
18
+ `hoist-intl`, ...) are warnings in the preset's levels. A gate, and an agent checking its own
19
+ work, uses `safe-ts check <entries> --deny-warnings` (or `--max-warnings <n>` while a count is
20
+ being burned down); otherwise "the checker passes" ignores the whole idiomatic layer
21
+ (Adopting SAFE-TS, "Rule levels").
22
+ - **`check` reads what its entries reach.** It follows relative imports, tsconfig.json `paths`,
23
+ workspace packages, `new Worker(new URL(...))` and `import()`. A file nothing imports (a
24
+ script, a test, a worker whose path is built at runtime) is checked only as an entry: give the
25
+ tests' and scripts' files too, or every file (the census does).
26
+ - **Vite-only aliases** (a `resolve.alias` entry without a tsconfig `paths` entry) are seen by
27
+ the Vite plugin only, and only those with a string `find`. `safe-ts check`, the editor and
28
+ the oxlint plugin name each import they can't resolve (`warning: could not resolve "@x/y"`):
29
+ add the alias to tsconfig.json `paths`, which is the source of truth (Adopting SAFE-TS, "How
30
+ imports are followed"). Behind an unresolved import, the legacy quarantine doesn't reach.
31
+
32
+ ## The oxlint plugin
33
+
34
+ - **The preset changes non-SAFE-TS rules too**, and `// @safe-ts legacy` doesn't silence those
35
+ (33 oxlint rules: `no-empty`, `no-prototype-builtins`, `unicorn/prefer-at`, ...): extending it
36
+ adds findings in legacy files. Downgrade them in `.oxlintrc.json` while files are legacy, and
37
+ remove the downgrades at the end (Adopting SAFE-TS, "Setup", the preset's oxlint rules).
38
+ - **Levels in oxlint come from `.oxlintrc.json`.** `"off"` in package.json's `"safe-ts"` wins
39
+ there too, but `"warn"` / `"error"` set in package.json don't change what oxlint prints:
40
+ set those in `.oxlintrc.json` as well.
41
+ - **In `.vue` files**, oxlint hands the plugin one script block at a time; template problems
42
+ are reported at the top of `<script setup>`, naming their line, and an unsaved component with
43
+ two script blocks asks to be saved (Vue setup, "oxlint and .vue files").
44
+ - **Type-aware oxlint and `items[0]!`.** Without `noUncheckedIndexedAccess` in the tsconfig oxlint
45
+ reads, `typescript/no-unnecessary-type-assertion` calls the `!` unnecessary while `safe-ts`
46
+ needs it. Turn the flag on in `tsconfig.json` at the start (Adopting SAFE-TS, "The tsconfig
47
+ flags on an existing project").
48
+
49
+ ## The build and the runtime
50
+
51
+ - **`safeTs({ exclude })` takes files away from the transform entirely**, prelude imports
52
+ included: an excluded file must not use `q`, `match`, `parseJson` or prelude names. For code
53
+ that isn't migrated yet, use the legacy marker instead; a legacy file gets only the rewrites
54
+ it needs to run (Adopting SAFE-TS, "Setup", "Existing code").
55
+ - **The prelude and `typeRoots`**: with `typeRoots` set, `"types": ["@evobug_com/safe-ts-prelude"]`
56
+ fails (TS2688). Add `"node_modules"` to `typeRoots`.
57
+ - **A project inside the project** (its own `package.json` and `tsconfig.json`) needs its own
58
+ prelude entry and std dependency: the transform reads the nearest tsconfig.json.
59
+ - **The Node loader's shared validator modules** are imported as
60
+ `./file.ts?safe-ts-json=<key>`. A resolve hook of your own that appends `.ts` to relative
61
+ specifiers breaks them: keep the query, or set `SAFE_TS_SHARED_VALIDATORS=0` (Adopting
62
+ SAFE-TS, "Running TypeScript in Node").
63
+ - **Bun** runs the transform through the Bun plugin, not the Node loader:
64
+ `preload = ["@evobug_com/safe-ts-transform/bun"]` in `bunfig.toml`, and again under `[test]`.
65
+ The `bun build` command takes no plugins: bundle with `Bun.build({ plugins: [safeTsBun()] })`.
66
+ `bun --preload @evobug_com/safe-ts-transform/register` stops with a message naming the Bun
67
+ preload (guide: Bun).
68
+ - **`safe-ts emit` doesn't write `.vue` files**: type-check components with `vue-tsc`.
69
+ - **Vite loads `vite.config.ts` without the plugin**: what it imports can't use the prelude or
70
+ `q(...)`, unless it goes through `loadTransformed` (Adopting SAFE-TS, "The Vite config").
71
+
72
+ ## The codemods
73
+
74
+ - **`.vue` files are rewritten with the `.ts` files they import**, so give a codemod the whole
75
+ `src/`, never the `.ts` files alone. A component whose change would go into code Vue generates
76
+ (a handler written as a name, `@click="save"`; an expression with HTML entities) is left as
77
+ written and listed; Pug templates and scripts that aren't TypeScript aren't read (Adopting
78
+ SAFE-TS, "Vue components").
79
+ - **`null-to-undefined` keeps the `null` of outside data**, and of what holds it: a setup store
80
+ or composable returning `ref<T | null>(null)` keeps it, and so do its readers; prop types,
81
+ event types and slot props keep theirs. Convert those by hand where the architecture says so.
82
+ - **`throw-to-result` converts top-level functions only**, and only when every caller can take
83
+ a `Result`; the report's "Needs a decision" lists the rest.
84
+
85
+ ## Rules and the checker
86
+
87
+ - **Calls a `Result` isn't followed through**: a return type written as an alias
88
+ (`type Loaded = Promise<Result<...>>`), a function reached through a parameter, a class
89
+ instance's field, a `ref`, `reactive()` or a `Map`, and `.then(save)` with a function passed
90
+ by name (rule page `must-use-result`, "What the rule can't see"). Store members, returned
91
+ objects and factories are followed. Search every caller of every changed member anyway.
92
+ - **`validate<T>` refuses library types**: a package's types, global types from `@types/...`
93
+ and `declare module "..."` blocks. Namespace members (generated `Backend.Models.User`), types
94
+ behind a tsconfig alias and workspace packages are fine (JSON guide, "What isn't supported").
95
+ - **`JSON.stringify` of a value it can't prove JSON-safe** is reported (`unhandled-failure`): a
96
+ `bigint`, a `toJSON`, a type that refers to itself, an `async` callback's result. Give the
97
+ value a type that is plain data, or `unsafe(...)` with a reason.
98
+ - **`stable-shape` and three or more conditional spreads** in one literal (eight shapes):
99
+ declare the fields `Option<T>` and always write them ([patterns-core.md](patterns-core.md#an-optional-key)).
100
+ - **Heuristics by name**: `panic-on-loading` goes by the names in the condition (`hydrated`,
101
+ `isLoading`, a `Loading` variant), and the census's patterns are regular expressions. Both
102
+ are a map for review, not a proof.
103
+ - **The idiomatic layer reports nothing until package.json turns it on**
104
+ (`"safe-ts": { "idiomatic": true }`), whatever the oxlint preset lists. `safe-ts check
105
+ --idiomatic` shows it for one run.
106
+
107
+ ## std and the framework packages
108
+
109
+ - **vue-tsc and `is` under `v-for`**: inside an event handler of a `v-else-if` / `v-else`
110
+ branch under `v-for`, the row narrowed by `is` is `never` (vue-tsc 3.3). Give that branch its
111
+ own `v-if` (Vue guide: Async state).
112
+ - **`<Match :on>`** is the old prop name: it fails vue-tsc. Write `<Match :value>`.
113
+ - **React's `useTask`** has `abort()` but no `reset()` or `panic`: to dismiss an answer, start
114
+ a new run or keep a "dismissed" state next to it.
115
+ - **Brands and `Open`/`Patch` aren't in the prelude**: import them from the module that makes
116
+ them (`@evobug_com/safe-ts-std/html`, `/url`, `/regexp`, `/ascii`, `/open`, `/patch`).
117
+ - **`defineSanitizer` can't check that the function sanitizes**: it is where the project vouches
118
+ for it, like `trust`. Review its module like an escape hatch.
119
+ - **`strict-truthiness` is silent where the type isn't known** (an inferred return, a package's
120
+ value, `unknown`), and `x || fallback` as a value is `prefer-nullish-default`'s.
121
+ - **`Open<K>` is an object at runtime** (`{ tag, value }`): send `.value` to the server.
122
+ `json-type` refuses an `Open` whose `K` isn't string literals.
123
+ - **`toBase64` encodes text as UTF-8**, where `btoa` wrote characters U+0080 to U+00FF as one
124
+ byte each: the encoded text of such characters changes ([patterns-core.md](patterns-core.md#base64)).