typenative 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) 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 +271 -1
  4. package/CONTRIBUTION.md +2 -1
  5. package/README.md +15 -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 +41 -0
  10. package/bin/node/events.js +15 -10
  11. package/bin/node/process.js +13 -0
  12. package/bin/node/punycode.js +2 -2
  13. package/bin/node/timers.js +4 -2
  14. package/bin/node/url.js +1 -1
  15. package/bin/parse-node.js +2 -2
  16. package/bin/regex_vm.js +2057 -0
  17. package/bin/transpiler.js +17225 -4830
  18. package/bin/typecheck-node.js +2 -1
  19. package/bin/version.js +1 -1
  20. package/conformance.md +57 -15
  21. package/examples/README.md +46 -23
  22. package/examples/angular-templates/README.md +139 -0
  23. package/examples/angular-templates/bench.mjs +173 -0
  24. package/examples/angular-templates/dom-type-globals.d.ts +21 -0
  25. package/examples/angular-templates/dom-type-stubs.ts +21 -0
  26. package/examples/angular-templates/main.ts +135 -0
  27. package/examples/angular-templates/parity.mjs +157 -0
  28. package/examples/angular-templates/run-node.mjs +69 -0
  29. package/examples/angular-templates/vendor/angular/compiler/LICENSE +21 -0
  30. package/examples/desktop-notes/README.md +11 -13
  31. package/examples/dupe-finder/README.md +7 -5
  32. package/examples/fibonacci/README.md +7 -7
  33. package/examples/hello-world/README.md +6 -6
  34. package/examples/json-server/README.md +19 -18
  35. package/examples/mandelbrot-png/README.md +11 -13
  36. package/examples/marked-cli/README.md +38 -37
  37. package/examples/openai-chat/README.md +148 -0
  38. package/examples/openai-chat/bench.mjs +175 -0
  39. package/examples/openai-chat/main.ts +488 -0
  40. package/examples/react-compiler/README.md +170 -0
  41. package/examples/react-compiler/bench.mjs +181 -0
  42. package/examples/react-compiler/main.ts +158 -0
  43. package/examples/react-compiler/parity.mjs +362 -0
  44. package/examples/react-compiler/run-node.mjs +88 -0
  45. package/examples/react-compiler/vendor/babel/LICENSE +22 -0
  46. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-lower.json +15 -0
  47. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-upper.json +51 -0
  48. package/examples/react-compiler/vendor/charcodes/package.json +25 -0
  49. package/examples/react-compiler/vendor/invariant/LICENSE +21 -0
  50. package/examples/react-compiler/vendor/invariant/invariant.cjs +51 -0
  51. package/examples/react-compiler/vendor/invariant/invariant.d.cts +11 -0
  52. package/examples/react-compiler/vendor/invariant/types/LICENSE +21 -0
  53. package/examples/react-compiler/vendor/jridgewell/gen-mapping/LICENSE +19 -0
  54. package/examples/react-compiler/vendor/jridgewell/resolve-uri/LICENSE +19 -0
  55. package/examples/react-compiler/vendor/jridgewell/sourcemap-codec/LICENSE +19 -0
  56. package/examples/react-compiler/vendor/jridgewell/trace-mapping/LICENSE +19 -0
  57. package/examples/react-compiler/vendor/js-tokens/LICENSE +21 -0
  58. package/examples/react-compiler/vendor/js-tokens/index.cjs +23 -0
  59. package/examples/react-compiler/vendor/js-tokens/index.d.cts +13 -0
  60. package/examples/react-compiler/vendor/jsesc/LICENSE-MIT.txt +20 -0
  61. package/examples/react-compiler/vendor/jsesc/jsesc.cjs +337 -0
  62. package/examples/react-compiler/vendor/jsesc/jsesc.d.cts +384 -0
  63. package/examples/react-compiler/vendor/jsesc/types/LICENSE +21 -0
  64. package/examples/react-compiler/vendor/picocolors/LICENSE +15 -0
  65. package/examples/react-compiler/vendor/picocolors/picocolors.cjs +75 -0
  66. package/examples/react-compiler/vendor/picocolors/picocolors.d.cts +5 -0
  67. package/examples/react-compiler/vendor/picocolors/types.d.ts +51 -0
  68. package/examples/react-compiler/vendor/react-compiler/LICENSE +21 -0
  69. package/examples/react-compiler/vendor/stubs/babel-core.ts +31 -0
  70. package/examples/react-compiler/vendor/stubs/debug.ts +18 -0
  71. package/examples/react-compiler/vendor/stubs/js-tokens.d.ts +13 -0
  72. package/examples/react-compiler/vendor/stubs/pretty-format.ts +18 -0
  73. package/examples/react-compiler/vendor/zod/LICENSE +21 -0
  74. package/examples/react-compiler/vendor/zod-validation-error/LICENSE +9 -0
  75. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/NonEmptyArray.ts +5 -0
  76. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinPath.ts +49 -0
  77. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinValues.ts +48 -0
  78. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/stringify.ts +50 -0
  79. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/titleCase.ts +6 -0
  80. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/MessageBuilder.ts +126 -0
  81. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/ValidationError.ts +39 -0
  82. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/custom.ts +12 -0
  83. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/errorMap.ts +78 -0
  84. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/index.ts +2 -0
  85. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidElement.ts +12 -0
  86. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidKey.ts +12 -0
  87. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidStringFormat.ts +131 -0
  88. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidType.ts +54 -0
  89. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidUnion.ts +12 -0
  90. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidValue.ts +40 -0
  91. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/notMultipleOf.ts +12 -0
  92. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooBig.ts +76 -0
  93. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooSmall.ts +76 -0
  94. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/types.ts +27 -0
  95. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/unrecognizedKeys.ts +27 -0
  96. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromError.ts +13 -0
  97. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodError.ts +61 -0
  98. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodIssue.ts +38 -0
  99. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/index.ts +20 -0
  100. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationError.ts +5 -0
  101. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationErrorLike.ts +8 -0
  102. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isZodErrorLike.ts +11 -0
  103. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/toValidationError.ts +20 -0
  104. package/examples/react-compiler/vendor.mjs +688 -0
  105. package/examples/todo-cli/README.md +9 -9
  106. package/examples/yaml-cli/README.md +38 -28
  107. package/package.json +8 -5
  108. package/performance/README.md +195 -0
  109. package/performance/any-dynamic.ts +21 -0
  110. package/performance/any-record-view.ts +20 -0
  111. package/performance/arr-hof.ts +21 -0
  112. package/performance/arr-push-index.ts +15 -0
  113. package/performance/arr-sort.ts +21 -0
  114. package/performance/async-await.ts +24 -0
  115. package/performance/class-dispatch.ts +52 -0
  116. package/performance/events-emit.ts +27 -0
  117. package/performance/exc-throw-rare.ts +25 -0
  118. package/performance/exc-try-catch.ts +26 -0
  119. package/performance/fn-closures.ts +29 -0
  120. package/performance/fn-recursion-tree.ts +31 -0
  121. package/performance/gen-for-of.ts +46 -0
  122. package/performance/json-roundtrip.ts +27 -0
  123. package/performance/map-delete.ts +24 -0
  124. package/performance/map-string-keys.ts +22 -0
  125. package/performance/num-arith-loop.ts +14 -0
  126. package/performance/num-bitwise.ts +21 -0
  127. package/performance/num-mod-int.ts +16 -0
  128. package/performance/num-to-string.ts +16 -0
  129. package/performance/obj-alloc.ts +32 -0
  130. package/performance/regex-exec.ts +29 -0
  131. package/performance/regex-site.ts +28 -0
  132. package/performance/set-ops.ts +20 -0
  133. package/performance/str-char-scan.ts +35 -0
  134. package/performance/str-concat-plus.ts +18 -0
  135. package/performance/str-concat.ts +24 -0
  136. package/performance/str-short-scan.ts +26 -0
  137. package/performance/str-split-join.ts +23 -0
  138. package/performance/str-template.ts +16 -0
  139. package/performance/union-switch.ts +57 -0
  140. package/tsparser/check.go +2 -1
  141. package/tsparser/main.go +1 -0
  142. package/types/typenative-npm.d.ts +3 -2
  143. package/types/typenative.d.ts +42 -12
  144. package/ROUND2-HANDOFF.md +0 -200
@@ -0,0 +1,181 @@
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
+ }
@@ -0,0 +1,158 @@
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 { parse, type ParserPlugin } from './vendor/babel/parser/src/index.ts';
14
+ import traverse, { type NodePath } from './vendor/babel/traverse/src/index.ts';
15
+ import generate from './vendor/babel/generator/src/index.ts';
16
+ import type * as t from './vendor/babel/types/src/index.ts';
17
+ import { CompilerError } from './vendor/react-compiler/src/CompilerError.ts';
18
+ import {
19
+ compileProgram,
20
+ type LoggerEvent,
21
+ type PluginOptions,
22
+ } from './vendor/react-compiler/src/Entrypoint/index.ts';
23
+ import { parseConfigPragmaForTests } from './vendor/react-compiler/src/Utils/TestUtils.ts';
24
+
25
+ const DEMO = `// @compilationMode:"infer"
26
+ import { useState } from 'react';
27
+
28
+ export function TodoList({ todos, filter, onToggle }) {
29
+ const [query, setQuery] = useState('');
30
+ const visible = todos.filter(
31
+ (todo) => (filter === 'all' || todo.status === filter) && todo.title.includes(query),
32
+ );
33
+ const remaining = todos.filter((todo) => todo.status !== 'done').length;
34
+
35
+ if (todos.length === 0) {
36
+ return <p className="empty">Nothing to do</p>;
37
+ }
38
+ return (
39
+ <section>
40
+ <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search" />
41
+ <ul>
42
+ {visible.map((todo) => (
43
+ <li key={todo.id} className={todo.status} onClick={() => onToggle(todo.id)}>
44
+ {todo.title}
45
+ </li>
46
+ ))}
47
+ </ul>
48
+ <footer>{remaining} of {todos.length} left</footer>
49
+ </section>
50
+ );
51
+ }
52
+
53
+ export function useTotal(items, taxRate) {
54
+ const subtotal = items.reduce((sum, item) => sum + item.price * item.quantity, 0);
55
+ const tax = subtotal * taxRate;
56
+ return { subtotal, tax, total: subtotal + tax };
57
+ }
58
+ `;
59
+
60
+ function position(loc: t.SourceLocation | null | undefined): string {
61
+ return loc ? `${loc.start.line}:${loc.start.column}` : '?';
62
+ }
63
+
64
+ // A logger event as a comment line (the first line of an error's text: a
65
+ // pipeline error carries its stack, which differs between runtimes)
66
+ function describe(event: LoggerEvent): string {
67
+ switch (event.kind) {
68
+ case 'CompileSuccess':
69
+ return (
70
+ `// CompileSuccess ${event.fnName ?? '(anonymous)'} at ${position(event.fnLoc)}: ` +
71
+ `${event.memoSlots} slots, ${event.memoBlocks} blocks, ${event.memoValues} values, ` +
72
+ `${event.prunedMemoBlocks} pruned blocks, ${event.prunedMemoValues} pruned values`
73
+ );
74
+ case 'CompileError': {
75
+ const description = event.detail.description ? `. ${event.detail.description}` : '';
76
+ return `// CompileError at ${position(event.detail.loc ?? event.fnLoc)}: [${event.detail.category}] ${event.detail.reason}${description}`;
77
+ }
78
+ case 'CompileDiagnostic':
79
+ return `// CompileDiagnostic at ${position(event.fnLoc)}: [${event.detail.category}] ${event.detail.reason}`;
80
+ case 'CompileSkip':
81
+ return `// CompileSkip at ${position(event.fnLoc)}: ${event.reason}`;
82
+ case 'PipelineError':
83
+ case 'CompileUnexpectedThrow':
84
+ return `// ${event.kind} at ${position(event.fnLoc)}: ${event.data.split('\n')[0]}`;
85
+ case 'Timing':
86
+ return '// Timing';
87
+ }
88
+ }
89
+
90
+ function compile(source: string, filename: string): string {
91
+ const firstLine = source.substring(0, source.indexOf('\n'));
92
+ const flow = firstLine.includes('@flow');
93
+ const plugins: ParserPlugin[] = flow
94
+ ? ['flow', 'jsx']
95
+ : ['typescript', 'jsx', 'explicitResourceManagement'];
96
+ const ast = parse(source, {
97
+ sourceFilename: filename,
98
+ sourceType: firstLine.includes('@script') ? 'script' : 'module',
99
+ plugins,
100
+ });
101
+
102
+ // The options the compiler's fixture runner (snap) uses
103
+ const events: LoggerEvent[] = [];
104
+ const config = parseConfigPragmaForTests(firstLine, { compilationMode: 'all' });
105
+ const opts: PluginOptions = {
106
+ ...config,
107
+ environment: {
108
+ ...config.environment,
109
+ assertValidMutableRanges: true,
110
+ validatePreserveExistingMemoizationGuarantees: firstLine.includes(
111
+ '@validatePreserveExistingMemoizationGuarantees',
112
+ ),
113
+ },
114
+ logger: {
115
+ logEvent: (_filename: string | null, event: LoggerEvent): void => {
116
+ events.push(event);
117
+ },
118
+ },
119
+ enableReanimatedCheck: false,
120
+ target: '19',
121
+ };
122
+
123
+ traverse(ast, {
124
+ Program(program: NodePath<t.Program>) {
125
+ compileProgram(program, {
126
+ opts,
127
+ filename,
128
+ comments: ast.comments ?? [],
129
+ code: source,
130
+ });
131
+ program.skip();
132
+ },
133
+ });
134
+
135
+ const out = [generate(ast, {}, source).code];
136
+ for (const event of events) out.push(describe(event));
137
+ return out.join('\n');
138
+ }
139
+
140
+ const file = process.argv[2];
141
+ const source = file ? fs.readFileSync(file, 'utf-8') : DEMO;
142
+ const filename = file ?? 'demo.jsx';
143
+ try {
144
+ console.log(compile(source, filename));
145
+ } catch (e) {
146
+ // (an error the compiler or the parser throws, as a comment: the same
147
+ // under both runtimes)
148
+ const message = e instanceof CompilerError ? e.withPrintedMessage(source, { eslint: false }).message : (e as Error).message;
149
+ console.log(`// compile error: ${message}`);
150
+ // TN_DEBUG_ERRORS=1 surfaces the thrown value and its stack (a pass
151
+ // failure whose message is empty prints as `undefined` otherwise)
152
+ if (process.env.TN_DEBUG_ERRORS) {
153
+ console.log(`// debug: typeof=${typeof e} string=${String(e)}`);
154
+ const stack = (e as Error)?.stack;
155
+ if (stack) console.log(stack);
156
+ }
157
+ process.exitCode = 1;
158
+ }