@evobug_com/safe-ts-transform 0.2.0 → 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.
- package/README.md +6 -1
- package/bun-plugin.mjs +136 -0
- package/bun.mjs +19 -0
- package/cache.mjs +112 -12
- package/index.d.ts +104 -6
- package/index.mjs +190 -15
- package/package.json +9 -5
- package/register.mjs +44 -5
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @evobug_com/safe-ts-transform
|
|
2
2
|
|
|
3
|
-
SAFE-TS build-time transform: a Vite/Rolldown/Rollup plugin
|
|
3
|
+
SAFE-TS build-time transform: a Vite/Rolldown/Rollup plugin, a Node loader and a Bun plugin that rewrite q(), match(), parseJson<T>(), loops and @inline, and run the SAFE-TS checks.
|
|
4
4
|
|
|
5
5
|
**Documentation: [safe-ts.evobug-pages.com/guide/adoption](https://safe-ts.evobug-pages.com/guide/adoption)**
|
|
6
6
|
|
|
@@ -8,6 +8,11 @@ SAFE-TS build-time transform: a Vite/Rolldown/Rollup plugin and a Node loader th
|
|
|
8
8
|
npm install -D @evobug_com/safe-ts-transform
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
+
The checker's settings go in the `"safe-ts"` field of package.json: each rule's level, per rule
|
|
12
|
+
and per directory ([rule levels](https://safe-ts.evobug-pages.com/guide/adoption#rule-levels-errors-warnings-off)), and the
|
|
13
|
+
opt-in [idiomatic rules](https://safe-ts.evobug-pages.com/guide/adoption#idiomatic-rules) (`"idiomatic": true`). One line that is
|
|
14
|
+
right as it is takes `// safe-ts-ignore <rule>: <reason>` ([ignoring one finding](https://safe-ts.evobug-pages.com/guide/adoption#ignoring-one-finding)).
|
|
15
|
+
|
|
11
16
|
Part of [SAFE-TS](https://safe-ts.evobug-pages.com/), a strict, Rust-flavoured subset of TypeScript. The website has the
|
|
12
17
|
guides, a page per rule, and a playground that runs the checker in your browser.
|
|
13
18
|
|
package/bun-plugin.mjs
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// The safe-ts transform as a Bun plugin: the same rewrite the Node loader (register.mjs) and the
|
|
2
|
+
// Vite plugin make, for Bun's runtime (`bun run`, `bun test`, through the `./bun` preload) and
|
|
3
|
+
// for its bundler (`Bun.build({ plugins: [safeTsBun()] })`).
|
|
4
|
+
//
|
|
5
|
+
// Bun has no `module.registerHooks`, so the Node loader can't run there; `Bun.plugin` is its
|
|
6
|
+
// equivalent. The shared validator modules (`<declaring file>?safe-ts-json=<key>`) are served
|
|
7
|
+
// from a namespace of their own, and the Node loader's disk cache (cache.mjs) is used as is.
|
|
8
|
+
import { readFileSync } from "node:fs";
|
|
9
|
+
import { createRequire } from "node:module";
|
|
10
|
+
import { dirname, resolve } from "node:path";
|
|
11
|
+
import { pathToFileURL } from "node:url";
|
|
12
|
+
|
|
13
|
+
import { openCache } from "./cache.mjs";
|
|
14
|
+
import { devChecksEnabled, SHARED_QUERY, sharedModule, sharedModuleId, transformWithDependencies } from "./index.mjs";
|
|
15
|
+
|
|
16
|
+
const require = createRequire(import.meta.url);
|
|
17
|
+
|
|
18
|
+
/** The files the transform takes, outside node_modules (Bun's own loader keeps those). */
|
|
19
|
+
const TS_FILE = /^(?!.*[\\/]node_modules[\\/]).*\.(ts|tsx|mts|cts)$/;
|
|
20
|
+
// index.mjs re-exports this module, so its imports may not be initialised yet at the top level.
|
|
21
|
+
const SHARED_IMPORT = /\?safe-ts-json=/;
|
|
22
|
+
const NAMESPACE = "safe-ts-json";
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The directory imports of `importer` resolve from. Bun names an importer in another namespace
|
|
26
|
+
* with that prefix (`safe-ts-json:/src/types.ts?safe-ts-json=v$User`).
|
|
27
|
+
*/
|
|
28
|
+
function importerDir(importer) {
|
|
29
|
+
const path = importer.startsWith(`${NAMESPACE}:`) ? importer.slice(NAMESPACE.length + 1) : importer;
|
|
30
|
+
return dirname(path.split("?")[0]);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Bun plugin: rewrites q(), match(), parseJson<T>(), validate<T>(), loops and prelude names in
|
|
35
|
+
* project TypeScript, for `Bun.plugin(...)` (the runtime) and `Bun.build({ plugins })` (the
|
|
36
|
+
* bundler). Options default to what fits where it runs: at runtime as the Node loader does
|
|
37
|
+
* (dev checks unless NODE_ENV=production, no rule checks), in `Bun.build` as `vite build` does.
|
|
38
|
+
*
|
|
39
|
+
* @param {{ check?: "warn" | "error" | false, devChecks?: boolean, sharedValidators?: boolean }} [options]
|
|
40
|
+
* check: run the safe-ts rules on every transformed file. "warn" prints problems, "error"
|
|
41
|
+
* fails the load (the build, or the import at runtime); false turns it off. Default: "warn"
|
|
42
|
+
* in `Bun.build`, false at runtime.
|
|
43
|
+
* devChecks: insert dev-only runtime checks. Default: off in `Bun.build`; at runtime, on
|
|
44
|
+
* unless NODE_ENV=production, and SAFE_TS_DEV_CHECKS=1 / =0 overrides it.
|
|
45
|
+
* sharedValidators: one validator module per named type (default), or a copy per file
|
|
46
|
+
* (false; at runtime also SAFE_TS_SHARED_VALIDATORS=0).
|
|
47
|
+
*/
|
|
48
|
+
export function safeTsBun(options = {}) {
|
|
49
|
+
return {
|
|
50
|
+
name: "safe-ts",
|
|
51
|
+
setup(build) {
|
|
52
|
+
// `Bun.build` passes its config; `Bun.plugin` (the runtime) doesn't.
|
|
53
|
+
const bundling = build.config !== undefined;
|
|
54
|
+
const env = process.env;
|
|
55
|
+
const check = options.check ?? (bundling ? "warn" : false);
|
|
56
|
+
const devChecks = options.devChecks ?? (bundling ? false : devChecksEnabled(env));
|
|
57
|
+
const sharedValidators =
|
|
58
|
+
options.sharedValidators ?? (bundling || !["0", "false"].includes(env.SAFE_TS_SHARED_VALIDATORS ?? ""));
|
|
59
|
+
const cache = openCache(env, { devChecks, sharedValidators });
|
|
60
|
+
const root = process.cwd();
|
|
61
|
+
let checker;
|
|
62
|
+
// The files the runtime transformed, for the Vite plugin's config check (index.mjs), as
|
|
63
|
+
// the Node loader records them.
|
|
64
|
+
const loaded = bundling ? undefined : (globalThis[Symbol.for("safe-ts.loader.files")] ??= new Set());
|
|
65
|
+
const warned = new Set();
|
|
66
|
+
const warn = (message) => {
|
|
67
|
+
if (warned.has(message)) return;
|
|
68
|
+
warned.add(message);
|
|
69
|
+
process.stderr.write(`safe-ts warning: ${message}\n`);
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
// `./types.ts?safe-ts-json=v$User` from a transformed file (or from another shared
|
|
73
|
+
// module): the declaring file, with the key, in a namespace of its own.
|
|
74
|
+
for (const namespace of ["file", NAMESPACE]) {
|
|
75
|
+
build.onResolve({ filter: SHARED_IMPORT, namespace }, (args) => {
|
|
76
|
+
const shared = sharedModuleId(args.path);
|
|
77
|
+
const from = importerDir(args.importer);
|
|
78
|
+
return { path: `${resolve(from, shared.file)}?${SHARED_QUERY}=${shared.key}`, namespace: NAMESPACE };
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
// A bare import in a shared module (the std helpers) resolves from the declaring file, or
|
|
82
|
+
// else from the current directory: a package of types may not depend on the std library.
|
|
83
|
+
build.onResolve({ filter: /^[^./]/, namespace: NAMESPACE }, (args) => {
|
|
84
|
+
const from = importerDir(args.importer);
|
|
85
|
+
try {
|
|
86
|
+
return { path: Bun.resolveSync(args.path, from) };
|
|
87
|
+
} catch {
|
|
88
|
+
return { path: Bun.resolveSync(args.path, root) };
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
// Relative imports in a shared module (types it imports for its own checks).
|
|
92
|
+
build.onResolve({ filter: /^\.\.?\//, namespace: NAMESPACE }, (args) => ({
|
|
93
|
+
path: Bun.resolveSync(args.path, importerDir(args.importer)),
|
|
94
|
+
}));
|
|
95
|
+
|
|
96
|
+
build.onLoad({ filter: /./, namespace: NAMESPACE }, (args) => {
|
|
97
|
+
const shared = sharedModuleId(args.path);
|
|
98
|
+
// Keyed by URL, as the Node loader keys it: the cache's sweep reads the file from it.
|
|
99
|
+
const url = `${pathToFileURL(shared.file).href}?${SHARED_QUERY}=${shared.key}`;
|
|
100
|
+
let contents = cache?.get(url, shared.key);
|
|
101
|
+
if (contents === undefined) {
|
|
102
|
+
const module = sharedModule(shared.file, shared.key);
|
|
103
|
+
contents = module.code;
|
|
104
|
+
cache?.set(url, shared.key, module);
|
|
105
|
+
}
|
|
106
|
+
return { contents, loader: "ts" };
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
build.onLoad({ filter: TS_FILE }, (args) => {
|
|
110
|
+
const file = args.path;
|
|
111
|
+
const code = readFileSync(file, "utf8");
|
|
112
|
+
const loader = file.endsWith(".tsx") ? "tsx" : "ts";
|
|
113
|
+
if (check) {
|
|
114
|
+
checker ??= new (require("@evobug_com/safe-ts-native").Checker)(root);
|
|
115
|
+
const problems = checker.checkFile(file, code);
|
|
116
|
+
if (problems.length > 0) {
|
|
117
|
+
const lines = problems.map((d) => ` ${file}:${d.line}:${d.column + 1} safe-ts(${d.rule}): ${d.message}`);
|
|
118
|
+
const message = `safe-ts: ${problems.length} problem(s)\n${lines.join("\n")}`;
|
|
119
|
+
if (check === "error") throw new Error(message);
|
|
120
|
+
process.stderr.write(`${message}\n`);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
let contents = cache?.get(file, code);
|
|
124
|
+
if (contents === undefined) {
|
|
125
|
+
const result = transformWithDependencies(file, code, { devChecks, sharedValidators });
|
|
126
|
+
contents = result.code;
|
|
127
|
+
// A file with a warning isn't cached, so the warning shows on every run until it's fixed.
|
|
128
|
+
if (result.warnings.length === 0) cache?.set(file, code, result);
|
|
129
|
+
for (const warning of result.warnings) warn(warning);
|
|
130
|
+
}
|
|
131
|
+
loaded?.add(file);
|
|
132
|
+
return { contents, loader };
|
|
133
|
+
});
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
package/bun.mjs
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Run TypeScript with `q(...)` support directly in Bun: the Bun counterpart of `./register`.
|
|
2
|
+
// Preload it, in bunfig.toml (both lines: `bun test` reads only its own section):
|
|
3
|
+
// preload = ["@evobug_com/safe-ts-transform/bun"]
|
|
4
|
+
// [test]
|
|
5
|
+
// preload = ["@evobug_com/safe-ts-transform/bun"]
|
|
6
|
+
// or on the command line: bun --preload @evobug_com/safe-ts-transform/bun src/main.ts
|
|
7
|
+
// Dev checks, the cache and shared validators follow the same variables as the Node loader:
|
|
8
|
+
// SAFE_TS_DEV_CHECKS, NODE_ENV=production, SAFE_TS_CACHE, SAFE_TS_CACHE_DIR,
|
|
9
|
+
// SAFE_TS_SHARED_VALIDATORS. For `Bun.build`, pass `safeTsBun()` from the package instead.
|
|
10
|
+
import { safeTsBun } from "./bun-plugin.mjs";
|
|
11
|
+
|
|
12
|
+
if (typeof globalThis.Bun?.plugin !== "function") {
|
|
13
|
+
throw new Error(
|
|
14
|
+
"safe-ts: @evobug_com/safe-ts-transform/bun is the preload for Bun. In Node, use " +
|
|
15
|
+
"`node --import @evobug_com/safe-ts-transform/register`: https://safe-ts.evobug-pages.com/guide/bun",
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
Bun.plugin(safeTsBun());
|
package/cache.mjs
CHANGED
|
@@ -1,28 +1,41 @@
|
|
|
1
1
|
// The Node loader's on-disk cache of transformed files (register.mjs), so a restart, a worker
|
|
2
2
|
// thread or a test process doesn't transform the same file again.
|
|
3
3
|
//
|
|
4
|
-
// One
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
4
|
+
// One directory per source file, one entry in it per set of options (dev checks, shared
|
|
5
|
+
// validators, the current directory) and transform version: a later version of the file
|
|
6
|
+
// replaces its entry, so the cache doesn't grow with edits. Writing an entry prunes the file's
|
|
7
|
+
// directory to its newest few entries (`KEEP`), so entries made by an older addon or with options
|
|
8
|
+
// no longer used go away; about once a day, a write also drops the directories of files that no
|
|
9
|
+
// longer exist. A shared validator module (`<file>?safe-ts-json=<key>`) is an entry of its own,
|
|
10
|
+
// keyed by its URL; its "content" is the key, and its dependencies are the declarations it was
|
|
11
|
+
// built from, the declaring file first. An entry is used only when the file's content, every
|
|
12
|
+
// file the transform read for it (imported types, `@inline` functions, enum tables, the
|
|
13
|
+
// tsconfig), the transform's version and the options all match. Entries are written to a
|
|
14
|
+
// temporary file and renamed into place, so threads and processes writing at once never leave a
|
|
15
|
+
// partial entry.
|
|
11
16
|
//
|
|
12
17
|
// Where: SAFE_TS_CACHE_DIR, else node_modules/.cache/safe-ts in the nearest directory above the
|
|
13
18
|
// current one that has node_modules, else the system's temporary directory. SAFE_TS_CACHE=0 (or
|
|
14
|
-
// false) turns it off.
|
|
19
|
+
// false) turns it off. Deleting the directory (`rm -rf node_modules/.cache/safe-ts`) is always
|
|
20
|
+
// safe. Problems with the cache never fail a load: the file is transformed.
|
|
15
21
|
import { createRequire } from "node:module";
|
|
16
22
|
import { hash, randomBytes } from "node:crypto";
|
|
17
|
-
import { accessSync, constants, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
23
|
+
import { accessSync, constants, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
|
18
24
|
import { tmpdir } from "node:os";
|
|
19
25
|
import { dirname, join } from "node:path";
|
|
26
|
+
import { fileURLToPath } from "node:url";
|
|
20
27
|
import { threadId } from "node:worker_threads";
|
|
21
28
|
|
|
22
29
|
const require = createRequire(import.meta.url);
|
|
23
30
|
|
|
24
31
|
/** Bumped when the entry format changes. */
|
|
25
|
-
const FORMAT =
|
|
32
|
+
const FORMAT = 2;
|
|
33
|
+
|
|
34
|
+
/** Entries kept per source file: the newest, by when they were written. */
|
|
35
|
+
export const KEEP = 3;
|
|
36
|
+
|
|
37
|
+
/** How often a write also looks for entries of files that are gone. */
|
|
38
|
+
const SWEEP_EVERY_MS = 24 * 60 * 60 * 1000;
|
|
26
39
|
|
|
27
40
|
const digest = (data) => hash("sha256", data, "hex");
|
|
28
41
|
|
|
@@ -87,7 +100,9 @@ export function openCache(env, options) {
|
|
|
87
100
|
if (dir === undefined) return undefined;
|
|
88
101
|
// Dev checks name files relative to the current directory: it is part of the key too.
|
|
89
102
|
const version = JSON.stringify([FORMAT, transformVersion(), options.devChecks === true, options.sharedValidators === true, process.cwd()]);
|
|
90
|
-
const
|
|
103
|
+
const versionKey = digest(version).slice(0, 24);
|
|
104
|
+
const fileDir = (filename) => join(dir, digest(filename).slice(0, 32));
|
|
105
|
+
const entryPath = (filename) => join(fileDir(filename), `${versionKey}.json`);
|
|
91
106
|
// Many files depend on the same few (the tsconfig, std modules): hash each version once.
|
|
92
107
|
const dependencyDigests = new Map();
|
|
93
108
|
const dependencyDigest = (file) => {
|
|
@@ -127,12 +142,97 @@ export function openCache(env, options) {
|
|
|
127
142
|
const temporary = `${target}.${process.pid}.${threadId}.${randomBytes(4).toString("hex")}.tmp`;
|
|
128
143
|
try {
|
|
129
144
|
const dependencies = result.dependencies.map((file) => [file, dependencyDigest(file)]);
|
|
130
|
-
|
|
145
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
146
|
+
writeFileSync(temporary, JSON.stringify({ format: FORMAT, file: filename, source: digest(code), dependencies, code: result.code }));
|
|
131
147
|
renameSync(temporary, target);
|
|
132
148
|
} catch {
|
|
133
149
|
// A dependency gone in between, a full disk, a read-only directory: just don't cache.
|
|
134
150
|
rmSync(temporary, { force: true });
|
|
151
|
+
return;
|
|
135
152
|
}
|
|
153
|
+
prune(target);
|
|
154
|
+
sweep(dir);
|
|
136
155
|
},
|
|
137
156
|
};
|
|
138
157
|
}
|
|
158
|
+
|
|
159
|
+
/** Keep the newest `KEEP` entries of one file's directory: `written` and the newest others. */
|
|
160
|
+
function prune(written) {
|
|
161
|
+
const fileDir = dirname(written);
|
|
162
|
+
try {
|
|
163
|
+
const entries = readdirSync(fileDir).filter((name) => name.endsWith(".json") && join(fileDir, name) !== written);
|
|
164
|
+
if (entries.length < KEEP) return;
|
|
165
|
+
const dated = entries.map((name) => {
|
|
166
|
+
const path = join(fileDir, name);
|
|
167
|
+
try {
|
|
168
|
+
return { path, at: statSync(path).mtimeMs };
|
|
169
|
+
} catch {
|
|
170
|
+
return { path, at: 0 };
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
dated.sort((a, b) => b.at - a.at);
|
|
174
|
+
for (const { path } of dated.slice(KEEP - 1)) rmSync(path, { force: true });
|
|
175
|
+
} catch {
|
|
176
|
+
// Another process pruned it first.
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* About once a day: drop the directories of source files that no longer exist, and the flat
|
|
182
|
+
* entries of the first cache format. The marker file's time says when it last ran.
|
|
183
|
+
*/
|
|
184
|
+
function sweep(dir) {
|
|
185
|
+
const marker = join(dir, "swept");
|
|
186
|
+
try {
|
|
187
|
+
if (Date.now() - statSync(marker).mtimeMs < SWEEP_EVERY_MS) return;
|
|
188
|
+
} catch {
|
|
189
|
+
// Never swept.
|
|
190
|
+
}
|
|
191
|
+
try {
|
|
192
|
+
writeFileSync(marker, "");
|
|
193
|
+
const now = new Date();
|
|
194
|
+
utimesSync(marker, now, now);
|
|
195
|
+
for (const name of readdirSync(dir)) {
|
|
196
|
+
const path = join(dir, name);
|
|
197
|
+
if (/^[0-9a-f]{40}\.json$/.test(name)) {
|
|
198
|
+
rmSync(path, { force: true });
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
if (!/^[0-9a-f]{32}$/.test(name)) continue;
|
|
202
|
+
const entries = readdirSync(path).filter((entry) => entry.endsWith(".json"));
|
|
203
|
+
const file = entries.length === 0 ? undefined : sourceOf(join(path, entries[0]));
|
|
204
|
+
if (file === undefined || !exists(sourcePath(file))) rmSync(path, { recursive: true, force: true });
|
|
205
|
+
}
|
|
206
|
+
} catch {
|
|
207
|
+
// Another process is sweeping, or the directory is read-only.
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** The source path an entry was made for. */
|
|
212
|
+
function sourceOf(entry) {
|
|
213
|
+
try {
|
|
214
|
+
const file = JSON.parse(readFileSync(entry, "utf8"))?.file;
|
|
215
|
+
return typeof file === "string" ? file : undefined;
|
|
216
|
+
} catch {
|
|
217
|
+
return undefined;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** A path, or a shared module's URL (`file:///src/types.ts?safe-ts-json=...`): its file. */
|
|
222
|
+
function sourcePath(file) {
|
|
223
|
+
if (!file.startsWith("file:")) return file;
|
|
224
|
+
try {
|
|
225
|
+
return fileURLToPath(file.split("?")[0]);
|
|
226
|
+
} catch {
|
|
227
|
+
return file;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function exists(path) {
|
|
232
|
+
try {
|
|
233
|
+
statSync(path);
|
|
234
|
+
return true;
|
|
235
|
+
} catch {
|
|
236
|
+
return false;
|
|
237
|
+
}
|
|
238
|
+
}
|
package/index.d.ts
CHANGED
|
@@ -6,7 +6,9 @@
|
|
|
6
6
|
export type SafeTsOptions = {
|
|
7
7
|
/**
|
|
8
8
|
* Run the safe-ts rules on every transformed file. "warn" (default) prints problems in the
|
|
9
|
-
* terminal; "error" shows Vite's error overlay and fails the build
|
|
9
|
+
* terminal; "error" shows Vite's error overlay and fails the build when a finding is an
|
|
10
|
+
* error (rules at "warn", in package.json's `"safe-ts": { "rules" }` or the oxlint preset,
|
|
11
|
+
* are only printed); false turns it off.
|
|
10
12
|
*/
|
|
11
13
|
check?: "warn" | "error" | false;
|
|
12
14
|
/**
|
|
@@ -24,8 +26,20 @@ export type SafeTsOptions = {
|
|
|
24
26
|
* its own that every file using it imports, instead of a copy per file. On by default.
|
|
25
27
|
*/
|
|
26
28
|
sharedValidators?: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Files the plugin leaves alone: not checked, not transformed. Globs relative to Vite's root
|
|
31
|
+
* (`"src/vendor/**"`, `"**\/*.generated.ts"`), regular expressions tested on the absolute path
|
|
32
|
+
* (with `/` on every OS), or a function of the absolute path; one or a list. An excluded file
|
|
33
|
+
* must not need the transform (`q`, `match`, `parseJson`, prelude names). For code not
|
|
34
|
+
* migrated yet, use the `// @safe-ts legacy` marker instead: it turns the rules off and keeps
|
|
35
|
+
* the rewrites the file needs to run.
|
|
36
|
+
*/
|
|
37
|
+
exclude?: SafeTsExclude | readonly SafeTsExclude[];
|
|
27
38
|
};
|
|
28
39
|
|
|
40
|
+
/** One `exclude` entry: a glob, a regular expression, or a test of the absolute path. */
|
|
41
|
+
export type SafeTsExclude = string | RegExp | ((file: string) => boolean);
|
|
42
|
+
|
|
29
43
|
/** A source map, as the plugin returns it. */
|
|
30
44
|
export type SafeTsSourceMap = {
|
|
31
45
|
version: number;
|
|
@@ -42,9 +56,10 @@ export interface SafeTsPlugin {
|
|
|
42
56
|
enforce: "pre";
|
|
43
57
|
configResolved(config: {
|
|
44
58
|
readonly root: string;
|
|
59
|
+
readonly resolve?: { readonly alias?: unknown };
|
|
45
60
|
readonly command: "build" | "serve";
|
|
46
61
|
readonly configFile?: string | undefined;
|
|
47
|
-
readonly logger: { warn(message: string): void };
|
|
62
|
+
readonly logger: { warn(message: string): void; info(message: string): void };
|
|
48
63
|
}): void;
|
|
49
64
|
resolveId(
|
|
50
65
|
this: { resolve(source: string, importer?: string, options?: { skipSelf?: boolean }): Promise<{ id: string } | null> },
|
|
@@ -62,6 +77,9 @@ export interface SafeTsPlugin {
|
|
|
62
77
|
code: string,
|
|
63
78
|
id: string,
|
|
64
79
|
): { code: string; map: SafeTsSourceMap } | null;
|
|
80
|
+
buildStart(): void;
|
|
81
|
+
/** At the end of `vite build`: `safe-ts: 1,293 files checked, 960 legacy, 0 problems`. */
|
|
82
|
+
buildEnd(this: { info?(message: string): void } | void): void;
|
|
65
83
|
renderChunk(code: string, chunk: { readonly isEntry: boolean; readonly name: string }): { code: string; map: SafeTsSourceMap } | null;
|
|
66
84
|
generateBundle(options: unknown, bundle: { [fileName: string]: object }): void;
|
|
67
85
|
}
|
|
@@ -69,18 +87,89 @@ export interface SafeTsPlugin {
|
|
|
69
87
|
/** Bundler plugin (Vite, Rolldown, Rollup): rewrites q(), match(), parseJson<T>() and more. */
|
|
70
88
|
export function safeTs(options?: SafeTsOptions): SafeTsPlugin;
|
|
71
89
|
|
|
90
|
+
export type SafeTsBunOptions = {
|
|
91
|
+
/**
|
|
92
|
+
* Run the safe-ts rules on every transformed file. "warn" prints problems; "error" fails the
|
|
93
|
+
* load (the build, or the import at runtime); false turns it off. Default: "warn" in
|
|
94
|
+
* `Bun.build`, false at runtime (`Bun.plugin`), as with the Node loader.
|
|
95
|
+
*/
|
|
96
|
+
check?: "warn" | "error" | false;
|
|
97
|
+
/**
|
|
98
|
+
* Insert dev-only runtime checks. Default: off in `Bun.build`; at runtime on unless
|
|
99
|
+
* `NODE_ENV=production`, and `SAFE_TS_DEV_CHECKS=1` / `=0` overrides that.
|
|
100
|
+
*/
|
|
101
|
+
devChecks?: boolean;
|
|
102
|
+
/** One validator module per named type (default), or a copy per file (false). */
|
|
103
|
+
sharedValidators?: boolean;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** What the Bun plugin reads of Bun's `PluginBuilder` (typed by its shape, without bun-types). */
|
|
107
|
+
export interface SafeTsBunBuilder {
|
|
108
|
+
readonly config?: object;
|
|
109
|
+
onResolve(
|
|
110
|
+
constraints: { filter: RegExp; namespace?: string },
|
|
111
|
+
callback: (args: { path: string; importer: string }) => { path: string; namespace?: string },
|
|
112
|
+
): unknown;
|
|
113
|
+
onLoad(
|
|
114
|
+
constraints: { filter: RegExp; namespace?: string },
|
|
115
|
+
callback: (args: { path: string }) => { contents: string; loader: "ts" | "tsx" },
|
|
116
|
+
): unknown;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The Bun plugin: assignable to Bun's `BunPlugin`. */
|
|
120
|
+
export interface SafeTsBunPlugin {
|
|
121
|
+
name: "safe-ts";
|
|
122
|
+
setup(build: SafeTsBunBuilder): void;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Bun plugin: the same rewrite as `safeTs()` and the Node loader, for `Bun.build({ plugins:
|
|
127
|
+
* [safeTsBun()] })` and `Bun.plugin(safeTsBun())`. For `bun run` and `bun test`, preload
|
|
128
|
+
* `@evobug_com/safe-ts-transform/bun` instead, which registers it.
|
|
129
|
+
*/
|
|
130
|
+
export function safeTsBun(options?: SafeTsBunOptions): SafeTsBunPlugin;
|
|
131
|
+
|
|
72
132
|
/** Rewrite one file. Throws with all errors if the file can't be transformed. */
|
|
73
133
|
export function transform(filename: string, code: string, options?: { devChecks?: boolean }): string;
|
|
74
134
|
|
|
135
|
+
/**
|
|
136
|
+
* A bundler alias with a string `find` (Vite's `resolve.alias`): `find` and anything below it
|
|
137
|
+
* (`find/x`) resolve to `replacement`, an absolute path. Tried before tsconfig.json `paths`.
|
|
138
|
+
*/
|
|
139
|
+
export type SafeTsAlias = { find: string; replacement: string };
|
|
140
|
+
|
|
75
141
|
/**
|
|
76
142
|
* `transform`, also returning the other files the result depends on (imported types, `@inline`
|
|
77
|
-
* functions, enum tables, the tsconfig that turns the prelude on).
|
|
143
|
+
* functions, enum tables, the tsconfig that turns the prelude on). Imports resolve through
|
|
144
|
+
* tsconfig.json `paths`, and `aliases` first.
|
|
78
145
|
*/
|
|
79
146
|
export function transformWithDependencies(
|
|
80
147
|
filename: string,
|
|
81
148
|
code: string,
|
|
82
|
-
options?: { devChecks?: boolean; sharedValidators?: boolean },
|
|
83
|
-
): { code: string; dependencies: string[] };
|
|
149
|
+
options?: { devChecks?: boolean; sharedValidators?: boolean; aliases?: readonly SafeTsAlias[] },
|
|
150
|
+
): { code: string; dependencies: string[]; warnings: string[]; legacy: boolean };
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The aliases of a resolved Vite config (`config.resolve.alias`) the checker can use: string
|
|
154
|
+
* `find`, absolute `replacement`. Regular expressions are left out.
|
|
155
|
+
*/
|
|
156
|
+
export function stringAliases(alias: unknown): SafeTsAlias[];
|
|
157
|
+
|
|
158
|
+
/** Is `file` library code: under a `node_modules` directory below `root`? */
|
|
159
|
+
export function isLibraryFile(file: string, root: string): boolean;
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Import a module with the safe-ts transform from code that wasn't transformed (a Vite config:
|
|
163
|
+
* Vite loads it without plugins). Registers the Node loader's hooks in this process (in Bun, the
|
|
164
|
+
* Bun plugin), then imports `url` through them; returns the module's exports.
|
|
165
|
+
*
|
|
166
|
+
* ```ts
|
|
167
|
+
* const { offlinePage } = await loadTransformed<typeof import("./scripts/plugins.ts")>(
|
|
168
|
+
* new URL("./scripts/plugins.ts", import.meta.url),
|
|
169
|
+
* );
|
|
170
|
+
* ```
|
|
171
|
+
*/
|
|
172
|
+
export function loadTransformed<Module = Record<string, unknown>>(url: URL | string): Promise<Module>;
|
|
84
173
|
|
|
85
174
|
/** The query parameter of a shared validator module: `/src/types.ts?safe-ts-json=v$User`. */
|
|
86
175
|
export const SHARED_QUERY: "safe-ts-json";
|
|
@@ -92,7 +181,7 @@ export const SHARED_QUERY: "safe-ts-json";
|
|
|
92
181
|
export function sharedModuleId(id: string): { file: string; key: string } | undefined;
|
|
93
182
|
|
|
94
183
|
/** The shared module `key` of types declared in `file`, and the files it was built from. */
|
|
95
|
-
export function sharedModule(file: string, key: string): { code: string; dependencies: string[] };
|
|
184
|
+
export function sharedModule(file: string, key: string, aliases?: readonly SafeTsAlias[]): { code: string; dependencies: string[] };
|
|
96
185
|
|
|
97
186
|
/**
|
|
98
187
|
* Whether the Node loader inserts dev checks: yes unless `NODE_ENV=production`;
|
|
@@ -106,6 +195,15 @@ export function devChecksEnabled(env: Record<string, string | undefined>): boole
|
|
|
106
195
|
*/
|
|
107
196
|
export function configFileWarning(configFile: string | undefined): string | undefined;
|
|
108
197
|
|
|
198
|
+
/** The line `vite build` ends with: `safe-ts: 1,293 files checked, 960 legacy, 0 problems`. */
|
|
199
|
+
export function summaryLine(
|
|
200
|
+
stats: { files: number; legacy: number; excluded: number; problems: number },
|
|
201
|
+
checked: boolean,
|
|
202
|
+
): string;
|
|
203
|
+
|
|
204
|
+
/** The `exclude` option as a test of an absolute file path and Vite's root. */
|
|
205
|
+
export function excludeFilter(exclude: SafeTsExclude | readonly SafeTsExclude[] | undefined): (file: string, root: string) => boolean;
|
|
206
|
+
|
|
109
207
|
/** Source map for a line-preserving rewrite (every generated line maps to its original line). */
|
|
110
208
|
export function lineMap(
|
|
111
209
|
file: string,
|
package/index.mjs
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
// safe-ts build-time transform: prelude imports, parseJson<T> validators, match -> switch,
|
|
2
2
|
// and q(...) early returns. Every rewrite keeps the original line structure.
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
3
4
|
import { createRequire } from "node:module";
|
|
4
|
-
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
5
7
|
|
|
6
8
|
import MagicString from "magic-string";
|
|
7
9
|
|
|
8
10
|
const require = createRequire(import.meta.url);
|
|
9
11
|
const native = require("@evobug_com/safe-ts-native");
|
|
10
12
|
|
|
13
|
+
export { safeTsBun } from "./bun-plugin.mjs";
|
|
14
|
+
|
|
11
15
|
const TS_FILE = /\.(ts|mts|cts|tsx)$/;
|
|
12
16
|
const VUE_FILE = /\.vue$/;
|
|
13
17
|
|
|
@@ -25,17 +29,35 @@ export function transform(filename, code, options = {}) {
|
|
|
25
29
|
* `transform`, also returning the other files the result depends on (types, `@inline`
|
|
26
30
|
* functions and enum tables read from imports, the tsconfig that turns the prelude on): a
|
|
27
31
|
* cached result stays valid while none of them changes. Used by the Node loader's cache.
|
|
32
|
+
* Imports resolve through tsconfig.json `paths`; `aliases` adds a bundler's own
|
|
33
|
+
* (`[{ find: "@", replacement: "/abs/src" }]`), as the Vite plugin does with `resolve.alias`.
|
|
28
34
|
*/
|
|
29
35
|
export function transformWithDependencies(filename, code, options = {}) {
|
|
30
36
|
const result = native.transform(filename, code, {
|
|
31
37
|
devChecks: options.devChecks === true,
|
|
32
38
|
sharedValidators: options.sharedValidators === true,
|
|
39
|
+
...(options.aliases?.length ? { aliases: options.aliases } : {}),
|
|
33
40
|
});
|
|
34
41
|
if (result.errors.length > 0) {
|
|
35
42
|
const lines = result.errors.map((e) => ` ${filename}:${e.line}:${e.column + 1} ${e.rule}: ${e.message}`);
|
|
36
43
|
throw new Error(`safe-ts transform failed:\n${lines.join("\n")}`);
|
|
37
44
|
}
|
|
38
|
-
return { code: result.code, dependencies: result.dependencies ?? [] };
|
|
45
|
+
return { code: result.code, dependencies: result.dependencies ?? [], warnings: result.warnings ?? [], legacy: result.legacy === true };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Import `url` (a `file:` URL, `URL`, or absolute path) with the safe-ts transform, from code
|
|
50
|
+
* that itself wasn't transformed: a Vite config, which Vite loads without plugins. Registers the
|
|
51
|
+
* Node loader's hooks in this process (as `--import @evobug_com/safe-ts-transform/register`
|
|
52
|
+
* does), then imports the module through them, so it and everything it imports are transformed.
|
|
53
|
+
* Returns the module's namespace: its exports, functions included. A module Node already loaded
|
|
54
|
+
* without the hooks stays as it was: load it only this way. In Bun (`bunx --bun vite`), the same
|
|
55
|
+
* with the Bun plugin (bun.mjs) in place of the hooks.
|
|
56
|
+
*/
|
|
57
|
+
export async function loadTransformed(url) {
|
|
58
|
+
await import(process.versions.bun === undefined ? "./register.mjs" : "./bun.mjs");
|
|
59
|
+
const href = url instanceof URL ? url.href : isAbsolute(String(url)) ? pathToFileURL(String(url)).href : String(url);
|
|
60
|
+
return import(href);
|
|
39
61
|
}
|
|
40
62
|
|
|
41
63
|
/** The query parameter of a shared validator module: `/src/types.ts?safe-ts-json=v$User`. */
|
|
@@ -59,12 +81,36 @@ export function sharedModuleId(id) {
|
|
|
59
81
|
* was built from (`file` included): it stays valid while none of them changes. Throws if `file`
|
|
60
82
|
* no longer declares the type.
|
|
61
83
|
*/
|
|
62
|
-
export function sharedModule(file, key) {
|
|
63
|
-
const result = native.sharedModule(file, key);
|
|
84
|
+
export function sharedModule(file, key, aliases) {
|
|
85
|
+
const result = aliases?.length ? native.sharedModule(file, key, aliases) : native.sharedModule(file, key);
|
|
64
86
|
if (result.code == null) throw new Error(`safe-ts: shared validators ${file}?${SHARED_QUERY}=${key}: ${result.error}`);
|
|
65
87
|
return { code: result.code, dependencies: result.dependencies };
|
|
66
88
|
}
|
|
67
89
|
|
|
90
|
+
/**
|
|
91
|
+
* The aliases of a resolved Vite config (`config.resolve.alias`) that the checker can use: a
|
|
92
|
+
* string `find` and an absolute `replacement`. A `find` that is a regular expression can't be
|
|
93
|
+
* handed over: write that alias in tsconfig.json `paths` too.
|
|
94
|
+
*/
|
|
95
|
+
export function stringAliases(alias) {
|
|
96
|
+
const entries = Array.isArray(alias)
|
|
97
|
+
? alias
|
|
98
|
+
: Object.entries(alias ?? {}).map(([find, replacement]) => ({ find, replacement }));
|
|
99
|
+
return entries
|
|
100
|
+
.filter((a) => typeof a?.find === "string" && typeof a.replacement === "string" && isAbsolute(a.replacement))
|
|
101
|
+
.map((a) => ({ find: a.find, replacement: a.replacement }));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Is `file` library code: under a `node_modules` directory below `root`? A project that itself
|
|
106
|
+
* lives under some `node_modules` is still a project. (The checker decides the same way.)
|
|
107
|
+
*/
|
|
108
|
+
export function isLibraryFile(file, root) {
|
|
109
|
+
const below = relative(root, file);
|
|
110
|
+
const inside = below !== "" && !below.startsWith("..") && !isAbsolute(below);
|
|
111
|
+
return (inside ? below : file).split(/[\\/]/).includes("node_modules");
|
|
112
|
+
}
|
|
113
|
+
|
|
68
114
|
/**
|
|
69
115
|
* Whether the Node loader (`register.mjs`) inserts dev checks: yes unless
|
|
70
116
|
* `NODE_ENV=production`; `SAFE_TS_DEV_CHECKS=1` / `=0` (or `true` / `false`) overrides that.
|
|
@@ -100,7 +146,9 @@ export function lineMap(file, original, transformed) {
|
|
|
100
146
|
* @param {{ check?: "warn" | "error" | false, compileHints?: boolean | string[], devChecks?: boolean }} [options]
|
|
101
147
|
* check: run the safe-ts rules on every transformed file (the same checks as the editor).
|
|
102
148
|
* "warn" (default) prints problems in the terminal; "error" shows Vite's error overlay in
|
|
103
|
-
* the browser and fails the build
|
|
149
|
+
* the browser and fails the build when a finding is an error (a rule at "warn" in
|
|
150
|
+
* package.json's `"safe-ts": { "rules" }`, or in the oxlint preset, is only printed); false
|
|
151
|
+
* turns it off.
|
|
104
152
|
* compileHints: add `//# allFunctionsCalledOnLoad` to entry chunks (`true`) or to the chunks
|
|
105
153
|
* with these names, so Chrome 136+ compiles their functions eagerly, in the background,
|
|
106
154
|
* instead of on first call (https://v8.dev/blog/explicit-compile-hints). It costs memory and
|
|
@@ -112,20 +160,38 @@ export function lineMap(file, original, transformed) {
|
|
|
112
160
|
* sharedValidators: generate the validator (and test-data generator) of each named type once,
|
|
113
161
|
* in a module of its own that every file using it imports, instead of a copy per file. On by
|
|
114
162
|
* default; false gives every file its own copies, as before.
|
|
163
|
+
* exclude: files the plugin leaves alone, neither checked nor transformed: globs relative to
|
|
164
|
+
* Vite's root (`"src/vendor/**"`), regular expressions tested on the absolute path, or a
|
|
165
|
+
* function of the absolute path; one or a list. An excluded file must not need the transform
|
|
166
|
+
* (`q`, `match`, `parseJson`, prelude names). For code that isn't migrated yet, the
|
|
167
|
+
* `// @safe-ts legacy` marker is usually what you want: such a file is not reported on, and
|
|
168
|
+
* gets only the rewrites it needs to run.
|
|
169
|
+
*
|
|
170
|
+
* `vite build` ends with one line: `safe-ts: 1,293 files checked, 960 legacy, 0 problems`.
|
|
115
171
|
*/
|
|
116
172
|
export function safeTs(options = {}) {
|
|
117
173
|
const check = options.check ?? "warn";
|
|
174
|
+
const excluded = excludeFilter(options.exclude);
|
|
118
175
|
const hints = options.compileHints ?? false;
|
|
119
176
|
const wantsHint = (chunk) => (hints === true ? chunk.isEntry : Array.isArray(hints) && hints.includes(chunk.name));
|
|
120
177
|
let devChecks = options.devChecks ?? false;
|
|
121
178
|
const sharedValidators = options.sharedValidators ?? true;
|
|
122
179
|
let root = process.cwd();
|
|
123
180
|
let checker;
|
|
181
|
+
let logger;
|
|
182
|
+
let command;
|
|
183
|
+
// For the line at the end of a build.
|
|
184
|
+
let stats = { files: 0, legacy: 0, excluded: 0, problems: 0 };
|
|
185
|
+
let aliases = [];
|
|
186
|
+
const unresolvedWarned = new Set();
|
|
124
187
|
return {
|
|
125
188
|
name: "safe-ts",
|
|
126
189
|
enforce: "pre",
|
|
127
190
|
configResolved(config) {
|
|
128
191
|
root = config.root;
|
|
192
|
+
logger = config.logger;
|
|
193
|
+
command = config.command;
|
|
194
|
+
aliases = stringAliases(config.resolve?.alias);
|
|
129
195
|
devChecks = options.devChecks ?? config.command === "serve";
|
|
130
196
|
const warning = configFileWarning(config.configFile);
|
|
131
197
|
if (warning !== undefined) config.logger.warn(warning);
|
|
@@ -147,7 +213,7 @@ export function safeTs(options = {}) {
|
|
|
147
213
|
load(id) {
|
|
148
214
|
const shared = sharedModuleId(id);
|
|
149
215
|
if (shared === undefined) return null;
|
|
150
|
-
const module = sharedModule(shared.file, shared.key);
|
|
216
|
+
const module = sharedModule(shared.file, shared.key, aliases);
|
|
151
217
|
// The dev server invalidates the module when the declaring file changes; these cover the
|
|
152
218
|
// rest (types it extends or picks from elsewhere).
|
|
153
219
|
if (typeof this?.addWatchFile === "function") for (const file of module.dependencies) this.addWatchFile(file);
|
|
@@ -158,26 +224,59 @@ export function safeTs(options = {}) {
|
|
|
158
224
|
const [file, query] = id.split("?");
|
|
159
225
|
// `App.vue?vue&type=script...`: parts @vitejs/plugin-vue serves from the SFC it got from us.
|
|
160
226
|
const wanted = VUE_FILE.test(file) ? query === undefined : TS_FILE.test(file);
|
|
161
|
-
if (!wanted || file
|
|
227
|
+
if (!wanted || isLibraryFile(file, root)) return null;
|
|
228
|
+
if (excluded(file, root)) {
|
|
229
|
+
stats.excluded++;
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
stats.files++;
|
|
162
233
|
if (check) {
|
|
163
|
-
checker ??= new native.Checker(root);
|
|
234
|
+
checker ??= new native.Checker(root, { aliases });
|
|
164
235
|
const problems = checker.checkFile(file, code);
|
|
236
|
+
stats.problems += problems.length;
|
|
237
|
+
// Once per import and file: the checker can't follow these, so it misses what they do.
|
|
238
|
+
for (const specifier of checker.unresolvedImports?.(file, code) ?? []) {
|
|
239
|
+
const key = `${file}\0${specifier}`;
|
|
240
|
+
if (unresolvedWarned.has(key)) continue;
|
|
241
|
+
unresolvedWarned.add(key);
|
|
242
|
+
this.warn(`safe-ts: could not resolve "${specifier}" from ${relative(root, file).replaceAll("\\", "/")}`);
|
|
243
|
+
}
|
|
165
244
|
if (problems.length > 0) {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
245
|
+
// A rule's level comes from package.json (`"safe-ts": { "rules": ... }`), else the
|
|
246
|
+
// oxlint preset's: with check "error", only errors stop the build.
|
|
247
|
+
const errors = problems.filter((d) => d.severity !== "warning");
|
|
248
|
+
const label = (d) => (d.severity === "warning" ? " warning" : "");
|
|
249
|
+
const lines = problems.map((d) => ` ${file}:${d.line}:${d.column + 1} safe-ts(${d.rule})${label(d)}: ${d.message}`);
|
|
250
|
+
const counts = [[errors.length, "error"], [problems.length - errors.length, "warning"]]
|
|
251
|
+
.filter(([n]) => n > 0)
|
|
252
|
+
.map(([n, word]) => `${n} ${word}${n === 1 ? "" : "s"}`);
|
|
253
|
+
const message = `safe-ts: ${counts.join(", ")}\n${lines.join("\n")}`;
|
|
254
|
+
if (check === "error" && errors.length > 0) {
|
|
255
|
+
this.error({ message, id: file, loc: { line: errors[0].line, column: errors[0].column } });
|
|
170
256
|
} else {
|
|
171
257
|
this.warn(message);
|
|
172
258
|
}
|
|
173
259
|
}
|
|
174
260
|
}
|
|
175
|
-
const { code: out, dependencies } = transformWithDependencies(file, code, { devChecks, sharedValidators });
|
|
261
|
+
const { code: out, dependencies, warnings, legacy } = transformWithDependencies(file, code, { devChecks, sharedValidators, aliases });
|
|
262
|
+
if (legacy) stats.legacy++;
|
|
263
|
+
for (const warning of warnings) this.warn(`safe-ts: ${warning}`);
|
|
176
264
|
// Generated validators follow the types they were made from, wherever those are declared.
|
|
177
265
|
// (Not when a wrapper plugin calls this hook without a context.)
|
|
178
266
|
if (typeof this?.addWatchFile === "function") for (const dependency of dependencies) this.addWatchFile(dependency);
|
|
179
267
|
return out === code ? null : { code: out, map: lineMap(file, code, out) };
|
|
180
268
|
},
|
|
269
|
+
buildStart() {
|
|
270
|
+
stats = { files: 0, legacy: 0, excluded: 0, problems: 0 };
|
|
271
|
+
},
|
|
272
|
+
// One line, so a build log shows the plugin ran and what it saw. Not on the dev server,
|
|
273
|
+
// which transforms files as the browser asks for them: there is no point where all are done.
|
|
274
|
+
buildEnd() {
|
|
275
|
+
if (command === "serve" || (stats.files === 0 && stats.excluded === 0)) return;
|
|
276
|
+
const line = summaryLine(stats, check !== false);
|
|
277
|
+
if (logger !== undefined) logger.info(line);
|
|
278
|
+
else if (typeof this?.info === "function") this.info(line);
|
|
279
|
+
},
|
|
181
280
|
renderChunk(code, chunk) {
|
|
182
281
|
if (!wantsHint(chunk)) return null;
|
|
183
282
|
const s = new MagicString(code);
|
|
@@ -204,13 +303,77 @@ export function safeTs(options = {}) {
|
|
|
204
303
|
|
|
205
304
|
const COMPILE_HINT = "//# allFunctionsCalledOnLoad";
|
|
206
305
|
|
|
306
|
+
/** `safe-ts: 1,293 files checked, 960 legacy, 0 problems` (`transformed`, without the count, when `check` is off). */
|
|
307
|
+
export function summaryLine(stats, checked) {
|
|
308
|
+
const n = (count) => count.toLocaleString("en-US");
|
|
309
|
+
const files = `${n(stats.files)} file${stats.files === 1 ? "" : "s"}`;
|
|
310
|
+
const parts = checked
|
|
311
|
+
? [`${files} checked`, `${n(stats.legacy)} legacy`, `${n(stats.problems)} problem${stats.problems === 1 ? "" : "s"}`]
|
|
312
|
+
: [`${files} transformed (check: false)`, `${n(stats.legacy)} legacy`];
|
|
313
|
+
if (stats.excluded > 0) parts.push(`${n(stats.excluded)} excluded`);
|
|
314
|
+
return `safe-ts: ${parts.join(", ")}`;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* The `exclude` option as a test of (absolute file, Vite root): globs match the path relative
|
|
319
|
+
* to the root (or the absolute path, for an absolute glob), regular expressions the absolute
|
|
320
|
+
* path, a function gets the absolute path. Paths use `/` on every OS.
|
|
321
|
+
*/
|
|
322
|
+
export function excludeFilter(exclude) {
|
|
323
|
+
if (exclude === undefined || exclude === null) return () => false;
|
|
324
|
+
const list = Array.isArray(exclude) ? exclude : [exclude];
|
|
325
|
+
const tests = list.map((pattern) => {
|
|
326
|
+
if (typeof pattern === "function") return (file) => pattern(file) === true;
|
|
327
|
+
if (pattern instanceof RegExp) return (file) => { pattern.lastIndex = 0; return pattern.test(file); };
|
|
328
|
+
if (typeof pattern === "string") {
|
|
329
|
+
const glob = globRegExp(pattern.replaceAll("\\", "/"));
|
|
330
|
+
const absolute = isAbsolute(pattern) || /^[A-Za-z]:\//.test(pattern);
|
|
331
|
+
return (file, root) => glob.test(absolute ? file : relative(root, file).replaceAll("\\", "/"));
|
|
332
|
+
}
|
|
333
|
+
throw new TypeError(`safe-ts: exclude takes globs, regular expressions or a function, not ${typeof pattern}`);
|
|
334
|
+
});
|
|
335
|
+
return (file, root) => {
|
|
336
|
+
const path = file.replaceAll("\\", "/");
|
|
337
|
+
return tests.some((test) => test(path, root));
|
|
338
|
+
};
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** `**` any directories, `*` and `?` within one, `{a,b}` either; a leading `./` is dropped. */
|
|
342
|
+
function globRegExp(glob) {
|
|
343
|
+
let source = "";
|
|
344
|
+
let braces = 0;
|
|
345
|
+
const text = glob.replace(/^\.\//, "");
|
|
346
|
+
for (let i = 0; i < text.length; i++) {
|
|
347
|
+
const c = text[i];
|
|
348
|
+
if (c === "*" && text[i + 1] === "*") {
|
|
349
|
+
const slash = text[i + 2] === "/";
|
|
350
|
+
source += slash ? "(?:.*/)?" : ".*";
|
|
351
|
+
i += slash ? 2 : 1;
|
|
352
|
+
} else if (c === "*") source += "[^/]*";
|
|
353
|
+
else if (c === "?") source += "[^/]";
|
|
354
|
+
else if (c === "{") {
|
|
355
|
+
braces++;
|
|
356
|
+
source += "(?:";
|
|
357
|
+
} else if (c === "}" && braces > 0) {
|
|
358
|
+
braces--;
|
|
359
|
+
source += ")";
|
|
360
|
+
} else if (c === "," && braces > 0) source += "|";
|
|
361
|
+
else source += c.replace(/[.+^$()|[\]\\{}]/g, "\\$&");
|
|
362
|
+
}
|
|
363
|
+
return new RegExp(`^${source}$`);
|
|
364
|
+
}
|
|
365
|
+
|
|
207
366
|
/** Set by the Node loader (`register.mjs`): the files it transformed in this process. */
|
|
208
367
|
const LOADED = Symbol.for("safe-ts.loader.files");
|
|
209
368
|
|
|
369
|
+
/** The loader's hooks, imported by a config: they apply only to what it loads afterwards. */
|
|
370
|
+
const REGISTER_IMPORT = /["']@evobug_com\/safe-ts-transform\/register(?:\.mjs)?["']/;
|
|
371
|
+
|
|
210
372
|
/**
|
|
211
373
|
* Vite loads its config file, and what the config imports, without plugins: code there that
|
|
212
374
|
* needs the transform fails (`PropagateError is not defined`, "q() was not compiled"). Unless
|
|
213
375
|
* the Node loader transformed it (`--configLoader native` with the loader registered first).
|
|
376
|
+
* Only what runs counts: imports of types, `import()` and `loadTransformed(...)` are left out.
|
|
214
377
|
*/
|
|
215
378
|
export function configFileWarning(configFile) {
|
|
216
379
|
if (typeof configFile !== "string" || globalThis[LOADED]?.has(configFile)) return undefined;
|
|
@@ -223,10 +386,22 @@ export function configFileWarning(configFile) {
|
|
|
223
386
|
const untransformed = needs.filter((n) => !globalThis[LOADED]?.has(n.file));
|
|
224
387
|
if (untransformed.length === 0) return undefined;
|
|
225
388
|
const lines = untransformed.map((n) => ` ${n.file}: uses ${n.needs}`);
|
|
389
|
+
let registers = false;
|
|
390
|
+
try {
|
|
391
|
+
registers = REGISTER_IMPORT.test(readFileSync(configFile, "utf8"));
|
|
392
|
+
} catch {
|
|
393
|
+
// Gone in between: no hint.
|
|
394
|
+
}
|
|
395
|
+
const register = registers
|
|
396
|
+
? "Importing @evobug_com/safe-ts-transform/register in the config doesn't cover these: a module's imports " +
|
|
397
|
+
"load before its code runs, so the hooks apply only to what the config loads later (`import()` in a hook, " +
|
|
398
|
+
"`loadTransformed(...)`).\n"
|
|
399
|
+
: "";
|
|
226
400
|
return (
|
|
227
401
|
`safe-ts: Vite loads ${configFile} without the safe-ts transform (plugins don't apply to the config), ` +
|
|
228
|
-
`but it imports code that needs it:\n${lines.join("\n")}\n` +
|
|
229
|
-
"That code fails when it runs.
|
|
402
|
+
`but it imports code that needs it:\n${lines.join("\n")}\n${register}` +
|
|
403
|
+
"That code fails when it runs. Load it with `await loadTransformed(new URL(\"./plugins.ts\", import.meta.url))` " +
|
|
404
|
+
"from @evobug_com/safe-ts-transform, start Vite with `--configLoader native` and " +
|
|
230
405
|
'NODE_OPTIONS="--import @evobug_com/safe-ts-transform/register", or keep code the config imports free of it: ' +
|
|
231
406
|
"https://safe-ts.evobug-pages.com/guide/adoption#the-vite-config"
|
|
232
407
|
);
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@evobug_com/safe-ts-transform",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "SAFE-TS build-time transform: a Vite/Rolldown/Rollup plugin
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "SAFE-TS build-time transform: a Vite/Rolldown/Rollup plugin, a Node loader and a Bun plugin that rewrite q(), match(), parseJson<T>(), loops and @inline, and run the SAFE-TS checks.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"safe-ts",
|
|
7
7
|
"typescript",
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
"rollup-plugin",
|
|
11
11
|
"rolldown",
|
|
12
12
|
"node-loader",
|
|
13
|
+
"bun-plugin",
|
|
13
14
|
"transform",
|
|
14
15
|
"result",
|
|
15
16
|
"pattern-matching"
|
|
@@ -29,12 +30,15 @@
|
|
|
29
30
|
"types": "./index.d.ts",
|
|
30
31
|
"default": "./index.mjs"
|
|
31
32
|
},
|
|
32
|
-
"./register": "./register.mjs"
|
|
33
|
+
"./register": "./register.mjs",
|
|
34
|
+
"./bun": "./bun.mjs"
|
|
33
35
|
},
|
|
34
36
|
"files": [
|
|
35
37
|
"index.mjs",
|
|
36
38
|
"index.d.ts",
|
|
37
39
|
"register.mjs",
|
|
40
|
+
"bun.mjs",
|
|
41
|
+
"bun-plugin.mjs",
|
|
38
42
|
"cache.mjs",
|
|
39
43
|
"LICENSE-MIT",
|
|
40
44
|
"LICENSE-APACHE"
|
|
@@ -43,11 +47,11 @@
|
|
|
43
47
|
"node": ">=22.18.0"
|
|
44
48
|
},
|
|
45
49
|
"dependencies": {
|
|
46
|
-
"@evobug_com/safe-ts-native": "0.
|
|
50
|
+
"@evobug_com/safe-ts-native": "0.4.0",
|
|
47
51
|
"magic-string": "^1.4.5"
|
|
48
52
|
},
|
|
49
53
|
"peerDependencies": {
|
|
50
|
-
"@evobug_com/safe-ts-std": "^0.
|
|
54
|
+
"@evobug_com/safe-ts-std": "^0.4.0",
|
|
51
55
|
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
|
52
56
|
},
|
|
53
57
|
"peerDependenciesMeta": {
|
package/register.mjs
CHANGED
|
@@ -3,16 +3,37 @@
|
|
|
3
3
|
// Dev checks (https://safe-ts.evobug-pages.com/guide/dev-checks) are on unless
|
|
4
4
|
// NODE_ENV=production; SAFE_TS_DEV_CHECKS=1 or =0 overrides that.
|
|
5
5
|
// Transformed files are cached on disk (cache.mjs); SAFE_TS_CACHE=0 turns that off.
|
|
6
|
+
// A file that uses prelude names where no tsconfig.json turns the prelude on (a copy of a script
|
|
7
|
+
// outside the project) is still loaded, with a warning: those names aren't defined there.
|
|
6
8
|
// The validators of named types are generated once, in shared modules every file using them
|
|
7
9
|
// imports (`<declaring file>?safe-ts-json=<key>`, served here); SAFE_TS_SHARED_VALIDATORS=0
|
|
8
10
|
// gives every file its own copies instead.
|
|
11
|
+
// Imports Node can't resolve are resolved as the checker resolves them: tsconfig.json `paths`
|
|
12
|
+
// and `baseUrl` (`@utils/x`), and extensions or `index` files left out.
|
|
13
|
+
// Bun has no `module.registerHooks`: there, preload `@evobug_com/safe-ts-transform/bun` (bun.mjs).
|
|
9
14
|
import { readFileSync } from "node:fs";
|
|
10
|
-
import { registerHooks }
|
|
15
|
+
// Not `import { registerHooks }`: where it's missing (Bun, Node before 22.15) that is a
|
|
16
|
+
// SyntaxError naming `registerHooks`, before any code here could say what to use instead.
|
|
17
|
+
import * as nodeModule from "node:module";
|
|
11
18
|
import { join } from "node:path";
|
|
12
19
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
13
20
|
|
|
14
21
|
import { openCache } from "./cache.mjs";
|
|
15
|
-
import { devChecksEnabled, sharedModule, sharedModuleId, transformWithDependencies } from "./index.mjs";
|
|
22
|
+
import { devChecksEnabled, isLibraryFile, sharedModule, sharedModuleId, transformWithDependencies } from "./index.mjs";
|
|
23
|
+
|
|
24
|
+
const native = nodeModule.createRequire(import.meta.url)("@evobug_com/safe-ts-native");
|
|
25
|
+
const root = process.cwd();
|
|
26
|
+
|
|
27
|
+
const { registerHooks } = nodeModule;
|
|
28
|
+
if (typeof registerHooks !== "function") {
|
|
29
|
+
throw new Error(
|
|
30
|
+
process.versions.bun !== undefined
|
|
31
|
+
? "safe-ts: @evobug_com/safe-ts-transform/register is the Node loader, and Bun has no `module.registerHooks`. " +
|
|
32
|
+
'In Bun, preload the Bun plugin instead: `preload = ["@evobug_com/safe-ts-transform/bun"]` in bunfig.toml ' +
|
|
33
|
+
"(and under `[test]`), or `bun --preload @evobug_com/safe-ts-transform/bun`: https://safe-ts.evobug-pages.com/guide/bun"
|
|
34
|
+
: `safe-ts: the Node loader needs \`module.registerHooks\` (Node 22.15 or later); this is Node ${process.versions.node}.`,
|
|
35
|
+
);
|
|
36
|
+
}
|
|
16
37
|
|
|
17
38
|
const TS_FILE = /\.(ts|mts)$/;
|
|
18
39
|
const HAS_EXTENSION = /\.[cm]?[jt]sx?$/;
|
|
@@ -22,6 +43,7 @@ const cache = openCache(process.env, { devChecks, sharedValidators });
|
|
|
22
43
|
|
|
23
44
|
// The files this thread transformed, for the Vite plugin's config check (index.mjs).
|
|
24
45
|
const loaded = (globalThis[Symbol.for("safe-ts.loader.files")] ??= new Set());
|
|
46
|
+
const warned = new Set();
|
|
25
47
|
|
|
26
48
|
registerHooks({
|
|
27
49
|
resolve(specifier, context, nextResolve) {
|
|
@@ -35,7 +57,18 @@ registerHooks({
|
|
|
35
57
|
}
|
|
36
58
|
// Extensionless relative imports, as with bundlers / `moduleResolution: "Bundler"`.
|
|
37
59
|
if (error?.code === "ERR_MODULE_NOT_FOUND" && /^\.\.?\//.test(specifier) && !HAS_EXTENSION.test(specifier)) {
|
|
38
|
-
|
|
60
|
+
try {
|
|
61
|
+
return nextResolve(`${specifier}.ts`, context);
|
|
62
|
+
} catch {
|
|
63
|
+
// A directory's index file: the checker's resolution, below.
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// tsconfig `paths` (`@utils/x`) and the rest of a bundler's resolution, as the checker
|
|
67
|
+
// follows them: a file runs with the imports `safe-ts check` saw.
|
|
68
|
+
const notFound = error?.code === "ERR_MODULE_NOT_FOUND" || error?.code === "ERR_UNSUPPORTED_DIR_IMPORT";
|
|
69
|
+
if (notFound && context.parentURL?.startsWith("file:") && typeof native.resolveModule === "function") {
|
|
70
|
+
const found = native.resolveModule(fileURLToPath(context.parentURL.split("?")[0]), specifier);
|
|
71
|
+
if (found != null) return nextResolve(pathToFileURL(found).href, context);
|
|
39
72
|
}
|
|
40
73
|
throw error;
|
|
41
74
|
}
|
|
@@ -53,7 +86,7 @@ registerHooks({
|
|
|
53
86
|
}
|
|
54
87
|
return { format: "module-typescript", source, shortCircuit: true };
|
|
55
88
|
}
|
|
56
|
-
if (!url.startsWith("file:") || !TS_FILE.test(new URL(url).pathname) || url
|
|
89
|
+
if (!url.startsWith("file:") || !TS_FILE.test(new URL(url).pathname) || isLibraryFile(fileURLToPath(url), root)) {
|
|
57
90
|
return nextLoad(url, context);
|
|
58
91
|
}
|
|
59
92
|
const filename = fileURLToPath(url);
|
|
@@ -62,7 +95,13 @@ registerHooks({
|
|
|
62
95
|
if (source === undefined) {
|
|
63
96
|
const result = transformWithDependencies(filename, code, { devChecks, sharedValidators });
|
|
64
97
|
source = result.code;
|
|
65
|
-
|
|
98
|
+
// A file with a warning isn't cached, so the warning shows on every run until it's fixed.
|
|
99
|
+
if (result.warnings.length === 0) cache?.set(filename, code, result);
|
|
100
|
+
for (const warning of result.warnings) {
|
|
101
|
+
// Right away (not `process.emitWarning`, which waits a tick): the file may fail as it loads.
|
|
102
|
+
if (!warned.has(warning)) process.stderr.write(`safe-ts warning: ${warning}\n`);
|
|
103
|
+
warned.add(warning);
|
|
104
|
+
}
|
|
66
105
|
}
|
|
67
106
|
loaded.add(filename);
|
|
68
107
|
return { format: "module-typescript", source, shortCircuit: true };
|