@evobug_com/safe-ts-transform 0.1.0 → 0.3.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 +2 -0
- package/cache.mjs +238 -0
- package/index.d.ts +103 -3
- package/index.mjs +157 -6
- package/package.json +5 -4
- package/register.mjs +47 -3
package/README.md
CHANGED
|
@@ -11,4 +11,6 @@ npm install -D @evobug_com/safe-ts-transform
|
|
|
11
11
|
Part of [SAFE-TS](https://safe-ts.evobug-pages.com/), a strict, Rust-flavoured subset of TypeScript. The website has the
|
|
12
12
|
guides, a page per rule, and a playground that runs the checker in your browser.
|
|
13
13
|
|
|
14
|
+
Changes in each version: [CHANGELOG.md](https://git.evobug.com/Evobug/Safe-Ts/src/branch/main/CHANGELOG.md).
|
|
15
|
+
|
|
14
16
|
Source: https://git.evobug.com/Evobug/Safe-Ts. Licensed under MIT OR Apache-2.0.
|
package/cache.mjs
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
// The Node loader's on-disk cache of transformed files (register.mjs), so a restart, a worker
|
|
2
|
+
// thread or a test process doesn't transform the same file again.
|
|
3
|
+
//
|
|
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.
|
|
16
|
+
//
|
|
17
|
+
// Where: SAFE_TS_CACHE_DIR, else node_modules/.cache/safe-ts in the nearest directory above the
|
|
18
|
+
// current one that has node_modules, else the system's temporary directory. SAFE_TS_CACHE=0 (or
|
|
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.
|
|
21
|
+
import { createRequire } from "node:module";
|
|
22
|
+
import { hash, randomBytes } from "node:crypto";
|
|
23
|
+
import { accessSync, constants, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
|
24
|
+
import { tmpdir } from "node:os";
|
|
25
|
+
import { dirname, join } from "node:path";
|
|
26
|
+
import { fileURLToPath } from "node:url";
|
|
27
|
+
import { threadId } from "node:worker_threads";
|
|
28
|
+
|
|
29
|
+
const require = createRequire(import.meta.url);
|
|
30
|
+
|
|
31
|
+
/** Bumped when the entry format changes. */
|
|
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;
|
|
39
|
+
|
|
40
|
+
const digest = (data) => hash("sha256", data, "hex");
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* What produced the code: this package (which pins the native addon's version), and the addon
|
|
44
|
+
* file itself, so a rebuilt addon of the same version doesn't reuse old output.
|
|
45
|
+
*/
|
|
46
|
+
function transformVersion() {
|
|
47
|
+
const native = require("@evobug_com/safe-ts-native");
|
|
48
|
+
const versions = [require("./package.json").version];
|
|
49
|
+
try {
|
|
50
|
+
const addon = statSync(native.loadedFrom);
|
|
51
|
+
versions.push(native.loadedFrom, addon.size, addon.mtimeMs);
|
|
52
|
+
} catch {
|
|
53
|
+
// An addon loaded some other way: the package versions alone.
|
|
54
|
+
}
|
|
55
|
+
return versions;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function writableDir(dir) {
|
|
59
|
+
try {
|
|
60
|
+
mkdirSync(dir, { recursive: true });
|
|
61
|
+
accessSync(dir, constants.W_OK);
|
|
62
|
+
return dir;
|
|
63
|
+
} catch {
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The directory for the cache: see the top of this file. */
|
|
69
|
+
export function cacheDir(env, cwd = process.cwd()) {
|
|
70
|
+
if (env.SAFE_TS_CACHE_DIR) return writableDir(env.SAFE_TS_CACHE_DIR);
|
|
71
|
+
for (let dir = cwd; ; dir = dirname(dir)) {
|
|
72
|
+
let found = false;
|
|
73
|
+
try {
|
|
74
|
+
found = statSync(join(dir, "node_modules")).isDirectory();
|
|
75
|
+
} catch {
|
|
76
|
+
// Not here; look further up.
|
|
77
|
+
}
|
|
78
|
+
if (found) {
|
|
79
|
+
const usable = writableDir(join(dir, "node_modules", ".cache", "safe-ts"));
|
|
80
|
+
if (usable !== undefined) return usable;
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
if (dirname(dir) === dir) break;
|
|
84
|
+
}
|
|
85
|
+
const user = typeof process.getuid === "function" ? process.getuid() : "user";
|
|
86
|
+
return writableDir(join(tmpdir(), `safe-ts-cache-${user}`));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The cache for this process, or undefined when it is turned off or no directory is writable.
|
|
91
|
+
*
|
|
92
|
+
* @param {Record<string, string | undefined>} env
|
|
93
|
+
* @param {{ devChecks: boolean, sharedValidators?: boolean }} options what the transform is asked
|
|
94
|
+
* for: part of each key.
|
|
95
|
+
*/
|
|
96
|
+
export function openCache(env, options) {
|
|
97
|
+
const flag = env.SAFE_TS_CACHE;
|
|
98
|
+
if (flag === "0" || flag === "false") return undefined;
|
|
99
|
+
const dir = cacheDir(env);
|
|
100
|
+
if (dir === undefined) return undefined;
|
|
101
|
+
// Dev checks name files relative to the current directory: it is part of the key too.
|
|
102
|
+
const version = JSON.stringify([FORMAT, transformVersion(), options.devChecks === true, options.sharedValidators === true, process.cwd()]);
|
|
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`);
|
|
106
|
+
// Many files depend on the same few (the tsconfig, std modules): hash each version once.
|
|
107
|
+
const dependencyDigests = new Map();
|
|
108
|
+
const dependencyDigest = (file) => {
|
|
109
|
+
const { mtimeMs, size } = statSync(file);
|
|
110
|
+
const known = dependencyDigests.get(file);
|
|
111
|
+
if (known?.mtimeMs === mtimeMs && known.size === size) return known.digest;
|
|
112
|
+
const found = digest(readFileSync(file));
|
|
113
|
+
dependencyDigests.set(file, { mtimeMs, size, digest: found });
|
|
114
|
+
return found;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
dir,
|
|
119
|
+
/** The cached code for `filename` with content `code`, if still valid. */
|
|
120
|
+
get(filename, code) {
|
|
121
|
+
let entry;
|
|
122
|
+
try {
|
|
123
|
+
entry = JSON.parse(readFileSync(entryPath(filename), "utf8"));
|
|
124
|
+
} catch {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
if (entry?.format !== FORMAT || entry.source !== digest(code) || typeof entry.code !== "string") return undefined;
|
|
128
|
+
for (const [file, expected] of entry.dependencies ?? []) {
|
|
129
|
+
let actual;
|
|
130
|
+
try {
|
|
131
|
+
actual = dependencyDigest(file);
|
|
132
|
+
} catch {
|
|
133
|
+
return undefined;
|
|
134
|
+
}
|
|
135
|
+
if (actual !== expected) return undefined;
|
|
136
|
+
}
|
|
137
|
+
return entry.code;
|
|
138
|
+
},
|
|
139
|
+
/** Store what the transform made of `code`: `{ code, dependencies }`. */
|
|
140
|
+
set(filename, code, result) {
|
|
141
|
+
const target = entryPath(filename);
|
|
142
|
+
const temporary = `${target}.${process.pid}.${threadId}.${randomBytes(4).toString("hex")}.tmp`;
|
|
143
|
+
try {
|
|
144
|
+
const dependencies = result.dependencies.map((file) => [file, dependencyDigest(file)]);
|
|
145
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
146
|
+
writeFileSync(temporary, JSON.stringify({ format: FORMAT, file: filename, source: digest(code), dependencies, code: result.code }));
|
|
147
|
+
renameSync(temporary, target);
|
|
148
|
+
} catch {
|
|
149
|
+
// A dependency gone in between, a full disk, a read-only directory: just don't cache.
|
|
150
|
+
rmSync(temporary, { force: true });
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
prune(target);
|
|
154
|
+
sweep(dir);
|
|
155
|
+
},
|
|
156
|
+
};
|
|
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
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
// The plugin is typed by its own shape, not with Vite's `Plugin`: a copy of Vite's types (as
|
|
2
|
+
// vite-plus ships) is a different `Plugin`, and the two don't match under
|
|
3
|
+
// `exactOptionalPropertyTypes`. Only the hooks the plugin defines, with the parameters it
|
|
4
|
+
// reads, so it is assignable to the `Plugin` of Vite, Rolldown or Rollup.
|
|
2
5
|
|
|
3
6
|
export type SafeTsOptions = {
|
|
4
7
|
/**
|
|
@@ -11,13 +14,110 @@ export type SafeTsOptions = {
|
|
|
11
14
|
* names, so Chrome 136+ compiles their functions eagerly. Off by default.
|
|
12
15
|
*/
|
|
13
16
|
compileHints?: boolean | string[];
|
|
17
|
+
/**
|
|
18
|
+
* Insert dev-only runtime checks. By default on for Vite's dev server and off for
|
|
19
|
+
* `vite build` and other bundlers.
|
|
20
|
+
*/
|
|
21
|
+
devChecks?: boolean;
|
|
22
|
+
/**
|
|
23
|
+
* Generate the validator (and test-data generator) of each named type once, in a module of
|
|
24
|
+
* its own that every file using it imports, instead of a copy per file. On by default.
|
|
25
|
+
*/
|
|
26
|
+
sharedValidators?: boolean;
|
|
14
27
|
};
|
|
15
28
|
|
|
29
|
+
/** A source map, as the plugin returns it. */
|
|
30
|
+
export type SafeTsSourceMap = {
|
|
31
|
+
version: number;
|
|
32
|
+
file?: string;
|
|
33
|
+
sources: string[];
|
|
34
|
+
sourcesContent?: string[];
|
|
35
|
+
names: string[];
|
|
36
|
+
mappings: string;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** The bundler plugin (Vite, Rolldown, Rollup share these hooks). */
|
|
40
|
+
export interface SafeTsPlugin {
|
|
41
|
+
name: "safe-ts";
|
|
42
|
+
enforce: "pre";
|
|
43
|
+
configResolved(config: {
|
|
44
|
+
readonly root: string;
|
|
45
|
+
readonly command: "build" | "serve";
|
|
46
|
+
readonly configFile?: string | undefined;
|
|
47
|
+
readonly logger: { warn(message: string): void };
|
|
48
|
+
}): void;
|
|
49
|
+
resolveId(
|
|
50
|
+
this: { resolve(source: string, importer?: string, options?: { skipSelf?: boolean }): Promise<{ id: string } | null> },
|
|
51
|
+
source: string,
|
|
52
|
+
importer: string | undefined,
|
|
53
|
+
options: object,
|
|
54
|
+
): Promise<{ id: string } | string | null>;
|
|
55
|
+
load(this: { addWatchFile?(id: string): void } | void, id: string): { code: string; map: null; moduleType: "ts" } | null;
|
|
56
|
+
transform(
|
|
57
|
+
this: {
|
|
58
|
+
warn(message: string): void;
|
|
59
|
+
error(error: { message: string; id: string; loc: { line: number; column: number } }): never;
|
|
60
|
+
addWatchFile?(id: string): void;
|
|
61
|
+
},
|
|
62
|
+
code: string,
|
|
63
|
+
id: string,
|
|
64
|
+
): { code: string; map: SafeTsSourceMap } | null;
|
|
65
|
+
renderChunk(code: string, chunk: { readonly isEntry: boolean; readonly name: string }): { code: string; map: SafeTsSourceMap } | null;
|
|
66
|
+
generateBundle(options: unknown, bundle: { [fileName: string]: object }): void;
|
|
67
|
+
}
|
|
68
|
+
|
|
16
69
|
/** Bundler plugin (Vite, Rolldown, Rollup): rewrites q(), match(), parseJson<T>() and more. */
|
|
17
|
-
export function safeTs(options?: SafeTsOptions):
|
|
70
|
+
export function safeTs(options?: SafeTsOptions): SafeTsPlugin;
|
|
18
71
|
|
|
19
72
|
/** Rewrite one file. Throws with all errors if the file can't be transformed. */
|
|
20
|
-
export function transform(filename: string, code: string): string;
|
|
73
|
+
export function transform(filename: string, code: string, options?: { devChecks?: boolean }): string;
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* `transform`, also returning the other files the result depends on (imported types, `@inline`
|
|
77
|
+
* functions, enum tables, the tsconfig that turns the prelude on).
|
|
78
|
+
*/
|
|
79
|
+
export function transformWithDependencies(
|
|
80
|
+
filename: string,
|
|
81
|
+
code: string,
|
|
82
|
+
options?: { devChecks?: boolean; sharedValidators?: boolean },
|
|
83
|
+
): { code: string; dependencies: string[]; warnings: string[] };
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Import a module with the safe-ts transform from code that wasn't transformed (a Vite config:
|
|
87
|
+
* Vite loads it without plugins). Registers the Node loader's hooks in this process, then
|
|
88
|
+
* imports `url` through them; returns the module's exports.
|
|
89
|
+
*
|
|
90
|
+
* ```ts
|
|
91
|
+
* const { offlinePage } = await loadTransformed<typeof import("./scripts/plugins.ts")>(
|
|
92
|
+
* new URL("./scripts/plugins.ts", import.meta.url),
|
|
93
|
+
* );
|
|
94
|
+
* ```
|
|
95
|
+
*/
|
|
96
|
+
export function loadTransformed<Module = Record<string, unknown>>(url: URL | string): Promise<Module>;
|
|
97
|
+
|
|
98
|
+
/** The query parameter of a shared validator module: `/src/types.ts?safe-ts-json=v$User`. */
|
|
99
|
+
export const SHARED_QUERY: "safe-ts-json";
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* With `sharedValidators`, transformed files import the validators of named types from
|
|
103
|
+
* `<declaring file>?safe-ts-json=<key>`. The declaring file and key of such an id, or undefined.
|
|
104
|
+
*/
|
|
105
|
+
export function sharedModuleId(id: string): { file: string; key: string } | undefined;
|
|
106
|
+
|
|
107
|
+
/** The shared module `key` of types declared in `file`, and the files it was built from. */
|
|
108
|
+
export function sharedModule(file: string, key: string): { code: string; dependencies: string[] };
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Whether the Node loader inserts dev checks: yes unless `NODE_ENV=production`;
|
|
112
|
+
* `SAFE_TS_DEV_CHECKS=1` / `=0` overrides that.
|
|
113
|
+
*/
|
|
114
|
+
export function devChecksEnabled(env: Record<string, string | undefined>): boolean;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The warning the plugin prints when the Vite config imports code that only works after the
|
|
118
|
+
* transform (Vite loads its config without plugins), or undefined.
|
|
119
|
+
*/
|
|
120
|
+
export function configFileWarning(configFile: string | undefined): string | undefined;
|
|
21
121
|
|
|
22
122
|
/** Source map for a line-preserving rewrite (every generated line maps to its original line). */
|
|
23
123
|
export function lineMap(
|
package/index.mjs
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
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";
|
|
5
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
6
|
+
import { pathToFileURL } from "node:url";
|
|
4
7
|
|
|
5
8
|
import MagicString from "magic-string";
|
|
6
9
|
|
|
@@ -17,12 +20,65 @@ const VUE_FILE = /\.vue$/;
|
|
|
17
20
|
* (https://safe-ts.evobug-pages.com/guide/dev-checks). Off unless set.
|
|
18
21
|
*/
|
|
19
22
|
export function transform(filename, code, options = {}) {
|
|
20
|
-
|
|
23
|
+
return transformWithDependencies(filename, code, options).code;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* `transform`, also returning the other files the result depends on (types, `@inline`
|
|
28
|
+
* functions and enum tables read from imports, the tsconfig that turns the prelude on): a
|
|
29
|
+
* cached result stays valid while none of them changes. Used by the Node loader's cache.
|
|
30
|
+
*/
|
|
31
|
+
export function transformWithDependencies(filename, code, options = {}) {
|
|
32
|
+
const result = native.transform(filename, code, {
|
|
33
|
+
devChecks: options.devChecks === true,
|
|
34
|
+
sharedValidators: options.sharedValidators === true,
|
|
35
|
+
});
|
|
21
36
|
if (result.errors.length > 0) {
|
|
22
37
|
const lines = result.errors.map((e) => ` ${filename}:${e.line}:${e.column + 1} ${e.rule}: ${e.message}`);
|
|
23
38
|
throw new Error(`safe-ts transform failed:\n${lines.join("\n")}`);
|
|
24
39
|
}
|
|
25
|
-
return result.code;
|
|
40
|
+
return { code: result.code, dependencies: result.dependencies ?? [], warnings: result.warnings ?? [] };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Import `url` (a `file:` URL, `URL`, or absolute path) with the safe-ts transform, from code
|
|
45
|
+
* that itself wasn't transformed: a Vite config, which Vite loads without plugins. Registers the
|
|
46
|
+
* Node loader's hooks in this process (as `--import @evobug_com/safe-ts-transform/register`
|
|
47
|
+
* does), then imports the module through them, so it and everything it imports are transformed.
|
|
48
|
+
* Returns the module's namespace: its exports, functions included. A module Node already loaded
|
|
49
|
+
* without the hooks stays as it was: load it only this way.
|
|
50
|
+
*/
|
|
51
|
+
export async function loadTransformed(url) {
|
|
52
|
+
await import("./register.mjs");
|
|
53
|
+
const href = url instanceof URL ? url.href : isAbsolute(String(url)) ? pathToFileURL(String(url)).href : String(url);
|
|
54
|
+
return import(href);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The query parameter of a shared validator module: `/src/types.ts?safe-ts-json=v$User`. */
|
|
58
|
+
export const SHARED_QUERY = "safe-ts-json";
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* With `sharedValidators`, a transformed file imports the validators and generators of named
|
|
62
|
+
* types from shared modules, `<declaring file>?safe-ts-json=<key>`, one per type and options,
|
|
63
|
+
* instead of generating its own copies. This tells such an id or URL path apart: the declaring
|
|
64
|
+
* file and the key, or undefined.
|
|
65
|
+
*/
|
|
66
|
+
export function sharedModuleId(id) {
|
|
67
|
+
const at = id.indexOf("?");
|
|
68
|
+
if (at < 0) return undefined;
|
|
69
|
+
const key = new URLSearchParams(id.slice(at + 1)).get(SHARED_QUERY);
|
|
70
|
+
return key === null ? undefined : { file: id.slice(0, at), key };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The shared module `key` of types declared in `file` (see `sharedModuleId`), and the files it
|
|
75
|
+
* was built from (`file` included): it stays valid while none of them changes. Throws if `file`
|
|
76
|
+
* no longer declares the type.
|
|
77
|
+
*/
|
|
78
|
+
export function sharedModule(file, key) {
|
|
79
|
+
const result = native.sharedModule(file, key);
|
|
80
|
+
if (result.code == null) throw new Error(`safe-ts: shared validators ${file}?${SHARED_QUERY}=${key}: ${result.error}`);
|
|
81
|
+
return { code: result.code, dependencies: result.dependencies };
|
|
26
82
|
}
|
|
27
83
|
|
|
28
84
|
/**
|
|
@@ -69,11 +125,16 @@ export function lineMap(file, original, transformed) {
|
|
|
69
125
|
* devChecks: insert dev-only runtime checks (https://safe-ts.evobug-pages.com/guide/dev-checks).
|
|
70
126
|
* By default on for Vite's dev server (`vite`, `vite dev`, `vite serve`, and tools built on
|
|
71
127
|
* it in serve mode, like Vitest) and off for `vite build`, `vite preview` and other bundlers.
|
|
128
|
+
* sharedValidators: generate the validator (and test-data generator) of each named type once,
|
|
129
|
+
* in a module of its own that every file using it imports, instead of a copy per file. On by
|
|
130
|
+
* default; false gives every file its own copies, as before.
|
|
72
131
|
*/
|
|
73
132
|
export function safeTs(options = {}) {
|
|
74
133
|
const check = options.check ?? "warn";
|
|
75
134
|
const hints = options.compileHints ?? false;
|
|
135
|
+
const wantsHint = (chunk) => (hints === true ? chunk.isEntry : Array.isArray(hints) && hints.includes(chunk.name));
|
|
76
136
|
let devChecks = options.devChecks ?? false;
|
|
137
|
+
const sharedValidators = options.sharedValidators ?? true;
|
|
77
138
|
let root = process.cwd();
|
|
78
139
|
let checker;
|
|
79
140
|
return {
|
|
@@ -82,8 +143,34 @@ export function safeTs(options = {}) {
|
|
|
82
143
|
configResolved(config) {
|
|
83
144
|
root = config.root;
|
|
84
145
|
devChecks = options.devChecks ?? config.command === "serve";
|
|
146
|
+
const warning = configFileWarning(config.configFile);
|
|
147
|
+
if (warning !== undefined) config.logger.warn(warning);
|
|
148
|
+
},
|
|
149
|
+
// `./types.ts?safe-ts-json=v$User`, imported by transformed files: the declaring file with
|
|
150
|
+
// the query. A bare import in such a module (the std helpers) resolves from the declaring
|
|
151
|
+
// file, or else from the root (a package of types may not depend on the std library).
|
|
152
|
+
async resolveId(source, importer, resolveOptions) {
|
|
153
|
+
if (importer === undefined || importer.startsWith("\0")) return null;
|
|
154
|
+
const importerFile = importer.split("?")[0];
|
|
155
|
+
const shared = sharedModuleId(source);
|
|
156
|
+
if (shared !== undefined && /^\.\.?\//.test(source)) {
|
|
157
|
+
return `${resolve(dirname(importerFile), shared.file).replaceAll("\\", "/")}?${SHARED_QUERY}=${shared.key}`;
|
|
158
|
+
}
|
|
159
|
+
if (sharedModuleId(importer) === undefined || /^[./\0]/.test(source)) return null;
|
|
160
|
+
const options = { ...resolveOptions, skipSelf: true };
|
|
161
|
+
return (await this.resolve(source, importerFile, options)) ?? this.resolve(source, join(root, "index.html"), options);
|
|
162
|
+
},
|
|
163
|
+
load(id) {
|
|
164
|
+
const shared = sharedModuleId(id);
|
|
165
|
+
if (shared === undefined) return null;
|
|
166
|
+
const module = sharedModule(shared.file, shared.key);
|
|
167
|
+
// The dev server invalidates the module when the declaring file changes; these cover the
|
|
168
|
+
// rest (types it extends or picks from elsewhere).
|
|
169
|
+
if (typeof this?.addWatchFile === "function") for (const file of module.dependencies) this.addWatchFile(file);
|
|
170
|
+
return { code: module.code, map: null, moduleType: "ts" };
|
|
85
171
|
},
|
|
86
172
|
transform(code, id) {
|
|
173
|
+
if (sharedModuleId(id) !== undefined) return null;
|
|
87
174
|
const [file, query] = id.split("?");
|
|
88
175
|
// `App.vue?vue&type=script...`: parts @vitejs/plugin-vue serves from the SFC it got from us.
|
|
89
176
|
const wanted = VUE_FILE.test(file) ? query === undefined : TS_FILE.test(file);
|
|
@@ -101,15 +188,79 @@ export function safeTs(options = {}) {
|
|
|
101
188
|
}
|
|
102
189
|
}
|
|
103
190
|
}
|
|
104
|
-
const out =
|
|
191
|
+
const { code: out, dependencies, warnings } = transformWithDependencies(file, code, { devChecks, sharedValidators });
|
|
192
|
+
for (const warning of warnings) this.warn(`safe-ts: ${warning}`);
|
|
193
|
+
// Generated validators follow the types they were made from, wherever those are declared.
|
|
194
|
+
// (Not when a wrapper plugin calls this hook without a context.)
|
|
195
|
+
if (typeof this?.addWatchFile === "function") for (const dependency of dependencies) this.addWatchFile(dependency);
|
|
105
196
|
return out === code ? null : { code: out, map: lineMap(file, code, out) };
|
|
106
197
|
},
|
|
107
198
|
renderChunk(code, chunk) {
|
|
108
|
-
|
|
109
|
-
if (!wanted) return null;
|
|
199
|
+
if (!wantsHint(chunk)) return null;
|
|
110
200
|
const s = new MagicString(code);
|
|
111
|
-
s.prepend(
|
|
201
|
+
s.prepend(`${COMPILE_HINT}\n`);
|
|
112
202
|
return { code: s.toString(), map: s.generateMap({ hires: true }) };
|
|
113
203
|
},
|
|
204
|
+
// A minifier that runs after `renderChunk` (Rolldown's, in Vite 8) drops the comment: put it
|
|
205
|
+
// back on the final code, and move the source map down by the line it takes.
|
|
206
|
+
generateBundle(_options, bundle) {
|
|
207
|
+
for (const chunk of Object.values(bundle)) {
|
|
208
|
+
if (chunk.type !== "chunk" || !wantsHint(chunk) || chunk.code.startsWith(COMPILE_HINT)) continue;
|
|
209
|
+
chunk.code = `${COMPILE_HINT}\n${chunk.code}`;
|
|
210
|
+
if (chunk.map) chunk.map.mappings = `;${chunk.map.mappings}`;
|
|
211
|
+
const mapFile = bundle[chunk.sourcemapFileName ?? `${chunk.fileName}.map`];
|
|
212
|
+
if (mapFile?.type === "asset") {
|
|
213
|
+
const map = JSON.parse(String(typeof mapFile.source === "string" ? mapFile.source : new TextDecoder().decode(mapFile.source)));
|
|
214
|
+
map.mappings = `;${map.mappings}`;
|
|
215
|
+
mapFile.source = JSON.stringify(map);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
},
|
|
114
219
|
};
|
|
115
220
|
}
|
|
221
|
+
|
|
222
|
+
const COMPILE_HINT = "//# allFunctionsCalledOnLoad";
|
|
223
|
+
|
|
224
|
+
/** Set by the Node loader (`register.mjs`): the files it transformed in this process. */
|
|
225
|
+
const LOADED = Symbol.for("safe-ts.loader.files");
|
|
226
|
+
|
|
227
|
+
/** The loader's hooks, imported by a config: they apply only to what it loads afterwards. */
|
|
228
|
+
const REGISTER_IMPORT = /["']@evobug_com\/safe-ts-transform\/register(?:\.mjs)?["']/;
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Vite loads its config file, and what the config imports, without plugins: code there that
|
|
232
|
+
* needs the transform fails (`PropagateError is not defined`, "q() was not compiled"). Unless
|
|
233
|
+
* the Node loader transformed it (`--configLoader native` with the loader registered first).
|
|
234
|
+
* Only what runs counts: imports of types, `import()` and `loadTransformed(...)` are left out.
|
|
235
|
+
*/
|
|
236
|
+
export function configFileWarning(configFile) {
|
|
237
|
+
if (typeof configFile !== "string" || globalThis[LOADED]?.has(configFile)) return undefined;
|
|
238
|
+
let needs;
|
|
239
|
+
try {
|
|
240
|
+
needs = native.transformNeeds(configFile);
|
|
241
|
+
} catch {
|
|
242
|
+
return undefined;
|
|
243
|
+
}
|
|
244
|
+
const untransformed = needs.filter((n) => !globalThis[LOADED]?.has(n.file));
|
|
245
|
+
if (untransformed.length === 0) return undefined;
|
|
246
|
+
const lines = untransformed.map((n) => ` ${n.file}: uses ${n.needs}`);
|
|
247
|
+
let registers = false;
|
|
248
|
+
try {
|
|
249
|
+
registers = REGISTER_IMPORT.test(readFileSync(configFile, "utf8"));
|
|
250
|
+
} catch {
|
|
251
|
+
// Gone in between: no hint.
|
|
252
|
+
}
|
|
253
|
+
const register = registers
|
|
254
|
+
? "Importing @evobug_com/safe-ts-transform/register in the config doesn't cover these: a module's imports " +
|
|
255
|
+
"load before its code runs, so the hooks apply only to what the config loads later (`import()` in a hook, " +
|
|
256
|
+
"`loadTransformed(...)`).\n"
|
|
257
|
+
: "";
|
|
258
|
+
return (
|
|
259
|
+
`safe-ts: Vite loads ${configFile} without the safe-ts transform (plugins don't apply to the config), ` +
|
|
260
|
+
`but it imports code that needs it:\n${lines.join("\n")}\n${register}` +
|
|
261
|
+
"That code fails when it runs. Load it with `await loadTransformed(new URL(\"./plugins.ts\", import.meta.url))` " +
|
|
262
|
+
"from @evobug_com/safe-ts-transform, start Vite with `--configLoader native` and " +
|
|
263
|
+
'NODE_OPTIONS="--import @evobug_com/safe-ts-transform/register", or keep code the config imports free of it: ' +
|
|
264
|
+
"https://safe-ts.evobug-pages.com/guide/adoption#the-vite-config"
|
|
265
|
+
);
|
|
266
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@evobug_com/safe-ts-transform",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "SAFE-TS build-time transform: a Vite/Rolldown/Rollup plugin and a Node loader that rewrite q(), match(), parseJson<T>(), loops and @inline, and run the SAFE-TS checks.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"safe-ts",
|
|
@@ -35,6 +35,7 @@
|
|
|
35
35
|
"index.mjs",
|
|
36
36
|
"index.d.ts",
|
|
37
37
|
"register.mjs",
|
|
38
|
+
"cache.mjs",
|
|
38
39
|
"LICENSE-MIT",
|
|
39
40
|
"LICENSE-APACHE"
|
|
40
41
|
],
|
|
@@ -42,12 +43,12 @@
|
|
|
42
43
|
"node": ">=22.18.0"
|
|
43
44
|
},
|
|
44
45
|
"dependencies": {
|
|
45
|
-
"@evobug_com/safe-ts-native": "0.
|
|
46
|
+
"@evobug_com/safe-ts-native": "0.3.0",
|
|
46
47
|
"magic-string": "^1.4.5"
|
|
47
48
|
},
|
|
48
49
|
"peerDependencies": {
|
|
49
|
-
"@evobug_com/safe-ts-std": "^0.
|
|
50
|
-
"vite": "
|
|
50
|
+
"@evobug_com/safe-ts-std": "^0.3.0",
|
|
51
|
+
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
|
51
52
|
},
|
|
52
53
|
"peerDependenciesMeta": {
|
|
53
54
|
"vite": {
|
package/register.mjs
CHANGED
|
@@ -2,21 +2,40 @@
|
|
|
2
2
|
// node --import ./packages/safe-ts-transform/register.mjs src/main.ts
|
|
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
|
+
// 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.
|
|
8
|
+
// The validators of named types are generated once, in shared modules every file using them
|
|
9
|
+
// imports (`<declaring file>?safe-ts-json=<key>`, served here); SAFE_TS_SHARED_VALIDATORS=0
|
|
10
|
+
// gives every file its own copies instead.
|
|
5
11
|
import { readFileSync } from "node:fs";
|
|
6
12
|
import { registerHooks } from "node:module";
|
|
7
|
-
import {
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
8
15
|
|
|
9
|
-
import {
|
|
16
|
+
import { openCache } from "./cache.mjs";
|
|
17
|
+
import { devChecksEnabled, sharedModule, sharedModuleId, transformWithDependencies } from "./index.mjs";
|
|
10
18
|
|
|
11
19
|
const TS_FILE = /\.(ts|mts)$/;
|
|
12
20
|
const HAS_EXTENSION = /\.[cm]?[jt]sx?$/;
|
|
13
21
|
const devChecks = devChecksEnabled(process.env);
|
|
22
|
+
const sharedValidators = !["0", "false"].includes(process.env.SAFE_TS_SHARED_VALIDATORS ?? "");
|
|
23
|
+
const cache = openCache(process.env, { devChecks, sharedValidators });
|
|
24
|
+
|
|
25
|
+
// The files this thread transformed, for the Vite plugin's config check (index.mjs).
|
|
26
|
+
const loaded = (globalThis[Symbol.for("safe-ts.loader.files")] ??= new Set());
|
|
27
|
+
const warned = new Set();
|
|
14
28
|
|
|
15
29
|
registerHooks({
|
|
16
30
|
resolve(specifier, context, nextResolve) {
|
|
17
31
|
try {
|
|
18
32
|
return nextResolve(specifier, context);
|
|
19
33
|
} catch (error) {
|
|
34
|
+
// A shared module imports the std helpers from the declaring file's directory; a package
|
|
35
|
+
// of types may not depend on the std library, so then from the current directory.
|
|
36
|
+
if (error?.code === "ERR_MODULE_NOT_FOUND" && context.parentURL && sharedModuleId(context.parentURL) !== undefined) {
|
|
37
|
+
return nextResolve(specifier, { ...context, parentURL: pathToFileURL(join(process.cwd(), "index.js")).href });
|
|
38
|
+
}
|
|
20
39
|
// Extensionless relative imports, as with bundlers / `moduleResolution: "Bundler"`.
|
|
21
40
|
if (error?.code === "ERR_MODULE_NOT_FOUND" && /^\.\.?\//.test(specifier) && !HAS_EXTENSION.test(specifier)) {
|
|
22
41
|
return nextResolve(`${specifier}.ts`, context);
|
|
@@ -25,11 +44,36 @@ registerHooks({
|
|
|
25
44
|
}
|
|
26
45
|
},
|
|
27
46
|
load(url, context, nextLoad) {
|
|
47
|
+
const shared = url.startsWith("file:") ? sharedModuleId(url) : undefined;
|
|
48
|
+
if (shared !== undefined) {
|
|
49
|
+
// One module per key; its cache entry depends on the declarations it was built from.
|
|
50
|
+
const file = fileURLToPath(shared.file);
|
|
51
|
+
let source = cache?.get(url, shared.key);
|
|
52
|
+
if (source === undefined) {
|
|
53
|
+
const module = sharedModule(file, shared.key);
|
|
54
|
+
source = module.code;
|
|
55
|
+
cache?.set(url, shared.key, module);
|
|
56
|
+
}
|
|
57
|
+
return { format: "module-typescript", source, shortCircuit: true };
|
|
58
|
+
}
|
|
28
59
|
if (!url.startsWith("file:") || !TS_FILE.test(new URL(url).pathname) || url.includes("/node_modules/")) {
|
|
29
60
|
return nextLoad(url, context);
|
|
30
61
|
}
|
|
31
62
|
const filename = fileURLToPath(url);
|
|
32
|
-
const
|
|
63
|
+
const code = readFileSync(filename, "utf8");
|
|
64
|
+
let source = cache?.get(filename, code);
|
|
65
|
+
if (source === undefined) {
|
|
66
|
+
const result = transformWithDependencies(filename, code, { devChecks, sharedValidators });
|
|
67
|
+
source = result.code;
|
|
68
|
+
// A file with a warning isn't cached, so the warning shows on every run until it's fixed.
|
|
69
|
+
if (result.warnings.length === 0) cache?.set(filename, code, result);
|
|
70
|
+
for (const warning of result.warnings) {
|
|
71
|
+
// Right away (not `process.emitWarning`, which waits a tick): the file may fail as it loads.
|
|
72
|
+
if (!warned.has(warning)) process.stderr.write(`safe-ts warning: ${warning}\n`);
|
|
73
|
+
warned.add(warning);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
loaded.add(filename);
|
|
33
77
|
return { format: "module-typescript", source, shortCircuit: true };
|
|
34
78
|
},
|
|
35
79
|
});
|