@anvil-di/anvil-codegen-wasm 0.0.2

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 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 describing the origin of the Work and
141
+ 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 Support. While redistributing the Work or
166
+ Derivative Works thereof, You may choose to offer, and charge a
167
+ fee for, acceptance of support, warranty, indemnity, or other
168
+ liability obligations and/or rights consistent with this License.
169
+ However, in accepting such obligations, You may act only on Your
170
+ own behalf and on Your sole responsibility, not on behalf of any
171
+ other Contributor, and only if You agree to indemnify, defend,
172
+ and hold each Contributor harmless for any liability incurred by,
173
+ or claims asserted against, such Contributor by reason of your
174
+ accepting any such warranty or support.
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 2026 typescript-di contributors
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
200
+ implied. See the License for the specific language governing
201
+ permissions and limitations under the License.
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # `@msulak/anvil-codegen-wasm`
2
+
3
+ WASM build of the [`@msulak/anvil`](https://github.com/msulak13/tsdi) codegen pipeline. Same parser, graph builder, validator, and emitter as the native CLI — exactly the Rust source, compiled with `wasm-pack` — running in-process for any host that runs WebAssembly (Node, browsers, Workers, Bun, Deno, StackBlitz).
4
+
5
+ ## Why
6
+
7
+ The native [`@msulak/anvil-cli`](../anvil-cli/README.md) is fast, but every invocation still pays a process-spawn cost (~10ms). Inside a bundler's hot path, that's the difference between "imperceptible" and "every save has a noticeable hitch". `@msulak/anvil-codegen-wasm` is a direct function call:
8
+
9
+ ```ts
10
+ import { compile } from "@msulak/anvil-codegen-wasm";
11
+
12
+ const result = compile({
13
+ entryPath: "/abs/src/app-component.ts",
14
+ files: { "/abs/src/app-component.ts": "...", "/abs/src/heater.ts": "..." },
15
+ version: "0.0.1",
16
+ });
17
+ ```
18
+
19
+ No spawn, no IPC, no file write — `result.emittedFiles` is the dagger output as in-memory strings, ready to feed straight into Vite's transform pipeline or write to disk if you prefer.
20
+
21
+ ## API
22
+
23
+ ```ts
24
+ interface CompileInput {
25
+ entryPath: string; // absolute path to the @Component
26
+ files: Record<string, string>; // every reachable file, abs path → source
27
+ aliases?: PathAlias[]; // tsconfig `paths` aliases
28
+ version: string; // baked into the dagger banner comment
29
+ }
30
+
31
+ interface PathAlias {
32
+ pattern: string; // "@/*"
33
+ target: string; // "src/*"
34
+ baseDir: string; // absolute dir the relative target resolves against
35
+ }
36
+
37
+ interface CompileOutput {
38
+ emittedFiles: { path: string; contents: string }[];
39
+ diagnostics: Diagnostic[]; // structured; route to bundler error UI
40
+ }
41
+ ```
42
+
43
+ Diagnostics are **non-fatal** — the function returns normally even when validation fails. Hosts decide how to render them (Vite overlay, Rollup `this.warn`, Webpack stats output, plain `console.error`, etc.).
44
+
45
+ ## How it gets built
46
+
47
+ The Rust source lives in `crates/anvil-codegen-wasm/`. `wasm-pack build --target nodejs` produces:
48
+
49
+ - `dist/anvil_codegen_wasm_bg.wasm` — the WASM blob (~1.4MB unoptimized; gzips to ~400KB)
50
+ - `dist/anvil_codegen_wasm.js` — the wasm-bindgen JS glue
51
+ - `lib/index.js` — typed ESM wrapper (this package)
52
+
53
+ The blob includes the entire pipeline: `oxc_parser`, `oxc_codegen`, `anvil-core` (graph + validation), `anvil-parser` (decorator extraction), and `anvil-codegen` (TS emission). The only piece that's *different* from the native CLI is the resolver — the WASM build uses a small custom in-memory resolver instead of `oxc_resolver`'s full filesystem-backed implementation. Tsconfig `paths` aliases work; the rest of `oxc_resolver`'s feature set (browser fields, conditional exports, workspace overrides) is the bundler's job.
54
+
55
+ ## Path conventions
56
+
57
+ The wasm32 Rust target uses Unix-style path semantics — backslashes are part of filenames, not separators. The WASM compile boundary normalizes Windows-style paths (`C:\Users\foo`) to forward-slash form (`C:/Users/foo`) automatically; the emitted file paths come back in the same form. Hosts running on Windows can convert back to backslashes for `fs.writeFileSync` calls. (The `@msulak/anvil-unplugin` does this transparently.)
58
+
59
+ ## Output equivalence
60
+
61
+ Both the WASM and native paths emit **byte-identical output** for the same input — same parser, same graph builder, same emitter, same `oxc_codegen` canonicalization. The golden-fixture suite under `tests/fixtures/` validates the native path; the WASM path is unit-tested for the same shapes (parser → graph → emit) in this package's `src/index.test.ts`.
62
+
63
+ ## Tradeoffs vs the native binary
64
+
65
+ | Property | Native | WASM |
66
+ |---|---|---|
67
+ | Cold start | ~10ms (process spawn) | ~80-150ms (wasm compile + instantiate) |
68
+ | Steady-state codegen | 1× | ~1.5-2× slower (oxc parsing is the bottleneck) |
69
+ | Bundler hot path | spawn + IPC per build | direct function call |
70
+ | Install footprint | one of five platform packages (~4MB) | single ~1.4MB .wasm |
71
+ | Reach | linux/macos/windows on x64+arm64 | anywhere V8/wasmtime runs |
72
+
73
+ Both paths are first-class. `@msulak/anvil-unplugin` defaults to native (faster) and accepts `mode: "wasm"` as an in-process opt-in.
package/lib/index.d.ts ADDED
@@ -0,0 +1,145 @@
1
+ /**
2
+ * `@anvil-di/anvil-codegen-wasm` — runs the entire anvil codegen pipeline in
3
+ * pure WebAssembly. No native binary, no platform-specific package,
4
+ * no `spawnSync` cost in the bundler hot path.
5
+ *
6
+ * Same parser, graph builder, validator, and emitter as the native
7
+ * CLI — built from the identical Rust source via `wasm-pack`. The
8
+ * only difference is the file source: this build reads from an
9
+ * in-memory `Record<string, string>` instead of `std::fs`.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { compile } from "@anvil-di/anvil-codegen-wasm";
14
+ *
15
+ * const result = compile({
16
+ * entryPath: "/abs/src/app-component.ts",
17
+ * files: {
18
+ * "/abs/src/app-component.ts": "...source...",
19
+ * "/abs/src/heater.ts": "...source...",
20
+ * "/abs/node_modules/@anvil-di/anvil/index.d.ts": "export const Inject: any; ...",
21
+ * },
22
+ * version: "0.0.1",
23
+ * });
24
+ *
25
+ * for (const file of result.emittedFiles) {
26
+ * console.log(`emit ${file.path} (${file.contents.length} bytes)`);
27
+ * }
28
+ * for (const diag of result.diagnostics) {
29
+ * console.error(`${diag.code}: ${diag.summary}`);
30
+ * }
31
+ * ```
32
+ */
33
+ /** Input bundle for {@link compile}. */
34
+ export interface CompileInput {
35
+ /**
36
+ * Absolute path of the `@Component` entry file. Must be a key
37
+ * in `files`.
38
+ */
39
+ entryPath: string;
40
+ /**
41
+ * Project sources keyed by absolute path. Must include the entry
42
+ * and every transitively-reachable source file (the host walks
43
+ * the graph; anvil only consumes what it's given).
44
+ *
45
+ * Bare-specifier imports like `import { Inject } from "@anvil-di/anvil"`
46
+ * are resolved against entries whose paths contain
47
+ * `node_modules/@anvil-di/anvil/...` — so include the runtime stub package
48
+ * under such a path if your source uses anvil decorators.
49
+ */
50
+ files: Record<string, string>;
51
+ /**
52
+ * Optional tsconfig `compilerOptions.paths` aliases. The host is
53
+ * expected to pre-parse the user's tsconfig and forward the alias
54
+ * table.
55
+ */
56
+ aliases?: PathAlias[];
57
+ /**
58
+ * Version string surfaced into the generated dagger's banner
59
+ * comment, so users can correlate emitted output with the
60
+ * @anvil-di/anvil-codegen-wasm package version that produced it.
61
+ */
62
+ version: string;
63
+ }
64
+ /** One tsconfig `paths` alias, in anvil's wire format. */
65
+ export interface PathAlias {
66
+ /** Alias pattern (e.g. `"@/*"`). */
67
+ pattern: string;
68
+ /** Target template (e.g. `"src/*"`). */
69
+ target: string;
70
+ /**
71
+ * Absolute directory the relative `target` paths resolve against
72
+ * (typically the tsconfig's own dir, or its `baseUrl`).
73
+ */
74
+ baseDir: string;
75
+ }
76
+ /** Output from {@link compile}. */
77
+ export interface CompileOutput {
78
+ /**
79
+ * Generated `.anvil.ts` files, one per `@Component` that
80
+ * validated successfully. Empty when **every** component had
81
+ * diagnostics; partial when some components passed and others
82
+ * didn't.
83
+ */
84
+ emittedFiles: EmittedFile[];
85
+ /**
86
+ * Structured validation diagnostics. Empty for a clean compile.
87
+ * Hosts route these into the bundler's error pipeline (Vite
88
+ * overlay, Rollup `this.warn`, Webpack stats output, etc.).
89
+ */
90
+ diagnostics: Diagnostic[];
91
+ }
92
+ /** A single emitted dagger file. */
93
+ export interface EmittedFile {
94
+ /**
95
+ * Absolute path (mirrors the source `@Component` file's path
96
+ * with `.ts` swapped for `.anvil.ts`).
97
+ */
98
+ path: string;
99
+ /** The full TypeScript source — banner comment + dagger class. */
100
+ contents: string;
101
+ }
102
+ /** A validation diagnostic. */
103
+ export interface Diagnostic {
104
+ /**
105
+ * Stable, machine-readable code. Examples: `"anvil::missing_binding"`,
106
+ * `"anvil::cycle"`, `"anvil::scope_mismatch"`.
107
+ */
108
+ code: string;
109
+ /** One-line human-readable summary suitable for `Vite.overlay.error`. */
110
+ summary: string;
111
+ /** Primary source location (where the error anchors). */
112
+ primary: SpanLabel;
113
+ /**
114
+ * Additional related locations — duplicate declarations, cycle
115
+ * members, the requesting binding for a missing dep, etc.
116
+ */
117
+ related: SpanLabel[];
118
+ }
119
+ /** A source-anchored sub-message attached to a {@link Diagnostic}. */
120
+ export interface SpanLabel {
121
+ /** Absolute path of the file the span is in. */
122
+ path: string;
123
+ /** Inclusive byte offset of the first character. */
124
+ start: number;
125
+ /** Exclusive byte offset just past the last character. */
126
+ end: number;
127
+ /** Human-readable note rendered next to the source span. */
128
+ message: string;
129
+ }
130
+ /**
131
+ * Run the codegen pipeline end-to-end against an in-memory file map.
132
+ *
133
+ * Synchronous — the WASM module is loaded eagerly the first time
134
+ * this package is imported, and `compile` itself is a pure function
135
+ * over the input bundle. Subsequent calls reuse the same WASM
136
+ * instance.
137
+ *
138
+ * Throws when the **input** is malformed (bad paths, missing files,
139
+ * malformed JSON shape). **Validation diagnostics** are not
140
+ * exceptions — they flow through `output.diagnostics` so partial
141
+ * progress is visible (e.g. component A validated, component B
142
+ * didn't, here's why).
143
+ */
144
+ export declare function compile(input: CompileInput): CompileOutput;
145
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAQH,wCAAwC;AACxC,MAAM,WAAW,YAAY;IAC3B;;;OAGG;IACH,SAAS,EAAE,MAAM,CAAC;IAClB;;;;;;;;;OASG;IACH,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B;;;;OAIG;IACH,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC;IACtB;;;;OAIG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,0DAA0D;AAC1D,MAAM,WAAW,SAAS;IACxB,oCAAoC;IACpC,OAAO,EAAE,MAAM,CAAC;IAChB,wCAAwC;IACxC,MAAM,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,mCAAmC;AACnC,MAAM,WAAW,aAAa;IAC5B;;;;;OAKG;IACH,YAAY,EAAE,WAAW,EAAE,CAAC;IAC5B;;;;OAIG;IACH,WAAW,EAAE,UAAU,EAAE,CAAC;CAC3B;AAED,oCAAoC;AACpC,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IACb,kEAAkE;IAClE,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,+BAA+B;AAC/B,MAAM,WAAW,UAAU;IACzB;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IACb,yEAAyE;IACzE,OAAO,EAAE,MAAM,CAAC;IAChB,yDAAyD;IACzD,OAAO,EAAE,SAAS,CAAC;IACnB;;;OAGG;IACH,OAAO,EAAE,SAAS,EAAE,CAAC;CACtB;AAED,sEAAsE;AACtE,MAAM,WAAW,SAAS;IACxB,gDAAgD;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,oDAAoD;IACpD,KAAK,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,GAAG,EAAE,MAAM,CAAC;IACZ,4DAA4D;IAC5D,OAAO,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,YAAY,GAAG,aAAa,CAE1D"}
package/lib/index.js ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * `@anvil-di/anvil-codegen-wasm` — runs the entire anvil codegen pipeline in
3
+ * pure WebAssembly. No native binary, no platform-specific package,
4
+ * no `spawnSync` cost in the bundler hot path.
5
+ *
6
+ * Same parser, graph builder, validator, and emitter as the native
7
+ * CLI — built from the identical Rust source via `wasm-pack`. The
8
+ * only difference is the file source: this build reads from an
9
+ * in-memory `Record<string, string>` instead of `std::fs`.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { compile } from "@anvil-di/anvil-codegen-wasm";
14
+ *
15
+ * const result = compile({
16
+ * entryPath: "/abs/src/app-component.ts",
17
+ * files: {
18
+ * "/abs/src/app-component.ts": "...source...",
19
+ * "/abs/src/heater.ts": "...source...",
20
+ * "/abs/node_modules/@anvil-di/anvil/index.d.ts": "export const Inject: any; ...",
21
+ * },
22
+ * version: "0.0.1",
23
+ * });
24
+ *
25
+ * for (const file of result.emittedFiles) {
26
+ * console.log(`emit ${file.path} (${file.contents.length} bytes)`);
27
+ * }
28
+ * for (const diag of result.diagnostics) {
29
+ * console.error(`${diag.code}: ${diag.summary}`);
30
+ * }
31
+ * ```
32
+ */
33
+ // The wasm-pack output is CommonJS-ish — it uses synchronous
34
+ // `require("./anvil_codegen_wasm_bg.wasm")` to load the blob. We
35
+ // re-export it under a typed surface so consumers don't see the
36
+ // wasm-bindgen `any` types directly.
37
+ import { compile as wasmCompile } from "../dist/anvil_codegen_wasm.js";
38
+ /**
39
+ * Run the codegen pipeline end-to-end against an in-memory file map.
40
+ *
41
+ * Synchronous — the WASM module is loaded eagerly the first time
42
+ * this package is imported, and `compile` itself is a pure function
43
+ * over the input bundle. Subsequent calls reuse the same WASM
44
+ * instance.
45
+ *
46
+ * Throws when the **input** is malformed (bad paths, missing files,
47
+ * malformed JSON shape). **Validation diagnostics** are not
48
+ * exceptions — they flow through `output.diagnostics` so partial
49
+ * progress is visible (e.g. component A validated, component B
50
+ * didn't, here's why).
51
+ */
52
+ export function compile(input) {
53
+ return wasmCompile(input);
54
+ }
55
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,6DAA6D;AAC7D,iEAAiE;AACjE,gEAAgE;AAChE,qCAAqC;AACrC,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAyGvE;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,OAAO,CAAC,KAAmB;IACzC,OAAO,WAAW,CAAC,KAAK,CAAkB,CAAC;AAC7C,CAAC"}
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "@anvil-di/anvil-codegen-wasm",
3
+ "version": "0.0.2",
4
+ "description": "WASM build of the anvil codegen pipeline. Same parser + graph + emitter as the native CLI, in-process for any host that runs WebAssembly (Node, browsers, Workers, Bun).",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./lib/index.js",
8
+ "module": "./lib/index.js",
9
+ "types": "./lib/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./lib/index.d.ts",
13
+ "import": "./lib/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "lib",
19
+ "src"
20
+ ],
21
+ "devDependencies": {
22
+ "@types/node": "^22.10.0",
23
+ "typescript": "^5.7.2",
24
+ "vitest": "^2.1.8"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "build:wasm": "wasm-pack build ../../crates/anvil-codegen-wasm --target nodejs --release --out-dir ../../packages/anvil-codegen-wasm/dist --out-name anvil_codegen_wasm && tsc -p tsconfig.json",
31
+ "build": "tsc -p tsconfig.json",
32
+ "typecheck": "tsc -p tsconfig.json --noEmit",
33
+ "test": "vitest run"
34
+ }
35
+ }
@@ -0,0 +1,120 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { compile } from "./index.js";
3
+
4
+ const ANVIL_STUB = [
5
+ "export const Inject: any;",
6
+ "export const Module: any;",
7
+ "export const Provides: any;",
8
+ "export const Component: any;",
9
+ "export const Singleton: any;",
10
+ "export const Binds: any;",
11
+ "export const Subcomponent: any;",
12
+ "export const IntoSet: any;",
13
+ ].join("\n");
14
+
15
+ describe("@anvil-di/anvil-codegen-wasm", () => {
16
+ it("compiles a simple project end-to-end (parser → graph → emit)", () => {
17
+ const result = compile({
18
+ entryPath: "/proj/src/app-component.ts",
19
+ version: "0.0.1-wasm-test",
20
+ files: {
21
+ "/proj/node_modules/@anvil-di/anvil/index.d.ts": ANVIL_STUB,
22
+ "/proj/src/heater.ts": `
23
+ import { Inject, Singleton } from "@anvil-di/anvil";
24
+ @Inject @Singleton
25
+ export class Heater { constructor() {} on(): void {} }
26
+ `,
27
+ "/proj/src/pump.ts": `
28
+ import { Inject } from "@anvil-di/anvil";
29
+ import { Heater } from "./heater";
30
+ @Inject
31
+ export class Pump {
32
+ constructor(private heater: Heater) {}
33
+ pump(): void { this.heater.on(); }
34
+ }
35
+ `,
36
+ "/proj/src/app-component.ts": `
37
+ import { Component, Singleton } from "@anvil-di/anvil";
38
+ import { Pump } from "./pump";
39
+ import { Heater } from "./heater";
40
+ @Singleton
41
+ @Component({ modules: [] })
42
+ export abstract class App {
43
+ abstract pump(): Pump;
44
+ abstract heater(): Heater;
45
+ }
46
+ `,
47
+ },
48
+ });
49
+
50
+ expect(result.diagnostics).toEqual([]);
51
+ expect(result.emittedFiles).toHaveLength(1);
52
+ const dagger = result.emittedFiles[0]!;
53
+ expect(dagger.path).toMatch(/app-component\.anvil\.ts$/);
54
+ expect(dagger.contents).toContain("AnvilApp");
55
+ expect(dagger.contents).toContain("createApp");
56
+ expect(dagger.contents).toContain("0.0.1-wasm-test");
57
+ expect(dagger.contents).toContain("private _heater"); // singleton cache
58
+ expect(dagger.contents).toContain("return new Pump(this.getHeater())");
59
+ });
60
+
61
+ it("surfaces validation diagnostics through the structured output", () => {
62
+ const result = compile({
63
+ entryPath: "/proj/src/app-component.ts",
64
+ version: "0.0.1",
65
+ files: {
66
+ "/proj/node_modules/@anvil-di/anvil/index.d.ts": ANVIL_STUB,
67
+ // Heater has no @Inject — Pump's dep is unresolvable.
68
+ "/proj/src/heater.ts": "export class Heater {}",
69
+ "/proj/src/pump.ts": `
70
+ import { Inject } from "@anvil-di/anvil";
71
+ import { Heater } from "./heater";
72
+ @Inject
73
+ export class Pump { constructor(private h: Heater) {} }
74
+ `,
75
+ "/proj/src/app-component.ts": `
76
+ import { Component } from "@anvil-di/anvil";
77
+ import { Pump } from "./pump";
78
+ @Component({ modules: [] })
79
+ export abstract class App { abstract pump(): Pump; }
80
+ `,
81
+ },
82
+ });
83
+
84
+ expect(result.emittedFiles).toEqual([]); // validation failed; no emit
85
+ expect(result.diagnostics.length).toBeGreaterThan(0);
86
+ expect(result.diagnostics.some((d) => d.code === "anvil::missing_binding")).toBe(true);
87
+ const diag = result.diagnostics.find((d) => d.code === "anvil::missing_binding")!;
88
+ expect(diag.summary).toContain("Heater");
89
+ expect(diag.primary.path).toMatch(/pump\.ts$/);
90
+ });
91
+
92
+ it("byte-identical output as the native CLI for the same input", () => {
93
+ // Smoke test that the WASM emit pipeline matches the native one
94
+ // — the dagger we emit should contain the exact same emit shape
95
+ // (Dagger class, factories, banner) for an equivalent project.
96
+ const result = compile({
97
+ entryPath: "/proj/app.ts",
98
+ version: "1.0.0",
99
+ files: {
100
+ "/proj/node_modules/@anvil-di/anvil/index.d.ts": ANVIL_STUB,
101
+ "/proj/app.ts": `
102
+ import { Component, Inject } from "@anvil-di/anvil";
103
+ @Inject
104
+ export class Repo { constructor() {} }
105
+ @Component({ modules: [] })
106
+ export abstract class App { abstract repo(): Repo; }
107
+ `,
108
+ },
109
+ });
110
+ expect(result.diagnostics).toEqual([]);
111
+ expect(result.emittedFiles).toHaveLength(1);
112
+ const dagger = result.emittedFiles[0]!.contents;
113
+ // Hallmarks of the canonical emit shape — these are the
114
+ // invariants the native codegen tests assert too.
115
+ expect(dagger).toMatch(/^\/\/ AUTO-GENERATED by anvil v1\.0\.0/);
116
+ expect(dagger).toContain("export class AnvilApp extends App");
117
+ expect(dagger).toContain("static create(): App");
118
+ expect(dagger).toContain("export function createApp(): App");
119
+ });
120
+ });
package/src/index.ts ADDED
@@ -0,0 +1,159 @@
1
+ /**
2
+ * `@anvil-di/anvil-codegen-wasm` — runs the entire anvil codegen pipeline in
3
+ * pure WebAssembly. No native binary, no platform-specific package,
4
+ * no `spawnSync` cost in the bundler hot path.
5
+ *
6
+ * Same parser, graph builder, validator, and emitter as the native
7
+ * CLI — built from the identical Rust source via `wasm-pack`. The
8
+ * only difference is the file source: this build reads from an
9
+ * in-memory `Record<string, string>` instead of `std::fs`.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { compile } from "@anvil-di/anvil-codegen-wasm";
14
+ *
15
+ * const result = compile({
16
+ * entryPath: "/abs/src/app-component.ts",
17
+ * files: {
18
+ * "/abs/src/app-component.ts": "...source...",
19
+ * "/abs/src/heater.ts": "...source...",
20
+ * "/abs/node_modules/@anvil-di/anvil/index.d.ts": "export const Inject: any; ...",
21
+ * },
22
+ * version: "0.0.1",
23
+ * });
24
+ *
25
+ * for (const file of result.emittedFiles) {
26
+ * console.log(`emit ${file.path} (${file.contents.length} bytes)`);
27
+ * }
28
+ * for (const diag of result.diagnostics) {
29
+ * console.error(`${diag.code}: ${diag.summary}`);
30
+ * }
31
+ * ```
32
+ */
33
+
34
+ // The wasm-pack output is CommonJS-ish — it uses synchronous
35
+ // `require("./anvil_codegen_wasm_bg.wasm")` to load the blob. We
36
+ // re-export it under a typed surface so consumers don't see the
37
+ // wasm-bindgen `any` types directly.
38
+ import { compile as wasmCompile } from "../dist/anvil_codegen_wasm.js";
39
+
40
+ /** Input bundle for {@link compile}. */
41
+ export interface CompileInput {
42
+ /**
43
+ * Absolute path of the `@Component` entry file. Must be a key
44
+ * in `files`.
45
+ */
46
+ entryPath: string;
47
+ /**
48
+ * Project sources keyed by absolute path. Must include the entry
49
+ * and every transitively-reachable source file (the host walks
50
+ * the graph; anvil only consumes what it's given).
51
+ *
52
+ * Bare-specifier imports like `import { Inject } from "@anvil-di/anvil"`
53
+ * are resolved against entries whose paths contain
54
+ * `node_modules/@anvil-di/anvil/...` — so include the runtime stub package
55
+ * under such a path if your source uses anvil decorators.
56
+ */
57
+ files: Record<string, string>;
58
+ /**
59
+ * Optional tsconfig `compilerOptions.paths` aliases. The host is
60
+ * expected to pre-parse the user's tsconfig and forward the alias
61
+ * table.
62
+ */
63
+ aliases?: PathAlias[];
64
+ /**
65
+ * Version string surfaced into the generated dagger's banner
66
+ * comment, so users can correlate emitted output with the
67
+ * @anvil-di/anvil-codegen-wasm package version that produced it.
68
+ */
69
+ version: string;
70
+ }
71
+
72
+ /** One tsconfig `paths` alias, in anvil's wire format. */
73
+ export interface PathAlias {
74
+ /** Alias pattern (e.g. `"@/*"`). */
75
+ pattern: string;
76
+ /** Target template (e.g. `"src/*"`). */
77
+ target: string;
78
+ /**
79
+ * Absolute directory the relative `target` paths resolve against
80
+ * (typically the tsconfig's own dir, or its `baseUrl`).
81
+ */
82
+ baseDir: string;
83
+ }
84
+
85
+ /** Output from {@link compile}. */
86
+ export interface CompileOutput {
87
+ /**
88
+ * Generated `.anvil.ts` files, one per `@Component` that
89
+ * validated successfully. Empty when **every** component had
90
+ * diagnostics; partial when some components passed and others
91
+ * didn't.
92
+ */
93
+ emittedFiles: EmittedFile[];
94
+ /**
95
+ * Structured validation diagnostics. Empty for a clean compile.
96
+ * Hosts route these into the bundler's error pipeline (Vite
97
+ * overlay, Rollup `this.warn`, Webpack stats output, etc.).
98
+ */
99
+ diagnostics: Diagnostic[];
100
+ }
101
+
102
+ /** A single emitted dagger file. */
103
+ export interface EmittedFile {
104
+ /**
105
+ * Absolute path (mirrors the source `@Component` file's path
106
+ * with `.ts` swapped for `.anvil.ts`).
107
+ */
108
+ path: string;
109
+ /** The full TypeScript source — banner comment + dagger class. */
110
+ contents: string;
111
+ }
112
+
113
+ /** A validation diagnostic. */
114
+ export interface Diagnostic {
115
+ /**
116
+ * Stable, machine-readable code. Examples: `"anvil::missing_binding"`,
117
+ * `"anvil::cycle"`, `"anvil::scope_mismatch"`.
118
+ */
119
+ code: string;
120
+ /** One-line human-readable summary suitable for `Vite.overlay.error`. */
121
+ summary: string;
122
+ /** Primary source location (where the error anchors). */
123
+ primary: SpanLabel;
124
+ /**
125
+ * Additional related locations — duplicate declarations, cycle
126
+ * members, the requesting binding for a missing dep, etc.
127
+ */
128
+ related: SpanLabel[];
129
+ }
130
+
131
+ /** A source-anchored sub-message attached to a {@link Diagnostic}. */
132
+ export interface SpanLabel {
133
+ /** Absolute path of the file the span is in. */
134
+ path: string;
135
+ /** Inclusive byte offset of the first character. */
136
+ start: number;
137
+ /** Exclusive byte offset just past the last character. */
138
+ end: number;
139
+ /** Human-readable note rendered next to the source span. */
140
+ message: string;
141
+ }
142
+
143
+ /**
144
+ * Run the codegen pipeline end-to-end against an in-memory file map.
145
+ *
146
+ * Synchronous — the WASM module is loaded eagerly the first time
147
+ * this package is imported, and `compile` itself is a pure function
148
+ * over the input bundle. Subsequent calls reuse the same WASM
149
+ * instance.
150
+ *
151
+ * Throws when the **input** is malformed (bad paths, missing files,
152
+ * malformed JSON shape). **Validation diagnostics** are not
153
+ * exceptions — they flow through `output.diagnostics` so partial
154
+ * progress is visible (e.g. component A validated, component B
155
+ * didn't, here's why).
156
+ */
157
+ export function compile(input: CompileInput): CompileOutput {
158
+ return wasmCompile(input) as CompileOutput;
159
+ }