typenative 0.5.0 → 0.6.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.
Files changed (149) hide show
  1. package/.github/workflows/ci.yml +2 -2
  2. package/.github/workflows/npm-publish-github-packages.yml +2 -2
  3. package/CHANGELOG.md +339 -0
  4. package/CONTRIBUTION.md +2 -1
  5. package/README.md +16 -7
  6. package/bin/cli.js +1 -0
  7. package/bin/index.js +62 -3
  8. package/bin/main.js +1 -0
  9. package/bin/node/core.js +46 -0
  10. package/bin/node/events.js +154 -15
  11. package/bin/node/http.js +1265 -127
  12. package/bin/node/process.js +13 -0
  13. package/bin/node/punycode.js +2 -2
  14. package/bin/node/stream.js +56 -7
  15. package/bin/node/stream_web.js +2 -2
  16. package/bin/node/timers.js +4 -2
  17. package/bin/node/url.js +28 -3
  18. package/bin/parse-node.js +2 -2
  19. package/bin/regex_vm.js +2105 -0
  20. package/bin/transpiler.js +17970 -4419
  21. package/bin/typecheck-node.js +2 -1
  22. package/bin/version.js +1 -1
  23. package/conformance.md +57 -15
  24. package/examples/README.md +50 -28
  25. package/examples/angular-templates/README.md +141 -0
  26. package/examples/angular-templates/bench.mjs +173 -0
  27. package/examples/angular-templates/dom-type-globals.d.ts +21 -0
  28. package/examples/angular-templates/dom-type-stubs.ts +21 -0
  29. package/examples/angular-templates/main.ts +135 -0
  30. package/examples/angular-templates/parity.mjs +157 -0
  31. package/examples/angular-templates/run-node.mjs +69 -0
  32. package/examples/angular-templates/vendor/angular/compiler/LICENSE +21 -0
  33. package/examples/desktop-notes/README.md +11 -13
  34. package/examples/dupe-finder/README.md +7 -5
  35. package/examples/fibonacci/README.md +7 -7
  36. package/examples/hello-world/README.md +6 -6
  37. package/examples/json-server/README.md +22 -18
  38. package/examples/mandelbrot-png/README.md +11 -13
  39. package/examples/marked-cli/README.md +60 -44
  40. package/examples/marked-cli/main.ts +122 -4
  41. package/examples/openai-chat/README.md +148 -0
  42. package/examples/openai-chat/bench.mjs +175 -0
  43. package/examples/openai-chat/main.ts +488 -0
  44. package/examples/react-compiler/README.md +185 -0
  45. package/examples/react-compiler/bench.mjs +181 -0
  46. package/examples/react-compiler/main.ts +324 -0
  47. package/examples/react-compiler/parity.mjs +362 -0
  48. package/examples/react-compiler/run-node.mjs +90 -0
  49. package/examples/react-compiler/vendor/babel/LICENSE +22 -0
  50. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-lower.json +15 -0
  51. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-upper.json +51 -0
  52. package/examples/react-compiler/vendor/charcodes/package.json +25 -0
  53. package/examples/react-compiler/vendor/invariant/LICENSE +21 -0
  54. package/examples/react-compiler/vendor/invariant/invariant.cjs +51 -0
  55. package/examples/react-compiler/vendor/invariant/invariant.d.cts +11 -0
  56. package/examples/react-compiler/vendor/invariant/types/LICENSE +21 -0
  57. package/examples/react-compiler/vendor/jridgewell/gen-mapping/LICENSE +19 -0
  58. package/examples/react-compiler/vendor/jridgewell/resolve-uri/LICENSE +19 -0
  59. package/examples/react-compiler/vendor/jridgewell/sourcemap-codec/LICENSE +19 -0
  60. package/examples/react-compiler/vendor/jridgewell/trace-mapping/LICENSE +19 -0
  61. package/examples/react-compiler/vendor/js-tokens/LICENSE +21 -0
  62. package/examples/react-compiler/vendor/js-tokens/index.cjs +23 -0
  63. package/examples/react-compiler/vendor/js-tokens/index.d.cts +13 -0
  64. package/examples/react-compiler/vendor/jsesc/LICENSE-MIT.txt +20 -0
  65. package/examples/react-compiler/vendor/jsesc/jsesc.cjs +337 -0
  66. package/examples/react-compiler/vendor/jsesc/jsesc.d.cts +384 -0
  67. package/examples/react-compiler/vendor/jsesc/types/LICENSE +21 -0
  68. package/examples/react-compiler/vendor/picocolors/LICENSE +15 -0
  69. package/examples/react-compiler/vendor/picocolors/picocolors.cjs +75 -0
  70. package/examples/react-compiler/vendor/picocolors/picocolors.d.cts +5 -0
  71. package/examples/react-compiler/vendor/picocolors/types.d.ts +51 -0
  72. package/examples/react-compiler/vendor/react-compiler/LICENSE +21 -0
  73. package/examples/react-compiler/vendor/stubs/babel-core.ts +31 -0
  74. package/examples/react-compiler/vendor/stubs/debug.ts +18 -0
  75. package/examples/react-compiler/vendor/stubs/js-tokens.d.ts +13 -0
  76. package/examples/react-compiler/vendor/stubs/pretty-format.ts +18 -0
  77. package/examples/react-compiler/vendor/zod/LICENSE +21 -0
  78. package/examples/react-compiler/vendor/zod-validation-error/LICENSE +9 -0
  79. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/NonEmptyArray.ts +5 -0
  80. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinPath.ts +49 -0
  81. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinValues.ts +48 -0
  82. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/stringify.ts +50 -0
  83. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/titleCase.ts +6 -0
  84. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/MessageBuilder.ts +126 -0
  85. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/ValidationError.ts +39 -0
  86. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/custom.ts +12 -0
  87. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/errorMap.ts +78 -0
  88. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/index.ts +2 -0
  89. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidElement.ts +12 -0
  90. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidKey.ts +12 -0
  91. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidStringFormat.ts +131 -0
  92. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidType.ts +54 -0
  93. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidUnion.ts +12 -0
  94. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidValue.ts +40 -0
  95. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/notMultipleOf.ts +12 -0
  96. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooBig.ts +76 -0
  97. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooSmall.ts +76 -0
  98. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/types.ts +27 -0
  99. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/unrecognizedKeys.ts +27 -0
  100. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromError.ts +13 -0
  101. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodError.ts +61 -0
  102. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodIssue.ts +38 -0
  103. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/index.ts +20 -0
  104. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationError.ts +5 -0
  105. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationErrorLike.ts +8 -0
  106. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isZodErrorLike.ts +11 -0
  107. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/toValidationError.ts +20 -0
  108. package/examples/react-compiler/vendor.mjs +688 -0
  109. package/examples/todo-cli/README.md +9 -9
  110. package/examples/yaml-cli/README.md +50 -34
  111. package/examples/yaml-cli/main.ts +236 -14
  112. package/package.json +8 -5
  113. package/performance/README.md +196 -0
  114. package/performance/any-dynamic.ts +21 -0
  115. package/performance/any-record-view.ts +20 -0
  116. package/performance/arr-hof.ts +21 -0
  117. package/performance/arr-push-index.ts +15 -0
  118. package/performance/arr-sort.ts +21 -0
  119. package/performance/async-await.ts +24 -0
  120. package/performance/class-dispatch.ts +52 -0
  121. package/performance/events-emit.ts +27 -0
  122. package/performance/exc-throw-rare.ts +25 -0
  123. package/performance/exc-try-catch.ts +26 -0
  124. package/performance/fn-closures.ts +29 -0
  125. package/performance/fn-recursion-tree.ts +31 -0
  126. package/performance/gen-for-of.ts +46 -0
  127. package/performance/json-roundtrip.ts +27 -0
  128. package/performance/map-delete.ts +24 -0
  129. package/performance/map-string-keys.ts +22 -0
  130. package/performance/num-arith-loop.ts +14 -0
  131. package/performance/num-bitwise.ts +21 -0
  132. package/performance/num-mod-int.ts +16 -0
  133. package/performance/num-to-string.ts +16 -0
  134. package/performance/obj-alloc.ts +32 -0
  135. package/performance/regex-exec.ts +29 -0
  136. package/performance/regex-site.ts +28 -0
  137. package/performance/set-ops.ts +20 -0
  138. package/performance/str-char-scan.ts +35 -0
  139. package/performance/str-concat-plus.ts +18 -0
  140. package/performance/str-concat.ts +24 -0
  141. package/performance/str-short-scan.ts +26 -0
  142. package/performance/str-split-join.ts +23 -0
  143. package/performance/str-template.ts +16 -0
  144. package/performance/union-switch.ts +57 -0
  145. package/tsparser/check.go +2 -1
  146. package/tsparser/main.go +1 -0
  147. package/types/typenative-npm.d.ts +3 -2
  148. package/types/typenative.d.ts +42 -12
  149. package/ROUND2-HANDOFF.md +0 -200
@@ -0,0 +1,173 @@
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
+ }
@@ -0,0 +1,21 @@
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
+ }
@@ -0,0 +1,21 @@
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
+ }
@@ -0,0 +1,135 @@
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
+ }
@@ -0,0 +1,157 @@
1
+ // Parity check: Node.js vs the TypeNative build of the Angular template compiler.
2
+ //
3
+ // Fetches the component templates of Angular's own compiler compliance tests
4
+ // (packages/compiler-cli/test/compliance/test_cases, at a pinned commit) into
5
+ // .cache/, compiles main.ts to a native binary with the TypeNative CLI from
6
+ // this repo checkout, then compiles every template with both runtimes. stdout,
7
+ // stderr and the exit code must match byte for byte. Failures are written to
8
+ // .cache/failures/.
9
+ //
10
+ // The corpus: every external .html template, and every inline `template:`
11
+ // string literal (backtick strings with `${…}` substitutions and concatenated
12
+ // strings are left out: their text is only known when the test file runs).
13
+ //
14
+ // Usage: node parity.mjs [filter] (filter: a substring of a case id)
15
+
16
+ import { spawn, spawnSync } from 'node:child_process';
17
+ import fs from 'node:fs';
18
+ import os from 'node:os';
19
+ import path from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
+
22
+ const here = path.dirname(fileURLToPath(import.meta.url));
23
+ const repoRoot = path.resolve(here, '..', '..');
24
+ const cli = path.join(repoRoot, 'bin', 'cli.js');
25
+ const cache = path.join(here, '.cache');
26
+ const upstream = path.join(cache, 'angular-src');
27
+ const COMMIT = '939171c6f92eb9e7401afa142a343aff4f3ff859';
28
+ const TEST_CASES = 'packages/compiler-cli/test/compliance/test_cases';
29
+ const casesDir = path.join(upstream, TEST_CASES);
30
+ const inputsDir = path.join(cache, 'templates');
31
+ const failuresDir = path.join(cache, 'failures');
32
+ const exePath = path.join(cache, process.platform === 'win32' ? 'ng-compile.exe' : 'ng-compile');
33
+ const filter = process.argv[2] ?? '';
34
+
35
+ function run(command, args, options = {}) {
36
+ const result = spawnSync(command, args, { stdio: 'inherit', ...options });
37
+ if (result.status !== 0) {
38
+ console.error(`${command} ${args.join(' ')} failed`);
39
+ process.exit(1);
40
+ }
41
+ }
42
+
43
+ // The compliance test cases at the pinned commit (a sparse, blobless fetch)
44
+ function fetchCases() {
45
+ if (fs.existsSync(casesDir)) return;
46
+ fs.mkdirSync(upstream, { recursive: true });
47
+ console.log(`Fetching angular/angular ${COMMIT.slice(0, 7)} ${TEST_CASES} ...`);
48
+ const git = (...args) => run('git', ['-C', upstream, ...args]);
49
+ git('init', '--quiet');
50
+ git('remote', 'add', 'origin', 'https://github.com/angular/angular.git');
51
+ git('sparse-checkout', 'set', TEST_CASES);
52
+ git('fetch', '--quiet', '--depth', '1', '--filter=blob:none', 'origin', COMMIT);
53
+ git('checkout', '--quiet', 'FETCH_HEAD');
54
+ }
55
+
56
+ // A JS string literal's body with its escapes resolved
57
+ function unescape(body) {
58
+ return body.replace(/\\(u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|\r?\n|.)/g, (_, c) => {
59
+ if (c[0] === 'u') return String.fromCodePoint(parseInt(c[1] === '{' ? c.slice(2, -1) : c.slice(1), 16));
60
+ if (c[0] === 'x') return String.fromCharCode(parseInt(c.slice(1), 16));
61
+ if (c === '\n' || c === '\r\n') return '';
62
+ return { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', 0: '\0' }[c] ?? c;
63
+ });
64
+ }
65
+
66
+ // The `template:` string literals of a test file
67
+ function inlineTemplates(file) {
68
+ const src = fs.readFileSync(file, 'utf8');
69
+ const found = [];
70
+ const re = /\btemplate:\s*/g;
71
+ while (re.exec(src)) {
72
+ const start = re.lastIndex;
73
+ const quote = src[start];
74
+ if (quote !== '`' && quote !== "'" && quote !== '"') continue;
75
+ let end = start + 1;
76
+ let substitution = false;
77
+ while (end < src.length && src[end] !== quote) {
78
+ if (src[end] === '\\') end++;
79
+ else if (quote === '`' && src[end] === '$' && src[end + 1] === '{') substitution = true;
80
+ end++;
81
+ }
82
+ if (substitution || src.slice(end + 1).trimStart().startsWith('+')) continue;
83
+ found.push(unescape(src.slice(start + 1, end)));
84
+ }
85
+ return found;
86
+ }
87
+
88
+ function listCases() {
89
+ const cases = [];
90
+ const walk = (dir) => {
91
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
92
+ const file = path.join(dir, entry.name);
93
+ const id = path.relative(casesDir, file).split(path.sep).join('/');
94
+ if (entry.isDirectory()) walk(file);
95
+ else if (entry.name.endsWith('.html')) cases.push({ id, template: fs.readFileSync(file, 'utf8') });
96
+ else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts') && !entry.name.includes('golden')) {
97
+ inlineTemplates(file).forEach((template, index) => cases.push({ id: `${id}#${index}`, template }));
98
+ }
99
+ }
100
+ };
101
+ walk(casesDir);
102
+ return cases;
103
+ }
104
+
105
+ function spawnCollect(command, args) {
106
+ return new Promise((resolve) => {
107
+ const child = spawn(command, args, { cwd: here });
108
+ let stdout = '';
109
+ let stderr = '';
110
+ const timer = setTimeout(() => child.kill('SIGKILL'), 60_000);
111
+ child.stdout.on('data', (d) => (stdout += d));
112
+ child.stderr.on('data', (d) => (stderr += d));
113
+ child.on('close', (code, signal) => {
114
+ clearTimeout(timer);
115
+ resolve({ stdout, stderr, code: signal ? signal : code });
116
+ });
117
+ });
118
+ }
119
+
120
+ fetchCases();
121
+ const cases = listCases().filter((c) => c.id.includes(filter));
122
+ console.log(`Compiling main.ts with TypeNative ...`);
123
+ run(process.execPath, [cli, '--source', path.join(here, 'main.ts'), '--output', exePath], { cwd: repoRoot });
124
+ run(process.execPath, [path.join(here, 'run-node.mjs'), '--build'], { cwd: here });
125
+
126
+ fs.rmSync(failuresDir, { recursive: true, force: true });
127
+ fs.rmSync(inputsDir, { recursive: true, force: true });
128
+ fs.mkdirSync(failuresDir, { recursive: true });
129
+ fs.mkdirSync(inputsDir, { recursive: true });
130
+
131
+ let passed = 0;
132
+ let next = 0;
133
+ const failed = [];
134
+ async function worker() {
135
+ while (next < cases.length) {
136
+ const index = next++;
137
+ const { id, template } = cases[index];
138
+ const input = path.join(inputsDir, `${index}.html`);
139
+ fs.writeFileSync(input, template);
140
+ const [node, native] = await Promise.all([
141
+ spawnCollect(process.execPath, [path.join(here, 'run-node.mjs'), input]),
142
+ spawnCollect(exePath, [input])
143
+ ]);
144
+ if (node.stdout === native.stdout && node.stderr === native.stderr && node.code === native.code) {
145
+ passed++;
146
+ continue;
147
+ }
148
+ failed.push(id);
149
+ const report = (name, r) => `--- ${name} (exit ${r.code})\n${r.stdout}${r.stderr ? `--- ${name} stderr\n${r.stderr}` : ''}`;
150
+ fs.writeFileSync(path.join(failuresDir, `${index}.txt`), `${id}\n--- template\n${template}\n${report('node', node)}${report('native', native)}`);
151
+ }
152
+ }
153
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(8, os.availableParallelism() - 1)) }, worker));
154
+
155
+ for (const id of failed.sort()) console.log(`FAIL ${id}`);
156
+ console.log(`${passed}/${cases.length} templates match (${((100 * passed) / Math.max(1, cases.length)).toFixed(2)}%)`);
157
+ process.exitCode = failed.length > 0 ? 1 : 0;
@@ -0,0 +1,69 @@
1
+ // Runs main.ts under Node.js, compiled to JavaScript.
2
+ //
3
+ // Node runs TypeScript itself only by stripping types (Node 26 removed
4
+ // --experimental-transform-types), and Angular's compiler source uses enums
5
+ // and other syntax that mode rejects. So this compiles main.ts and every file
6
+ // it imports to JavaScript with the `typescript` package of this repository
7
+ // (into .cache/node/, rebuilt when a source file is newer than the build),
8
+ // then runs .cache/node/main.js with the given arguments. That is also how the
9
+ // compiler runs for Node users: the published @angular/compiler is JavaScript.
10
+ //
11
+ // Usage: node run-node.mjs [template.html]
12
+ // node run-node.mjs --build (build only; used by parity.mjs and bench.mjs)
13
+
14
+ import fs from 'node:fs';
15
+ import { createRequire } from 'node:module';
16
+ import path from 'node:path';
17
+ import { fileURLToPath, pathToFileURL } from 'node:url';
18
+
19
+ const here = path.dirname(fileURLToPath(import.meta.url));
20
+ const outDir = path.join(here, '.cache', 'node');
21
+ export const nodeMain = path.join(outDir, 'main.js');
22
+
23
+ function newestSource(dir, newest = 0) {
24
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
25
+ const full = path.join(dir, entry.name);
26
+ if (entry.isDirectory()) newest = newestSource(full, newest);
27
+ else newest = Math.max(newest, fs.statSync(full).mtimeMs);
28
+ }
29
+ return newest;
30
+ }
31
+
32
+ export function buildNode() {
33
+ const sources = Math.max(
34
+ fs.statSync(path.join(here, 'main.ts')).mtimeMs,
35
+ fs.statSync(path.join(here, 'dom-type-stubs.ts')).mtimeMs,
36
+ newestSource(path.join(here, 'vendor'))
37
+ );
38
+ if (fs.existsSync(nodeMain) && fs.statSync(nodeMain).mtimeMs >= sources) return;
39
+
40
+ const ts = createRequire(path.join(here, '..', '..', 'package.json'))('typescript');
41
+ fs.rmSync(outDir, { recursive: true, force: true });
42
+ const program = ts.createProgram([path.join(here, 'main.ts')], {
43
+ target: ts.ScriptTarget.ES2024,
44
+ module: ts.ModuleKind.ESNext,
45
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
46
+ rewriteRelativeImportExtensions: true,
47
+ allowImportingTsExtensions: true,
48
+ resolveJsonModule: true,
49
+ esModuleInterop: true,
50
+ lib: [],
51
+ types: [],
52
+ noLib: true,
53
+ noCheck: true,
54
+ skipLibCheck: true,
55
+ rootDir: here,
56
+ outDir,
57
+ });
58
+ const result = program.emit();
59
+ for (const d of result.diagnostics) console.error(ts.flattenDiagnosticMessageText(d.messageText, '\n'));
60
+ fs.writeFileSync(path.join(outDir, 'package.json'), '{ "type": "module" }\n');
61
+ }
62
+
63
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
64
+ buildNode();
65
+ if (process.argv[2] !== '--build') {
66
+ process.argv = [process.argv[0], nodeMain, ...process.argv.slice(2)];
67
+ await import(pathToFileURL(nodeMain).href);
68
+ }
69
+ }
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) 2010-2026 Google LLC. https://angular.dev/license
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
13
+ all 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
21
+ THE SOFTWARE.
@@ -83,25 +83,23 @@ times **spawn until `GET /` answers 200**, which is what the user waits for befo
83
83
  the window can paint. It then lists the notes, opens 20 of them, saves one, and
84
84
  reads the app's own **resident memory** from `/api/info`.
85
85
 
86
- **Environment:** Windows 11 Pro, AMD Ryzen 5 5500U, Node v24.19.0, Go 1.26.0,
87
- TypeNative 0.4.2, default (non-`--release`) build.
86
+ **Environment:** Windows 11 Pro, AMD Ryzen 5 7600, Node v26.13.0, Go 1.27.4,
87
+ TypeNative 0.5.0 (unreleased changes), default (non-`--release`) build.
88
88
 
89
89
  | Spawn → first page | min | median | mean | max |
90
90
  |--------------------|-----------|-----------|-----------|-----------|
91
- | Node.js | 212.53 ms | 246.86 ms | 241.53 ms | 273.47 ms |
92
- | TypeNative | 42.59 ms | 51.29 ms | 119.99 ms | 719.02 ms |
91
+ | Node.js | 94.46 ms | 99.11 ms | 103.46 ms | 119.13 ms |
92
+ | TypeNative | 20.61 ms | 22.41 ms | 25.95 ms | 60.24 ms |
93
93
 
94
94
  | Resident memory | min | median | mean | max |
95
95
  |-----------------|----------|----------|----------|----------|
96
- | Node.js | 71.4 MiB | 72.6 MiB | 72.6 MiB | 73.5 MiB |
97
- | TypeNative | 11.1 MiB | 15.3 MiB | 13.4 MiB | 15.8 MiB |
98
-
99
- **TypeNative serves the first page 4.8x sooner and uses 4.7x less memory**
100
- (median). One TypeNative run took 719 ms, which is why its mean is so far above its
101
- median. The app is a single 12.4 MiB binary with the UI included, or 8.7 MiB with
102
- `--gui --release`. An Electron build of the same app would ship about 100 MiB of
103
- Chromium and Node. This app uses the webview the OS already has, and its backend
104
- idles at about 15 MiB.
96
+ | Node.js | 71.2 MiB | 72.6 MiB | 72.5 MiB | 73.0 MiB |
97
+ | TypeNative | 7.0 MiB | 10.8 MiB | 10.5 MiB | 11.0 MiB |
98
+
99
+ **TypeNative serves the first page 4.4x sooner and uses 6.7x less memory**
100
+ (median). The app is a single 13.9 MiB binary with the UI included. An Electron
101
+ build of the same app would ship about 100 MiB of Chromium and Node. This app uses
102
+ the webview the OS already has, and its backend idles at about 11 MiB.
105
103
 
106
104
  These figures cover the headless server process only. They leave out the webview's
107
105
  own processes, which are about the same for both runtimes, and the extra window
@@ -60,16 +60,18 @@ duplicates. It runs each runtime once to warm the OS file cache, then times
60
60
  **complete process runs** of both and checks that the two reports are
61
61
  byte-identical.
62
62
 
63
- **Environment:** Windows 11 Pro, AMD Ryzen 5 5500U, Node v24.19.0, Go 1.26.0,
64
- TypeNative 0.4.1, default (non-`--release`) build.
63
+ **Environment:** Windows 11 Pro, AMD Ryzen 5 7600, Node v26.13.0, Go 1.27.4,
64
+ TypeNative 0.5.0 (unreleased changes), default (non-`--release`) build.
65
65
 
66
66
  | Runtime | min | median | mean | max |
67
67
  |------------|-----------|-----------|-----------|-----------|
68
- | Node.js | 659.14 ms | 674.33 ms | 675.70 ms | 700.33 ms |
69
- | TypeNative | 398.94 ms | 412.47 ms | 411.52 ms | 423.42 ms |
68
+ | Node.js | 633.88 ms | 644.81 ms | 643.63 ms | 653.21 ms |
69
+ | TypeNative | 219.28 ms | 223.93 ms | 761.60 ms | 5605.76 ms |
70
70
 
71
71
  Both runtimes found the same 449 duplicate groups (1,494 files hashed,
72
- 81.9 MiB wasted). **TypeNative finishes the scan 1.6x faster** (median). The
72
+ 81.9 MiB wasted). **TypeNative finishes the scan 2.9x faster** (median). One native run in
73
+ ten took several seconds (it happened on every re-run, likely antivirus
74
+ scanning), which skews the mean and max but not the median. The
73
75
  work is reading and hashing about 180 MiB, so the gap comes from Go's
74
76
  SHA-256 and file I/O, and from skipping the ~100 ms Node startup. The OS
75
77
  file cache is warm in both cases. On a cold cache, disk speed dominates and