typenative 0.7.0 → 0.7.1
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/bin/node/assert.js +2 -2
- package/bin/node/child_process.js +66 -8
- package/bin/node/fs.js +1012 -4
- package/bin/node/histogram.js +1991 -0
- package/bin/node/process.js +14 -2
- package/bin/node/sqlite.js +1488 -5
- package/bin/node/stream.js +2 -1
- package/bin/node/system_extra.js +3 -270
- package/bin/node/test.js +39 -1
- package/bin/node/test_report.js +47 -1
- package/bin/node/test_run.js +57 -2
- package/bin/node/util.js +8 -5
- package/bin/node/webassembly.js +20 -5
- package/bin/node/webview.js +3257 -244
- package/bin/node/zlib.js +118 -14
- package/bin/node/zlib_iter.js +585 -0
- package/bin/transpiler.js +1370 -258
- package/bin/version.js +1 -1
- package/govendor/software.sslmate.com/src/go-pkcs12/.gitattributes +10 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/LICENSE +28 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/README.md +31 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/bmp-string.go +63 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/crypto.go +331 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/errors.go +23 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/go.mod +3 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/internal/rc2/rc2.go +271 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/mac.go +202 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/pbkdf.go +184 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/pkcs12.go +1000 -0
- package/govendor/software.sslmate.com/src/go-pkcs12/safebags.go +107 -0
- package/package.json +10 -1
- package/types/tsconfig.json +17 -0
- package/types/typenative-npm.d.ts +492 -12
- package/types/typenative.d.ts +88 -2
- package/.gitattributes +0 -1
- package/.github/workflows/ci.yml +0 -68
- package/.github/workflows/npm-publish-github-packages.yml +0 -88
- package/CHANGELOG.md +0 -1746
- package/CONTRIBUTION.md +0 -133
- package/conformance.md +0 -1497
- package/examples/README.md +0 -114
- package/examples/angular-templates/README.md +0 -141
- package/examples/angular-templates/bench.mjs +0 -173
- package/examples/angular-templates/dom-type-globals.d.ts +0 -21
- package/examples/angular-templates/dom-type-stubs.ts +0 -21
- package/examples/angular-templates/main.ts +0 -135
- package/examples/angular-templates/parity.mjs +0 -157
- package/examples/angular-templates/run-node.mjs +0 -69
- package/examples/angular-templates/vendor/angular/compiler/LICENSE +0 -21
- package/examples/desktop-notes/README.md +0 -106
- package/examples/desktop-notes/bench.mjs +0 -125
- package/examples/desktop-notes/main.ts +0 -131
- package/examples/desktop-notes/package-lock.json +0 -726
- package/examples/desktop-notes/package.json +0 -9
- package/examples/desktop-notes/ui.ts +0 -176
- package/examples/dupe-finder/README.md +0 -78
- package/examples/dupe-finder/bench.mjs +0 -120
- package/examples/dupe-finder/main.ts +0 -87
- package/examples/fibonacci/README.md +0 -89
- package/examples/fibonacci/bench.mjs +0 -87
- package/examples/fibonacci/main.ts +0 -21
- package/examples/hello-world/README.md +0 -62
- package/examples/hello-world/bench.mjs +0 -66
- package/examples/hello-world/main.ts +0 -7
- package/examples/json-server/README.md +0 -132
- package/examples/json-server/bench.mjs +0 -263
- package/examples/json-server/main.ts +0 -67
- package/examples/mandelbrot-png/README.md +0 -63
- package/examples/mandelbrot-png/bench.mjs +0 -95
- package/examples/mandelbrot-png/main.ts +0 -98
- package/examples/mandelbrot-png/preview.png +0 -0
- package/examples/marked-cli/README.md +0 -174
- package/examples/marked-cli/bench.mjs +0 -178
- package/examples/marked-cli/main.ts +0 -410
- package/examples/marked-cli/parity.mjs +0 -185
- package/examples/marked-cli/vendor/marked/LICENSE +0 -44
- package/examples/marked-cli/vendor/marked/VENDOR.md +0 -26
- package/examples/openai-chat/README.md +0 -148
- package/examples/openai-chat/bench.mjs +0 -175
- package/examples/openai-chat/main.ts +0 -488
- package/examples/react-compiler/README.md +0 -185
- package/examples/react-compiler/bench.mjs +0 -181
- package/examples/react-compiler/main.ts +0 -324
- package/examples/react-compiler/parity.mjs +0 -362
- package/examples/react-compiler/run-node.mjs +0 -90
- package/examples/react-compiler/vendor/babel/LICENSE +0 -22
- package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-lower.json +0 -15
- package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-upper.json +0 -51
- package/examples/react-compiler/vendor/charcodes/package.json +0 -25
- package/examples/react-compiler/vendor/invariant/LICENSE +0 -21
- package/examples/react-compiler/vendor/invariant/invariant.cjs +0 -51
- package/examples/react-compiler/vendor/invariant/invariant.d.cts +0 -11
- package/examples/react-compiler/vendor/invariant/types/LICENSE +0 -21
- package/examples/react-compiler/vendor/jridgewell/gen-mapping/LICENSE +0 -19
- package/examples/react-compiler/vendor/jridgewell/resolve-uri/LICENSE +0 -19
- package/examples/react-compiler/vendor/jridgewell/sourcemap-codec/LICENSE +0 -19
- package/examples/react-compiler/vendor/jridgewell/trace-mapping/LICENSE +0 -19
- package/examples/react-compiler/vendor/js-tokens/LICENSE +0 -21
- package/examples/react-compiler/vendor/js-tokens/index.cjs +0 -23
- package/examples/react-compiler/vendor/js-tokens/index.d.cts +0 -13
- package/examples/react-compiler/vendor/jsesc/LICENSE-MIT.txt +0 -20
- package/examples/react-compiler/vendor/jsesc/jsesc.cjs +0 -337
- package/examples/react-compiler/vendor/jsesc/jsesc.d.cts +0 -384
- package/examples/react-compiler/vendor/jsesc/types/LICENSE +0 -21
- package/examples/react-compiler/vendor/picocolors/LICENSE +0 -15
- package/examples/react-compiler/vendor/picocolors/picocolors.cjs +0 -75
- package/examples/react-compiler/vendor/picocolors/picocolors.d.cts +0 -5
- package/examples/react-compiler/vendor/picocolors/types.d.ts +0 -51
- package/examples/react-compiler/vendor/react-compiler/LICENSE +0 -21
- package/examples/react-compiler/vendor/stubs/babel-core.ts +0 -31
- package/examples/react-compiler/vendor/stubs/debug.ts +0 -18
- package/examples/react-compiler/vendor/stubs/js-tokens.d.ts +0 -13
- package/examples/react-compiler/vendor/stubs/pretty-format.ts +0 -18
- package/examples/react-compiler/vendor/zod/LICENSE +0 -21
- package/examples/react-compiler/vendor/zod-validation-error/LICENSE +0 -9
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/NonEmptyArray.ts +0 -5
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinPath.ts +0 -49
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinValues.ts +0 -48
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/stringify.ts +0 -50
- package/examples/react-compiler/vendor/zod-validation-error/lib/utils/titleCase.ts +0 -6
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/MessageBuilder.ts +0 -126
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/ValidationError.ts +0 -39
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/custom.ts +0 -12
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/errorMap.ts +0 -78
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/index.ts +0 -2
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidElement.ts +0 -12
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidKey.ts +0 -12
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidStringFormat.ts +0 -131
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidType.ts +0 -54
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidUnion.ts +0 -12
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidValue.ts +0 -40
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/notMultipleOf.ts +0 -12
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooBig.ts +0 -76
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooSmall.ts +0 -76
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/types.ts +0 -27
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/unrecognizedKeys.ts +0 -27
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromError.ts +0 -13
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodError.ts +0 -61
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodIssue.ts +0 -38
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/index.ts +0 -20
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationError.ts +0 -5
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationErrorLike.ts +0 -8
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isZodErrorLike.ts +0 -11
- package/examples/react-compiler/vendor/zod-validation-error/lib/v4/toValidationError.ts +0 -20
- package/examples/react-compiler/vendor.mjs +0 -688
- package/examples/todo-cli/README.md +0 -69
- package/examples/todo-cli/bench.mjs +0 -89
- package/examples/todo-cli/main.ts +0 -92
- package/examples/yaml-cli/README.md +0 -152
- package/examples/yaml-cli/bench.mjs +0 -265
- package/examples/yaml-cli/main.ts +0 -251
- package/examples/yaml-cli/parity.mjs +0 -156
- package/examples/yaml-cli/vendor/yaml/LICENSE +0 -13
- package/examples/yaml-cli/vendor/yaml/VENDOR.md +0 -25
- package/performance/README.md +0 -248
- package/performance/any-dynamic.ts +0 -21
- package/performance/any-record-view.ts +0 -20
- package/performance/arr-for-of.ts +0 -29
- package/performance/arr-hof.ts +0 -21
- package/performance/arr-push-index.ts +0 -15
- package/performance/arr-push-local.ts +0 -39
- package/performance/arr-slice-concat.ts +0 -24
- package/performance/arr-sort.ts +0 -21
- package/performance/async-await.ts +0 -24
- package/performance/async-promise-all.ts +0 -38
- package/performance/bigint-arith.ts +0 -36
- package/performance/buf-encode.ts +0 -29
- package/performance/class-accessors.ts +0 -48
- package/performance/class-dispatch.ts +0 -52
- package/performance/date-format.ts +0 -18
- package/performance/events-emit.ts +0 -27
- package/performance/exc-throw-rare.ts +0 -25
- package/performance/exc-try-catch.ts +0 -26
- package/performance/fn-closures.ts +0 -29
- package/performance/fn-recursion-tree.ts +0 -31
- package/performance/fn-rest-spread.ts +0 -43
- package/performance/gen-for-of.ts +0 -46
- package/performance/gen-next.ts +0 -32
- package/performance/iter-helpers.ts +0 -38
- package/performance/json-any.ts +0 -30
- package/performance/json-roundtrip.ts +0 -27
- package/performance/map-delete.ts +0 -24
- package/performance/map-iterate.ts +0 -26
- package/performance/map-number-keys.ts +0 -37
- package/performance/map-string-keys.ts +0 -22
- package/performance/num-arith-loop.ts +0 -14
- package/performance/num-bitwise.ts +0 -21
- package/performance/num-hash-imul.ts +0 -36
- package/performance/num-mod-int.ts +0 -16
- package/performance/num-to-string.ts +0 -16
- package/performance/obj-alloc.ts +0 -32
- package/performance/obj-keys-entries.ts +0 -44
- package/performance/obj-optional-chain.ts +0 -42
- package/performance/obj-record-dict.ts +0 -24
- package/performance/obj-spread-destructure.ts +0 -40
- package/performance/regex-exec.ts +0 -29
- package/performance/regex-replace-fn.ts +0 -24
- package/performance/regex-site.ts +0 -28
- package/performance/set-ops.ts +0 -20
- package/performance/str-char-scan.ts +0 -35
- package/performance/str-concat-plus.ts +0 -18
- package/performance/str-concat.ts +0 -24
- package/performance/str-methods.ts +0 -24
- package/performance/str-short-scan.ts +0 -26
- package/performance/str-split-join.ts +0 -23
- package/performance/str-switch-compare.ts +0 -50
- package/performance/str-template.ts +0 -16
- package/performance/str-unicode.ts +0 -25
- package/performance/typed-array.ts +0 -30
- package/performance/union-switch.ts +0 -57
- package/performance/union-typeof.ts +0 -40
- package/performance/wasm-call.ts +0 -63
- package/tsparser/check.go +0 -158
- package/tsparser/go.mod +0 -14
- package/tsparser/go.sum +0 -22
- package/tsparser/main.go +0 -363
- package/tsparser/tsparser.exe +0 -4
package/examples/README.md
DELETED
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
# Examples
|
|
2
|
-
|
|
3
|
-
Small, complete TypeNative programs, each runnable as-is under **both**
|
|
4
|
-
Node.js and a compiled TypeNative binary, with a `bench.mjs` that measures
|
|
5
|
-
Node vs TypeNative on the same workload and a README documenting the results.
|
|
6
|
-
|
|
7
|
-
| Example | Demonstrates | Headline result (this machine*) |
|
|
8
|
-
|-----------------------------------|----------------------------------------------------------------------------|--------------------------------------------------------------|
|
|
9
|
-
| [hello-world](hello-world/) | `console.log`, `process.argv`, template literals | **9.2x faster startup** (4.9 ms vs 45.2 ms) |
|
|
10
|
-
| [fibonacci](fibonacci/) | Recursion, `perf_hooks` timing, CPU-bound number crunching | **2.1x faster compute** (31.8 ms vs 66.1 ms) |
|
|
11
|
-
| [json-server](json-server/) | `node:http` web server with GET + POST JSON routes, zero dependencies | **1.6x Node's HTTP throughput** (94k vs 57k GET req/s) |
|
|
12
|
-
| [todo-cli](todo-cli/) | A to-do CLI persisting to a JSON file, run many times a day | **10.2x faster per command** (5.4 ms vs 54.8 ms) |
|
|
13
|
-
| [dupe-finder](dupe-finder/) | Recursive directory walk, SHA-256 hashing, JSON report written to disk | **2.8x faster scan** (231 ms vs 643 ms, 2,000 files) |
|
|
14
|
-
| [mandelbrot-png](mandelbrot-png/) | Fractal render + hand-written PNG encoder on `node:zlib`, no image library | **1.1x faster** (419 ms vs 462 ms) |
|
|
15
|
-
| [desktop-notes](desktop-notes/) | Notes app in a native webview window, UI compiled into one binary | **3.9x faster launch, 6.7x less memory** (11 vs 72 MiB) |
|
|
16
|
-
| [yaml-cli](yaml-cli/) | The `yaml` package's own CLI from its unmodified source, 100% Node parity | **11.3x faster per call** (9 vs 107 ms); 1.1x faster on 10 MB† |
|
|
17
|
-
| [marked-cli](marked-cli/) | The `marked` markdown CLI from its unmodified source, 100% Node parity | **8.2x faster per call** (13 vs 107 ms); 1.1x faster on 10 MB‡ |
|
|
18
|
-
| [openai-chat](openai-chat/) | Chat client for any OpenAI-compatible API: streaming `fetch` + SSE parsing, readline REPL | **1.1x faster per answer** (700 vs 766 ms streamed) |
|
|
19
|
-
| [angular-templates](angular-templates/) | Angular's template compiler (`@angular/compiler`, 233 files) to Ivy instructions, 100% Node parity | **4.3x faster per template** (52 vs 223 ms); 1.2x faster at 64 KB§ |
|
|
20
|
-
| [react-compiler](react-compiler/) | The React Compiler (`babel-plugin-react-compiler` + Babel 7.29 + zod 4, ~470 files) compiling components to their auto-memoized form, 100% Node parity | **3.5x faster per file** (103 vs 364 ms); **1.7x faster at 64 KB** (623 vs 1,085 ms) |
|
|
21
|
-
|
|
22
|
-
\* Windows 11 Pro, AMD Ryzen 5 7600, Node v26.13.0, Go 1.27.4, TypeNative
|
|
23
|
-
0.7.0, all examples. See each example's README for full
|
|
24
|
-
methodology and numbers.
|
|
25
|
-
|
|
26
|
-
† Large inputs are converted in up to six worker processes, one contiguous
|
|
27
|
-
run of documents each; the single-process path is still about 2.1x slower
|
|
28
|
-
than Node on 10 MB. yaml-cli's [parity.mjs](yaml-cli/parity.mjs) also checks
|
|
29
|
-
every output against Node byte for byte on the yaml-test-suite (1,608 cases).
|
|
30
|
-
|
|
31
|
-
‡ Large inputs are parsed in up to six worker processes, one contiguous run of
|
|
32
|
-
sections each, at top-level heading boundaries; a single process is still about
|
|
33
|
-
1.6x slower than Node on 10 MB. marked-cli's
|
|
34
|
-
[parity.mjs](marked-cli/parity.mjs) checks every output against Node byte for
|
|
35
|
-
byte on marked's spec suites (2,859 cases).
|
|
36
|
-
|
|
37
|
-
§ The native binary is faster at every template size measured (3.0x at 9 KB,
|
|
38
|
-
1.2x at 65 KB); most component templates are a few KB. angular-templates'
|
|
39
|
-
[parity.mjs](angular-templates/parity.mjs) checks every output against Node
|
|
40
|
-
byte for byte on the templates of Angular's compiler compliance suite (612
|
|
41
|
-
templates).
|
|
42
|
-
|
|
43
|
-
¶ The largest codebase TypeNative compiles. The native binary is faster at
|
|
44
|
-
every size measured (2.5x at 9 KB, 1.7x at 64 KB); most component files are
|
|
45
|
-
a few KB.
|
|
46
|
-
react-compiler's [parity.mjs](react-compiler/parity.mjs) checks every output
|
|
47
|
-
against Node byte for byte (memoized code, `// CompileSuccess` memo slot and
|
|
48
|
-
block counts, and compile errors with their code frames) on 15 fixtures
|
|
49
|
-
covering components, hooks, the compiler's pragmas, JSX outlining, TypeScript
|
|
50
|
-
syntax and the error paths.
|
|
51
|
-
|
|
52
|
-
## Running an example
|
|
53
|
-
|
|
54
|
-
From a checkout of this repository (requires Node.js ≥ 24 and Go ≥ 1.26; run
|
|
55
|
-
`npm ci && npm run build` once if `bin/cli.js` does not exist yet):
|
|
56
|
-
|
|
57
|
-
```sh
|
|
58
|
-
# compile + run, one step
|
|
59
|
-
node bin/cli.js --source examples/hello-world/main.ts --script
|
|
60
|
-
|
|
61
|
-
# or compile a distributable binary
|
|
62
|
-
node bin/cli.js --source examples/hello-world/main.ts --output dist/hello.exe
|
|
63
|
-
./dist/hello.exe
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
With the published npm package, run the same commands from inside an example
|
|
67
|
-
folder using `npx typenative` instead of `node bin/cli.js`.
|
|
68
|
-
|
|
69
|
-
Under plain Node.js, the examples run directly too:
|
|
70
|
-
|
|
71
|
-
```sh
|
|
72
|
-
cd examples/fibonacci
|
|
73
|
-
node main.ts 35
|
|
74
|
-
```
|
|
75
|
-
|
|
76
|
-
desktop-notes also needs `npm install` in its folder first, for the webview
|
|
77
|
-
package. Its compiled build doesn't.
|
|
78
|
-
|
|
79
|
-
## Reproducing the benchmarks
|
|
80
|
-
|
|
81
|
-
Each example folder contains a self-contained harness that compiles the
|
|
82
|
-
example with the repo's own CLI and compares both runtimes:
|
|
83
|
-
|
|
84
|
-
```sh
|
|
85
|
-
cd examples/hello-world && node bench.mjs
|
|
86
|
-
cd examples/fibonacci && node bench.mjs 35 15
|
|
87
|
-
cd examples/json-server && node bench.mjs
|
|
88
|
-
cd examples/todo-cli && node bench.mjs
|
|
89
|
-
cd examples/dupe-finder && node bench.mjs
|
|
90
|
-
cd examples/mandelbrot-png && node bench.mjs
|
|
91
|
-
cd examples/desktop-notes && npm install && node bench.mjs
|
|
92
|
-
cd examples/yaml-cli && node bench.mjs # and node parity.mjs
|
|
93
|
-
cd examples/marked-cli && node bench.mjs # and node parity.mjs
|
|
94
|
-
cd examples/openai-chat && node bench.mjs # against a local mock API, no key needed
|
|
95
|
-
cd examples/angular-templates && node bench.mjs # and node parity.mjs
|
|
96
|
-
cd examples/react-compiler && node parity.mjs # and node bench.mjs
|
|
97
|
-
```
|
|
98
|
-
|
|
99
|
-
TypeNative's clearest wins are process startup and memory. Startup is about
|
|
100
|
-
9x faster, which is what you feel in a CLI like todo-cli. A long-running app
|
|
101
|
-
like desktop-notes idles at about a seventh of Node's memory. Disk- and
|
|
102
|
-
hash-bound work (dupe-finder) runs about 3x faster, HTTP serving (json-server)
|
|
103
|
-
handles about 1.6x more requests per second than Node 26, pure floating-point
|
|
104
|
-
loops (mandelbrot-png) run at about the same speed as V8's JIT, and
|
|
105
|
-
recursion-heavy code (fibonacci) runs about 2x faster. Every example
|
|
106
|
-
also ships as one dependency-free binary. The READMEs report what was
|
|
107
|
-
measured, including run-to-run variation and how each load was generated.
|
|
108
|
-
|
|
109
|
-
## Build check
|
|
110
|
-
|
|
111
|
-
`npm run conformance` type-checks and builds every `examples/*/main.ts` (as
|
|
112
|
-
`example-<name>`), so a change to TypeNative that breaks an example fails the
|
|
113
|
-
suite. Run just these with `node scripts/conformance.mjs example`. See the
|
|
114
|
-
[Examples section of conformance.md](../conformance.md#examples).
|
|
@@ -1,141 +0,0 @@
|
|
|
1
|
-
# Angular template compiler
|
|
2
|
-
|
|
3
|
-
The Angular template compiler, natively. [vendor/angular/compiler/](vendor/angular/compiler/)
|
|
4
|
-
holds `@angular/compiler`'s TypeScript source (`packages/compiler/src`: 233
|
|
5
|
-
files, about 66,000 lines, MIT licensed). Its logic is upstream's own; the only
|
|
6
|
-
edits are mechanical, so Node.js can run the files directly: import specifiers
|
|
7
|
-
carry their `.ts` extension, and type-only imports are marked `type`.
|
|
8
|
-
[main.ts](main.ts) parses an Angular template (control flow, bindings, pipes,
|
|
9
|
-
i18n, `@defer`, `@let`, …) with `parseTemplate`, compiles it to a component
|
|
10
|
-
definition with `compileComponentFromMetadata`, and prints the Ivy
|
|
11
|
-
instructions as JavaScript, the way the Angular CLI's output reads.
|
|
12
|
-
|
|
13
|
-
This is the largest real codebase TypeNative compiles. The compiler is
|
|
14
|
-
built around deep class hierarchies with abstract members and `super` calls,
|
|
15
|
-
visitor interfaces implemented by dozens of classes, generators, structural
|
|
16
|
-
object types that extend each other, `Map`s and `Set`s of arrays and objects,
|
|
17
|
-
`bigint` message fingerprints, and template-literal code generation whose
|
|
18
|
-
output must match V8's byte for byte.
|
|
19
|
-
|
|
20
|
-
## Usage
|
|
21
|
-
|
|
22
|
-
```sh
|
|
23
|
-
ng-compile # compile the built-in demo template
|
|
24
|
-
ng-compile app.component.html # compile a template file
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
A template with syntax errors prints them as `// error: …` comments. An error
|
|
28
|
-
the compiler throws prints as `// compile error: …` and exits with code 1.
|
|
29
|
-
|
|
30
|
-
## Run it
|
|
31
|
-
|
|
32
|
-
With Node.js. Node runs TypeScript only by stripping types, and Angular's
|
|
33
|
-
compiler source uses enums, which that mode rejects, so `run-node.mjs`
|
|
34
|
-
compiles `main.ts` and everything it imports to JavaScript with the
|
|
35
|
-
repository's `typescript` package once, caches it in `.cache/node/`, and runs
|
|
36
|
-
it:
|
|
37
|
-
|
|
38
|
-
```sh
|
|
39
|
-
node run-node.mjs my.component.html
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
With TypeNative:
|
|
43
|
-
|
|
44
|
-
```sh
|
|
45
|
-
npx typenative --source main.ts --output dist/ng-compile
|
|
46
|
-
./dist/ng-compile app.component.html
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
From a checkout of this repository:
|
|
50
|
-
|
|
51
|
-
```sh
|
|
52
|
-
node bin/cli.js --source examples/angular-templates/main.ts --output dist/ng-compile
|
|
53
|
-
```
|
|
54
|
-
|
|
55
|
-
## Parity with Node.js
|
|
56
|
-
|
|
57
|
-
Reproduce with `node parity.mjs [filter]`. The script fetches the test cases
|
|
58
|
-
of Angular's compiler compliance suite
|
|
59
|
-
(`packages/compiler-cli/test/compliance/test_cases`, at commit `939171c`) into
|
|
60
|
-
`.cache/` (it isn't committed) and compiles `main.ts`. It then compiles every
|
|
61
|
-
component template in them with both runtimes: each external `.html` template,
|
|
62
|
-
and each inline `template:` string literal. stdout, stderr and the exit code
|
|
63
|
-
must match byte for byte, with no normalization. Failures are written to
|
|
64
|
-
`.cache/failures/`.
|
|
65
|
-
|
|
66
|
-
```
|
|
67
|
-
612/612 templates match (100.00%)
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
The corpus covers control flow (`@if`, `@for`, `@switch`, `@defer` with every
|
|
71
|
-
trigger, `@let`), i18n (attributes, ICUs nested in ICUs, meanings,
|
|
72
|
-
descriptions and custom ids, legacy message ids, line-ending normalization),
|
|
73
|
-
pipes, two-way bindings, listeners, directive matching, `ng-content`
|
|
74
|
-
projection, styling bindings and templates with errors (which
|
|
75
|
-
must report the same messages).
|
|
76
|
-
|
|
77
|
-
## Benchmark: Node.js vs TypeNative
|
|
78
|
-
|
|
79
|
-
Reproduce with `node bench.mjs [runs=30] [sizeRuns=5] [kilobytes=8,16,32,64]`.
|
|
80
|
-
The script compiles `main.ts`, then times **complete process runs** (spawn to
|
|
81
|
-
exit) of `ng-compile` under both runtimes, alternating Node and native runs,
|
|
82
|
-
and checks that the two outputs are identical:
|
|
83
|
-
|
|
84
|
-
- **(a) per-call latency:** the built-in demo template (control flow,
|
|
85
|
-
bindings, pipes, listeners, `@let`, `ng-content`), about one component's
|
|
86
|
-
worth. This is what a build tool or editor pays per template when it starts
|
|
87
|
-
a compiler process per file.
|
|
88
|
-
- **(b) scaling:** generated templates from 8 to 64 KB. Each is a dashboard of
|
|
89
|
-
cards using `@if`/`@for`/`@switch`, `@defer`, `@let`, property, class, style
|
|
90
|
-
and attribute bindings, listeners, two-way bindings, pipes, i18n attributes
|
|
91
|
-
and ICUs, `ng-template` references and `ng-content`, from a fixed-seed
|
|
92
|
-
generator, so every machine gets the same input. Each card is its own
|
|
93
|
-
embedded view (`@if (panels.x) { … }`), the way sections of a real template
|
|
94
|
-
are.
|
|
95
|
-
|
|
96
|
-
**Environment:** Windows 11 Pro, AMD Ryzen 5 7600 (6 cores, 12 threads),
|
|
97
|
-
Node v26.13.0, Go 1.27.4, TypeNative 0.7.0, default
|
|
98
|
-
(non-`--release`) build. The binary is 16.7 MB. Node runs the compiler as
|
|
99
|
-
precompiled JavaScript (see [Run it](#run-it)); that build is done once,
|
|
100
|
-
before timing.
|
|
101
|
-
|
|
102
|
-
(a) `ng-compile` (built-in demo template), 30 runs each:
|
|
103
|
-
|
|
104
|
-
| Runtime | min | median | mean | max |
|
|
105
|
-
| ---------- | --------- | ----------- | ----------- | ----------- |
|
|
106
|
-
| Node.js | 218.33 ms | 222.94 ms | 225.50 ms | 302.30 ms |
|
|
107
|
-
| TypeNative | 50.29 ms | 51.74 ms | 52.91 ms | 85.98 ms |
|
|
108
|
-
|
|
109
|
-
(b) `ng-compile generated.component.html`, 5 runs per size (medians):
|
|
110
|
-
|
|
111
|
-
| Template | Node.js | TypeNative | TypeNative vs Node |
|
|
112
|
-
| ------------------ | -------- | ---------- | ------------------ |
|
|
113
|
-
| 9 KB, 186 lines | 258 ms | 85 ms | 3.0x faster |
|
|
114
|
-
| 16 KB, 362 lines | 282 ms | 115 ms | 2.5x faster |
|
|
115
|
-
| 32 KB, 706 lines | 316 ms | 180 ms | 1.8x faster |
|
|
116
|
-
| 65 KB, 1,388 lines | 393 ms | 321 ms | 1.2x faster |
|
|
117
|
-
|
|
118
|
-
**Per call, TypeNative is 4.3x faster** (52 ms vs 223 ms, median). Almost
|
|
119
|
-
all of both times is fixed: a one-line template takes about as long. Node
|
|
120
|
-
spends it loading and evaluating the compiler's 233 modules before it
|
|
121
|
-
compiles anything. The native binary's 52 ms is mostly the compiler's own
|
|
122
|
-
module setup, such as the DOM schema and entity tables.
|
|
123
|
-
|
|
124
|
-
**The native binary is faster at every size measured, including 65 KB
|
|
125
|
-
(1.2x).** Past startup, compiling costs about 4 ms per KB natively against
|
|
126
|
-
about 2–3 ms per KB under V8's JIT, so the gap narrows as templates grow. Most
|
|
127
|
-
of the 64 KB run is the compiler's operation traversal: its 74 phases each
|
|
128
|
-
iterate the operation lists (`OpList`), and the garbage collector scans the
|
|
129
|
-
IR they build. Before this was fixed, about a third of the samples were
|
|
130
|
-
goroutine hand-offs: iterating an `OpList` reached through a dynamically
|
|
131
|
-
typed op field (`op.handlerOps`, `op.trackByOps`) went through reflection to
|
|
132
|
-
its `*[Symbol.iterator]()` channel, one goroutine per list. `TnToArray` now
|
|
133
|
-
recognizes the generator's push form directly (`Symbol_iterator__seq`) and
|
|
134
|
-
iterates it in place, with no reflection, channel or goroutine per list; the
|
|
135
|
-
64 KB run fell from about 600 ms to about 320 ms.
|
|
136
|
-
|
|
137
|
-
A template whose sections all share the root view is another matter: Angular
|
|
138
|
-
copies every `@let` and `#ref` of a view into each of its child views, so with
|
|
139
|
-
hundreds of them at the top level the compile becomes quadratic in both
|
|
140
|
-
runtimes. In this generator without the per-card `@if`, 64 KB took 2.7 s under
|
|
141
|
-
Node and 7.3 s natively.
|
|
@@ -1,173 +0,0 @@
|
|
|
1
|
-
// Benchmark: Node.js vs TypeNative for the Angular template compiler, both
|
|
2
|
-
// compiling a template to Ivy instructions (`ng-compile template.html`).
|
|
3
|
-
//
|
|
4
|
-
// Compiles main.ts to a native binary with the TypeNative CLI from this repo
|
|
5
|
-
// checkout (../../bin/cli.js), then measures:
|
|
6
|
-
// (a) per-call latency: complete process runs (spawn to exit) on the
|
|
7
|
-
// built-in demo template (control flow, bindings, pipes, listeners,
|
|
8
|
-
// @let, ng-content), about one component's worth;
|
|
9
|
-
// (b) scaling: generated templates of growing size (8 to 64 KB by
|
|
10
|
-
// default), each a dashboard of cards with @if/@for/@switch, @defer,
|
|
11
|
-
// @let, property/class/style/attr bindings, listeners, two-way
|
|
12
|
-
// bindings, pipes, i18n attributes and ICUs, ng-template references and
|
|
13
|
-
// ng-content. Each card is its own embedded view (`@if (panels.x)`), as
|
|
14
|
-
// sections of a real template are, so its @let and #refs stay local.
|
|
15
|
-
// Runs alternate Node and native, so drift on the machine hits both alike.
|
|
16
|
-
// Both runtimes' output must be identical, or the benchmark stops.
|
|
17
|
-
//
|
|
18
|
-
// Usage: node bench.mjs [runs=30] [sizeRuns=5] [kilobytes=8,16,32,64]
|
|
19
|
-
|
|
20
|
-
import { spawnSync } from 'node:child_process';
|
|
21
|
-
import fs from 'node:fs';
|
|
22
|
-
import path from 'node:path';
|
|
23
|
-
import { fileURLToPath } from 'node:url';
|
|
24
|
-
|
|
25
|
-
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
26
|
-
const repoRoot = path.resolve(here, '..', '..');
|
|
27
|
-
const cli = path.join(repoRoot, 'bin', 'cli.js');
|
|
28
|
-
const cache = path.join(here, '.cache');
|
|
29
|
-
const exePath = path.join(cache, process.platform === 'win32' ? 'ng-compile.exe' : 'ng-compile');
|
|
30
|
-
const bigPath = path.join(cache, 'generated.component.html');
|
|
31
|
-
const runs = Number(process.argv[2] ?? '30') || 30;
|
|
32
|
-
const sizeRuns = Number(process.argv[3] ?? '5') || 5;
|
|
33
|
-
const sizes = (process.argv[4] ?? '8,16,32,64').split(',').map(Number).filter((n) => n > 0);
|
|
34
|
-
|
|
35
|
-
// Deterministic pseudo-random numbers (a fixed-seed LCG): the same template
|
|
36
|
-
// on every run and every machine
|
|
37
|
-
let seed = 42;
|
|
38
|
-
function rand(n) {
|
|
39
|
-
seed = (seed * 1103515245 + 12345) % 2147483648;
|
|
40
|
-
return Math.floor(seed / 65536) % n;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
const WORDS = ['user', 'order', 'item', 'price', 'label', 'status', 'owner', 'total', 'title', 'count', 'tag', 'note'];
|
|
44
|
-
const PIPES = ['uppercase', 'lowercase', 'titlecase', 'json', 'async'];
|
|
45
|
-
|
|
46
|
-
function word() {
|
|
47
|
-
return WORDS[rand(WORDS.length)];
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
function card(i) {
|
|
51
|
-
const a = word();
|
|
52
|
-
const b = word();
|
|
53
|
-
const lines = [`@if (panels.${a}${i}) {`, `<article class="card card-${i}" [class.selected]="selected === ${i}" [style.width.px]="width + ${rand(100)}">`];
|
|
54
|
-
lines.push(` <h2 i18n-title title="Card ${a}" [attr.data-id]="${a}.id">{{ ${a}.${b} | ${PIPES[rand(PIPES.length)]} }} #${i}</h2>`);
|
|
55
|
-
lines.push(` @let ${a}Total${i} = ${a}.items.length * ${1 + rand(9)};`);
|
|
56
|
-
switch (rand(5)) {
|
|
57
|
-
case 0:
|
|
58
|
-
lines.push(` @if (${a}.${b} && ${a}Total${i} > ${rand(50)}) {`, ` <p class="hint">{{ ${a}.${b} }} of {{ ${a}Total${i} }}</p>`,
|
|
59
|
-
` } @else if (${a}.loading) {`, ` <spinner size="${rand(4)}" />`, ` } @else {`, ` <p>Nothing for {{ ${b} }}</p>`, ` }`);
|
|
60
|
-
break;
|
|
61
|
-
case 1:
|
|
62
|
-
lines.push(` <ul>`, ` @for (row of ${a}.rows; track row.id; let idx = $index, odd = $odd) {`,
|
|
63
|
-
` <li [class.odd]="odd" (click)="select(row, idx, $event)">{{ idx + 1 }}. {{ row.${b} }} ({{ row.price | currency }})</li>`,
|
|
64
|
-
` } @empty {`, ` <li i18n>No ${b} rows</li>`, ` }`, ` </ul>`);
|
|
65
|
-
break;
|
|
66
|
-
case 2:
|
|
67
|
-
lines.push(` @switch (${a}.mode) {`, ` @case ('edit') { <input [(ngModel)]="${a}.${b}" (keyup.enter)="save(${a})" [disabled]="busy" /> }`,
|
|
68
|
-
` @case ('view') { <span>{{ ${a}.${b} ?? 'n/a' }}</span> }`, ` @default { <em>{{ ${a}.mode }}</em> }`, ` }`);
|
|
69
|
-
break;
|
|
70
|
-
case 3:
|
|
71
|
-
lines.push(` @defer (on viewport; prefetch on idle) {`, ` <heavy-chart [data]="${a}.series" [title]="'${b} ' + ${i}" />`,
|
|
72
|
-
` } @placeholder (minimum 100ms) {`, ` <div class="skeleton"></div>`, ` } @loading {`, ` <p>Loading…</p>`, ` }`);
|
|
73
|
-
break;
|
|
74
|
-
default:
|
|
75
|
-
lines.push(` <span i18n>{${a}Total${i}, plural, =0 {no ${b}s} =1 {one ${b}} other {{{ ${a}Total${i} }} ${b}s}}</span>`,
|
|
76
|
-
` <ng-template #tpl${i} let-value="value"><b>{{ value }}</b></ng-template>`,
|
|
77
|
-
` <ng-container *ngTemplateOutlet="tpl${i}; context: { value: ${a}.${b} }" />`);
|
|
78
|
-
}
|
|
79
|
-
lines.push(` <button type="button" (click)="remove(${i})" [attr.aria-label]="'Remove ' + ${a}.${b}">Remove</button>`, `</article>`, `}`);
|
|
80
|
-
return lines.join('\n');
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function template(bytes) {
|
|
84
|
-
const out = ['<section class="dashboard">'];
|
|
85
|
-
let size = 0;
|
|
86
|
-
for (let i = 0; size < bytes; i++) {
|
|
87
|
-
const c = card(i);
|
|
88
|
-
out.push(c);
|
|
89
|
-
size += c.length + 1;
|
|
90
|
-
}
|
|
91
|
-
out.push(' <ng-content select="[slot=footer]" />', '</section>', '');
|
|
92
|
-
return out.join('\n');
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
function stats(samples) {
|
|
96
|
-
const sorted = [...samples].sort((a, b) => a - b);
|
|
97
|
-
const mean = samples.reduce((sum, x) => sum + x, 0) / samples.length;
|
|
98
|
-
return { min: sorted[0], median: sorted[Math.floor(sorted.length / 2)], mean, max: sorted[sorted.length - 1] };
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
function fmt(ms) {
|
|
102
|
-
return `${ms.toFixed(2)} ms`.padStart(13);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
function runOnce(command, args) {
|
|
106
|
-
const t0 = performance.now();
|
|
107
|
-
const result = spawnSync(command, args, { cwd: here, maxBuffer: 1 << 30 });
|
|
108
|
-
const elapsed = performance.now() - t0;
|
|
109
|
-
if (result.status !== 0) {
|
|
110
|
-
console.error(`run failed: ${command} ${args.join(' ')}\n${result.stdout}\n${result.stderr}`);
|
|
111
|
-
process.exit(1);
|
|
112
|
-
}
|
|
113
|
-
return { elapsed, stdout: result.stdout };
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// Alternating Node and native runs; the two outputs must match
|
|
117
|
-
function timeBoth(args, count) {
|
|
118
|
-
const node = [];
|
|
119
|
-
const native = [];
|
|
120
|
-
for (let i = 0; i < count; i++) {
|
|
121
|
-
const a = runOnce(process.execPath, ['run-node.mjs', ...args]);
|
|
122
|
-
const b = runOnce(exePath, args);
|
|
123
|
-
if (!a.stdout.equals(b.stdout)) {
|
|
124
|
-
console.error('Node and native output differ');
|
|
125
|
-
process.exit(1);
|
|
126
|
-
}
|
|
127
|
-
if (a.stdout.toString().startsWith('// error:')) {
|
|
128
|
-
console.error(`the template has errors:\n${a.stdout.toString().slice(0, 2000)}`);
|
|
129
|
-
process.exit(1);
|
|
130
|
-
}
|
|
131
|
-
node.push(a.elapsed);
|
|
132
|
-
native.push(b.elapsed);
|
|
133
|
-
}
|
|
134
|
-
return [stats(node), stats(native)];
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
function table(nodeStats, nativeStats) {
|
|
138
|
-
console.log('| Runtime | min | median | mean | max |');
|
|
139
|
-
console.log('|------------|--------------|--------------|--------------|--------------|');
|
|
140
|
-
console.log(`| Node.js |${fmt(nodeStats.min)} |${fmt(nodeStats.median)} |${fmt(nodeStats.mean)} |${fmt(nodeStats.max)} |`);
|
|
141
|
-
console.log(`| TypeNative |${fmt(nativeStats.min)} |${fmt(nativeStats.median)} |${fmt(nativeStats.mean)} |${fmt(nativeStats.max)} |`);
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// 1. Compile the CLI to a native binary.
|
|
145
|
-
fs.mkdirSync(cache, { recursive: true });
|
|
146
|
-
console.log('Compiling main.ts to a native binary with TypeNative...');
|
|
147
|
-
const build = spawnSync(process.execPath, [cli, '--source', 'main.ts', '--output', exePath], { cwd: here, stdio: 'inherit' });
|
|
148
|
-
if (build.status !== 0) process.exit(build.status ?? 1);
|
|
149
|
-
console.log(`Binary: ${(fs.statSync(exePath).size / (1024 * 1024)).toFixed(1)} MB`);
|
|
150
|
-
|
|
151
|
-
// Compile main.ts to JavaScript for the Node runs (see run-node.mjs), outside the timings
|
|
152
|
-
const nodeBuild = spawnSync(process.execPath, ['run-node.mjs', '--build'], { cwd: here, stdio: 'inherit' });
|
|
153
|
-
if (nodeBuild.status !== 0) process.exit(nodeBuild.status ?? 1);
|
|
154
|
-
|
|
155
|
-
// 2. Per-call latency on the demo template.
|
|
156
|
-
console.log(`\n(a) \`ng-compile\` (built-in demo template), ${runs} runs each (full process: spawn -> exit):\n`);
|
|
157
|
-
const [nodeCall, nativeCall] = timeBoth([], runs);
|
|
158
|
-
table(nodeCall, nativeCall);
|
|
159
|
-
console.log(`\nTypeNative is ${(nodeCall.median / nativeCall.median).toFixed(1)}x faster per call (median).`);
|
|
160
|
-
|
|
161
|
-
// 3. Scaling on generated templates.
|
|
162
|
-
console.log(`\n(b) \`ng-compile generated.component.html\`, ${sizeRuns} runs per size (medians):\n`);
|
|
163
|
-
console.log('| Template | Node.js | TypeNative | TypeNative vs Node |');
|
|
164
|
-
console.log('|-------------------|--------------|--------------|--------------------|');
|
|
165
|
-
for (const size of sizes) {
|
|
166
|
-
seed = 42;
|
|
167
|
-
const big = template(size * 1024);
|
|
168
|
-
fs.writeFileSync(bigPath, big);
|
|
169
|
-
const [nodeBig, nativeBig] = timeBoth([bigPath], sizeRuns);
|
|
170
|
-
const ratio = nodeBig.median / nativeBig.median;
|
|
171
|
-
const label = `${(big.length / 1024).toFixed(0)} KB, ${big.split('\n').length} lines`.padEnd(17);
|
|
172
|
-
console.log(`| ${label} |${fmt(nodeBig.median)} |${fmt(nativeBig.median)} | ${(ratio >= 1 ? `${ratio.toFixed(1)}x faster` : `${(1 / ratio).toFixed(1)}x slower`).padEnd(18)} |`);
|
|
173
|
-
}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
// Ambient declarations for the checker: the Trusted Types DOM API, which the
|
|
2
|
-
// Angular compiler references but never runs in a native binary (every use
|
|
3
|
-
// is guarded by `globalThis['trustedTypes']`, undefined there). The Go side
|
|
4
|
-
// of these types comes from dom-type-stubs.ts, imported by main.ts.
|
|
5
|
-
|
|
6
|
-
declare interface TrustedScript {}
|
|
7
|
-
|
|
8
|
-
declare interface TrustedTypePolicy {
|
|
9
|
-
createScript(script: string, ...args: unknown[]): TrustedScript;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
declare interface TrustedTypePolicyFactory {
|
|
13
|
-
createPolicy(
|
|
14
|
-
policyName: string,
|
|
15
|
-
policyOptions: {
|
|
16
|
-
createScript?: (script: string, ...args: unknown[]) => TrustedScript;
|
|
17
|
-
createScriptURL?: (scriptURL: string, ...args: unknown[]) => string;
|
|
18
|
-
[key: string]: unknown;
|
|
19
|
-
},
|
|
20
|
-
): TrustedTypePolicy;
|
|
21
|
-
}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
// Ambient DOM types the Angular compiler references but never executes in a
|
|
2
|
-
// native binary: the Trusted Types API does not exist there, and every use
|
|
3
|
-
// is guarded by `globalThis['trustedTypes']`, which is undefined. Declared
|
|
4
|
-
// as real (empty-shaped) interfaces so the compiled Go types exist.
|
|
5
|
-
|
|
6
|
-
export interface TrustedScript {}
|
|
7
|
-
|
|
8
|
-
export interface TrustedTypePolicy {
|
|
9
|
-
createScript(script: string, ...args: unknown[]): TrustedScript;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export interface TrustedTypePolicyFactory {
|
|
13
|
-
createPolicy(
|
|
14
|
-
policyName: string,
|
|
15
|
-
policyOptions: {
|
|
16
|
-
createScript?: (script: string, ...args: unknown[]) => TrustedScript;
|
|
17
|
-
createScriptURL?: (scriptURL: string, ...args: unknown[]) => string;
|
|
18
|
-
[key: string]: unknown;
|
|
19
|
-
},
|
|
20
|
-
): TrustedTypePolicy;
|
|
21
|
-
}
|
|
@@ -1,135 +0,0 @@
|
|
|
1
|
-
// Angular template compiler, natively: the vendored @angular/compiler parses
|
|
2
|
-
// an Angular template (control flow, bindings, pipes, i18n, @defer, …) and
|
|
3
|
-
// compiles it to the Ivy instructions of a component definition, printed as
|
|
4
|
-
// JavaScript. The output is the same as running this file under Node.
|
|
5
|
-
//
|
|
6
|
-
// node run-node.mjs [template.html]
|
|
7
|
-
// typenative --source main.ts --output ng-compile && ./ng-compile [template.html]
|
|
8
|
-
|
|
9
|
-
import './dom-type-stubs.ts';
|
|
10
|
-
import * as fs from 'node:fs';
|
|
11
|
-
import {
|
|
12
|
-
ChangeDetectionStrategy,
|
|
13
|
-
compileComponentFromMetadata,
|
|
14
|
-
ConstantPool,
|
|
15
|
-
DeclarationListEmitMode,
|
|
16
|
-
DeferBlockDepsEmitMode,
|
|
17
|
-
EmitterVisitorContext,
|
|
18
|
-
makeBindingParser,
|
|
19
|
-
outputAst as o,
|
|
20
|
-
parseTemplate,
|
|
21
|
-
ParseLocation,
|
|
22
|
-
ParseSourceFile,
|
|
23
|
-
ParseSourceSpan,
|
|
24
|
-
ViewEncapsulation,
|
|
25
|
-
type R3ComponentMetadata,
|
|
26
|
-
type R3TemplateDependency,
|
|
27
|
-
} from './vendor/angular/compiler/src/compiler.ts';
|
|
28
|
-
import { AbstractJsEmitterVisitor } from './vendor/angular/compiler/src/output/abstract_js_emitter.ts';
|
|
29
|
-
|
|
30
|
-
const DEMO_TEMPLATE = `<section class="card" [class.compact]="compact">
|
|
31
|
-
@if (user.name) {
|
|
32
|
-
<h1 title="Greeting">Hello {{ user.name | titlecase }}!</h1>
|
|
33
|
-
} @else {
|
|
34
|
-
<h1>Hello stranger</h1>
|
|
35
|
-
}
|
|
36
|
-
<ul>
|
|
37
|
-
@for (item of items; track item.id; let i = $index, last = $last) {
|
|
38
|
-
<li [class.active]="item.id === selectedId" (click)="pick(item.id, $event)">
|
|
39
|
-
{{ i + 1 }}. {{ item.label }}@if (!last) {,}
|
|
40
|
-
</li>
|
|
41
|
-
} @empty {
|
|
42
|
-
<li>No items yet</li>
|
|
43
|
-
}
|
|
44
|
-
</ul>
|
|
45
|
-
@switch (mode) {
|
|
46
|
-
@case ('edit') { <input [value]="draft" (input)="draft = $any($event.target).value" /> }
|
|
47
|
-
@default { <p>{{ draft || 'Nothing to edit' }}</p> }
|
|
48
|
-
}
|
|
49
|
-
<ng-template #tpl let-label="label"><b>{{ label }}</b></ng-template>
|
|
50
|
-
<button type="button" [disabled]="!items.length" (click)="save()">Save {{ items.length }}</button>
|
|
51
|
-
@let total = items.length * 2;
|
|
52
|
-
<footer [attr.data-total]="total" [style.color]="color">{{ total }} points</footer>
|
|
53
|
-
<ng-content select="[slot=footer]" />
|
|
54
|
-
</section>
|
|
55
|
-
`;
|
|
56
|
-
|
|
57
|
-
// Prints external references (Ivy instructions) as `i0.ɵɵname`, as the
|
|
58
|
-
// Angular CLI's output does
|
|
59
|
-
class SourceEmitter extends AbstractJsEmitterVisitor {
|
|
60
|
-
override visitExternalExpr(ast: o.ExternalExpr, ctx: EmitterVisitorContext): any {
|
|
61
|
-
const name = ast.value.name ?? 'unknown';
|
|
62
|
-
ctx.print(ast, ast.value.moduleName === '@angular/core' ? `i0.${name}` : name);
|
|
63
|
-
return null;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function emit(statement: o.Statement): string {
|
|
68
|
-
const ctx = EmitterVisitorContext.createRoot();
|
|
69
|
-
statement.visitStatement(new SourceEmitter(), ctx);
|
|
70
|
-
return ctx.toSource();
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
function compile(template: string, url: string): string {
|
|
74
|
-
const parsed = parseTemplate(template, url, { preserveWhitespaces: false });
|
|
75
|
-
const out: string[] = [];
|
|
76
|
-
if (parsed.errors !== null && parsed.errors.length > 0) {
|
|
77
|
-
for (const error of parsed.errors) out.push(`// error: ${error}`);
|
|
78
|
-
return out.join('\n');
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
const file = new ParseSourceFile('', 'demo.component.ts');
|
|
82
|
-
const start = new ParseLocation(file, 0, 0, 0);
|
|
83
|
-
const meta: R3ComponentMetadata<R3TemplateDependency> = {
|
|
84
|
-
name: 'DemoComponent',
|
|
85
|
-
type: { value: new o.ReadVarExpr('DemoComponent'), type: new o.ReadVarExpr('DemoComponent') },
|
|
86
|
-
typeArgumentCount: 0,
|
|
87
|
-
typeSourceSpan: new ParseSourceSpan(start, start),
|
|
88
|
-
deps: [],
|
|
89
|
-
selector: 'app-demo',
|
|
90
|
-
queries: [],
|
|
91
|
-
viewQueries: [],
|
|
92
|
-
host: { attributes: {}, listeners: {}, properties: {}, specialAttributes: {} },
|
|
93
|
-
lifecycle: { usesOnChanges: false },
|
|
94
|
-
inputs: {},
|
|
95
|
-
outputs: {},
|
|
96
|
-
usesInheritance: false,
|
|
97
|
-
controlCreate: null,
|
|
98
|
-
exportAs: null,
|
|
99
|
-
providers: null,
|
|
100
|
-
isStandalone: true,
|
|
101
|
-
isSignal: false,
|
|
102
|
-
hostDirectives: null,
|
|
103
|
-
legacyOptionalChaining: false,
|
|
104
|
-
i18nUseExternalIds: true,
|
|
105
|
-
template: { nodes: parsed.nodes, ngContentSelectors: parsed.ngContentSelectors, preserveWhitespaces: false },
|
|
106
|
-
declarations: [],
|
|
107
|
-
defer: { mode: DeferBlockDepsEmitMode.PerComponent, dependenciesFn: null },
|
|
108
|
-
declarationListEmitMode: DeclarationListEmitMode.Direct,
|
|
109
|
-
styles: [],
|
|
110
|
-
encapsulation: ViewEncapsulation.Emulated,
|
|
111
|
-
animations: null,
|
|
112
|
-
viewProviders: null,
|
|
113
|
-
relativeContextFilePath: 'demo.component.ts',
|
|
114
|
-
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
115
|
-
relativeTemplatePath: null,
|
|
116
|
-
hasDirectiveDependencies: false,
|
|
117
|
-
foreignImports: null,
|
|
118
|
-
};
|
|
119
|
-
|
|
120
|
-
const pool = new ConstantPool();
|
|
121
|
-
const compiled = compileComponentFromMetadata(meta, pool, makeBindingParser());
|
|
122
|
-
for (const statement of pool.statements) out.push(emit(statement));
|
|
123
|
-
out.push(emit(new o.DeclareVarStmt('ɵcmp', compiled.expression, undefined, o.StmtModifier.Final)));
|
|
124
|
-
return out.join('\n');
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
const path = process.argv[2];
|
|
128
|
-
const template = path ? fs.readFileSync(path, 'utf-8') : DEMO_TEMPLATE;
|
|
129
|
-
try {
|
|
130
|
-
console.log(compile(template, path ?? 'demo.component.html'));
|
|
131
|
-
} catch (e) {
|
|
132
|
-
// (an error the compiler throws, as a comment: the same under both runtimes)
|
|
133
|
-
console.log(`// compile error: ${(e as Error).message}`);
|
|
134
|
-
process.exitCode = 1;
|
|
135
|
-
}
|