@evobug_com/safe-ts-transform 0.0.0-stage → 0.2.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/LICENSE-APACHE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Evobug
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,16 @@
1
- # Temporary Holding Version
1
+ # @evobug_com/safe-ts-transform
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 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.
4
+
5
+ **Documentation: [safe-ts.evobug-pages.com/guide/adoption](https://safe-ts.evobug-pages.com/guide/adoption)**
6
+
7
+ ```sh
8
+ npm install -D @evobug_com/safe-ts-transform
9
+ ```
10
+
11
+ Part of [SAFE-TS](https://safe-ts.evobug-pages.com/), a strict, Rust-flavoured subset of TypeScript. The website has the
12
+ guides, a page per rule, and a playground that runs the checker in your browser.
13
+
14
+ Changes in each version: [CHANGELOG.md](https://git.evobug.com/Evobug/Safe-Ts/src/branch/main/CHANGELOG.md).
15
+
16
+ Source: https://git.evobug.com/Evobug/Safe-Ts. Licensed under MIT OR Apache-2.0.
package/cache.mjs ADDED
@@ -0,0 +1,138 @@
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 entry per file and set of options: a later version of the file replaces it, so the cache
5
+ // doesn't grow with edits. A shared validator module (`<file>?safe-ts-json=<key>`) is an entry
6
+ // of its own, keyed by its URL; its "content" is the key, and its dependencies are the
7
+ // declarations it was built from, the declaring file first. An entry is used only when the file's content, every file the
8
+ // transform read for it (imported types, `@inline` functions, enum tables, the tsconfig), the
9
+ // transform's version and the options all match. Entries are written to a temporary file and
10
+ // renamed into place, so threads and processes writing at once never leave a partial entry.
11
+ //
12
+ // Where: SAFE_TS_CACHE_DIR, else node_modules/.cache/safe-ts in the nearest directory above the
13
+ // current one that has node_modules, else the system's temporary directory. SAFE_TS_CACHE=0 (or
14
+ // false) turns it off. Problems with the cache never fail a load: the file is transformed.
15
+ import { createRequire } from "node:module";
16
+ import { hash, randomBytes } from "node:crypto";
17
+ import { accessSync, constants, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
18
+ import { tmpdir } from "node:os";
19
+ import { dirname, join } from "node:path";
20
+ import { threadId } from "node:worker_threads";
21
+
22
+ const require = createRequire(import.meta.url);
23
+
24
+ /** Bumped when the entry format changes. */
25
+ const FORMAT = 1;
26
+
27
+ const digest = (data) => hash("sha256", data, "hex");
28
+
29
+ /**
30
+ * What produced the code: this package (which pins the native addon's version), and the addon
31
+ * file itself, so a rebuilt addon of the same version doesn't reuse old output.
32
+ */
33
+ function transformVersion() {
34
+ const native = require("@evobug_com/safe-ts-native");
35
+ const versions = [require("./package.json").version];
36
+ try {
37
+ const addon = statSync(native.loadedFrom);
38
+ versions.push(native.loadedFrom, addon.size, addon.mtimeMs);
39
+ } catch {
40
+ // An addon loaded some other way: the package versions alone.
41
+ }
42
+ return versions;
43
+ }
44
+
45
+ function writableDir(dir) {
46
+ try {
47
+ mkdirSync(dir, { recursive: true });
48
+ accessSync(dir, constants.W_OK);
49
+ return dir;
50
+ } catch {
51
+ return undefined;
52
+ }
53
+ }
54
+
55
+ /** The directory for the cache: see the top of this file. */
56
+ export function cacheDir(env, cwd = process.cwd()) {
57
+ if (env.SAFE_TS_CACHE_DIR) return writableDir(env.SAFE_TS_CACHE_DIR);
58
+ for (let dir = cwd; ; dir = dirname(dir)) {
59
+ let found = false;
60
+ try {
61
+ found = statSync(join(dir, "node_modules")).isDirectory();
62
+ } catch {
63
+ // Not here; look further up.
64
+ }
65
+ if (found) {
66
+ const usable = writableDir(join(dir, "node_modules", ".cache", "safe-ts"));
67
+ if (usable !== undefined) return usable;
68
+ break;
69
+ }
70
+ if (dirname(dir) === dir) break;
71
+ }
72
+ const user = typeof process.getuid === "function" ? process.getuid() : "user";
73
+ return writableDir(join(tmpdir(), `safe-ts-cache-${user}`));
74
+ }
75
+
76
+ /**
77
+ * The cache for this process, or undefined when it is turned off or no directory is writable.
78
+ *
79
+ * @param {Record<string, string | undefined>} env
80
+ * @param {{ devChecks: boolean, sharedValidators?: boolean }} options what the transform is asked
81
+ * for: part of each key.
82
+ */
83
+ export function openCache(env, options) {
84
+ const flag = env.SAFE_TS_CACHE;
85
+ if (flag === "0" || flag === "false") return undefined;
86
+ const dir = cacheDir(env);
87
+ if (dir === undefined) return undefined;
88
+ // Dev checks name files relative to the current directory: it is part of the key too.
89
+ const version = JSON.stringify([FORMAT, transformVersion(), options.devChecks === true, options.sharedValidators === true, process.cwd()]);
90
+ const entryPath = (filename) => join(dir, `${digest(`${version}\0${filename}`).slice(0, 40)}.json`);
91
+ // Many files depend on the same few (the tsconfig, std modules): hash each version once.
92
+ const dependencyDigests = new Map();
93
+ const dependencyDigest = (file) => {
94
+ const { mtimeMs, size } = statSync(file);
95
+ const known = dependencyDigests.get(file);
96
+ if (known?.mtimeMs === mtimeMs && known.size === size) return known.digest;
97
+ const found = digest(readFileSync(file));
98
+ dependencyDigests.set(file, { mtimeMs, size, digest: found });
99
+ return found;
100
+ };
101
+
102
+ return {
103
+ dir,
104
+ /** The cached code for `filename` with content `code`, if still valid. */
105
+ get(filename, code) {
106
+ let entry;
107
+ try {
108
+ entry = JSON.parse(readFileSync(entryPath(filename), "utf8"));
109
+ } catch {
110
+ return undefined;
111
+ }
112
+ if (entry?.format !== FORMAT || entry.source !== digest(code) || typeof entry.code !== "string") return undefined;
113
+ for (const [file, expected] of entry.dependencies ?? []) {
114
+ let actual;
115
+ try {
116
+ actual = dependencyDigest(file);
117
+ } catch {
118
+ return undefined;
119
+ }
120
+ if (actual !== expected) return undefined;
121
+ }
122
+ return entry.code;
123
+ },
124
+ /** Store what the transform made of `code`: `{ code, dependencies }`. */
125
+ set(filename, code, result) {
126
+ const target = entryPath(filename);
127
+ const temporary = `${target}.${process.pid}.${threadId}.${randomBytes(4).toString("hex")}.tmp`;
128
+ try {
129
+ const dependencies = result.dependencies.map((file) => [file, dependencyDigest(file)]);
130
+ writeFileSync(temporary, JSON.stringify({ format: FORMAT, source: digest(code), dependencies, code: result.code }));
131
+ renameSync(temporary, target);
132
+ } catch {
133
+ // A dependency gone in between, a full disk, a read-only directory: just don't cache.
134
+ rmSync(temporary, { force: true });
135
+ }
136
+ },
137
+ };
138
+ }
package/index.d.ts ADDED
@@ -0,0 +1,114 @@
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.
5
+
6
+ export type SafeTsOptions = {
7
+ /**
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; false turns it off.
10
+ */
11
+ check?: "warn" | "error" | false;
12
+ /**
13
+ * Add `//# allFunctionsCalledOnLoad` to entry chunks (`true`) or to the chunks with these
14
+ * names, so Chrome 136+ compiles their functions eagerly. Off by default.
15
+ */
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;
27
+ };
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
+
69
+ /** Bundler plugin (Vite, Rolldown, Rollup): rewrites q(), match(), parseJson<T>() and more. */
70
+ export function safeTs(options?: SafeTsOptions): SafeTsPlugin;
71
+
72
+ /** Rewrite one file. Throws with all errors if the file can't be transformed. */
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[] };
84
+
85
+ /** The query parameter of a shared validator module: `/src/types.ts?safe-ts-json=v$User`. */
86
+ export const SHARED_QUERY: "safe-ts-json";
87
+
88
+ /**
89
+ * With `sharedValidators`, transformed files import the validators of named types from
90
+ * `<declaring file>?safe-ts-json=<key>`. The declaring file and key of such an id, or undefined.
91
+ */
92
+ export function sharedModuleId(id: string): { file: string; key: string } | undefined;
93
+
94
+ /** 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[] };
96
+
97
+ /**
98
+ * Whether the Node loader inserts dev checks: yes unless `NODE_ENV=production`;
99
+ * `SAFE_TS_DEV_CHECKS=1` / `=0` overrides that.
100
+ */
101
+ export function devChecksEnabled(env: Record<string, string | undefined>): boolean;
102
+
103
+ /**
104
+ * The warning the plugin prints when the Vite config imports code that only works after the
105
+ * transform (Vite loads its config without plugins), or undefined.
106
+ */
107
+ export function configFileWarning(configFile: string | undefined): string | undefined;
108
+
109
+ /** Source map for a line-preserving rewrite (every generated line maps to its original line). */
110
+ export function lineMap(
111
+ file: string,
112
+ original: string,
113
+ transformed: string,
114
+ ): { version: 3; sources: string[]; sourcesContent: string[]; names: string[]; mappings: string };
package/index.mjs ADDED
@@ -0,0 +1,233 @@
1
+ // safe-ts build-time transform: prelude imports, parseJson<T> validators, match -> switch,
2
+ // and q(...) early returns. Every rewrite keeps the original line structure.
3
+ import { createRequire } from "node:module";
4
+ import { dirname, join, resolve } from "node:path";
5
+
6
+ import MagicString from "magic-string";
7
+
8
+ const require = createRequire(import.meta.url);
9
+ const native = require("@evobug_com/safe-ts-native");
10
+
11
+ const TS_FILE = /\.(ts|mts|cts|tsx)$/;
12
+ const VUE_FILE = /\.vue$/;
13
+
14
+ /**
15
+ * Rewrite one file. Throws with all errors if the file can't be transformed.
16
+ *
17
+ * @param {{ devChecks?: boolean }} [options] devChecks: insert the dev-only runtime checks
18
+ * (https://safe-ts.evobug-pages.com/guide/dev-checks). Off unless set.
19
+ */
20
+ export function transform(filename, code, options = {}) {
21
+ return transformWithDependencies(filename, code, options).code;
22
+ }
23
+
24
+ /**
25
+ * `transform`, also returning the other files the result depends on (types, `@inline`
26
+ * functions and enum tables read from imports, the tsconfig that turns the prelude on): a
27
+ * cached result stays valid while none of them changes. Used by the Node loader's cache.
28
+ */
29
+ export function transformWithDependencies(filename, code, options = {}) {
30
+ const result = native.transform(filename, code, {
31
+ devChecks: options.devChecks === true,
32
+ sharedValidators: options.sharedValidators === true,
33
+ });
34
+ if (result.errors.length > 0) {
35
+ const lines = result.errors.map((e) => ` ${filename}:${e.line}:${e.column + 1} ${e.rule}: ${e.message}`);
36
+ throw new Error(`safe-ts transform failed:\n${lines.join("\n")}`);
37
+ }
38
+ return { code: result.code, dependencies: result.dependencies ?? [] };
39
+ }
40
+
41
+ /** The query parameter of a shared validator module: `/src/types.ts?safe-ts-json=v$User`. */
42
+ export const SHARED_QUERY = "safe-ts-json";
43
+
44
+ /**
45
+ * With `sharedValidators`, a transformed file imports the validators and generators of named
46
+ * types from shared modules, `<declaring file>?safe-ts-json=<key>`, one per type and options,
47
+ * instead of generating its own copies. This tells such an id or URL path apart: the declaring
48
+ * file and the key, or undefined.
49
+ */
50
+ export function sharedModuleId(id) {
51
+ const at = id.indexOf("?");
52
+ if (at < 0) return undefined;
53
+ const key = new URLSearchParams(id.slice(at + 1)).get(SHARED_QUERY);
54
+ return key === null ? undefined : { file: id.slice(0, at), key };
55
+ }
56
+
57
+ /**
58
+ * The shared module `key` of types declared in `file` (see `sharedModuleId`), and the files it
59
+ * was built from (`file` included): it stays valid while none of them changes. Throws if `file`
60
+ * no longer declares the type.
61
+ */
62
+ export function sharedModule(file, key) {
63
+ const result = native.sharedModule(file, key);
64
+ if (result.code == null) throw new Error(`safe-ts: shared validators ${file}?${SHARED_QUERY}=${key}: ${result.error}`);
65
+ return { code: result.code, dependencies: result.dependencies };
66
+ }
67
+
68
+ /**
69
+ * Whether the Node loader (`register.mjs`) inserts dev checks: yes unless
70
+ * `NODE_ENV=production`; `SAFE_TS_DEV_CHECKS=1` / `=0` (or `true` / `false`) overrides that.
71
+ */
72
+ export function devChecksEnabled(env) {
73
+ const flag = env.SAFE_TS_DEV_CHECKS;
74
+ if (flag === "1" || flag === "true") return true;
75
+ if (flag === "0" || flag === "false") return false;
76
+ return env.NODE_ENV !== "production";
77
+ }
78
+
79
+ /**
80
+ * Source map for a line-preserving rewrite: every generated line maps to the start of the
81
+ * same original line. Lines appended after the original end (generated validators) are
82
+ * left unmapped. Exact lines; columns point at the line start.
83
+ */
84
+ export function lineMap(file, original, transformed) {
85
+ const originalLines = original.split("\n").length;
86
+ const generatedLines = transformed.split("\n").length;
87
+ const segments = [];
88
+ for (let line = 0; line < generatedLines; line++) {
89
+ // VLQ: generated column 0, source 0, source line +1 (first: +0), source column 0.
90
+ segments.push(line >= originalLines ? "" : line === 0 ? "AAAA" : "AACA");
91
+ }
92
+ return { version: 3, sources: [file], sourcesContent: [original], names: [], mappings: segments.join(";") };
93
+ }
94
+
95
+ /**
96
+ * Bundler plugin (Vite, Rolldown, Rollup share this hook shape). Runs before TypeScript is
97
+ * stripped, on project files only (not node_modules). Vue components (`.vue`) are rewritten
98
+ * before `@vitejs/plugin-vue` compiles them: their script blocks, in place.
99
+ *
100
+ * @param {{ check?: "warn" | "error" | false, compileHints?: boolean | string[], devChecks?: boolean }} [options]
101
+ * check: run the safe-ts rules on every transformed file (the same checks as the editor).
102
+ * "warn" (default) prints problems in the terminal; "error" shows Vite's error overlay in
103
+ * the browser and fails the build; false turns it off.
104
+ * compileHints: add `//# allFunctionsCalledOnLoad` to entry chunks (`true`) or to the chunks
105
+ * with these names, so Chrome 136+ compiles their functions eagerly, in the background,
106
+ * instead of on first call (https://v8.dev/blog/explicit-compile-hints). It costs memory and
107
+ * compile time for functions that never run: use it for code that runs at startup. Off by
108
+ * default.
109
+ * devChecks: insert dev-only runtime checks (https://safe-ts.evobug-pages.com/guide/dev-checks).
110
+ * By default on for Vite's dev server (`vite`, `vite dev`, `vite serve`, and tools built on
111
+ * it in serve mode, like Vitest) and off for `vite build`, `vite preview` and other bundlers.
112
+ * sharedValidators: generate the validator (and test-data generator) of each named type once,
113
+ * in a module of its own that every file using it imports, instead of a copy per file. On by
114
+ * default; false gives every file its own copies, as before.
115
+ */
116
+ export function safeTs(options = {}) {
117
+ const check = options.check ?? "warn";
118
+ const hints = options.compileHints ?? false;
119
+ const wantsHint = (chunk) => (hints === true ? chunk.isEntry : Array.isArray(hints) && hints.includes(chunk.name));
120
+ let devChecks = options.devChecks ?? false;
121
+ const sharedValidators = options.sharedValidators ?? true;
122
+ let root = process.cwd();
123
+ let checker;
124
+ return {
125
+ name: "safe-ts",
126
+ enforce: "pre",
127
+ configResolved(config) {
128
+ root = config.root;
129
+ devChecks = options.devChecks ?? config.command === "serve";
130
+ const warning = configFileWarning(config.configFile);
131
+ if (warning !== undefined) config.logger.warn(warning);
132
+ },
133
+ // `./types.ts?safe-ts-json=v$User`, imported by transformed files: the declaring file with
134
+ // the query. A bare import in such a module (the std helpers) resolves from the declaring
135
+ // file, or else from the root (a package of types may not depend on the std library).
136
+ async resolveId(source, importer, resolveOptions) {
137
+ if (importer === undefined || importer.startsWith("\0")) return null;
138
+ const importerFile = importer.split("?")[0];
139
+ const shared = sharedModuleId(source);
140
+ if (shared !== undefined && /^\.\.?\//.test(source)) {
141
+ return `${resolve(dirname(importerFile), shared.file).replaceAll("\\", "/")}?${SHARED_QUERY}=${shared.key}`;
142
+ }
143
+ if (sharedModuleId(importer) === undefined || /^[./\0]/.test(source)) return null;
144
+ const options = { ...resolveOptions, skipSelf: true };
145
+ return (await this.resolve(source, importerFile, options)) ?? this.resolve(source, join(root, "index.html"), options);
146
+ },
147
+ load(id) {
148
+ const shared = sharedModuleId(id);
149
+ if (shared === undefined) return null;
150
+ const module = sharedModule(shared.file, shared.key);
151
+ // The dev server invalidates the module when the declaring file changes; these cover the
152
+ // rest (types it extends or picks from elsewhere).
153
+ if (typeof this?.addWatchFile === "function") for (const file of module.dependencies) this.addWatchFile(file);
154
+ return { code: module.code, map: null, moduleType: "ts" };
155
+ },
156
+ transform(code, id) {
157
+ if (sharedModuleId(id) !== undefined) return null;
158
+ const [file, query] = id.split("?");
159
+ // `App.vue?vue&type=script...`: parts @vitejs/plugin-vue serves from the SFC it got from us.
160
+ const wanted = VUE_FILE.test(file) ? query === undefined : TS_FILE.test(file);
161
+ if (!wanted || file.includes("/node_modules/")) return null;
162
+ if (check) {
163
+ checker ??= new native.Checker(root);
164
+ const problems = checker.checkFile(file, code);
165
+ if (problems.length > 0) {
166
+ const lines = problems.map((d) => ` ${file}:${d.line}:${d.column + 1} safe-ts(${d.rule}): ${d.message}`);
167
+ const message = `safe-ts: ${problems.length} problem(s)\n${lines.join("\n")}`;
168
+ if (check === "error") {
169
+ this.error({ message, id: file, loc: { line: problems[0].line, column: problems[0].column } });
170
+ } else {
171
+ this.warn(message);
172
+ }
173
+ }
174
+ }
175
+ const { code: out, dependencies } = transformWithDependencies(file, code, { devChecks, sharedValidators });
176
+ // Generated validators follow the types they were made from, wherever those are declared.
177
+ // (Not when a wrapper plugin calls this hook without a context.)
178
+ if (typeof this?.addWatchFile === "function") for (const dependency of dependencies) this.addWatchFile(dependency);
179
+ return out === code ? null : { code: out, map: lineMap(file, code, out) };
180
+ },
181
+ renderChunk(code, chunk) {
182
+ if (!wantsHint(chunk)) return null;
183
+ const s = new MagicString(code);
184
+ s.prepend(`${COMPILE_HINT}\n`);
185
+ return { code: s.toString(), map: s.generateMap({ hires: true }) };
186
+ },
187
+ // A minifier that runs after `renderChunk` (Rolldown's, in Vite 8) drops the comment: put it
188
+ // back on the final code, and move the source map down by the line it takes.
189
+ generateBundle(_options, bundle) {
190
+ for (const chunk of Object.values(bundle)) {
191
+ if (chunk.type !== "chunk" || !wantsHint(chunk) || chunk.code.startsWith(COMPILE_HINT)) continue;
192
+ chunk.code = `${COMPILE_HINT}\n${chunk.code}`;
193
+ if (chunk.map) chunk.map.mappings = `;${chunk.map.mappings}`;
194
+ const mapFile = bundle[chunk.sourcemapFileName ?? `${chunk.fileName}.map`];
195
+ if (mapFile?.type === "asset") {
196
+ const map = JSON.parse(String(typeof mapFile.source === "string" ? mapFile.source : new TextDecoder().decode(mapFile.source)));
197
+ map.mappings = `;${map.mappings}`;
198
+ mapFile.source = JSON.stringify(map);
199
+ }
200
+ }
201
+ },
202
+ };
203
+ }
204
+
205
+ const COMPILE_HINT = "//# allFunctionsCalledOnLoad";
206
+
207
+ /** Set by the Node loader (`register.mjs`): the files it transformed in this process. */
208
+ const LOADED = Symbol.for("safe-ts.loader.files");
209
+
210
+ /**
211
+ * Vite loads its config file, and what the config imports, without plugins: code there that
212
+ * needs the transform fails (`PropagateError is not defined`, "q() was not compiled"). Unless
213
+ * the Node loader transformed it (`--configLoader native` with the loader registered first).
214
+ */
215
+ export function configFileWarning(configFile) {
216
+ if (typeof configFile !== "string" || globalThis[LOADED]?.has(configFile)) return undefined;
217
+ let needs;
218
+ try {
219
+ needs = native.transformNeeds(configFile);
220
+ } catch {
221
+ return undefined;
222
+ }
223
+ const untransformed = needs.filter((n) => !globalThis[LOADED]?.has(n.file));
224
+ if (untransformed.length === 0) return undefined;
225
+ const lines = untransformed.map((n) => ` ${n.file}: uses ${n.needs}`);
226
+ return (
227
+ `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. Start Vite with `--configLoader native` and " +
230
+ 'NODE_OPTIONS="--import @evobug_com/safe-ts-transform/register", or keep code the config imports free of it: ' +
231
+ "https://safe-ts.evobug-pages.com/guide/adoption#the-vite-config"
232
+ );
233
+ }
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@evobug_com/safe-ts-transform",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
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
+ "keywords": [
6
+ "safe-ts",
7
+ "typescript",
8
+ "type-safety",
9
+ "vite-plugin",
10
+ "rollup-plugin",
11
+ "rolldown",
12
+ "node-loader",
13
+ "transform",
14
+ "result",
15
+ "pattern-matching"
16
+ ],
17
+ "license": "MIT OR Apache-2.0",
18
+ "homepage": "https://safe-ts.evobug-pages.com/guide/adoption",
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://git.evobug.com/Evobug/Safe-Ts.git",
22
+ "directory": "packages/safe-ts-transform"
23
+ },
24
+ "bugs": "https://git.evobug.com/Evobug/Safe-Ts/issues",
25
+ "type": "module",
26
+ "types": "./index.d.ts",
27
+ "exports": {
28
+ ".": {
29
+ "types": "./index.d.ts",
30
+ "default": "./index.mjs"
31
+ },
32
+ "./register": "./register.mjs"
33
+ },
34
+ "files": [
35
+ "index.mjs",
36
+ "index.d.ts",
37
+ "register.mjs",
38
+ "cache.mjs",
39
+ "LICENSE-MIT",
40
+ "LICENSE-APACHE"
41
+ ],
42
+ "engines": {
43
+ "node": ">=22.18.0"
44
+ },
45
+ "dependencies": {
46
+ "@evobug_com/safe-ts-native": "0.2.0",
47
+ "magic-string": "^1.4.5"
48
+ },
49
+ "peerDependencies": {
50
+ "@evobug_com/safe-ts-std": "^0.2.0",
51
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "vite": {
55
+ "optional": true
56
+ }
57
+ },
58
+ "publishConfig": {
59
+ "access": "public"
60
+ }
61
+ }
package/register.mjs ADDED
@@ -0,0 +1,70 @@
1
+ // Run TypeScript with `q(...)` support directly in Node (which strips types natively):
2
+ // node --import ./packages/safe-ts-transform/register.mjs src/main.ts
3
+ // Dev checks (https://safe-ts.evobug-pages.com/guide/dev-checks) are on unless
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
+ // The validators of named types are generated once, in shared modules every file using them
7
+ // imports (`<declaring file>?safe-ts-json=<key>`, served here); SAFE_TS_SHARED_VALIDATORS=0
8
+ // gives every file its own copies instead.
9
+ import { readFileSync } from "node:fs";
10
+ import { registerHooks } from "node:module";
11
+ import { join } from "node:path";
12
+ import { fileURLToPath, pathToFileURL } from "node:url";
13
+
14
+ import { openCache } from "./cache.mjs";
15
+ import { devChecksEnabled, sharedModule, sharedModuleId, transformWithDependencies } from "./index.mjs";
16
+
17
+ const TS_FILE = /\.(ts|mts)$/;
18
+ const HAS_EXTENSION = /\.[cm]?[jt]sx?$/;
19
+ const devChecks = devChecksEnabled(process.env);
20
+ const sharedValidators = !["0", "false"].includes(process.env.SAFE_TS_SHARED_VALIDATORS ?? "");
21
+ const cache = openCache(process.env, { devChecks, sharedValidators });
22
+
23
+ // The files this thread transformed, for the Vite plugin's config check (index.mjs).
24
+ const loaded = (globalThis[Symbol.for("safe-ts.loader.files")] ??= new Set());
25
+
26
+ registerHooks({
27
+ resolve(specifier, context, nextResolve) {
28
+ try {
29
+ return nextResolve(specifier, context);
30
+ } catch (error) {
31
+ // A shared module imports the std helpers from the declaring file's directory; a package
32
+ // of types may not depend on the std library, so then from the current directory.
33
+ if (error?.code === "ERR_MODULE_NOT_FOUND" && context.parentURL && sharedModuleId(context.parentURL) !== undefined) {
34
+ return nextResolve(specifier, { ...context, parentURL: pathToFileURL(join(process.cwd(), "index.js")).href });
35
+ }
36
+ // Extensionless relative imports, as with bundlers / `moduleResolution: "Bundler"`.
37
+ if (error?.code === "ERR_MODULE_NOT_FOUND" && /^\.\.?\//.test(specifier) && !HAS_EXTENSION.test(specifier)) {
38
+ return nextResolve(`${specifier}.ts`, context);
39
+ }
40
+ throw error;
41
+ }
42
+ },
43
+ load(url, context, nextLoad) {
44
+ const shared = url.startsWith("file:") ? sharedModuleId(url) : undefined;
45
+ if (shared !== undefined) {
46
+ // One module per key; its cache entry depends on the declarations it was built from.
47
+ const file = fileURLToPath(shared.file);
48
+ let source = cache?.get(url, shared.key);
49
+ if (source === undefined) {
50
+ const module = sharedModule(file, shared.key);
51
+ source = module.code;
52
+ cache?.set(url, shared.key, module);
53
+ }
54
+ return { format: "module-typescript", source, shortCircuit: true };
55
+ }
56
+ if (!url.startsWith("file:") || !TS_FILE.test(new URL(url).pathname) || url.includes("/node_modules/")) {
57
+ return nextLoad(url, context);
58
+ }
59
+ const filename = fileURLToPath(url);
60
+ const code = readFileSync(filename, "utf8");
61
+ let source = cache?.get(filename, code);
62
+ if (source === undefined) {
63
+ const result = transformWithDependencies(filename, code, { devChecks, sharedValidators });
64
+ source = result.code;
65
+ cache?.set(filename, code, result);
66
+ }
67
+ loaded.add(filename);
68
+ return { format: "module-typescript", source, shortCircuit: true };
69
+ },
70
+ });