typenative 0.4.0 → 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 (167) hide show
  1. package/.github/workflows/ci.yml +2 -0
  2. package/CHANGELOG.md +372 -0
  3. package/CONTRIBUTION.md +1 -1
  4. package/README.md +62 -22
  5. package/ROUND2-HANDOFF.md +200 -0
  6. package/bin/cli.js +2 -0
  7. package/bin/go/bridge.js +74 -14
  8. package/bin/go/convert.js +48 -0
  9. package/bin/go/metadata.js +13 -4
  10. package/bin/go/overrides.js +4 -6
  11. package/bin/go/stdlib.generated.js +2 -0
  12. package/bin/index.js +130 -2
  13. package/bin/main.js +2 -0
  14. package/bin/node/assert.js +2 -2
  15. package/bin/node/async_hooks.js +1 -1
  16. package/bin/node/buffer.js +16 -5
  17. package/bin/node/child_process.js +57 -9
  18. package/bin/node/cluster.js +44 -6
  19. package/bin/node/core.js +1 -1
  20. package/bin/node/crypto.js +205 -4
  21. package/bin/node/crypto_keys.js +21 -21
  22. package/bin/node/dgram.js +231 -7
  23. package/bin/node/diagnostics_channel.js +3 -3
  24. package/bin/node/dns.js +472 -9
  25. package/bin/node/errno_tables.js +445 -0
  26. package/bin/node/events.js +3 -3
  27. package/bin/node/fetch.js +2 -2
  28. package/bin/node/fs.js +24 -17
  29. package/bin/node/fs_watch.js +5 -5
  30. package/bin/node/http.js +131 -33
  31. package/bin/node/http2.js +7 -4
  32. package/bin/node/module_v8.js +142 -0
  33. package/bin/node/net.js +17 -14
  34. package/bin/node/path.js +17 -3
  35. package/bin/node/process.js +274 -9
  36. package/bin/node/readline.js +272 -1
  37. package/bin/node/registry.js +5 -1
  38. package/bin/node/sqlite.js +65 -17
  39. package/bin/node/stream.js +220 -22
  40. package/bin/node/stream_web.js +10 -10
  41. package/bin/node/system_extra.js +3 -3
  42. package/bin/node/test.js +834 -234
  43. package/bin/node/test_coverage.js +187 -0
  44. package/bin/node/test_report.js +1392 -0
  45. package/bin/node/test_run.js +575 -0
  46. package/bin/node/timers.js +4 -4
  47. package/bin/node/tls.js +5 -5
  48. package/bin/node/url.js +23 -5
  49. package/bin/node/util.js +49 -8
  50. package/bin/node/util_extra.js +13 -37
  51. package/bin/node/webview.js +654 -0
  52. package/bin/node/worker_threads.js +80 -20
  53. package/bin/node/zlib.js +3 -3
  54. package/bin/parse-node.js +4 -0
  55. package/bin/transpiler.js +14457 -1723
  56. package/bin/typecheck-node.js +1 -0
  57. package/bin/version.js +1 -1
  58. package/conformance.md +1153 -884
  59. package/examples/README.md +47 -10
  60. package/examples/desktop-notes/README.md +108 -0
  61. package/examples/desktop-notes/bench.mjs +125 -0
  62. package/examples/desktop-notes/main.ts +131 -0
  63. package/examples/desktop-notes/package-lock.json +726 -0
  64. package/examples/desktop-notes/package.json +9 -0
  65. package/examples/desktop-notes/ui.ts +176 -0
  66. package/examples/dupe-finder/README.md +76 -0
  67. package/examples/dupe-finder/bench.mjs +120 -0
  68. package/examples/dupe-finder/main.ts +87 -0
  69. package/examples/json-server/README.md +31 -29
  70. package/examples/json-server/bench.mjs +130 -38
  71. package/examples/mandelbrot-png/README.md +65 -0
  72. package/examples/mandelbrot-png/bench.mjs +95 -0
  73. package/examples/mandelbrot-png/main.ts +98 -0
  74. package/examples/mandelbrot-png/preview.png +0 -0
  75. package/examples/marked-cli/README.md +159 -0
  76. package/examples/marked-cli/bench.mjs +178 -0
  77. package/examples/marked-cli/main.ts +292 -0
  78. package/examples/marked-cli/parity.mjs +185 -0
  79. package/examples/marked-cli/vendor/marked/LICENSE +44 -0
  80. package/examples/marked-cli/vendor/marked/VENDOR.md +26 -0
  81. package/examples/todo-cli/README.md +69 -0
  82. package/examples/todo-cli/bench.mjs +89 -0
  83. package/examples/todo-cli/main.ts +92 -0
  84. package/examples/yaml-cli/README.md +136 -0
  85. package/examples/yaml-cli/bench.mjs +265 -0
  86. package/examples/yaml-cli/main.ts +29 -0
  87. package/examples/yaml-cli/parity.mjs +156 -0
  88. package/examples/yaml-cli/vendor/yaml/LICENSE +13 -0
  89. package/examples/yaml-cli/vendor/yaml/VENDOR.md +25 -0
  90. package/govendor/github.com/jchv/go-webview2/LICENSE +22 -0
  91. package/govendor/github.com/jchv/go-webview2/README.md +21 -0
  92. package/govendor/github.com/jchv/go-webview2/common.go +84 -0
  93. package/govendor/github.com/jchv/go-webview2/go.mod +3 -0
  94. package/govendor/github.com/jchv/go-webview2/internal/w32/w32.go +194 -0
  95. package/govendor/github.com/jchv/go-webview2/internal/w32/w32_386.go +14 -0
  96. package/govendor/github.com/jchv/go-webview2/internal/w32/w32_64bit.go +15 -0
  97. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_COLOR.go +8 -0
  98. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND.go +9 -0
  99. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_KEY_EVENT_KIND.go +10 -0
  100. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_MOVE_FOCUS_REASON.go +9 -0
  101. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_PHYSICAL_KEY_STATUS.go +10 -0
  102. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_WEB_RESOURCE_CONTEXT.go +23 -0
  103. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2AcceleratorKeyPressedEventArgs.go +78 -0
  104. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2AcceleratorKeyPressedEventHandler.go +52 -0
  105. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Controller.go +132 -0
  106. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Controller2.go +74 -0
  107. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2CreateCoreWebView2ControllerCompletedHandler.go +48 -0
  108. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2NavigationCompletedEventArgs.go +17 -0
  109. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2NavigationCompletedEventHandler.go +48 -0
  110. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Settings.go +270 -0
  111. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequest.go +43 -0
  112. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequestedEventArgs.go +51 -0
  113. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequestedEventHandler.go +48 -0
  114. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceResponse.go +21 -0
  115. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2_2.go +21 -0
  116. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2_3.go +60 -0
  117. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebViewSettings.go +396 -0
  118. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium.go +361 -0
  119. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_386.go +24 -0
  120. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_amd64.go +22 -0
  121. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_arm64.go +26 -0
  122. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc.go +13 -0
  123. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc_go17.go +51 -0
  124. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc_go18.go +16 -0
  125. package/govendor/github.com/jchv/go-webview2/pkg/edge/corewebview2.go +411 -0
  126. package/govendor/github.com/jchv/go-webview2/pkg/edge/guid.go +223 -0
  127. package/govendor/github.com/jchv/go-webview2/webview.go +482 -0
  128. package/govendor/github.com/jchv/go-webview2/webviewloader/README.md +3 -0
  129. package/govendor/github.com/jchv/go-webview2/webviewloader/module.go +153 -0
  130. package/govendor/github.com/jchv/go-webview2/webviewloader/module_386.go +6 -0
  131. package/govendor/github.com/jchv/go-webview2/webviewloader/module_amd64.go +6 -0
  132. package/govendor/github.com/jchv/go-webview2/webviewloader/module_arm64.go +6 -0
  133. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/arm64/WebView2Loader.dll +0 -0
  134. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/x64/WebView2Loader.dll +0 -0
  135. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/x86/WebView2Loader.dll +0 -0
  136. package/govendor/github.com/jchv/go-winloader/LICENSE.md +7 -0
  137. package/govendor/github.com/jchv/go-winloader/README.md +124 -0
  138. package/govendor/github.com/jchv/go-winloader/common.go +11 -0
  139. package/govendor/github.com/jchv/go-winloader/go.mod +3 -0
  140. package/govendor/github.com/jchv/go-winloader/internal/loader/loader.go +25 -0
  141. package/govendor/github.com/jchv/go-winloader/internal/loader/machine.go +53 -0
  142. package/govendor/github.com/jchv/go-winloader/internal/memloader/cache.go +42 -0
  143. package/govendor/github.com/jchv/go-winloader/internal/memloader/loader.go +253 -0
  144. package/govendor/github.com/jchv/go-winloader/internal/pe/export.go +76 -0
  145. package/govendor/github.com/jchv/go-winloader/internal/pe/format.go +522 -0
  146. package/govendor/github.com/jchv/go-winloader/internal/pe/import.go +106 -0
  147. package/govendor/github.com/jchv/go-winloader/internal/pe/module.go +91 -0
  148. package/govendor/github.com/jchv/go-winloader/internal/pe/reloc.go +177 -0
  149. package/govendor/github.com/jchv/go-winloader/internal/pe/util.go +40 -0
  150. package/govendor/github.com/jchv/go-winloader/internal/vmem/common.go +55 -0
  151. package/govendor/github.com/jchv/go-winloader/internal/vmem/memory_other.go +71 -0
  152. package/govendor/github.com/jchv/go-winloader/internal/vmem/memory_windows.go +179 -0
  153. package/govendor/github.com/jchv/go-winloader/internal/winloader/hacks_other.go +17 -0
  154. package/govendor/github.com/jchv/go-winloader/internal/winloader/hacks_windows.go +73 -0
  155. package/govendor/github.com/jchv/go-winloader/internal/winloader/loader_windows.go +64 -0
  156. package/govendor/github.com/jchv/go-winloader/internal/winloader/machine_windows.go +32 -0
  157. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_386.go +9 -0
  158. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_amd64.go +9 -0
  159. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_arm64.go +9 -0
  160. package/govendor/github.com/jchv/go-winloader/loader_other.go +24 -0
  161. package/govendor/github.com/jchv/go-winloader/loader_windows.go +33 -0
  162. package/govendor/manifest.txt +3 -1
  163. package/package.json +1 -1
  164. package/tsparser/main.go +4 -0
  165. package/types/typenative-go.d.ts +23 -0
  166. package/types/typenative-npm.d.ts +359 -7
  167. package/types/typenative.d.ts +283 -42
@@ -0,0 +1,265 @@
1
+ // Benchmark: Node.js vs TypeNative for the yaml CLI, both converting YAML to
2
+ // JSON (`yaml --json`).
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 a small
7
+ // docker-compose.yml, the kind of file a script or hook converts once;
8
+ // (b) throughput: one run on about 10 MB of generated Kubernetes-style
9
+ // manifests (Deployments, Services and ConfigMaps in one stream).
10
+ // Runs alternate Node and native, so drift on the machine hits both alike.
11
+ // Both runtimes' JSON must be identical, or the benchmark stops.
12
+ //
13
+ // Usage: node bench.mjs [runs=30] [throughputRuns=5] [megabytes=10]
14
+
15
+ import { spawnSync } from 'node:child_process';
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ const here = path.dirname(fileURLToPath(import.meta.url));
21
+ const repoRoot = path.resolve(here, '..', '..');
22
+ const cli = path.join(repoRoot, 'bin', 'cli.js');
23
+ const cache = path.join(here, '.cache');
24
+ const exePath = path.join(cache, process.platform === 'win32' ? 'yaml.exe' : 'yaml');
25
+ const runs = Number(process.argv[2] ?? '30') || 30;
26
+ const throughputRuns = Number(process.argv[3] ?? '5') || 5;
27
+ const megabytes = Number(process.argv[4] ?? '10') || 10;
28
+
29
+ const COMPOSE = `# A small web app: reverse proxy, API, worker, database and cache
30
+ services:
31
+ proxy:
32
+ image: nginx:1.27-alpine
33
+ ports: ["80:80", "443:443"]
34
+ volumes:
35
+ - ./nginx.conf:/etc/nginx/nginx.conf:ro
36
+ - certs:/etc/letsencrypt
37
+ depends_on: [api]
38
+ restart: unless-stopped
39
+ api:
40
+ build:
41
+ context: ./api
42
+ args:
43
+ NODE_ENV: production
44
+ environment:
45
+ DATABASE_URL: postgres://app:secret@db:5432/app
46
+ REDIS_URL: redis://cache:6379/0
47
+ LOG_LEVEL: info
48
+ WORKERS: 4
49
+ healthcheck:
50
+ test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
51
+ interval: 30s
52
+ timeout: 5s
53
+ retries: 3
54
+ depends_on:
55
+ db: { condition: service_healthy }
56
+ cache: { condition: service_started }
57
+ worker:
58
+ build: ./api
59
+ command: node dist/worker.js
60
+ environment: &worker-env
61
+ QUEUE: default
62
+ CONCURRENCY: 8
63
+ deploy:
64
+ replicas: 2
65
+ resources:
66
+ limits: { cpus: "0.50", memory: 512M }
67
+ db:
68
+ image: postgres:16
69
+ environment:
70
+ POSTGRES_USER: app
71
+ POSTGRES_PASSWORD: secret
72
+ POSTGRES_DB: app
73
+ volumes: [pgdata:/var/lib/postgresql/data]
74
+ healthcheck:
75
+ test: pg_isready -U app
76
+ interval: 10s
77
+ cache:
78
+ image: redis:7-alpine
79
+ command: >
80
+ redis-server
81
+ --maxmemory 256mb
82
+ --maxmemory-policy allkeys-lru
83
+ volumes:
84
+ pgdata: {}
85
+ certs: {}
86
+ `;
87
+
88
+ // Deterministic pseudo-random numbers (a fixed-seed LCG): the same manifests
89
+ // on every run and every machine
90
+ let seed = 42;
91
+ function rand(n) {
92
+ seed = (seed * 1103515245 + 12345) % 2147483648;
93
+ return seed % n;
94
+ }
95
+
96
+ const APPS = ['checkout', 'catalog', 'payments', 'search', 'auth', 'billing', 'notifications', 'inventory'];
97
+ const TEAMS = ['core', 'growth', 'platform', 'data'];
98
+
99
+ function deployment(name, i) {
100
+ const team = TEAMS[rand(TEAMS.length)];
101
+ const env = Array.from({ length: 6 }, (_, k) => ` - name: FEATURE_${k}_ENABLED\n value: "${rand(2) === 1}"`).join('\n');
102
+ return `apiVersion: apps/v1
103
+ kind: Deployment
104
+ metadata:
105
+ name: ${name}
106
+ namespace: ${team}
107
+ labels:
108
+ app.kubernetes.io/name: ${name}
109
+ app.kubernetes.io/part-of: shop
110
+ team: ${team}
111
+ annotations:
112
+ deployment.kubernetes.io/revision: "${1 + rand(40)}"
113
+ spec:
114
+ replicas: ${1 + rand(12)}
115
+ selector:
116
+ matchLabels:
117
+ app.kubernetes.io/name: ${name}
118
+ strategy:
119
+ type: RollingUpdate
120
+ rollingUpdate: { maxSurge: 25%, maxUnavailable: 0 }
121
+ template:
122
+ metadata:
123
+ labels:
124
+ app.kubernetes.io/name: ${name}
125
+ version: v${1 + rand(5)}.${rand(20)}.${rand(100)}
126
+ spec:
127
+ serviceAccountName: ${name}
128
+ containers:
129
+ - name: app
130
+ image: registry.example.com/shop/${name}:${(i * 7919).toString(16)}
131
+ imagePullPolicy: IfNotPresent
132
+ ports:
133
+ - { name: http, containerPort: 8080, protocol: TCP }
134
+ - { name: metrics, containerPort: 9090, protocol: TCP }
135
+ args: ["--port=8080", "--log-format=json", "--shutdown-grace=${10 + rand(50)}s"]
136
+ env:
137
+ - name: POD_NAME
138
+ valueFrom:
139
+ fieldRef: { fieldPath: metadata.name }
140
+ ${env}
141
+ resources:
142
+ requests: { cpu: ${50 + rand(450)}m, memory: ${64 + rand(448)}Mi }
143
+ limits: { cpu: "${1 + rand(3)}", memory: ${512 + rand(1536)}Mi }
144
+ readinessProbe:
145
+ httpGet: { path: /ready, port: http }
146
+ initialDelaySeconds: ${rand(15)}
147
+ periodSeconds: 10
148
+ livenessProbe:
149
+ httpGet: { path: /healthz, port: http }
150
+ failureThreshold: 3
151
+ `;
152
+ }
153
+
154
+ function service(name, team) {
155
+ return `apiVersion: v1
156
+ kind: Service
157
+ metadata:
158
+ name: ${name}
159
+ namespace: ${team}
160
+ spec:
161
+ type: ClusterIP
162
+ selector:
163
+ app.kubernetes.io/name: ${name}
164
+ ports:
165
+ - name: http
166
+ port: 80
167
+ targetPort: http
168
+ `;
169
+ }
170
+
171
+ function configMap(name, team) {
172
+ const lines = Array.from({ length: 8 }, (_, k) => ` key_${k} = ${rand(100000) / 100}`).join('\n');
173
+ return `apiVersion: v1
174
+ kind: ConfigMap
175
+ metadata:
176
+ name: ${name}-config
177
+ namespace: ${team}
178
+ data:
179
+ LOG_LEVEL: ${['debug', 'info', 'warn'][rand(3)]}
180
+ TIMEOUT_MS: "${100 * (1 + rand(50))}"
181
+ app.properties: |
182
+ ${lines}
183
+ `;
184
+ }
185
+
186
+ function manifests(bytes) {
187
+ const docs = [];
188
+ let size = 0;
189
+ for (let i = 0; size < bytes; i++) {
190
+ const name = `${APPS[i % APPS.length]}-${i}`;
191
+ const team = TEAMS[i % TEAMS.length];
192
+ for (const doc of [deployment(name, i), service(name, team), configMap(name, team)]) {
193
+ docs.push(doc);
194
+ size += doc.length + 4;
195
+ }
196
+ }
197
+ return docs.join('---\n');
198
+ }
199
+
200
+ function stats(samples) {
201
+ const sorted = [...samples].sort((a, b) => a - b);
202
+ const mean = samples.reduce((sum, x) => sum + x, 0) / samples.length;
203
+ return { min: sorted[0], median: sorted[Math.floor(sorted.length / 2)], mean, max: sorted[sorted.length - 1] };
204
+ }
205
+
206
+ function fmt(ms) {
207
+ return `${ms.toFixed(2)} ms`.padStart(13);
208
+ }
209
+
210
+ function runOnce(command, args, input) {
211
+ const t0 = performance.now();
212
+ const result = spawnSync(command, args, { cwd: here, input, maxBuffer: 1 << 30 });
213
+ const elapsed = performance.now() - t0;
214
+ if (result.status !== 0) {
215
+ console.error(`run failed: ${command} ${args.join(' ')}\n${result.stderr}`);
216
+ process.exit(1);
217
+ }
218
+ return { elapsed, stdout: result.stdout };
219
+ }
220
+
221
+ // Alternating Node and native runs; the two outputs must match
222
+ function timeBoth(input, count) {
223
+ const node = [];
224
+ const native = [];
225
+ for (let i = 0; i < count; i++) {
226
+ const a = runOnce(process.execPath, ['main.ts', '--json'], input);
227
+ const b = runOnce(exePath, ['--json'], input);
228
+ if (!a.stdout.equals(b.stdout)) {
229
+ console.error('Node and native JSON differ');
230
+ process.exit(1);
231
+ }
232
+ node.push(a.elapsed);
233
+ native.push(b.elapsed);
234
+ }
235
+ return [stats(node), stats(native)];
236
+ }
237
+
238
+ function table(nodeStats, nativeStats, extra = () => '') {
239
+ console.log(`| Runtime | min | median | mean | max |${extra('head')}`);
240
+ console.log(`|------------|--------------|--------------|--------------|--------------|${extra('rule')}`);
241
+ console.log(`| Node.js |${fmt(nodeStats.min)} |${fmt(nodeStats.median)} |${fmt(nodeStats.mean)} |${fmt(nodeStats.max)} |${extra(nodeStats)}`);
242
+ console.log(`| TypeNative |${fmt(nativeStats.min)} |${fmt(nativeStats.median)} |${fmt(nativeStats.mean)} |${fmt(nativeStats.max)} |${extra(nativeStats)}`);
243
+ }
244
+
245
+ // 1. Compile the CLI to a native binary.
246
+ fs.mkdirSync(cache, { recursive: true });
247
+ console.log('Compiling main.ts to a native binary with TypeNative...');
248
+ const build = spawnSync(process.execPath, [cli, '--source', 'main.ts', '--output', exePath], { cwd: here, stdio: 'inherit' });
249
+ if (build.status !== 0) process.exit(build.status ?? 1);
250
+
251
+ // 2. Per-call latency on a small docker-compose.yml.
252
+ const compose = Buffer.from(COMPOSE);
253
+ console.log(`\n(a) \`yaml --json < docker-compose.yml\` (${compose.length} bytes), ${runs} runs each (full process: spawn -> exit):\n`);
254
+ const [nodeCall, nativeCall] = timeBoth(compose, runs);
255
+ table(nodeCall, nativeCall);
256
+ console.log(`\nTypeNative is ${(nodeCall.median / nativeCall.median).toFixed(1)}x faster per call (median).`);
257
+
258
+ // 3. Throughput on generated Kubernetes manifests.
259
+ const big = Buffer.from(manifests(megabytes * 1024 * 1024));
260
+ const mb = big.length / (1024 * 1024);
261
+ console.log(`\n(b) \`yaml --json < manifests.yaml\` (${mb.toFixed(1)} MB, ${big.toString().split('\n---\n').length} documents), ${throughputRuns} runs each:\n`);
262
+ const [nodeBig, nativeBig] = timeBoth(big, throughputRuns);
263
+ table(nodeBig, nativeBig, (s) => (s === 'head' ? ' MB/s (median) |' : s === 'rule' ? '---------------|' : ` ${(mb / (s.median / 1000)).toFixed(2).padStart(13)} |`));
264
+ const ratio = nodeBig.median / nativeBig.median;
265
+ console.log(`\nTypeNative is ${ratio >= 1 ? `${ratio.toFixed(1)}x faster` : `${(1 / ratio).toFixed(1)}x slower`} on throughput (median).`);
@@ -0,0 +1,29 @@
1
+ // The `yaml` npm package's own command-line tool, compiled from its unmodified
2
+ // upstream TypeScript (vendor/yaml/src, see vendor/yaml/VENDOR.md). This file
3
+ // is a TypeScript port of upstream's bin.js: it hands stdin and the arguments
4
+ // to cli() and turns the error it reports into an exit code.
5
+ //
6
+ // yaml < in.yaml re-emit the YAML stream
7
+ // yaml --json < in.yaml print it as JSON
8
+ // yaml valid < in.yaml exit 1 on the first error
9
+ // yaml lex < in.yaml print the lexer's tokens
10
+ // yaml cst < in.yaml print the concrete syntax tree
11
+ //
12
+ // Runs as-is under Node.js (`node main.ts`) and compiles with TypeNative.
13
+ import { UserError, cli, help } from './vendor/yaml/src/cli.ts';
14
+
15
+ cli(
16
+ process.stdin,
17
+ (error) => {
18
+ if (error instanceof UserError) {
19
+ if (error.code === UserError.ARGS) console.error(`${help}\n`);
20
+ console.error(error.message);
21
+ process.exitCode = error.code;
22
+ } else if (error) {
23
+ // bin.js rethrows here; Node then prints the error and exits with 1
24
+ console.error(error);
25
+ process.exitCode = 1;
26
+ }
27
+ },
28
+ process.argv.slice(2)
29
+ );
@@ -0,0 +1,156 @@
1
+ // Parity check: Node.js vs the TypeNative build of the yaml CLI.
2
+ //
3
+ // Fetches the yaml-test-suite (tag data-2022-01-17) into .cache/, compiles
4
+ // main.ts to a native binary with the TypeNative CLI from this repo checkout,
5
+ // then feeds every test's in.yaml to both, in each mode: default (re-emit the
6
+ // YAML), --json, valid and lex. stdout, stderr and the exit code must match
7
+ // byte for byte (stack frames aside: see withoutStackFrames). Failures are
8
+ // written to .cache/failures/.
9
+ //
10
+ // Usage: node parity.mjs [filter] (filter: a test id substring or a mode)
11
+
12
+ import { spawn, spawnSync } from 'node:child_process';
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
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 cache = path.join(here, '.cache');
22
+ const suite = path.join(cache, 'yaml-test-suite');
23
+ const failuresDir = path.join(cache, 'failures');
24
+ const exePath = path.join(cache, process.platform === 'win32' ? 'yaml.exe' : 'yaml');
25
+ const filter = process.argv[2] ?? '';
26
+ const MODES = [
27
+ { name: 'default', args: [] },
28
+ { name: 'json', args: ['--json'] },
29
+ { name: 'valid', args: ['valid'] },
30
+ { name: 'lex', args: ['lex'] }
31
+ ];
32
+
33
+ function run(command, args, options = {}) {
34
+ const result = spawnSync(command, args, { stdio: 'inherit', ...options });
35
+ if (result.status !== 0) {
36
+ console.error(`${command} ${args.join(' ')} failed`);
37
+ process.exit(1);
38
+ }
39
+ }
40
+
41
+ // The corpus: yaml-test-suite's data branch, one directory per test (some
42
+ // with numbered sub-tests), each with an in.yaml
43
+ function fetchSuite() {
44
+ if (fs.existsSync(path.join(suite, '.git')) || fs.existsSync(path.join(suite, '229Q'))) return;
45
+ fs.mkdirSync(cache, { recursive: true });
46
+ console.log('Fetching yaml-test-suite data-2022-01-17 ...');
47
+ run('git', ['clone', '--quiet', '--depth', '1', '--branch', 'data-2022-01-17', 'https://github.com/yaml/yaml-test-suite.git', suite]);
48
+ }
49
+
50
+ function listInputs() {
51
+ const inputs = [];
52
+ const walk = (dir, id) => {
53
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
54
+ if (entry.isDirectory() && entry.name !== '.git') walk(path.join(dir, entry.name), id ? `${id}-${entry.name}` : entry.name);
55
+ else if (entry.name === 'in.yaml') inputs.push({ id, file: path.join(dir, entry.name) });
56
+ }
57
+ };
58
+ walk(suite, '');
59
+ return inputs;
60
+ }
61
+
62
+ function exec(command, args, input) {
63
+ return new Promise((resolve) => {
64
+ const p = spawn(command, args, { cwd: here, stdio: ['pipe', 'pipe', 'pipe'] });
65
+ const stdout = [];
66
+ const stderr = [];
67
+ p.stdout.on('data', (d) => stdout.push(d));
68
+ p.stderr.on('data', (d) => stderr.push(d));
69
+ const timer = setTimeout(() => p.kill('SIGKILL'), 10000);
70
+ p.on('close', (code, signal) => {
71
+ clearTimeout(timer);
72
+ resolve({ code: signal ? signal : code, stdout: Buffer.concat(stdout), stderr: Buffer.concat(stderr) });
73
+ });
74
+ p.stdin.on('error', () => {});
75
+ p.stdin.end(input);
76
+ });
77
+ }
78
+
79
+ // Node prints an error's stack (" at …" lines, the frames of the JS call
80
+ // stack); a native binary has no JS frames to show. The frames are dropped
81
+ // (an inspected error's own properties, which follow the last frame as " {",
82
+ // stay where they are); warnings' process ids differ too
83
+ function withoutStackFrames(buffer) {
84
+ const out = [];
85
+ for (const line of buffer.toString().split('\n')) {
86
+ if (/^ {4}at /.test(line)) {
87
+ if (line.endsWith(' {')) out[out.length - 1] += ' {';
88
+ continue;
89
+ }
90
+ // (and process warnings name the process id)
91
+ out.push(line.replace(/^\(node:\d+\) /, '(node) '));
92
+ }
93
+ return Buffer.from(out.join('\n'));
94
+ }
95
+
96
+ function sameOutput(a, b) {
97
+ return a.code === b.code && a.stdout.equals(b.stdout) && withoutStackFrames(a.stderr).equals(withoutStackFrames(b.stderr));
98
+ }
99
+
100
+ function report(failure) {
101
+ const { id, mode, input, node, native } = failure;
102
+ const text = [
103
+ `# ${id} (${mode})`,
104
+ '## input',
105
+ input.toString(),
106
+ `## node (exit ${node.code})`,
107
+ '### stdout', node.stdout.toString(), '### stderr', node.stderr.toString(),
108
+ `## native (exit ${native.code})`,
109
+ '### stdout', native.stdout.toString(), '### stderr', native.stderr.toString()
110
+ ].join('\n');
111
+ fs.writeFileSync(path.join(failuresDir, `${id}-${mode}.txt`), text);
112
+ }
113
+
114
+ fetchSuite();
115
+ console.log('Compiling main.ts ...');
116
+ run(process.execPath, [cli, '--source', path.join(here, 'main.ts'), '--output', exePath], { cwd: here });
117
+
118
+ const cases = [];
119
+ for (const input of listInputs()) {
120
+ for (const mode of MODES) {
121
+ if (filter && !input.id.includes(filter) && mode.name !== filter) continue;
122
+ cases.push({ ...input, mode });
123
+ }
124
+ }
125
+ fs.rmSync(failuresDir, { recursive: true, force: true });
126
+ fs.mkdirSync(failuresDir, { recursive: true });
127
+
128
+ let next = 0;
129
+ let passed = 0;
130
+ const failed = [];
131
+ async function worker() {
132
+ while (next < cases.length) {
133
+ const c = cases[next++];
134
+ const input = fs.readFileSync(c.file);
135
+ const [node, native] = await Promise.all([
136
+ exec(process.execPath, [path.join(here, 'main.ts'), ...c.mode.args], input),
137
+ exec(exePath, c.mode.args, input)
138
+ ]);
139
+ if (sameOutput(node, native)) passed++;
140
+ else {
141
+ failed.push(`${c.id} (${c.mode.name})`);
142
+ report({ id: c.id, mode: c.mode.name, input, node, native });
143
+ }
144
+ }
145
+ }
146
+ const workers = Math.max(2, Math.min(16, os.availableParallelism()));
147
+ await Promise.all(Array.from({ length: workers }, () => worker()));
148
+
149
+ const rate = cases.length ? ((100 * passed) / cases.length).toFixed(2) : '100.00';
150
+ console.log(`\n${passed}/${cases.length} cases match (${rate}%)`);
151
+ if (failed.length > 0) {
152
+ console.log(`${failed.length} failures (details in .cache/failures/):`);
153
+ for (const f of failed.slice(0, 40)) console.log(` ${f}`);
154
+ if (failed.length > 40) console.log(` … and ${failed.length - 40} more`);
155
+ process.exitCode = 1;
156
+ }
@@ -0,0 +1,13 @@
1
+ Copyright Eemeli Aro <eemeli@gmail.com>
2
+
3
+ Permission to use, copy, modify, and/or distribute this software for any purpose
4
+ with or without fee is hereby granted, provided that the above copyright notice
5
+ and this permission notice appear in all copies.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
9
+ FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
11
+ OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
12
+ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
13
+ THIS SOFTWARE.
@@ -0,0 +1,25 @@
1
+ # Vendored: `yaml`
2
+
3
+ | | |
4
+ | ---------- | ----------------------------------------------------------------------------------- |
5
+ | Upstream | [eemeli/yaml](https://github.com/eemeli/yaml) |
6
+ | Tag | `v3.0.0-2` |
7
+ | Commit | `15aa653fa2b94c4c9041a04964e83b9d794cf345` |
8
+ | License | ISC ([LICENSE](LICENSE)) |
9
+ | Copied | `src/` and `LICENSE`, byte for byte. Upstream's tests, docs and `bin.js` aren't vendored |
10
+
11
+ `bin.js` is ported to [../../main.ts](../../main.ts) instead of vendored. It's a
12
+ JavaScript file that imports the built package, and main.ts makes the same
13
+ `cli()` call from TypeScript.
14
+
15
+ ## Patches
16
+
17
+ None. `src/` is upstream's tree unmodified. To check:
18
+
19
+ ```sh
20
+ git clone --depth 1 --branch v3.0.0-2 https://github.com/eemeli/yaml.git /tmp/yaml
21
+ diff -r /tmp/yaml/src src && diff /tmp/yaml/LICENSE LICENSE
22
+ ```
23
+
24
+ Anything in this tree that TypeNative couldn't compile was fixed in the
25
+ transpiler, never here. Each fix has a probe in [conformance/](../../../../conformance/).
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 John Chadwick
4
+ Some portions Copyright (c) 2017 Serge Zaitsev
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1,21 @@
1
+ [![Go](https://github.com/jchv/go-webview2/actions/workflows/go.yml/badge.svg)](https://github.com/jchv/go-webview2/actions/workflows/go.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/jchv/go-webview2)](https://goreportcard.com/report/github.com/jchv/go-webview2) [![Go Reference](https://pkg.go.dev/badge/github.com/jchv/go-webview2.svg)](https://pkg.go.dev/github.com/jchv/go-webview2)
2
+
3
+ # go-webview2
4
+ This package provides an interface for using the Microsoft Edge WebView2 component with Go. It is based on [webview/webview](https://github.com/webview/webview) and provides a compatible API.
5
+
6
+ Please note that this package only supports Windows, since it provides functionality specific to WebView2. If you wish to use this library for Windows, but use webview/webview for all other operating systems, you could use the [go-webview-selector](https://github.com/jchv/go-webview-selector) package instead. However, you will not be able to use WebView2-specific functionality.
7
+
8
+ If you wish to build desktop applications in Go using web technologies, please consider [Wails](https://wails.io/). It uses go-webview2 internally on Windows.
9
+
10
+ ## Demo
11
+ If you are using Windows 10+, the WebView2 runtime should already be installed. If you don't have it installed, you can download and install a copy from Microsoft's website:
12
+
13
+ [WebView2 runtime](https://developer.microsoft.com/en-us/microsoft-edge/webview2/)
14
+
15
+ After that, you should be able to run go-webview2 directly:
16
+
17
+ ```
18
+ go run ./cmd/demo
19
+ ```
20
+
21
+ This will use go-winloader to load an embedded copy of WebView2Loader.dll. If you want, you can also provide a newer version of WebView2Loader.dll in the DLL search path and it should be picked up instead. It can be acquired from the WebView2 SDK (which is permissively licensed.)
@@ -0,0 +1,84 @@
1
+ package webview2
2
+
3
+ import "unsafe"
4
+
5
+ // This is copied from webview/webview.
6
+ // The documentation is included for convenience.
7
+
8
+ // Hint is used to configure window sizing and resizing behavior.
9
+ type Hint int
10
+
11
+ const (
12
+ // HintNone specifies that width and height are default size
13
+ HintNone Hint = iota
14
+
15
+ // HintFixed specifies that window size can not be changed by a user
16
+ HintFixed
17
+
18
+ // HintMin specifies that width and height are minimum bounds
19
+ HintMin
20
+
21
+ // HintMax specifies that width and height are maximum bounds
22
+ HintMax
23
+ )
24
+
25
+ // WebView is the interface for the webview.
26
+ type WebView interface {
27
+
28
+ // Run runs the main loop until it's terminated. After this function exits -
29
+ // you must destroy the webview.
30
+ Run()
31
+
32
+ // Terminate stops the main loop. It is safe to call this function from
33
+ // a background thread.
34
+ Terminate()
35
+
36
+ // Dispatch posts a function to be executed on the main thread. You normally
37
+ // do not need to call this function, unless you want to tweak the native
38
+ // window.
39
+ Dispatch(f func())
40
+
41
+ // Destroy destroys a webview and closes the native window.
42
+ Destroy()
43
+
44
+ // Window returns a native window handle pointer. When using GTK backend the
45
+ // pointer is GtkWindow pointer, when using Cocoa backend the pointer is
46
+ // NSWindow pointer, when using Win32 backend the pointer is HWND pointer.
47
+ Window() unsafe.Pointer
48
+
49
+ // SetTitle updates the title of the native window. Must be called from the UI
50
+ // thread.
51
+ SetTitle(title string)
52
+
53
+ // SetSize updates native window size. See Hint constants.
54
+ SetSize(w int, h int, hint Hint)
55
+
56
+ // Navigate navigates webview to the given URL. URL may be a data URI, i.e.
57
+ // "data:text/text,<html>...</html>". It is often ok not to url-encode it
58
+ // properly, webview will re-encode it for you.
59
+ Navigate(url string)
60
+
61
+ // SetHtml sets the webview HTML directly.
62
+ // The origin of the page is `about:blank`.
63
+ SetHtml(html string)
64
+
65
+ // Init injects JavaScript code at the initialization of the new page. Every
66
+ // time the webview will open a the new page - this initialization code will
67
+ // be executed. It is guaranteed that code is executed before window.onload.
68
+ Init(js string)
69
+
70
+ // Eval evaluates arbitrary JavaScript code. Evaluation happens asynchronously,
71
+ // also the result of the expression is ignored. Use RPC bindings if you want
72
+ // to receive notifications about the results of the evaluation.
73
+ Eval(js string)
74
+
75
+ // Bind binds a callback function so that it will appear under the given name
76
+ // as a global JavaScript function. Internally it uses webview_init().
77
+ // Callback receives a request string and a user-provided argument pointer.
78
+ // Request string is a JSON array of all the arguments passed to the
79
+ // JavaScript function.
80
+ //
81
+ // f must be a function
82
+ // f must return either value and error or just error
83
+ Bind(name string, f interface{}) error
84
+ }
@@ -0,0 +1,3 @@
1
+ module github.com/jchv/go-webview2
2
+
3
+ go 1.16