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.
Files changed (217) hide show
  1. package/bin/node/assert.js +2 -2
  2. package/bin/node/child_process.js +66 -8
  3. package/bin/node/fs.js +1012 -4
  4. package/bin/node/histogram.js +1991 -0
  5. package/bin/node/process.js +14 -2
  6. package/bin/node/sqlite.js +1488 -5
  7. package/bin/node/stream.js +2 -1
  8. package/bin/node/system_extra.js +3 -270
  9. package/bin/node/test.js +39 -1
  10. package/bin/node/test_report.js +47 -1
  11. package/bin/node/test_run.js +57 -2
  12. package/bin/node/util.js +8 -5
  13. package/bin/node/webassembly.js +20 -5
  14. package/bin/node/webview.js +3257 -244
  15. package/bin/node/zlib.js +118 -14
  16. package/bin/node/zlib_iter.js +585 -0
  17. package/bin/transpiler.js +1370 -258
  18. package/bin/version.js +1 -1
  19. package/govendor/software.sslmate.com/src/go-pkcs12/.gitattributes +10 -0
  20. package/govendor/software.sslmate.com/src/go-pkcs12/LICENSE +28 -0
  21. package/govendor/software.sslmate.com/src/go-pkcs12/README.md +31 -0
  22. package/govendor/software.sslmate.com/src/go-pkcs12/bmp-string.go +63 -0
  23. package/govendor/software.sslmate.com/src/go-pkcs12/crypto.go +331 -0
  24. package/govendor/software.sslmate.com/src/go-pkcs12/errors.go +23 -0
  25. package/govendor/software.sslmate.com/src/go-pkcs12/go.mod +3 -0
  26. package/govendor/software.sslmate.com/src/go-pkcs12/internal/rc2/rc2.go +271 -0
  27. package/govendor/software.sslmate.com/src/go-pkcs12/mac.go +202 -0
  28. package/govendor/software.sslmate.com/src/go-pkcs12/pbkdf.go +184 -0
  29. package/govendor/software.sslmate.com/src/go-pkcs12/pkcs12.go +1000 -0
  30. package/govendor/software.sslmate.com/src/go-pkcs12/safebags.go +107 -0
  31. package/package.json +10 -1
  32. package/types/tsconfig.json +17 -0
  33. package/types/typenative-npm.d.ts +492 -12
  34. package/types/typenative.d.ts +88 -2
  35. package/.gitattributes +0 -1
  36. package/.github/workflows/ci.yml +0 -68
  37. package/.github/workflows/npm-publish-github-packages.yml +0 -88
  38. package/CHANGELOG.md +0 -1746
  39. package/CONTRIBUTION.md +0 -133
  40. package/conformance.md +0 -1497
  41. package/examples/README.md +0 -114
  42. package/examples/angular-templates/README.md +0 -141
  43. package/examples/angular-templates/bench.mjs +0 -173
  44. package/examples/angular-templates/dom-type-globals.d.ts +0 -21
  45. package/examples/angular-templates/dom-type-stubs.ts +0 -21
  46. package/examples/angular-templates/main.ts +0 -135
  47. package/examples/angular-templates/parity.mjs +0 -157
  48. package/examples/angular-templates/run-node.mjs +0 -69
  49. package/examples/angular-templates/vendor/angular/compiler/LICENSE +0 -21
  50. package/examples/desktop-notes/README.md +0 -106
  51. package/examples/desktop-notes/bench.mjs +0 -125
  52. package/examples/desktop-notes/main.ts +0 -131
  53. package/examples/desktop-notes/package-lock.json +0 -726
  54. package/examples/desktop-notes/package.json +0 -9
  55. package/examples/desktop-notes/ui.ts +0 -176
  56. package/examples/dupe-finder/README.md +0 -78
  57. package/examples/dupe-finder/bench.mjs +0 -120
  58. package/examples/dupe-finder/main.ts +0 -87
  59. package/examples/fibonacci/README.md +0 -89
  60. package/examples/fibonacci/bench.mjs +0 -87
  61. package/examples/fibonacci/main.ts +0 -21
  62. package/examples/hello-world/README.md +0 -62
  63. package/examples/hello-world/bench.mjs +0 -66
  64. package/examples/hello-world/main.ts +0 -7
  65. package/examples/json-server/README.md +0 -132
  66. package/examples/json-server/bench.mjs +0 -263
  67. package/examples/json-server/main.ts +0 -67
  68. package/examples/mandelbrot-png/README.md +0 -63
  69. package/examples/mandelbrot-png/bench.mjs +0 -95
  70. package/examples/mandelbrot-png/main.ts +0 -98
  71. package/examples/mandelbrot-png/preview.png +0 -0
  72. package/examples/marked-cli/README.md +0 -174
  73. package/examples/marked-cli/bench.mjs +0 -178
  74. package/examples/marked-cli/main.ts +0 -410
  75. package/examples/marked-cli/parity.mjs +0 -185
  76. package/examples/marked-cli/vendor/marked/LICENSE +0 -44
  77. package/examples/marked-cli/vendor/marked/VENDOR.md +0 -26
  78. package/examples/openai-chat/README.md +0 -148
  79. package/examples/openai-chat/bench.mjs +0 -175
  80. package/examples/openai-chat/main.ts +0 -488
  81. package/examples/react-compiler/README.md +0 -185
  82. package/examples/react-compiler/bench.mjs +0 -181
  83. package/examples/react-compiler/main.ts +0 -324
  84. package/examples/react-compiler/parity.mjs +0 -362
  85. package/examples/react-compiler/run-node.mjs +0 -90
  86. package/examples/react-compiler/vendor/babel/LICENSE +0 -22
  87. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-lower.json +0 -15
  88. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-upper.json +0 -51
  89. package/examples/react-compiler/vendor/charcodes/package.json +0 -25
  90. package/examples/react-compiler/vendor/invariant/LICENSE +0 -21
  91. package/examples/react-compiler/vendor/invariant/invariant.cjs +0 -51
  92. package/examples/react-compiler/vendor/invariant/invariant.d.cts +0 -11
  93. package/examples/react-compiler/vendor/invariant/types/LICENSE +0 -21
  94. package/examples/react-compiler/vendor/jridgewell/gen-mapping/LICENSE +0 -19
  95. package/examples/react-compiler/vendor/jridgewell/resolve-uri/LICENSE +0 -19
  96. package/examples/react-compiler/vendor/jridgewell/sourcemap-codec/LICENSE +0 -19
  97. package/examples/react-compiler/vendor/jridgewell/trace-mapping/LICENSE +0 -19
  98. package/examples/react-compiler/vendor/js-tokens/LICENSE +0 -21
  99. package/examples/react-compiler/vendor/js-tokens/index.cjs +0 -23
  100. package/examples/react-compiler/vendor/js-tokens/index.d.cts +0 -13
  101. package/examples/react-compiler/vendor/jsesc/LICENSE-MIT.txt +0 -20
  102. package/examples/react-compiler/vendor/jsesc/jsesc.cjs +0 -337
  103. package/examples/react-compiler/vendor/jsesc/jsesc.d.cts +0 -384
  104. package/examples/react-compiler/vendor/jsesc/types/LICENSE +0 -21
  105. package/examples/react-compiler/vendor/picocolors/LICENSE +0 -15
  106. package/examples/react-compiler/vendor/picocolors/picocolors.cjs +0 -75
  107. package/examples/react-compiler/vendor/picocolors/picocolors.d.cts +0 -5
  108. package/examples/react-compiler/vendor/picocolors/types.d.ts +0 -51
  109. package/examples/react-compiler/vendor/react-compiler/LICENSE +0 -21
  110. package/examples/react-compiler/vendor/stubs/babel-core.ts +0 -31
  111. package/examples/react-compiler/vendor/stubs/debug.ts +0 -18
  112. package/examples/react-compiler/vendor/stubs/js-tokens.d.ts +0 -13
  113. package/examples/react-compiler/vendor/stubs/pretty-format.ts +0 -18
  114. package/examples/react-compiler/vendor/zod/LICENSE +0 -21
  115. package/examples/react-compiler/vendor/zod-validation-error/LICENSE +0 -9
  116. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/NonEmptyArray.ts +0 -5
  117. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinPath.ts +0 -49
  118. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinValues.ts +0 -48
  119. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/stringify.ts +0 -50
  120. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/titleCase.ts +0 -6
  121. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/MessageBuilder.ts +0 -126
  122. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/ValidationError.ts +0 -39
  123. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/custom.ts +0 -12
  124. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/errorMap.ts +0 -78
  125. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/index.ts +0 -2
  126. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidElement.ts +0 -12
  127. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidKey.ts +0 -12
  128. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidStringFormat.ts +0 -131
  129. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidType.ts +0 -54
  130. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidUnion.ts +0 -12
  131. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidValue.ts +0 -40
  132. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/notMultipleOf.ts +0 -12
  133. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooBig.ts +0 -76
  134. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooSmall.ts +0 -76
  135. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/types.ts +0 -27
  136. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/unrecognizedKeys.ts +0 -27
  137. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromError.ts +0 -13
  138. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodError.ts +0 -61
  139. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodIssue.ts +0 -38
  140. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/index.ts +0 -20
  141. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationError.ts +0 -5
  142. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationErrorLike.ts +0 -8
  143. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isZodErrorLike.ts +0 -11
  144. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/toValidationError.ts +0 -20
  145. package/examples/react-compiler/vendor.mjs +0 -688
  146. package/examples/todo-cli/README.md +0 -69
  147. package/examples/todo-cli/bench.mjs +0 -89
  148. package/examples/todo-cli/main.ts +0 -92
  149. package/examples/yaml-cli/README.md +0 -152
  150. package/examples/yaml-cli/bench.mjs +0 -265
  151. package/examples/yaml-cli/main.ts +0 -251
  152. package/examples/yaml-cli/parity.mjs +0 -156
  153. package/examples/yaml-cli/vendor/yaml/LICENSE +0 -13
  154. package/examples/yaml-cli/vendor/yaml/VENDOR.md +0 -25
  155. package/performance/README.md +0 -248
  156. package/performance/any-dynamic.ts +0 -21
  157. package/performance/any-record-view.ts +0 -20
  158. package/performance/arr-for-of.ts +0 -29
  159. package/performance/arr-hof.ts +0 -21
  160. package/performance/arr-push-index.ts +0 -15
  161. package/performance/arr-push-local.ts +0 -39
  162. package/performance/arr-slice-concat.ts +0 -24
  163. package/performance/arr-sort.ts +0 -21
  164. package/performance/async-await.ts +0 -24
  165. package/performance/async-promise-all.ts +0 -38
  166. package/performance/bigint-arith.ts +0 -36
  167. package/performance/buf-encode.ts +0 -29
  168. package/performance/class-accessors.ts +0 -48
  169. package/performance/class-dispatch.ts +0 -52
  170. package/performance/date-format.ts +0 -18
  171. package/performance/events-emit.ts +0 -27
  172. package/performance/exc-throw-rare.ts +0 -25
  173. package/performance/exc-try-catch.ts +0 -26
  174. package/performance/fn-closures.ts +0 -29
  175. package/performance/fn-recursion-tree.ts +0 -31
  176. package/performance/fn-rest-spread.ts +0 -43
  177. package/performance/gen-for-of.ts +0 -46
  178. package/performance/gen-next.ts +0 -32
  179. package/performance/iter-helpers.ts +0 -38
  180. package/performance/json-any.ts +0 -30
  181. package/performance/json-roundtrip.ts +0 -27
  182. package/performance/map-delete.ts +0 -24
  183. package/performance/map-iterate.ts +0 -26
  184. package/performance/map-number-keys.ts +0 -37
  185. package/performance/map-string-keys.ts +0 -22
  186. package/performance/num-arith-loop.ts +0 -14
  187. package/performance/num-bitwise.ts +0 -21
  188. package/performance/num-hash-imul.ts +0 -36
  189. package/performance/num-mod-int.ts +0 -16
  190. package/performance/num-to-string.ts +0 -16
  191. package/performance/obj-alloc.ts +0 -32
  192. package/performance/obj-keys-entries.ts +0 -44
  193. package/performance/obj-optional-chain.ts +0 -42
  194. package/performance/obj-record-dict.ts +0 -24
  195. package/performance/obj-spread-destructure.ts +0 -40
  196. package/performance/regex-exec.ts +0 -29
  197. package/performance/regex-replace-fn.ts +0 -24
  198. package/performance/regex-site.ts +0 -28
  199. package/performance/set-ops.ts +0 -20
  200. package/performance/str-char-scan.ts +0 -35
  201. package/performance/str-concat-plus.ts +0 -18
  202. package/performance/str-concat.ts +0 -24
  203. package/performance/str-methods.ts +0 -24
  204. package/performance/str-short-scan.ts +0 -26
  205. package/performance/str-split-join.ts +0 -23
  206. package/performance/str-switch-compare.ts +0 -50
  207. package/performance/str-template.ts +0 -16
  208. package/performance/str-unicode.ts +0 -25
  209. package/performance/typed-array.ts +0 -30
  210. package/performance/union-switch.ts +0 -57
  211. package/performance/union-typeof.ts +0 -40
  212. package/performance/wasm-call.ts +0 -63
  213. package/tsparser/check.go +0 -158
  214. package/tsparser/go.mod +0 -14
  215. package/tsparser/go.sum +0 -22
  216. package/tsparser/main.go +0 -363
  217. package/tsparser/tsparser.exe +0 -4
@@ -1,181 +0,0 @@
1
- // Benchmark: Node.js vs TypeNative for the React Compiler, both compiling
2
- // React components and hooks to their auto-memoized form.
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 (two components with hooks, derived lists, JSX with
8
- // conditionals, lists and event handlers);
9
- // (b) scaling: generated component files of growing size (8 to 64 KB by
10
- // default), each a screen of cards with hooks, derived arrays,
11
- // conditionals and JSX lists, from a fixed-seed generator, so every
12
- // machine gets the same input. Under Node the file runs through
13
- // run-node.mjs (the vendored compiler sources use enums, which Node's
14
- // type stripping cannot run; the TypeScript compile is cached).
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' ? 'react-compile.exe' : 'react-compile');
30
- const bigPath = path.join(cache, 'generated-screen.jsx');
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 components
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 HOOKS = ['useState', 'useReducer', 'useRef'];
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 hook = HOOKS[rand(HOOKS.length)];
54
- const lines = [`function Card${i}({ items, active, onSelect }) {`];
55
- switch (hook) {
56
- case 'useState':
57
- lines.push(` const [open, setOpen] = useState(false);`);
58
- break;
59
- case 'useReducer':
60
- lines.push(` const [open, toggle] = useReducer((state) => !state, false);`);
61
- break;
62
- default:
63
- lines.push(` const ref = useRef(null);`);
64
- }
65
- lines.push(` const total = items.reduce((sum, item) => sum + item.price, 0);`);
66
- lines.push(` const visible = items.filter((item) => item.status === active && item.title.includes('${a}'));`);
67
- if (hook !== 'useRef') {
68
- lines.push(` if (items.length === 0) {`, ` return <p className="empty">No ${a} items</p>;`, ` }`);
69
- }
70
- lines.push(` return (`);
71
- lines.push(` <section className={open ? "card open" : "card"} ref=${hook === 'useRef' ? '{ref}' : '{undefined}'}>`);
72
- lines.push(` <h2 onClick=${hook === 'useReducer' ? '{toggle}' : '{() => setOpen(!open)}'}>{total}</h2>`);
73
- lines.push(` <ul>`);
74
- lines.push(` {visible.map((item) => (`);
75
- lines.push(` <li key={item.id} className={item.status} onClick={() => onSelect(item.id)}>`);
76
- lines.push(` {item.title} ({item.${b}})`);
77
- lines.push(` </li>`);
78
- lines.push(` ))}`);
79
- lines.push(` </ul>`);
80
- lines.push(` <footer>{visible.length} of {items.length} ${a} items</footer>`);
81
- lines.push(` </section>`);
82
- lines.push(` );`);
83
- lines.push(`}`);
84
- return lines.join('\n');
85
- }
86
-
87
- function source(bytes) {
88
- const out = [`import { useReducer, useRef, useState } from 'react';`, ''];
89
- let size = 0;
90
- for (let i = 0; size < bytes; i++) {
91
- const c = card(i);
92
- out.push(c);
93
- size += c.length + 1;
94
- }
95
- out.push('export default Card0;', '');
96
- return out.join('\n');
97
- }
98
-
99
- function stats(samples) {
100
- const sorted = [...samples].sort((a, b) => a - b);
101
- const mean = samples.reduce((sum, x) => sum + x, 0) / samples.length;
102
- return { min: sorted[0], median: sorted[Math.floor(sorted.length / 2)], mean, max: sorted[sorted.length - 1] };
103
- }
104
-
105
- function fmt(ms) {
106
- return `${ms.toFixed(2)} ms`.padStart(13);
107
- }
108
-
109
- function runOnce(command, args) {
110
- const t0 = performance.now();
111
- const result = spawnSync(command, args, { cwd: here, maxBuffer: 1 << 30 });
112
- const elapsed = performance.now() - t0;
113
- if (result.status !== 0) {
114
- console.error(`run failed: ${command} ${args.join(' ')}\n${result.stdout}\n${result.stderr}`);
115
- process.exit(1);
116
- }
117
- return { elapsed, stdout: result.stdout };
118
- }
119
-
120
- // Alternating Node and native runs; the two outputs must match
121
- function timeBoth(args, count) {
122
- const node = [];
123
- const native = [];
124
- for (let i = 0; i < count; i++) {
125
- const a = runOnce(process.execPath, ['run-node.mjs', ...args]);
126
- const b = runOnce(exePath, args);
127
- if (!a.stdout.equals(b.stdout)) {
128
- console.error('Node and native output differ');
129
- process.exit(1);
130
- }
131
- if (a.stdout.toString().startsWith('// compile error:')) {
132
- console.error(`the source has errors:\n${a.stdout.toString().slice(0, 2000)}`);
133
- process.exit(1);
134
- }
135
- node.push(a.elapsed);
136
- native.push(b.elapsed);
137
- }
138
- return [stats(node), stats(native)];
139
- }
140
-
141
- function table(nodeStats, nativeStats) {
142
- console.log('| Runtime | min | median | mean | max |');
143
- console.log('|------------|--------------|--------------|--------------|--------------|');
144
- console.log(`| Node.js |${fmt(nodeStats.min)} |${fmt(nodeStats.median)} |${fmt(nodeStats.mean)} |${fmt(nodeStats.max)} |`);
145
- console.log(`| TypeNative |${fmt(nativeStats.min)} |${fmt(nativeStats.median)} |${fmt(nativeStats.mean)} |${fmt(nativeStats.max)} |`);
146
- }
147
-
148
- // 1. Compile the CLI to a native binary.
149
- fs.mkdirSync(cache, { recursive: true });
150
- console.log('Compiling main.ts to a native binary with TypeNative...');
151
- const build = spawnSync(process.execPath, [cli, '--source', 'main.ts', '--output', exePath], { cwd: here, stdio: 'inherit' });
152
- if (build.status !== 0) process.exit(build.status ?? 1);
153
- console.log(`Binary: ${(fs.statSync(exePath).size / (1024 * 1024)).toFixed(1)} MB`);
154
-
155
- // 2. Warm the Node cache (run-node.mjs compiles main.ts to .cache/node once).
156
- const warm = runOnce(process.execPath, ['run-node.mjs']);
157
- if (warm.stdout.toString().startsWith('// compile error:')) {
158
- console.error(`the demo has errors:\n${warm.stdout.toString().slice(0, 2000)}`);
159
- process.exit(1);
160
- }
161
-
162
- // 3. Per-call latency on the demo.
163
- console.log(`\n(a) \`react-compile\` (built-in demo), ${runs} runs each (full process: spawn -> exit):\n`);
164
- const [nodeCall, nativeCall] = timeBoth([], runs);
165
- table(nodeCall, nativeCall);
166
- const ratio = nodeCall.median / nativeCall.median;
167
- console.log(`\nTypeNative is ${(ratio >= 1 ? `${ratio.toFixed(1)}x faster` : `${(1 / ratio).toFixed(1)}x slower`)} per call (median).`);
168
-
169
- // 4. Scaling on generated component files.
170
- console.log(`\n(b) \`react-compile generated-screen.jsx\`, ${sizeRuns} runs per size (medians):\n`);
171
- console.log('| Source | Node.js | TypeNative | TypeNative vs Node |');
172
- console.log('|-------------------|--------------|--------------|--------------------|');
173
- for (const size of sizes) {
174
- seed = 42;
175
- const big = source(size * 1024);
176
- fs.writeFileSync(bigPath, big);
177
- const [nodeBig, nativeBig] = timeBoth([bigPath], sizeRuns);
178
- const ratioBig = nodeBig.median / nativeBig.median;
179
- const label = `${(big.length / 1024).toFixed(0)} KB, ${big.split('\n').length} lines`.padEnd(17);
180
- console.log(`| ${label} |${fmt(nodeBig.median)} |${fmt(nativeBig.median)} | ${(ratioBig >= 1 ? `${ratioBig.toFixed(1)}x faster` : `${(1 / ratioBig).toFixed(1)}x slower`).padEnd(18)} |`);
181
- }
@@ -1,324 +0,0 @@
1
- // React Compiler, natively: the vendored babel-plugin-react-compiler source
2
- // compiles React components and hooks to their auto-memoized form, the way
3
- // the Babel plugin does, on the vendored Babel parser, traverse and generator
4
- // (no @babel/core). The output is the same as running this file under Node.
5
- //
6
- // node run-node.mjs [file.jsx]
7
- // typenative --source main.ts --output react-compile && ./react-compile [file.jsx]
8
- //
9
- // The first line of the input can carry the compiler's test pragmas, as in
10
- // the compiler's own fixtures: `// @compilationMode:"infer" @enableJsxOutlining`.
11
-
12
- import * as fs from 'node:fs';
13
- import * as nodePath from 'node:path';
14
- import * as nodeOs from 'node:os';
15
- import { spawn } from 'node:child_process';
16
- import { parse, type ParserPlugin } from './vendor/babel/parser/src/index.ts';
17
- import traverse, { type NodePath } from './vendor/babel/traverse/src/index.ts';
18
- import generate from './vendor/babel/generator/src/index.ts';
19
- import type * as t from './vendor/babel/types/src/index.ts';
20
- import { CompilerError } from './vendor/react-compiler/src/CompilerError.ts';
21
- import {
22
- compileProgram,
23
- type LoggerEvent,
24
- type PluginOptions,
25
- } from './vendor/react-compiler/src/Entrypoint/index.ts';
26
- import { parseConfigPragmaForTests } from './vendor/react-compiler/src/Utils/TestUtils.ts';
27
-
28
- const DEMO = `// @compilationMode:"infer"
29
- import { useState } from 'react';
30
-
31
- export function TodoList({ todos, filter, onToggle }) {
32
- const [query, setQuery] = useState('');
33
- const visible = todos.filter(
34
- (todo) => (filter === 'all' || todo.status === filter) && todo.title.includes(query),
35
- );
36
- const remaining = todos.filter((todo) => todo.status !== 'done').length;
37
-
38
- if (todos.length === 0) {
39
- return <p className="empty">Nothing to do</p>;
40
- }
41
- return (
42
- <section>
43
- <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search" />
44
- <ul>
45
- {visible.map((todo) => (
46
- <li key={todo.id} className={todo.status} onClick={() => onToggle(todo.id)}>
47
- {todo.title}
48
- </li>
49
- ))}
50
- </ul>
51
- <footer>{remaining} of {todos.length} left</footer>
52
- </section>
53
- );
54
- }
55
-
56
- export function useTotal(items, taxRate) {
57
- const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
58
- const tax = subtotal * taxRate;
59
- return { subtotal, tax, total: subtotal + tax };
60
- }
61
- `;
62
-
63
- function position(loc: t.SourceLocation | null | undefined): string {
64
- return loc ? `${loc.start.line}:${loc.start.column}` : '?';
65
- }
66
-
67
- // A logger event as a comment line (the first line of an error's text: a
68
- // pipeline error carries its stack, which differs between runtimes)
69
- function describe(event: LoggerEvent): string {
70
- switch (event.kind) {
71
- case 'CompileSuccess':
72
- return (
73
- `// CompileSuccess ${event.fnName ?? '(anonymous)'} at ${position(event.fnLoc)}: ` +
74
- `${event.memoSlots} slots, ${event.memoBlocks} blocks, ${event.memoValues} values, ` +
75
- `${event.prunedMemoBlocks} pruned blocks, ${event.prunedMemoValues} pruned values`
76
- );
77
- case 'CompileError': {
78
- const description = event.detail.description ? `. ${event.detail.description}` : '';
79
- return `// CompileError at ${position(event.detail.loc ?? event.fnLoc)}: [${event.detail.category}] ${event.detail.reason}${description}`;
80
- }
81
- case 'CompileDiagnostic':
82
- return `// CompileDiagnostic at ${position(event.fnLoc)}: [${event.detail.category}] ${event.detail.reason}`;
83
- case 'CompileSkip':
84
- return `// CompileSkip at ${position(event.fnLoc)}: ${event.reason}`;
85
- case 'PipelineError':
86
- case 'CompileUnexpectedThrow':
87
- return `// ${event.kind} at ${position(event.fnLoc)}: ${event.data.split('\n')[0]}`;
88
- case 'Timing':
89
- return '// Timing';
90
- }
91
- }
92
-
93
- function compile(source: string, filename: string): string {
94
- const { code, events } = compileParts(source, filename);
95
- return [code, ...events].join('\n');
96
- }
97
-
98
- function compileParts(source: string, filename: string): { code: string; events: string[] } {
99
- const firstLine = source.substring(0, source.indexOf('\n'));
100
- const flow = firstLine.includes('@flow');
101
- const plugins: ParserPlugin[] = flow
102
- ? ['flow', 'jsx']
103
- : ['typescript', 'jsx', 'explicitResourceManagement'];
104
- const ast = parse(source, {
105
- sourceFilename: filename,
106
- sourceType: firstLine.includes('@script') ? 'script' : 'module',
107
- plugins,
108
- });
109
-
110
- // The options the compiler's fixture runner (snap) uses
111
- const events: LoggerEvent[] = [];
112
- const config = parseConfigPragmaForTests(firstLine, { compilationMode: 'all' });
113
- const opts: PluginOptions = {
114
- ...config,
115
- environment: {
116
- ...config.environment,
117
- assertValidMutableRanges: true,
118
- validatePreserveExistingMemoizationGuarantees: firstLine.includes(
119
- '@validatePreserveExistingMemoizationGuarantees',
120
- ),
121
- },
122
- logger: {
123
- logEvent: (_filename: string | null, event: LoggerEvent): void => {
124
- events.push(event);
125
- },
126
- },
127
- enableReanimatedCheck: false,
128
- target: '19',
129
- };
130
-
131
- traverse(ast, {
132
- Program(program: NodePath<t.Program>) {
133
- compileProgram(program, {
134
- opts,
135
- filename,
136
- comments: ast.comments ?? [],
137
- code: source,
138
- });
139
- program.skip();
140
- },
141
- });
142
-
143
- const code = generate(ast, {}, source).code;
144
- return { code, events: events.map(describe) };
145
- }
146
-
147
- // Large files of independent top-level functions: a worker process compiles
148
- // each contiguous run of functions, and the parent joins their output. The
149
- // per-function output is independent, and each chunk is padded so source
150
- // positions (the // CompileSuccess lines) stay the ones of the whole file.
151
- // Under Node each worker re-imports the compiler (expensive); TypeNative's
152
- // workers start from the compiled binary. TN_PARALLEL=0 disables it.
153
- const MAX_WORKERS = 6;
154
- const MIN_FUNCTIONS = 8;
155
-
156
- type Chunk = { first: string; text: string };
157
-
158
- function splitSource(source: string): Chunk[] | undefined {
159
- // (compiler temps are renamed per chunk; a source using such a name keeps
160
- // the single-process path)
161
- if (/\b_temp\d*\b/.test(source)) return undefined;
162
- const lines = source.split('\n');
163
- const starts: { name: string; line: number }[] = [];
164
- for (let i = 0; i < lines.length; i++) {
165
- const match = /^(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(/.exec(lines[i]);
166
- if (match) starts.push({ name: match[1], line: i });
167
- }
168
- if (starts.length < MIN_FUNCTIONS) return undefined;
169
- // (the header must be imports / comments only: the chunks share it)
170
- const header = lines.slice(0, starts[0].line);
171
- if (header.some((l) => l.trim() !== '' && !/^(import\b|\/\/|\/\*|\*|'use |"use )/.test(l.trim()))) return undefined;
172
- // (each function runs to the line before the next one; brace-counted, so
173
- // templates and strings with braces could fool it — then no parallelism)
174
- const ranges: { name: string; start: number; end: number }[] = [];
175
- for (let i = 0; i < starts.length; i++) {
176
- const start = starts[i].line;
177
- const limit = i + 1 < starts.length ? starts[i + 1].line : lines.length;
178
- let depth = 0;
179
- let end = -1;
180
- for (let j = start; j < limit; j++) {
181
- for (const ch of lines[j]) {
182
- if (ch === '{') depth++;
183
- else if (ch === '}') depth--;
184
- }
185
- if (depth === 0 && j > start) { end = j; break; }
186
- }
187
- if (end < 0 || !/^\}/.test(lines[end])) return undefined;
188
- // (only functions are split: anything else between them — variables,
189
- // statements — would be dropped, so such a file compiles in one process)
190
- if (i + 1 < starts.length) {
191
- for (let j = end + 1; j < starts[i + 1].line; j++) {
192
- const text = lines[j].trim();
193
- if (text !== '' && !/^(\/\/|\/\*|\*)/.test(text)) return undefined;
194
- }
195
- }
196
- ranges.push({ name: starts[i].name, start, end });
197
- }
198
- const workers = Math.min(MAX_WORKERS, Math.ceil(ranges.length / 10));
199
- // (one worker would only add a process start: compile in this one)
200
- if (workers < 2) return undefined;
201
- const chunks: Chunk[] = [];
202
- const per = Math.ceil(ranges.length / workers);
203
- for (let i = 0; i < ranges.length; i += per) {
204
- const group = ranges.slice(i, i + per);
205
- const firstStart = group[0].start;
206
- const padding = Math.max(0, firstStart - header.length);
207
- const pad: string[] = [];
208
- for (let k = 0; k < padding; k++) pad.push('');
209
- const body = lines.slice(firstStart, group[group.length - 1].end + 1);
210
- // the last chunk carries the rest of the file (export default …)
211
- const tail = i + per >= ranges.length ? lines.slice(group[group.length - 1].end + 1) : [];
212
- chunks.push({
213
- first: group[0].name,
214
- text: [...header, ...pad, ...body, ...tail].join('\n'),
215
- });
216
- }
217
- return chunks;
218
- }
219
-
220
- function runWorkerProcess(chunkFile: string): Promise<string> {
221
- return new Promise((resolve, reject) => {
222
- const nodeMain = process.env.TN_NODE_MAIN;
223
- const args = nodeMain ? [nodeMain, chunkFile, '--worker'] : [chunkFile, '--worker'];
224
- const child = spawn(process.execPath, args, { stdio: ['ignore', 'pipe', 'pipe'] });
225
- let out = '';
226
- let err = '';
227
- child.stdout?.on('data', (data: unknown) => (out += String(data)));
228
- child.stderr?.on('data', (data: unknown) => (err += String(data)));
229
- child.on('error', (e: unknown) => {
230
- reject(e);
231
- });
232
- child.on('close', (code: number | null) => {
233
- if (code === 0) {
234
- resolve(out);
235
- } else {
236
- reject(new Error(err || `worker exited with ${code}`));
237
- }
238
- });
239
- });
240
- }
241
-
242
- async function parallelCompile(source: string, filename: string, chunks: Chunk[]): Promise<string> {
243
- const dir = fs.mkdtempSync(nodePath.join(nodeOs.tmpdir(), 'tn-react-compile-'));
244
- try {
245
- const files: string[] = [];
246
- for (let i = 0; i < chunks.length; i++) {
247
- const file = nodePath.join(dir, `chunk${i}.jsx`);
248
- fs.writeFileSync(file, chunks[i].text);
249
- files.push(file);
250
- }
251
- const outputs: string[] = await Promise.all(files.map(runWorkerProcess));
252
- const codes: string[] = [];
253
- const events: string[] = [];
254
- for (const text of outputs) {
255
- const part = JSON.parse(text) as { code: string; events: string[] };
256
- codes.push(part.code);
257
- for (const event of part.events) events.push(event);
258
- }
259
- let prefix = '';
260
- const sections: string[] = [];
261
- let needsMemoCache = false;
262
- for (let i = 0; i < codes.length; i++) {
263
- const marker = `function ${chunks[i].first}(`;
264
- const at = codes[i].indexOf(marker);
265
- if (at < 0) throw new Error(`chunk ${i}: ${marker} not found`);
266
- if (i === 0) prefix = codes[i].slice(0, at);
267
- if (codes[i].includes('react/compiler-runtime')) needsMemoCache = true;
268
- // (each chunk numbers its generated _temp functions from 0: keep them
269
- // apart across the merged program)
270
- const section = codes[i].slice(at).replace(/\b_temp(\d*)\b/g, (_m, n: string) => `_temp${n}__tn${i}`).trimEnd();
271
- sections.push(section);
272
- }
273
- // (chunk 0 may not need the memo cache import when a later one does)
274
- if (needsMemoCache && !prefix.includes('react/compiler-runtime')) {
275
- prefix = `import { c as _c } from "react/compiler-runtime";\n${prefix}`;
276
- }
277
- return [prefix + sections.join('\n'), ...events].join('\n');
278
- } finally {
279
- fs.rmSync(dir, { recursive: true, force: true });
280
- }
281
- }
282
-
283
- const workerMode = process.argv.includes('--worker');
284
- const fileArgs = process.argv.slice(1).filter((a) => !a.startsWith('--'));
285
- const file = workerMode ? fileArgs[fileArgs.length - 1] : process.argv[2];
286
- const source = file ? fs.readFileSync(file, 'utf-8') : DEMO;
287
- const filename = file ?? 'demo.jsx';
288
-
289
- function printError(e: unknown): void {
290
- // (an error the compiler or the parser throws, as a comment: the same
291
- // under both runtimes)
292
- const message = e instanceof CompilerError ? e.withPrintedMessage(source, { eslint: false }).message : (e as Error).message;
293
- console.log(`// compile error: ${message}`);
294
- // TN_DEBUG_ERRORS=1 surfaces the thrown value and its stack (a pass
295
- // failure whose message is empty prints as `undefined` otherwise)
296
- if (process.env.TN_DEBUG_ERRORS) {
297
- console.log(`// debug: typeof=${typeof e} string=${String(e)}`);
298
- const stack = (e as Error)?.stack;
299
- if (stack) console.log(stack);
300
- }
301
- process.exitCode = 1;
302
- }
303
-
304
- if (workerMode) {
305
- try {
306
- console.log(JSON.stringify(compileParts(source, filename)));
307
- } catch (e) {
308
- printError(e);
309
- }
310
- } else {
311
- try {
312
- // (a worker re-runs this module; under Node it needs the module's path)
313
- const nodeRuntime = !process.env.TN_NODE_MAIN && /(^|[\\/])node(\.exe)?$/i.test(process.execPath);
314
- const chunks = process.env.TN_PARALLEL === '0' || nodeRuntime ? undefined : splitSource(source);
315
- console.log(chunks ? await parallelCompile(source, filename, chunks) : compile(source, filename));
316
- } catch {
317
- // (a worker failed: the whole file, compiled in this process)
318
- try {
319
- console.log(compile(source, filename));
320
- } catch (e) {
321
- printError(e);
322
- }
323
- }
324
- }