typenative 0.4.1 → 0.5.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 (151) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +62 -22
  3. package/ROUND2-HANDOFF.md +200 -0
  4. package/bin/cli.js +1 -0
  5. package/bin/index.js +13 -2
  6. package/bin/main.js +1 -0
  7. package/bin/node/assert.js +2 -2
  8. package/bin/node/async_hooks.js +1 -1
  9. package/bin/node/buffer.js +16 -5
  10. package/bin/node/child_process.js +7 -7
  11. package/bin/node/cluster.js +3 -3
  12. package/bin/node/crypto_keys.js +21 -21
  13. package/bin/node/dgram.js +1 -1
  14. package/bin/node/diagnostics_channel.js +3 -3
  15. package/bin/node/dns.js +2 -2
  16. package/bin/node/events.js +3 -3
  17. package/bin/node/fetch.js +2 -2
  18. package/bin/node/fs.js +3 -3
  19. package/bin/node/fs_watch.js +5 -5
  20. package/bin/node/http.js +3 -3
  21. package/bin/node/http2.js +3 -3
  22. package/bin/node/net.js +8 -8
  23. package/bin/node/path.js +17 -3
  24. package/bin/node/process.js +34 -11
  25. package/bin/node/readline.js +1 -1
  26. package/bin/node/registry.js +4 -1
  27. package/bin/node/sqlite.js +6 -6
  28. package/bin/node/stream.js +81 -15
  29. package/bin/node/stream_web.js +10 -10
  30. package/bin/node/system_extra.js +3 -3
  31. package/bin/node/test.js +674 -366
  32. package/bin/node/test_coverage.js +187 -0
  33. package/bin/node/test_report.js +1392 -0
  34. package/bin/node/test_run.js +575 -0
  35. package/bin/node/timers.js +4 -4
  36. package/bin/node/tls.js +5 -5
  37. package/bin/node/util.js +31 -7
  38. package/bin/node/util_extra.js +7 -7
  39. package/bin/node/webview.js +654 -0
  40. package/bin/node/worker_threads.js +1 -1
  41. package/bin/node/zlib.js +3 -3
  42. package/bin/parse-node.js +4 -0
  43. package/bin/transpiler.js +10390 -1178
  44. package/bin/version.js +1 -1
  45. package/conformance.md +468 -340
  46. package/examples/README.md +47 -10
  47. package/examples/desktop-notes/README.md +108 -0
  48. package/examples/desktop-notes/bench.mjs +125 -0
  49. package/examples/desktop-notes/main.ts +131 -0
  50. package/examples/desktop-notes/package-lock.json +726 -0
  51. package/examples/desktop-notes/package.json +9 -0
  52. package/examples/desktop-notes/ui.ts +176 -0
  53. package/examples/dupe-finder/README.md +76 -0
  54. package/examples/dupe-finder/bench.mjs +120 -0
  55. package/examples/dupe-finder/main.ts +87 -0
  56. package/examples/mandelbrot-png/README.md +65 -0
  57. package/examples/mandelbrot-png/bench.mjs +95 -0
  58. package/examples/mandelbrot-png/main.ts +98 -0
  59. package/examples/mandelbrot-png/preview.png +0 -0
  60. package/examples/marked-cli/README.md +159 -0
  61. package/examples/marked-cli/bench.mjs +178 -0
  62. package/examples/marked-cli/main.ts +292 -0
  63. package/examples/marked-cli/parity.mjs +185 -0
  64. package/examples/marked-cli/vendor/marked/LICENSE +44 -0
  65. package/examples/marked-cli/vendor/marked/VENDOR.md +26 -0
  66. package/examples/todo-cli/README.md +69 -0
  67. package/examples/todo-cli/bench.mjs +89 -0
  68. package/examples/todo-cli/main.ts +92 -0
  69. package/examples/yaml-cli/README.md +136 -0
  70. package/examples/yaml-cli/bench.mjs +265 -0
  71. package/examples/yaml-cli/main.ts +29 -0
  72. package/examples/yaml-cli/parity.mjs +156 -0
  73. package/examples/yaml-cli/vendor/yaml/LICENSE +13 -0
  74. package/examples/yaml-cli/vendor/yaml/VENDOR.md +25 -0
  75. package/govendor/github.com/jchv/go-webview2/LICENSE +22 -0
  76. package/govendor/github.com/jchv/go-webview2/README.md +21 -0
  77. package/govendor/github.com/jchv/go-webview2/common.go +84 -0
  78. package/govendor/github.com/jchv/go-webview2/go.mod +3 -0
  79. package/govendor/github.com/jchv/go-webview2/internal/w32/w32.go +194 -0
  80. package/govendor/github.com/jchv/go-webview2/internal/w32/w32_386.go +14 -0
  81. package/govendor/github.com/jchv/go-webview2/internal/w32/w32_64bit.go +15 -0
  82. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_COLOR.go +8 -0
  83. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND.go +9 -0
  84. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_KEY_EVENT_KIND.go +10 -0
  85. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_MOVE_FOCUS_REASON.go +9 -0
  86. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_PHYSICAL_KEY_STATUS.go +10 -0
  87. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_WEB_RESOURCE_CONTEXT.go +23 -0
  88. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2AcceleratorKeyPressedEventArgs.go +78 -0
  89. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2AcceleratorKeyPressedEventHandler.go +52 -0
  90. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Controller.go +132 -0
  91. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Controller2.go +74 -0
  92. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2CreateCoreWebView2ControllerCompletedHandler.go +48 -0
  93. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2NavigationCompletedEventArgs.go +17 -0
  94. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2NavigationCompletedEventHandler.go +48 -0
  95. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Settings.go +270 -0
  96. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequest.go +43 -0
  97. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequestedEventArgs.go +51 -0
  98. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequestedEventHandler.go +48 -0
  99. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceResponse.go +21 -0
  100. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2_2.go +21 -0
  101. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2_3.go +60 -0
  102. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebViewSettings.go +396 -0
  103. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium.go +361 -0
  104. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_386.go +24 -0
  105. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_amd64.go +22 -0
  106. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_arm64.go +26 -0
  107. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc.go +13 -0
  108. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc_go17.go +51 -0
  109. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc_go18.go +16 -0
  110. package/govendor/github.com/jchv/go-webview2/pkg/edge/corewebview2.go +411 -0
  111. package/govendor/github.com/jchv/go-webview2/pkg/edge/guid.go +223 -0
  112. package/govendor/github.com/jchv/go-webview2/webview.go +482 -0
  113. package/govendor/github.com/jchv/go-webview2/webviewloader/README.md +3 -0
  114. package/govendor/github.com/jchv/go-webview2/webviewloader/module.go +153 -0
  115. package/govendor/github.com/jchv/go-webview2/webviewloader/module_386.go +6 -0
  116. package/govendor/github.com/jchv/go-webview2/webviewloader/module_amd64.go +6 -0
  117. package/govendor/github.com/jchv/go-webview2/webviewloader/module_arm64.go +6 -0
  118. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/arm64/WebView2Loader.dll +0 -0
  119. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/x64/WebView2Loader.dll +0 -0
  120. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/x86/WebView2Loader.dll +0 -0
  121. package/govendor/github.com/jchv/go-winloader/LICENSE.md +7 -0
  122. package/govendor/github.com/jchv/go-winloader/README.md +124 -0
  123. package/govendor/github.com/jchv/go-winloader/common.go +11 -0
  124. package/govendor/github.com/jchv/go-winloader/go.mod +3 -0
  125. package/govendor/github.com/jchv/go-winloader/internal/loader/loader.go +25 -0
  126. package/govendor/github.com/jchv/go-winloader/internal/loader/machine.go +53 -0
  127. package/govendor/github.com/jchv/go-winloader/internal/memloader/cache.go +42 -0
  128. package/govendor/github.com/jchv/go-winloader/internal/memloader/loader.go +253 -0
  129. package/govendor/github.com/jchv/go-winloader/internal/pe/export.go +76 -0
  130. package/govendor/github.com/jchv/go-winloader/internal/pe/format.go +522 -0
  131. package/govendor/github.com/jchv/go-winloader/internal/pe/import.go +106 -0
  132. package/govendor/github.com/jchv/go-winloader/internal/pe/module.go +91 -0
  133. package/govendor/github.com/jchv/go-winloader/internal/pe/reloc.go +177 -0
  134. package/govendor/github.com/jchv/go-winloader/internal/pe/util.go +40 -0
  135. package/govendor/github.com/jchv/go-winloader/internal/vmem/common.go +55 -0
  136. package/govendor/github.com/jchv/go-winloader/internal/vmem/memory_other.go +71 -0
  137. package/govendor/github.com/jchv/go-winloader/internal/vmem/memory_windows.go +179 -0
  138. package/govendor/github.com/jchv/go-winloader/internal/winloader/hacks_other.go +17 -0
  139. package/govendor/github.com/jchv/go-winloader/internal/winloader/hacks_windows.go +73 -0
  140. package/govendor/github.com/jchv/go-winloader/internal/winloader/loader_windows.go +64 -0
  141. package/govendor/github.com/jchv/go-winloader/internal/winloader/machine_windows.go +32 -0
  142. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_386.go +9 -0
  143. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_amd64.go +9 -0
  144. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_arm64.go +9 -0
  145. package/govendor/github.com/jchv/go-winloader/loader_other.go +24 -0
  146. package/govendor/github.com/jchv/go-winloader/loader_windows.go +33 -0
  147. package/govendor/manifest.txt +3 -1
  148. package/package.json +1 -1
  149. package/tsparser/main.go +4 -0
  150. package/types/typenative-npm.d.ts +190 -2
  151. package/types/typenative.d.ts +98 -31
@@ -0,0 +1,9 @@
1
+ {
2
+ "name": "desktop-notes-example",
3
+ "private": true,
4
+ "type": "module",
5
+ "description": "The Node.js side of the example: compiled builds don't use this package",
6
+ "dependencies": {
7
+ "@webviewjs/webview": "1.0.0-rc.4"
8
+ }
9
+ }
@@ -0,0 +1,176 @@
1
+ // The app's whole user interface: one HTML page with inline CSS and JS. It is
2
+ // a TypeScript string, so it is compiled into the binary (no files to ship
3
+ // next to it) and works unchanged under Node.js.
4
+ export const page = `<!doctype html>
5
+ <html lang="en" translate="no">
6
+ <head>
7
+ <meta charset="utf-8">
8
+ <meta name="viewport" content="width=device-width, initial-scale=1">
9
+ <title>Notes</title>
10
+ <style>
11
+ :root {
12
+ color-scheme: light dark;
13
+ --bg: #f6f7f9; --side: #eceef2; --text: #1d2330; --muted: #677085;
14
+ --line: #d9dde5; --accent: #3d7be0; --active: #dde6f7; --danger: #c4402e;
15
+ }
16
+ @media (prefers-color-scheme: dark) {
17
+ :root { --bg: #16191f; --side: #1d212a; --text: #e8ebf2; --muted: #8b93a7;
18
+ --line: #2b313d; --active: #26324a; }
19
+ }
20
+ * { box-sizing: border-box; }
21
+ html, body { height: 100%; }
22
+ body { margin: 0; display: flex; background: var(--bg); color: var(--text);
23
+ font: 14px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; }
24
+ aside { width: 240px; flex-shrink: 0; background: var(--side); display: flex; flex-direction: column;
25
+ border-right: 1px solid var(--line); }
26
+ aside header { display: flex; gap: 6px; padding: 12px; }
27
+ #search { flex: 1; min-width: 0; padding: 6px 8px; border: 1px solid var(--line); border-radius: 6px;
28
+ background: var(--bg); color: inherit; font: inherit; }
29
+ button { border: 0; border-radius: 6px; padding: 6px 10px; font: inherit; cursor: pointer;
30
+ background: var(--accent); color: #fff; }
31
+ button.ghost { background: transparent; color: var(--danger); }
32
+ ul { list-style: none; margin: 0; padding: 0 6px; overflow-y: auto; flex: 1; }
33
+ li { padding: 8px 10px; border-radius: 6px; cursor: pointer; }
34
+ li.active { background: var(--active); }
35
+ li small { display: block; color: var(--muted); font-size: 12px; }
36
+ aside footer { padding: 10px 12px; font-size: 12px; color: var(--muted); border-top: 1px solid var(--line); }
37
+ main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
38
+ main header { display: flex; align-items: center; gap: 8px; padding: 12px 16px; border-bottom: 1px solid var(--line); }
39
+ #title { flex: 1; font-weight: 600; font-size: 16px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
40
+ #status { color: var(--muted); font-size: 12px; }
41
+ textarea { flex: 1; border: 0; padding: 16px; resize: none; outline: none; background: transparent; color: inherit;
42
+ font: 15px/1.6 ui-monospace, "Cascadia Code", Menlo, monospace; }
43
+ .empty { margin: auto; color: var(--muted); }
44
+ @media (max-width: 560px) { aside { width: 150px; } }
45
+ </style>
46
+ </head>
47
+ <body>
48
+ <aside>
49
+ <header>
50
+ <input id="search" placeholder="Search" autocomplete="off">
51
+ <button id="new" title="New note">+</button>
52
+ </header>
53
+ <ul id="list"></ul>
54
+ <footer id="info"></footer>
55
+ </aside>
56
+ <main>
57
+ <header>
58
+ <div id="title">No note selected</div>
59
+ <span id="status"></span>
60
+ <button id="delete" class="ghost" hidden>Delete</button>
61
+ </header>
62
+ <textarea id="editor" spellcheck="false" hidden></textarea>
63
+ <div class="empty" id="empty">Create a note with +</div>
64
+ </main>
65
+ <script>
66
+ const $ = (id) => document.getElementById(id);
67
+ let notes = [];
68
+ let current = null;
69
+ let saveTimer = 0;
70
+
71
+ const ago = (ms) => {
72
+ const s = Math.round((Date.now() - ms) / 1000);
73
+ if (s < 60) return 'just now';
74
+ if (s < 3600) return Math.floor(s / 60) + ' min ago';
75
+ if (s < 86400) return Math.floor(s / 3600) + ' h ago';
76
+ return new Date(ms).toLocaleDateString();
77
+ };
78
+
79
+ async function loadList() {
80
+ notes = await (await fetch('/api/notes')).json();
81
+ render();
82
+ }
83
+
84
+ function render() {
85
+ const q = $('search').value.toLowerCase();
86
+ $('list').innerHTML = '';
87
+ for (const n of notes.filter((n) => n.name.toLowerCase().includes(q))) {
88
+ const li = document.createElement('li');
89
+ li.className = n.name === current ? 'active' : '';
90
+ li.textContent = n.name;
91
+ const meta = document.createElement('small');
92
+ meta.textContent = ago(n.modified) + ' · ' + n.size + ' B';
93
+ li.append(meta);
94
+ li.onclick = () => open(n.name);
95
+ $('list').append(li);
96
+ }
97
+ }
98
+
99
+ async function open(name) {
100
+ await flush();
101
+ const res = await fetch('/api/notes/' + encodeURIComponent(name));
102
+ current = name;
103
+ $('editor').value = res.ok ? await res.text() : '';
104
+ $('title').textContent = name;
105
+ $('editor').hidden = false;
106
+ $('delete').hidden = false;
107
+ $('empty').hidden = true;
108
+ $('status').textContent = '';
109
+ $('editor').focus();
110
+ render();
111
+ }
112
+
113
+ async function flush() {
114
+ if (!saveTimer) return;
115
+ clearTimeout(saveTimer);
116
+ saveTimer = 0;
117
+ await save();
118
+ }
119
+
120
+ async function save() {
121
+ saveTimer = 0;
122
+ await fetch('/api/notes/' + encodeURIComponent(current), { method: 'PUT', body: $('editor').value });
123
+ $('status').textContent = 'Saved';
124
+ await loadList();
125
+ }
126
+
127
+ $('editor').oninput = () => {
128
+ $('status').textContent = 'Editing…';
129
+ clearTimeout(saveTimer);
130
+ saveTimer = setTimeout(save, 400);
131
+ };
132
+
133
+ $('new').onclick = async () => {
134
+ let n = 1;
135
+ while (notes.some((x) => x.name === 'Untitled ' + n)) n++;
136
+ current = 'Untitled ' + n;
137
+ await fetch('/api/notes/' + encodeURIComponent(current), { method: 'PUT', body: '' });
138
+ await loadList();
139
+ open(current);
140
+ };
141
+
142
+ $('delete').onclick = async () => {
143
+ clearTimeout(saveTimer);
144
+ saveTimer = 0;
145
+ await fetch('/api/notes/' + encodeURIComponent(current), { method: 'DELETE' });
146
+ current = null;
147
+ $('editor').hidden = true;
148
+ $('delete').hidden = true;
149
+ $('empty').hidden = false;
150
+ $('title').textContent = 'No note selected';
151
+ await loadList();
152
+ };
153
+
154
+ $('search').oninput = render;
155
+
156
+ async function refreshInfo() {
157
+ try {
158
+ const i = await (await fetch('/api/info')).json();
159
+ $('info').textContent = i.dir + ' · ' + i.runtime + ' · ' + (i.rss / 1048576).toFixed(1) + ' MiB';
160
+ } catch {
161
+ $('info').textContent = 'disconnected';
162
+ }
163
+ }
164
+
165
+ loadList().then(() => notes.length && open(notes[0].name));
166
+ refreshInfo();
167
+ setInterval(refreshInfo, 5000);
168
+ // Closing the window saves what the autosave hasn't reached. Not pagehide:
169
+ // webviews can tear the page down without it.
170
+ addEventListener('beforeunload', () => {
171
+ if (saveTimer) navigator.sendBeacon('/api/notes/' + encodeURIComponent(current), $('editor').value);
172
+ });
173
+ </script>
174
+ </body>
175
+ </html>
176
+ `;
@@ -0,0 +1,76 @@
1
+ # Duplicate Finder
2
+
3
+ Scans a directory tree, finds files with identical content and writes a JSON
4
+ report of the duplicates and the space they waste. It's a disk-bound and
5
+ hash-bound tool you can hand to anyone as one binary, with no runtime to
6
+ install.
7
+
8
+ Demonstrates: `fs.readdirSync` with `recursive` + `withFileTypes`,
9
+ `fs.statSync`, `fs.readFileSync` / `fs.writeFileSync`, SHA-256 via
10
+ `crypto.createHash`, `Map` grouping, sorting with a compound comparator,
11
+ `reduce`, `JSON.stringify` with indentation and `performance.now()`.
12
+
13
+ ## How it works
14
+
15
+ 1. Walk the tree and group every non-empty file by size.
16
+ 2. Hash (SHA-256) only the files whose size matches at least one other file.
17
+ A file with a unique size can't have a duplicate, so it's never read.
18
+ 3. Files with the same hash form a duplicate group. Groups are sorted by
19
+ wasted bytes (`size × (copies − 1)`) and written to the report.
20
+
21
+ ```sh
22
+ node main.ts ~/Downloads report.json
23
+ # Scanned 2000 files (243.5 MiB), hashed 1494
24
+ # Found 449 duplicate groups wasting 81.9 MiB
25
+ # <copies> x <size> B <first path> (the 5 biggest groups)
26
+ # Report written to report.json in 412 ms
27
+ ```
28
+
29
+ `report.json` lists every group with its hash, size and full file paths.
30
+
31
+ ## Run it
32
+
33
+ With Node.js:
34
+
35
+ ```sh
36
+ node main.ts <dir> [report.json]
37
+ ```
38
+
39
+ With TypeNative:
40
+
41
+ ```sh
42
+ npx typenative --source main.ts --output dist/dupes.exe
43
+ ./dist/dupes.exe <dir> [report.json]
44
+ ```
45
+
46
+ From a checkout of this repository:
47
+
48
+ ```sh
49
+ node bin/cli.js --source examples/dupe-finder/main.ts --output dist/dupes.exe
50
+ ```
51
+
52
+ ## Benchmark: Node.js vs TypeNative
53
+
54
+ Reproduce with `node bench.mjs [runs=10]`. The script compiles `main.ts` and
55
+ generates a deterministic fixture tree in a temp directory: 2,000 files
56
+ (1 KiB–256 KiB, 243.5 MiB) across 280 folders. A quarter of the files are
57
+ exact copies of earlier ones, and another quarter have the same size as an
58
+ earlier file but different bytes, so they get hashed without being
59
+ duplicates. It runs each runtime once to warm the OS file cache, then times
60
+ **complete process runs** of both and checks that the two reports are
61
+ byte-identical.
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.
65
+
66
+ | Runtime | min | median | mean | max |
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 |
70
+
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
73
+ work is reading and hashing about 180 MiB, so the gap comes from Go's
74
+ SHA-256 and file I/O, and from skipping the ~100 ms Node startup. The OS
75
+ file cache is warm in both cases. On a cold cache, disk speed dominates and
76
+ the gap narrows.
@@ -0,0 +1,120 @@
1
+ // Disk-scan benchmark: Node.js vs TypeNative for the duplicate finder.
2
+ //
3
+ // Compiles main.ts to a native binary with the TypeNative CLI from this repo
4
+ // checkout (../../bin/cli.js), generates a fixture tree in a temp directory
5
+ // (2,000 files in 40 folders, 1 KiB - 256 KiB, a quarter of them duplicates,
6
+ // plus same-size files with different content), then times complete process
7
+ // runs of both runtimes over it and checks that the two reports match.
8
+ //
9
+ // Usage: node bench.mjs [runs=10]
10
+
11
+ import { spawnSync } from 'node:child_process';
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+
17
+ const here = path.dirname(fileURLToPath(import.meta.url));
18
+ const repoRoot = path.resolve(here, '..', '..');
19
+ const cli = path.join(repoRoot, 'bin', 'cli.js');
20
+ const runs = Number(process.argv[2] ?? '10') || 10;
21
+ const exeName = process.platform === 'win32' ? 'dupes.exe' : 'dupes';
22
+ const exePath = path.join(here, 'dist', exeName);
23
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'dupes-bench-'));
24
+ const fixture = path.join(tmpDir, 'tree');
25
+
26
+ function stats(samples) {
27
+ const sorted = [...samples].sort((a, b) => a - b);
28
+ const mean = samples.reduce((sum, x) => sum + x, 0) / samples.length;
29
+ return { min: sorted[0], median: sorted[Math.floor(sorted.length / 2)], mean, max: sorted[sorted.length - 1] };
30
+ }
31
+
32
+ function fmt(ms) {
33
+ return `${ms.toFixed(2)} ms`.padStart(11);
34
+ }
35
+
36
+ // Deterministic pseudo-random bytes, so every run scans the same tree
37
+ function makeFixture() {
38
+ let seed = 42;
39
+ const rand = () => {
40
+ seed ^= seed << 13;
41
+ seed ^= seed >>> 17;
42
+ seed ^= seed << 5;
43
+ return (seed >>> 0) / 0x100000000;
44
+ };
45
+ const originals = [];
46
+ let bytes = 0;
47
+ for (let i = 0; i < 2000; i++) {
48
+ const dir = path.join(fixture, `dir-${i % 40}`, `sub-${i % 7}`);
49
+ fs.mkdirSync(dir, { recursive: true });
50
+ let content;
51
+ if (i % 4 === 3 && originals.length > 0) {
52
+ // An exact copy of an earlier file
53
+ content = originals[Math.floor(rand() * originals.length)];
54
+ } else if (i % 4 === 2 && originals.length > 0) {
55
+ // Same size as an earlier file, different bytes: hashed, but not a duplicate
56
+ const twin = originals[Math.floor(rand() * originals.length)];
57
+ content = Buffer.from(twin);
58
+ content[content.length - 1] ^= 0xff;
59
+ } else {
60
+ content = Buffer.alloc(1024 + 4 * Math.floor(rand() * 255 * 256));
61
+ for (let j = 0; j < content.length; j += 4) content.writeUInt32LE(Math.floor(rand() * 0xffffffff), j);
62
+ originals.push(content);
63
+ }
64
+ fs.writeFileSync(path.join(dir, `file-${i}.bin`), content);
65
+ bytes += content.length;
66
+ }
67
+ return bytes;
68
+ }
69
+
70
+ function timeRuns(command, args) {
71
+ const samples = [];
72
+ for (let i = 0; i < runs; i++) {
73
+ const t0 = performance.now();
74
+ const result = spawnSync(command, args, { cwd: here, encoding: 'utf8' });
75
+ const elapsed = performance.now() - t0;
76
+ if (result.status !== 0) {
77
+ console.error(`run failed: ${command} ${args.join(' ')}\n${result.stderr}`);
78
+ process.exit(1);
79
+ }
80
+ samples.push(elapsed);
81
+ }
82
+ return stats(samples);
83
+ }
84
+
85
+ // 1. Compile the finder to a native binary.
86
+ fs.mkdirSync(path.join(here, 'dist'), { recursive: true });
87
+ console.log('Compiling main.ts to a native binary with TypeNative...');
88
+ const build = spawnSync(process.execPath, [cli, '--source', 'main.ts', '--output', path.join('dist', exeName)], {
89
+ cwd: here,
90
+ stdio: 'inherit',
91
+ });
92
+ if (build.status !== 0) process.exit(build.status ?? 1);
93
+
94
+ // 2. Build the fixture tree.
95
+ const fixtureBytes = makeFixture();
96
+ console.log(`\nFixture: 2000 files, ${(fixtureBytes / 1024 / 1024).toFixed(1)} MiB in ${fixture}`);
97
+
98
+ // 3. Time full runs of both runtimes (the first run of each also warms the OS file cache).
99
+ const nodeReport = path.join(tmpDir, 'node.json');
100
+ const nativeReport = path.join(tmpDir, 'native.json');
101
+ timeRuns(process.execPath, ['main.ts', fixture, nodeReport]);
102
+ console.log(`\nTiming ${runs} full process runs of each runtime...\n`);
103
+ const nodeStats = timeRuns(process.execPath, ['main.ts', fixture, nodeReport]);
104
+ const nativeStats = timeRuns(exePath, [fixture, nativeReport]);
105
+
106
+ const same = fs.readFileSync(nodeReport, 'utf8') === fs.readFileSync(nativeReport, 'utf8');
107
+ const report = JSON.parse(fs.readFileSync(nativeReport, 'utf8'));
108
+ fs.rmSync(tmpDir, { recursive: true, force: true });
109
+
110
+ console.log(`Scan + hash + report, ${runs} runs (full process: spawn -> exit):\n`);
111
+ console.log('| Runtime | min | median | mean | max |');
112
+ console.log('|------------|-------------|-------------|-------------|-------------|');
113
+ console.log(`| Node.js |${fmt(nodeStats.min)} |${fmt(nodeStats.median)} |${fmt(nodeStats.mean)} |${fmt(nodeStats.max)} |`);
114
+ console.log(`| TypeNative |${fmt(nativeStats.min)} |${fmt(nativeStats.median)} |${fmt(nativeStats.mean)} |${fmt(nativeStats.max)} |`);
115
+ console.log(
116
+ `\nBoth found ${report.groups.length} duplicate groups (${report.hashedFiles} files hashed, ` +
117
+ `${(report.wastedBytes / 1024 / 1024).toFixed(1)} MiB wasted); reports identical: ${same}`
118
+ );
119
+ console.log(`TypeNative is ${(nodeStats.median / nativeStats.median).toFixed(1)}x faster (median).`);
120
+ if (!same) process.exit(1);
@@ -0,0 +1,87 @@
1
+ // Finds duplicate files under a directory and writes a JSON report.
2
+ // Files are grouped by size first, so only files that share a size are read
3
+ // and hashed (SHA-256). Duplicates are files whose hashes match.
4
+ //
5
+ // node main.ts <dir> [report.json]
6
+ // ./dupes <dir> [report.json] (default report: dupes.json)
7
+ import crypto from 'node:crypto';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ interface DuplicateGroup {
12
+ hash: string;
13
+ size: number;
14
+ files: string[];
15
+ }
16
+
17
+ interface Report {
18
+ root: string;
19
+ scannedFiles: number;
20
+ scannedBytes: number;
21
+ hashedFiles: number;
22
+ groups: DuplicateGroup[];
23
+ wastedBytes: number;
24
+ }
25
+
26
+ const root = path.resolve(process.argv[2] ?? '.');
27
+ const reportPath = process.argv[3] ?? 'dupes.json';
28
+ const started = performance.now();
29
+
30
+ // 1. Walk the tree and group every regular file by size.
31
+ const bySize = new Map<number, string[]>();
32
+ let scannedFiles = 0;
33
+ let scannedBytes = 0;
34
+ for (const entry of fs.readdirSync(root, { recursive: true, withFileTypes: true })) {
35
+ if (!entry.isFile()) continue;
36
+ const file = path.join(entry.parentPath, entry.name);
37
+ const size = fs.statSync(file).size;
38
+ scannedFiles++;
39
+ scannedBytes += size;
40
+ if (size === 0) continue;
41
+ const sameSize = bySize.get(size) ?? [];
42
+ sameSize.push(file);
43
+ bySize.set(size, sameSize);
44
+ }
45
+
46
+ // 2. Hash only the files that share a size with another file.
47
+ const byHash = new Map<string, DuplicateGroup>();
48
+ let hashedFiles = 0;
49
+ for (const [size, files] of bySize) {
50
+ if (files.length < 2) continue;
51
+ for (const file of files) {
52
+ const hash = crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
53
+ hashedFiles++;
54
+ const group = byHash.get(hash);
55
+ if (group) group.files.push(file);
56
+ else byHash.set(hash, { hash: hash, size: size, files: [file] });
57
+ }
58
+ }
59
+
60
+ // 3. Keep the groups with more than one file, biggest savings first.
61
+ const groups: DuplicateGroup[] = [];
62
+ for (const group of byHash.values()) {
63
+ if (group.files.length > 1) {
64
+ group.files.sort();
65
+ groups.push(group);
66
+ }
67
+ }
68
+ groups.sort((a, b) => b.size * (b.files.length - 1) - a.size * (a.files.length - 1) || (a.hash < b.hash ? -1 : 1));
69
+ const wastedBytes = groups.reduce((sum, g) => sum + g.size * (g.files.length - 1), 0);
70
+
71
+ const report: Report = {
72
+ root: root,
73
+ scannedFiles: scannedFiles,
74
+ scannedBytes: scannedBytes,
75
+ hashedFiles: hashedFiles,
76
+ groups: groups,
77
+ wastedBytes: wastedBytes
78
+ };
79
+ fs.writeFileSync(reportPath, JSON.stringify(report, null, 2));
80
+
81
+ const mib = (n: number): string => (n / 1024 / 1024).toFixed(1);
82
+ console.log(`Scanned ${scannedFiles} files (${mib(scannedBytes)} MiB), hashed ${hashedFiles}`);
83
+ console.log(`Found ${groups.length} duplicate groups wasting ${mib(wastedBytes)} MiB`);
84
+ for (const group of groups.slice(0, 5)) {
85
+ console.log(` ${group.files.length} x ${group.size} B ${path.relative(root, group.files[0])}`);
86
+ }
87
+ console.log(`Report written to ${reportPath} in ${Math.round(performance.now() - started)} ms`);
@@ -0,0 +1,65 @@
1
+ # Mandelbrot PNG
2
+
3
+ Renders the Mandelbrot set and writes it as a PNG. The PNG encoder is about
4
+ 40 lines of TypeScript on top of `node:zlib` (`deflateSync` for the pixel
5
+ data, `crc32` for the chunk checksums). The program needs no image library,
6
+ no native addon such as `sharp` or `canvas`, and no `node_modules`: the
7
+ compiled binary is a single 3.3 MB file.
8
+
9
+ Demonstrates: a tight floating-point loop, a function returning a tuple that
10
+ the caller destructures, `Uint8Array` / `DataView` big-endian writes,
11
+ `zlib.deflateSync` + `zlib.crc32`, `Math.log2` / `Math.cos`, and
12
+ `fs.writeFileSync` of binary data.
13
+
14
+ ![Mandelbrot render, 640x360](preview.png)
15
+
16
+ ## Run it
17
+
18
+ With Node.js:
19
+
20
+ ```sh
21
+ node main.ts 1920 1080 mandelbrot.png
22
+ # Rendered 1920x1080 in 533 ms, encoded 416056 bytes in 50 ms -> mandelbrot.png
23
+ ```
24
+
25
+ With TypeNative:
26
+
27
+ ```sh
28
+ npx typenative --source main.ts --output dist/mandelbrot.exe
29
+ ./dist/mandelbrot.exe 1920 1080 mandelbrot.png
30
+ # Rendered 1920x1080 in 534 ms, encoded 418872 bytes in 46 ms -> mandelbrot.png
31
+ ```
32
+
33
+ From a checkout of this repository:
34
+
35
+ ```sh
36
+ node bin/cli.js --source examples/mandelbrot-png/main.ts --output dist/mandelbrot.exe
37
+ ```
38
+
39
+ The two PNGs aren't byte-identical, because Node's deflate is zlib and
40
+ TypeNative's is Go's `compress/flate`. They do decode to **identical pixels**.
41
+
42
+ ## Benchmark: Node.js vs TypeNative
43
+
44
+ Reproduce with `node bench.mjs [width=1920] [height=1080] [runs=10]`. The
45
+ script compiles `main.ts`, times **complete process runs** (spawn to exit) of
46
+ both runtimes rendering the same image, then decodes both PNGs (checking every
47
+ chunk CRC) and compares the pixels.
48
+
49
+ **Environment:** Windows 11 Pro, AMD Ryzen 5 5500U, Node v24.19.0, Go 1.26.0,
50
+ TypeNative 0.4.1, default (non-`--release`) build.
51
+
52
+ | Runtime | min | median | mean | max |
53
+ |------------|-----------|-----------|-----------|-----------|
54
+ | Node.js | 678.34 ms | 744.01 ms | 769.12 ms | 918.37 ms |
55
+ | TypeNative | 591.29 ms | 596.63 ms | 599.53 ms | 623.04 ms |
56
+
57
+ **TypeNative is 1.2x faster end to end** (median), and its run-to-run spread
58
+ is much tighter (32 ms vs 240 ms). There's no JIT warm-up and no GC pauses
59
+ from a large heap. The render loop itself takes about the same time in both
60
+ runtimes (~530 ms). V8 compiles a tight float loop like the escape-time
61
+ iteration into machine code about as good as Go's. The difference comes from
62
+ startup (~100 ms) and slightly faster deflate. For recursion and
63
+ call-heavy code the compute gap is larger (see [fibonacci](../fibonacci/),
64
+ 1.9x). This example's main advantage is distribution: one dependency-free
65
+ binary that writes images.
@@ -0,0 +1,95 @@
1
+ // Render benchmark: Node.js vs TypeNative for the Mandelbrot PNG renderer.
2
+ //
3
+ // Compiles main.ts to a native binary with the TypeNative CLI from this repo
4
+ // checkout (../../bin/cli.js), then times complete process runs (spawn to
5
+ // exit) of both runtimes rendering the same image, and checks that the two
6
+ // PNGs decode to identical pixels. (The compressed bytes differ: Node uses
7
+ // zlib's deflate and TypeNative Go's compress/flate.)
8
+ //
9
+ // Usage: node bench.mjs [width=1920] [height=1080] [runs=10]
10
+
11
+ import { spawnSync } from 'node:child_process';
12
+ import fs from 'node:fs';
13
+ import os from 'node:os';
14
+ import path from 'node:path';
15
+ import zlib from 'node:zlib';
16
+ import { fileURLToPath } from 'node:url';
17
+
18
+ const here = path.dirname(fileURLToPath(import.meta.url));
19
+ const repoRoot = path.resolve(here, '..', '..');
20
+ const cli = path.join(repoRoot, 'bin', 'cli.js');
21
+ const width = process.argv[2] ?? '1920';
22
+ const height = process.argv[3] ?? '1080';
23
+ const runs = Number(process.argv[4] ?? '10') || 10;
24
+ const exeName = process.platform === 'win32' ? 'mandelbrot.exe' : 'mandelbrot';
25
+ const exePath = path.join(here, 'dist', exeName);
26
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mandelbrot-bench-'));
27
+
28
+ function stats(samples) {
29
+ const sorted = [...samples].sort((a, b) => a - b);
30
+ const mean = samples.reduce((sum, x) => sum + x, 0) / samples.length;
31
+ return { min: sorted[0], median: sorted[Math.floor(sorted.length / 2)], mean, max: sorted[sorted.length - 1] };
32
+ }
33
+
34
+ function fmt(ms) {
35
+ return `${ms.toFixed(2)} ms`.padStart(11);
36
+ }
37
+
38
+ // Inflated IDAT data (the raw scanlines), after checking every chunk's CRC
39
+ function decodePixels(file) {
40
+ const png = fs.readFileSync(file);
41
+ const idat = [];
42
+ for (let offset = 8; offset < png.length; ) {
43
+ const length = png.readUInt32BE(offset);
44
+ const typeAndData = png.subarray(offset + 4, offset + 8 + length);
45
+ if (zlib.crc32(typeAndData) !== png.readUInt32BE(offset + 8 + length)) throw new Error(`bad CRC in ${file}`);
46
+ if (typeAndData.toString('latin1', 0, 4) === 'IDAT') idat.push(typeAndData.subarray(4));
47
+ offset += 12 + length;
48
+ }
49
+ return zlib.inflateSync(Buffer.concat(idat));
50
+ }
51
+
52
+ function timeRuns(command, args) {
53
+ const samples = [];
54
+ for (let i = 0; i < runs; i++) {
55
+ const t0 = performance.now();
56
+ const result = spawnSync(command, args, { cwd: here, encoding: 'utf8' });
57
+ const elapsed = performance.now() - t0;
58
+ if (result.status !== 0) {
59
+ console.error(`run failed: ${command} ${args.join(' ')}\n${result.stderr}`);
60
+ process.exit(1);
61
+ }
62
+ samples.push(elapsed);
63
+ }
64
+ return stats(samples);
65
+ }
66
+
67
+ // 1. Compile the renderer to a native binary.
68
+ fs.mkdirSync(path.join(here, 'dist'), { recursive: true });
69
+ console.log('Compiling main.ts to a native binary with TypeNative...');
70
+ const build = spawnSync(process.execPath, [cli, '--source', 'main.ts', '--output', path.join('dist', exeName)], {
71
+ cwd: here,
72
+ stdio: 'inherit',
73
+ });
74
+ if (build.status !== 0) process.exit(build.status ?? 1);
75
+
76
+ // 2. Time full renders under both runtimes.
77
+ const nodePng = path.join(tmpDir, 'node.png');
78
+ const nativePng = path.join(tmpDir, 'native.png');
79
+ console.log(`\nTiming ${runs} full process runs of each runtime at ${width}x${height}...\n`);
80
+ const nodeStats = timeRuns(process.execPath, ['main.ts', width, height, nodePng]);
81
+ const nativeStats = timeRuns(exePath, [width, height, nativePng]);
82
+
83
+ const nodePixels = decodePixels(nodePng);
84
+ const same = nodePixels.equals(decodePixels(nativePng));
85
+ const sizes = [fs.statSync(nodePng).size, fs.statSync(nativePng).size];
86
+ fs.rmSync(tmpDir, { recursive: true, force: true });
87
+
88
+ console.log(`Render + PNG encode + write, ${runs} runs (full process: spawn -> exit):\n`);
89
+ console.log('| Runtime | min | median | mean | max |');
90
+ console.log('|------------|-------------|-------------|-------------|-------------|');
91
+ console.log(`| Node.js |${fmt(nodeStats.min)} |${fmt(nodeStats.median)} |${fmt(nodeStats.mean)} |${fmt(nodeStats.max)} |`);
92
+ console.log(`| TypeNative |${fmt(nativeStats.min)} |${fmt(nativeStats.median)} |${fmt(nativeStats.mean)} |${fmt(nativeStats.max)} |`);
93
+ console.log(`\nPNG sizes: Node ${sizes[0]} B, TypeNative ${sizes[1]} B; decoded pixels identical: ${same}`);
94
+ console.log(`TypeNative is ${(nodeStats.median / nativeStats.median).toFixed(1)}x faster (median).`);
95
+ if (!same) process.exit(1);