typenative 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/.github/workflows/ci.yml +2 -0
  2. package/CHANGELOG.md +201 -0
  3. package/CONTRIBUTION.md +1 -1
  4. package/bin/cli.js +1 -0
  5. package/bin/go/bridge.js +74 -14
  6. package/bin/go/convert.js +48 -0
  7. package/bin/go/metadata.js +13 -4
  8. package/bin/go/overrides.js +4 -6
  9. package/bin/go/stdlib.generated.js +2 -0
  10. package/bin/index.js +117 -0
  11. package/bin/main.js +1 -0
  12. package/bin/node/child_process.js +51 -3
  13. package/bin/node/cluster.js +41 -3
  14. package/bin/node/core.js +1 -1
  15. package/bin/node/crypto.js +205 -4
  16. package/bin/node/dgram.js +230 -6
  17. package/bin/node/dns.js +470 -7
  18. package/bin/node/errno_tables.js +445 -0
  19. package/bin/node/fs.js +21 -14
  20. package/bin/node/http.js +128 -30
  21. package/bin/node/http2.js +4 -1
  22. package/bin/node/module_v8.js +142 -0
  23. package/bin/node/net.js +9 -6
  24. package/bin/node/process.js +242 -0
  25. package/bin/node/readline.js +271 -0
  26. package/bin/node/registry.js +2 -1
  27. package/bin/node/sqlite.js +60 -12
  28. package/bin/node/stream.js +139 -7
  29. package/bin/node/test.js +311 -19
  30. package/bin/node/url.js +23 -5
  31. package/bin/node/util.js +18 -1
  32. package/bin/node/util_extra.js +6 -30
  33. package/bin/node/worker_threads.js +79 -19
  34. package/bin/transpiler.js +4019 -497
  35. package/bin/typecheck-node.js +1 -0
  36. package/bin/version.js +1 -1
  37. package/conformance.md +1025 -884
  38. package/examples/README.md +5 -5
  39. package/examples/json-server/README.md +31 -29
  40. package/examples/json-server/bench.mjs +130 -38
  41. package/package.json +1 -1
  42. package/types/typenative-go.d.ts +23 -0
  43. package/types/typenative-npm.d.ts +169 -5
  44. package/types/typenative.d.ts +185 -11
@@ -39,6 +39,8 @@ jobs:
39
39
  # The self-hosted compiler: same probes, and it must reproduce its own Go
40
40
  native:
41
41
  runs-on: ubuntu-latest
42
+ # Normally ~5–8 min (the self-compile is ~2); fail fast if a probe runs away
43
+ timeout-minutes: 25
42
44
  steps:
43
45
  - uses: actions/checkout@v4
44
46
 
package/CHANGELOG.md CHANGED
@@ -7,6 +7,207 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.4.1] - 2026-10-24
11
+
12
+ Node-accurate JSON (`stringify` with spacing and replacers, `parse` with a reviver, and JSON
13
+ modules), regexes with JS semantics that no longer re-scan the whole string on global matches,
14
+ `Date` and error-stack parity, generator iterator helpers, `go:embed` and
15
+ `go:runtime/coverage`, seven more Go bridge packages, and `async` calls that start when the
16
+ statement runs.
17
+
18
+ ### Added
19
+
20
+ - **`JSON.stringify`:**
21
+ - `space` (number or string) with Node's layout
22
+ - replacer functions and key lists
23
+ - `toJSON()` methods
24
+ - Dates as ISO strings, `Map` / `Set` as `{}`
25
+ - `TypeError`s for circular structures and bigints
26
+ - **`JSON.parse`:** reviver, and a `SyntaxError` for invalid JSON (it returned `null`)
27
+ - **Arrays:** writing past the end grows the array
28
+ - **Classes:** polymorphic `this` return types (fluent builders), and `obj[key]` on class
29
+ instances and typed objects
30
+ - **Generators:** iterator helpers (`map`, `filter`, `take`, `drop`, `flatMap`, `toArray`,
31
+ `forEach`, `some`, `every`, `find`, `reduce`), `Iterator.from` and `next()`
32
+ - **Weak references:** `WeakRef` / `FinalizationRegistry`
33
+ - **`Date`:**
34
+ - `new Date(string)` (ISO and the formats `toString` / `toUTCString` produce), and
35
+ `new Date(y, m, d, …)` in local time
36
+ - `Date.parse`, the setters (`setHours`, `setUTCDate`, …), `getTimezoneOffset`
37
+ - `toUTCString`, `toLocale*String` (en-US)
38
+ - Node's `toString` format for `String(date)` and templates
39
+ - Invalid Dates (`getTime()` is `NaN`)
40
+ - **Errors:** `err.stack` lists the TS frames (`at fn (file.ts:line)`); `AggregateError`
41
+ - **Functions:** `fn.bind`, `fn.name`, `fn.length`; `apply` on non-variadic functions, and
42
+ `call` / `apply` on function declarations
43
+ - **Statics:** `Promise.withResolvers`, `Promise.try`, `Object.is`, `Object.groupBy`,
44
+ `Map.groupBy`, `Array.of`, `Symbol.for` / `keyFor` / `description`, `BigInt()`,
45
+ `BigInt.asIntN` / `asUintN`
46
+ - **`Number`:** `toExponential`, `isSafeInteger`, `parseInt` / `parseFloat`, `MIN_VALUE`,
47
+ `NEGATIVE_INFINITY`
48
+ - **`Math`:** `fround`, `imul`, `clz32`, `asinh` / `acosh` / `atanh`, `sumPrecise`
49
+ - **`String`:** `codePointAt`, `String.fromCodePoint`, `substr`, `trimLeft` / `trimRight`,
50
+ `isWellFormed` / `toWellFormed`, `toLocaleUpperCase` / `toLocaleLowerCase`, `split` limit,
51
+ `lastIndexOf` position
52
+ - **`process`:** `stdout.columns` / `rows` / `getWindowSize()` (and `stderr`),
53
+ `stdin.setRawMode` / `isRaw` (undone at exit), `umask`, on Linux, macOS, FreeBSD and Windows
54
+ - **`node:readline`:** `emitKeypressEvents` and `'keypress'` events (Node's key decoder)
55
+ - **`node:child_process`:** `spawn` `detached`, `child.unref()` / `ref()`
56
+ - **`node:dgram`:** multicast (`addMembership` / `dropMembership`, `setMulticastInterface`), and
57
+ `setBroadcast` / `setTTL` / `setMulticastTTL` / `setMulticastLoopback` take effect (they were
58
+ accepted and ignored)
59
+ - **Errors:** `err.errno` and `util.getSystemErrorName` / `Message` / `Map` use Node's numbers for
60
+ the target OS (libuv's table: `ENOENT` is `-4058` on Windows, `ECONNREFUSED` `-61` on macOS) and
61
+ libuv's messages; `getSystemErrorMap` has all 85 entries in Node's order
62
+ - **`node:dns`:** `resolveAny` / `resolveCaa` / `resolveNaptr` / `resolvePtr` / `resolveSoa`,
63
+ `resolve4` / `resolve6` with `{ ttl: true }`, and the `Resolver` `tries` option
64
+ - **`node:module`** (`builtinModules`, `isBuiltin`), **`node:v8`** (`getHeapStatistics`,
65
+ `serialize` / `deserialize`) and **`node:sea`** (`isSea`)
66
+ - **`node:crypto`:** `Hash` / `Hmac` as streams; AES key wrap ciphers (`id-aes*-wrap`,
67
+ `id-aes*-wrap-pad`)
68
+ - **`node:http`:** `res.addTrailers()`
69
+ - **JSON modules:** `import data from './x.json' with { type: 'json' }` and
70
+ `createRequire(import.meta.url)('./x.json')`, read at compile time
71
+ - **Workers and `fork` for another file:** `new Worker('./worker.ts')` / `fork('./child.ts')` compile
72
+ that file into the binary as a second entry point, run in the child process
73
+ - **`node:test`:** `--test-name-pattern`, `--test-skip-pattern`, `--test-only` and
74
+ `--test-reporter` (`tap`, `spec`, `dot`, `junit`) from `NODE_OPTIONS`; Node's notice for `.only`
75
+ without `--test-only`
76
+ - **`node:stream`:** `'readable'` events and Node's `read()` / `read(size)`
77
+ - **`node:sqlite`:** statements are finalized once garbage-collected (they lived until
78
+ `db.close()`); `db.serialize()` / `db.deserialize()`
79
+ - **Go bridges:** a probe for every bridged `go:` package, new ones for `debug/*`, `log/syslog`,
80
+ `math/cmplx`, `net/http/fcgi`, `net/rpc`, `net/rpc/jsonrpc`, `net/smtp`, `testing/cryptotest`,
81
+ `testing/slogtest` and `testing/synctest`. Along with them:
82
+ - `pkg.T` in type annotations is the Go type (`let d: dwarf.Data | null = null`,
83
+ `(t: testing.T) => …`)
84
+ - `ref.value` can be written (`r.value = x`), also through `GoRef<T>` parameters, so TS classes
85
+ can be `net/rpc` services
86
+ - `chan<T>()` makes a `chan T`
87
+ - TS records pass where Go takes a `map[K]V`
88
+ - callbacks whose Go signature returns `(T, error)`
89
+ - **`go:embed`:** `embed.string(path)`, `embed.bytes(path)` and `embed.files(...patterns)` (an
90
+ `embed.FS`) compile to `//go:embed` vars; the CLI copies the files next to the Go sources
91
+ - **`go:runtime/coverage`**, with a `--cover` CLI option that builds with coverage counters. Probes
92
+ can pass CLI options with a first line like `// conformance-flags: --cover`
93
+
94
+ ### Fixed
95
+
96
+ - **Regex performance:** global `replace` / `split` / `matchAll` and backreference or
97
+ lookaround patterns no longer re-scan the whole string for every match (quadratic on long
98
+ input); the self-hosted compiler builds itself ~10× faster
99
+ - **Regex empty matches:** `/g` patterns can match empty at the end of input
100
+ (`'abc'.replace(/x*/g, '-')` is `-a-b-c-`)
101
+ - **Regex `split`:** follows JS: capture groups are included (`'a1b'.split(/(\d)/)` is `a`,
102
+ `1`, `b`), `limit` is honored, and empty matches split like JS
103
+ (`'aXbXXc'.split(/(?<=X)/)` is `aX`, `bX`, `X`, `c`)
104
+ - **Match `.index`:** `exec`, `match` and `matchAll` results have `.index` (a compile error
105
+ before); `search` returns a character index (it returned a byte offset)
106
+ - **`match` with `/g`:** returns every match (it returned the first match's groups)
107
+ - **Arrays as strings:** `arr.toString()`, `String(arr)` and `` `${arr}` `` join elements with
108
+ commas (they printed Go's `[a b]`)
109
+ - **`node:dns`:** `resolve(name, 'PTR')` queries the name's PTR records (it did a reverse lookup)
110
+ - **Templates:** `${err}` on an `Error` builds and prints `Name: message` (`null` when null)
111
+ - **`Date` annotations:** `let d: Date`, `Date` parameters, return types, fields and `as Date`
112
+ compiled to an undefined Go type
113
+ - **Named imports of Node values:** `import { METHODS } from 'node:http'` keeps its array type
114
+ (`METHODS.includes(…)` compiled as a string method)
115
+ - **`console.log` / `inspect`:** Maps and Sets nested in objects print as `Map(n) {…}` /
116
+ `Set(n) {…}` (string-keyed Maps printed as plain objects)
117
+ - **Worker messages / `v8.deserialize`:** Sets arrive as Sets and both pass `instanceof`
118
+ - **`Array<T>` / `ReadonlyArray<T>` annotations** compiled to an undefined Go type
119
+ - **`stream.push(cond ? text : null)`:** a nullable string is a chunk or the end of the stream
120
+ (`null` through it never ended the stream)
121
+ - **`hmac.digest()` a second time** returns an empty result, as in Node (it threw)
122
+ - **Destructured callback parameters** (`([k, v]) => …`, `({ a }) => …`) in `map` / `filter` & co.
123
+ were unsupported syntax
124
+ - **`[...map]`, `map.entries()`** and **`{ ...record, k: v }`** (such as `{ ...process.env }`)
125
+ did not build
126
+ - **`+` on two dynamic values** concatenates when one is a string (`'a' + 1` gave `1`)
127
+ - **`Object.keys` / `values` / `entries` and `for...in`** on typed objects (interfaces, object
128
+ literals, class instances) did not build
129
+ - **`JSON.parse`:** objects keep the text's key order (they came out sorted)
130
+ - **Indexing a typed array held as `any`** (`record.list[1].id`) gave `undefined`
131
+ - **Worker / IPC messages and `v8.deserialize`:** objects keep their key order (they arrived
132
+ sorted), records arrive as plain objects rather than `Map`s, and both convert to typed
133
+ `Record` fields
134
+ - **Optional method calls as statements** (`port?.postMessage(x)`) on `void` methods, and
135
+ `process.send?.(…)` / `process.disconnect?.()`, did not build
136
+ - **Dates:** local getters on `new Date(ms)` used UTC
137
+ - **Async arrows:** async arrows kept as values return promises (`return` of a plain value didn't
138
+ build)
139
+ - **`.then` on async calls:** the call starts when the statement runs, like JS (it started inside
140
+ the background goroutine, where `exec()` registering its listeners off the event loop could
141
+ race it)
142
+ - **Maps:** `[...map.keys()]` / `[...map.values()]` build
143
+ - **Optional chains:** comparing an optional chain or an `any` value with `null` / `undefined`
144
+ sees a nil pointer inside it
145
+ - **`length` fields:** `obj.length` on an object with its own `length` field read it (it compiled
146
+ to Go's `len()`)
147
+ - **Error casts:** `(err as Error)` works on instances of custom error classes
148
+ - **`any` variables:**
149
+ - a variable declared `any` / `unknown` with a primitive initializer is dynamic:
150
+ `const s: any = '6'; s - 1` builds, and reassigning another type works
151
+ - `==` between `any` values coerces like JS
152
+ - `<T>x` converts like `x as T`
153
+ - **Class members:**
154
+ - `#x` and `x` in one class no longer collide
155
+ - private fields and static properties stay out of `JSON.stringify`
156
+
157
+ Programs that built Go that didn't compile, or computed a wrong value, with no TypeNative error:
158
+
159
+ - **Classes:**
160
+ - methods without a return-type annotation compiled as returning nothing; they now infer it
161
+ like functions do, including returns nested in `if` / loops / `switch` / `try`
162
+ - field initializers ran before `super()` and the parameter properties, so
163
+ `d = this.k * 2` read `0`
164
+ - static members and getters / setters are inherited (`Child.make()`, `super.v`)
165
+ - private accessors (`get #x()`), `static #x` and `#x in obj` work
166
+ - async methods are lowered like async functions
167
+ - `instanceof Map` / `Set` / `Date` / `Array` work, and `instanceof Parent` is true for
168
+ subclass instances
169
+ - **Control flow:**
170
+ - a `switch` that covers every case without `default` builds; so does any statement after a
171
+ `switch`
172
+ - labeled blocks support `break label`
173
+ - **Async:** `return otherPromise()` in an async function settles with the awaited value, and
174
+ unannotated async functions build
175
+ - **Values and operators:**
176
+ - numeric enum reverse mapping (`Color[0]`)
177
+ - string enum members concatenate and print as strings (`console.log` printed `'a'`)
178
+ - bigint bitwise and shift operators
179
+ - Date arithmetic and ordering (`b - a`, `+d`, `a < b`)
180
+ - `any` operands of `-` / `*` / `/` convert like JS (`'6' - 1` is `5`)
181
+ - **Objects:**
182
+ - object-literal setters (they were dropped)
183
+ - repeated interfaces / enums, and an interface named like a class, merge
184
+ - `Object.hasOwn` / `defineProperty` with a computed key build instead of crashing the
185
+ compiler
186
+ - unsupported decorators and descriptors are reported as diagnostics instead of crashes
187
+ - **Go bridges:** a blocking call (`time.Sleep`) inside a callback failed to build, a panic in
188
+ one was swallowed, and `time.Sleep` hung inside a `synctest` bubble
189
+ - **`for (;;)`** without an initializer or update crashed the compiler
190
+
191
+ ### Documentation
192
+
193
+ - `conformance.md` separates ❌ (not implemented yet, feasible) from 🚫 (will not be implemented)
194
+ and explains why for each row. Several rows that were ❌ for "impossible" reasons are now
195
+ marked feasible: terminal size and raw mode, `umask`, `getCallSites`, workers and `fork` for
196
+ another file, and freeing SQLite statements on GC
197
+ - Rows for gaps the matrix didn't list, each checked by compiling a small program. Among them:
198
+ - Date parsing, setters and arithmetic
199
+ - `JSON.stringify` `space` / replacer / `toJSON`
200
+ - `err.stack`, `bind`, `Intl`, `Temporal`, `WeakRef`
201
+ - class methods without a return-type annotation
202
+ - field initializers that run too early
203
+ - `instanceof Map` / `Date`
204
+ - static and accessor inheritance
205
+ - A "Roadmap: known limitations" section, which the link in CONTRIBUTION.md pointed to
206
+ - The Go bridges table has no ⚠️ ("typed, no probe yet") status any more. A probe that can't run on
207
+ a platform opts out with a first line like `// conformance-skip: win32 (reason)`
208
+ - `go:plugin`, `go:unsafe`, `go:runtime/race` and `go:runtime/cgo` are 🚫 (cgo or raw memory),
209
+ each with the reason
210
+
10
211
  ## [0.4.0] - 2026-10-19
11
212
 
12
213
  A fuller CLI (`--target` cross-compilation, `--release`, `--emit-go`), typed arrays, Brotli and
package/CONTRIBUTION.md CHANGED
@@ -114,7 +114,7 @@ npm run bootstrap:check # native/typenative must emit the same Go for sr
114
114
  node scripts/conformance-parallel.mjs --native # full suite through your new binary
115
115
  ```
116
116
 
117
- CI ([`.github/workflows/ci.yml`](.github/workflows/ci.yml)) runs `npm run build`, `npm run check:go-types` and `npm run conformance:parallel` on Ubuntu, Windows and macOS (Node 24 + Go 1.26), plus a Linux job that builds the native compiler, runs `npm run bootstrap:check` and the suite through it. Probes that depend on the OS should hold on all three (branch on `process.platform` where Node itself differs).
117
+ CI ([`.github/workflows/ci.yml`](.github/workflows/ci.yml)) runs `npm run build`, `npm run check:go-types` and `npm run conformance:parallel` on Ubuntu, Windows and macOS (Node 24 + Go 1.26), plus a Linux job that builds the native compiler, runs `npm run bootstrap:check` and the suite through it. Probes that depend on the OS should hold on all three (branch on `process.platform` where Node itself differs). A probe that can't build on one of them (`go:log/syslog` has no Windows build) starts with `// conformance-skip: win32 (reason)`; the runners skip it there and list it.
118
118
 
119
119
  ## Pull requests
120
120
 
package/bin/cli.js CHANGED
@@ -77,6 +77,7 @@ import { VERSION } from './version.js';
77
77
  vendorDir: fileURLToPath(new URL('../govendor', import.meta.url)),
78
78
  target: args.target,
79
79
  release: args.release,
80
+ cover: args.cover,
80
81
  emitGo: args.emitGo
81
82
  });
82
83
  })();
package/bin/go/bridge.js CHANGED
@@ -6,7 +6,7 @@
6
6
  //
7
7
  // Kept in a plain style because this file is part of the self-hosted
8
8
  // compiler and must transpile with TypeNative.
9
- import { goPackage, goTypeInfo, allGoPaths } from './metadata.js';
9
+ import { goPackage, goTypeInfo, allGoPaths, bindQualifierPath } from './metadata.js';
10
10
  import { toGo, fromGo, mustCall, checkCall, isGoNumericKind } from './convert.js';
11
11
  import { isSyncCallback, isBlockingCall, goPathAliases } from './overrides.js';
12
12
  let services = {
@@ -26,6 +26,14 @@ let services = {
26
26
  };
27
27
  export function bindBridgeServices(s) {
28
28
  services = s;
29
+ bindQualifierPath(pathOfQualifier);
30
+ }
31
+ function pathOfQualifier(qualifier) {
32
+ for (const path of Object.keys(pathToLocal)) {
33
+ if (pathToLocal[path] === qualifier)
34
+ return path;
35
+ }
36
+ return '';
29
37
  }
30
38
  // Local import name → Go package path ('strings' → 'strings').
31
39
  const localToPath = {};
@@ -182,6 +190,10 @@ function goBuiltinName(callee) {
182
190
  export function isGoRefCall(node) {
183
191
  return !!node && node.kind === 'CallExpression' && goBuiltinName(node.expression) === 'ref';
184
192
  }
193
+ function chanElementType(node) {
194
+ const typeArg = (node.typeArguments ?? [])[0];
195
+ return typeArg ? services.goTypeOf(typeArg) : 'interface{}';
196
+ }
185
197
  // go:builtin calls: ref<T>(init?) → new(T), chan<T>(size?) → make(chan T).
186
198
  function visitGoBuiltinCall(node) {
187
199
  const name = goBuiltinName(node.expression);
@@ -198,11 +210,12 @@ function visitGoBuiltinCall(node) {
198
210
  }
199
211
  if (name === 'chan') {
200
212
  const size = (node.arguments ?? [])[0];
201
- // Element type from the contextual annotation is unavailable here;
202
- // default to interface{} (callers annotate: const ch: GoChan<T> = ...).
213
+ // The element type comes from chan<T>(); without one it is interface{}
214
+ // (callers annotate: const ch: GoChan<T> = chan()).
215
+ const goType = chanElementType(node);
203
216
  if (size)
204
- return `make(chan interface{}, int(${services.visit(size)}))`;
205
- return 'make(chan interface{})';
217
+ return `make(chan ${goType}, int(${services.visit(size)}))`;
218
+ return `make(chan ${goType})`;
206
219
  }
207
220
  return undefined;
208
221
  }
@@ -529,7 +542,12 @@ function goCallResults(node) {
529
542
  // pumps pending loop tasks.
530
543
  function emitBlocking(call, results, asStatement = false) {
531
544
  services.helper('goBlocking');
532
- const wrapped = `tnGoBlocking(func() interface{} { return ${call} })`;
545
+ if (results.length === 0)
546
+ return `tnGoBlocking(func() interface{} { ${call}; return nil })`;
547
+ // The results come back through named returns: void and multi-value calls fit too
548
+ const names = results.map((_, i) => `__r${i}`);
549
+ const decl = results.map((r, i) => `${names[i]} ${goLocalType(r)}`).join(', ');
550
+ const wrapped = `func() (${decl}) { tnGoBlocking(func() interface{} { ${names.join(', ')} = ${call}; return nil }); return }()`;
533
551
  return emitResults(wrapped, results, asStatement);
534
552
  }
535
553
  function isFuncType(goType) {
@@ -568,21 +586,28 @@ function emitCallback(node, goType, path, funcName) {
568
586
  services.declareLocal(name, tsType);
569
587
  }
570
588
  void isSyncCallback(path, funcName);
571
- const result = sig.results.length === 1 ? sig.results[0] : '';
589
+ // (T, error): the TS closure returns T (a throw stays a panic)
590
+ const withError = sig.results.length === 2 && sig.results[1] === 'error';
591
+ const result = sig.results.length === 1 || withError ? sig.results[0] : '';
572
592
  if (result) {
573
593
  ensureGoTypePackages(result);
574
594
  node.tnGoCallbackResult = result;
575
595
  }
576
- const resultDecl = sig.results.length > 0 ? ' ' + sig.results.map((r) => goLocalType(r)).join(', ') : '';
596
+ const localResults = sig.results.map((r) => goLocalType(r));
597
+ const resultDecl = localResults.length === 0 ? '' : localResults.length === 1 ? ` ${localResults[0]}` : ` (${localResults.join(', ')})`;
577
598
  const head = `func(${params.join(', ')})${resultDecl}`;
578
599
  const pre = prelude.length > 0 ? prelude.join('; ') + '; ' : '';
600
+ let inner = '';
579
601
  if (node.body && node.body.kind === 'Block') {
580
- return `${head} { ${pre}${services.visit(node.body)} }`;
602
+ inner = services.visit(node.body);
581
603
  }
582
- const body = services.visit(node.body);
583
- if (!result)
584
- return `${head} { ${pre}${body} }`;
585
- return `${head} { ${pre}return ${toGo(body, services.typeOf(node.body) ?? '', result)} }`;
604
+ else {
605
+ const body = services.visit(node.body);
606
+ inner = result ? `return ${toGo(body, services.typeOf(node.body) ?? '', result)}` : body;
607
+ }
608
+ if (withError)
609
+ return `${head} { ${pre}return func() ${goLocalType(result)} { ${inner} }(), nil }`;
610
+ return `${head} { ${pre}${inner} }`;
586
611
  }
587
612
  // "name T" → "T" (metadata signatures keep parameter names).
588
613
  function stripParamName(param) {
@@ -662,7 +687,7 @@ export function inferGoType(node) {
662
687
  if (node && node.kind === 'CallExpression') {
663
688
  const builtinName = goBuiltinName(node.expression);
664
689
  if (builtinName === 'chan')
665
- return 'chan interface{}';
690
+ return `chan ${chanElementType(node)}`;
666
691
  if (builtinName === 'ref') {
667
692
  const typeArg = (node.typeArguments ?? [])[0];
668
693
  const goType = typeArg ? services.goTypeOf(typeArg) : 'interface{}';
@@ -903,6 +928,41 @@ export function visitGoNew(node, path, typeName) {
903
928
  const empty = `${qualifier}.${typeName}{}`;
904
929
  return hasPtrReceiver(type) ? `(&${empty})` : empty;
905
930
  }
931
+ // Go type of a TS annotation naming a bridged type (`dwarf.Data`, or a named
932
+ // import). A struct is a pointer when the package hands out *T, a value when
933
+ // it hands out T (time.Time), else whatever `new pkg.T()` builds.
934
+ export function goAnnotationType(path, typeName) {
935
+ const info = goPackage(path);
936
+ if (!info || !Object.hasOwn(info.types, typeName))
937
+ return undefined;
938
+ const type = info.types[typeName];
939
+ if (type.tparams.length > 0)
940
+ return undefined;
941
+ if (type.numeric)
942
+ return 'float64';
943
+ services.pkg(path);
944
+ ensureGoQualifier(path);
945
+ const local = `${goQualifier(path)}.${typeName}`;
946
+ if (type.kind !== 'struct')
947
+ return local;
948
+ const full = `${path}.${typeName}`;
949
+ const results = [];
950
+ for (const name of Object.keys(info.funcs)) {
951
+ for (const r of info.funcs[name].results)
952
+ results.push(r);
953
+ }
954
+ for (const name of Object.keys(info.types)) {
955
+ for (const m of info.types[name].methods) {
956
+ for (const r of m.results)
957
+ results.push(r);
958
+ }
959
+ }
960
+ if (results.includes(`*${full}`))
961
+ return `*${local}`;
962
+ if (results.includes(full))
963
+ return local;
964
+ return hasPtrReceiver(type) ? `*${local}` : local;
965
+ }
906
966
  function fieldGoTypeOf(type, field) {
907
967
  for (const f of type.fields) {
908
968
  if (f.name === field)
package/bin/go/convert.js CHANGED
@@ -140,6 +140,15 @@ export function toGo(expr, fromType, toType) {
140
140
  }
141
141
  return `func() ${convertServices.localType(toType)} { __v := ${expr}; return __v[:] }()`;
142
142
  }
143
+ // TS records / Maps (*TnMap[K, V]) into Go maps of the same key and value types
144
+ if (sameMapTypes(fromType, toType)) {
145
+ convertServices.helper('goMaps');
146
+ return `tnGoMap(${expr})`;
147
+ }
148
+ if (fromType.startsWith('[]') && toType.startsWith('[]') && sameMapTypes(fromType.slice(2), toType.slice(2))) {
149
+ convertServices.helper('goMaps');
150
+ return `tnGoMaps(${expr})`;
151
+ }
143
152
  // Slices of numbers: tnGoNums[T](x) / element conversion.
144
153
  // []byte ↔ []byte passes through (Uint8Array needs no conversion).
145
154
  if (toType.startsWith('[]') && fromType.startsWith('[]')) {
@@ -187,6 +196,45 @@ export function toGo(expr, fromType, toType) {
187
196
  }
188
197
  return expr;
189
198
  }
199
+ // Whether fromType is *TnMap[K, V] and toType is map[K]V (any = interface{}).
200
+ function sameMapTypes(fromType, toType) {
201
+ if (!fromType.startsWith('*TnMap[') || !fromType.endsWith(']') || !toType.startsWith('map['))
202
+ return false;
203
+ const tnArgs = splitTopLevelTypes(fromType.slice(7, -1));
204
+ let depth = 0;
205
+ let close = -1;
206
+ for (let i = 3; i < toType.length && close < 0; i++) {
207
+ if (toType[i] === '[')
208
+ depth++;
209
+ else if (toType[i] === ']') {
210
+ depth--;
211
+ if (depth === 0)
212
+ close = i;
213
+ }
214
+ }
215
+ if (tnArgs.length !== 2 || close < 0)
216
+ return false;
217
+ const norm = (t) => (t.trim() === 'any' ? 'interface{}' : t.trim());
218
+ return norm(tnArgs[0]) === norm(toType.slice(4, close)) && norm(tnArgs[1]) === norm(toType.slice(close + 1));
219
+ }
220
+ function splitTopLevelTypes(s) {
221
+ const out = [];
222
+ let depth = 0;
223
+ let start = 0;
224
+ for (let i = 0; i < s.length; i++) {
225
+ const ch = s[i];
226
+ if (ch === '[' || ch === '(' || ch === '{')
227
+ depth++;
228
+ else if (ch === ']' || ch === ')' || ch === '}')
229
+ depth--;
230
+ else if (ch === ',' && depth === 0) {
231
+ out.push(s.slice(start, i));
232
+ start = i + 1;
233
+ }
234
+ }
235
+ out.push(s.slice(start));
236
+ return out;
237
+ }
190
238
  // Convert a Go expression back to a TS-facing value.
191
239
  export function fromGo(expr, goType) {
192
240
  if (!goType)
@@ -72,11 +72,12 @@ function parseResults(s) {
72
72
  export function goPackage(path) {
73
73
  if (path in packageCache)
74
74
  return packageCache[path];
75
- const raw = goStdlib[path];
76
- if (raw === undefined) {
75
+ // `in`, not `=== undefined`: natively a missing key reads as ''
76
+ if (!(path in goStdlib)) {
77
77
  packageCache[path] = null;
78
78
  return null;
79
79
  }
80
+ const raw = goStdlib[path];
80
81
  const info = { path, name: path, funcs: {}, types: {}, consts: {}, vars: {} };
81
82
  for (const line of raw.split('\n')) {
82
83
  if (!line)
@@ -161,12 +162,18 @@ export function goPackage(path) {
161
162
  }
162
163
  // Whether a package path has bridge metadata.
163
164
  export function hasGoPackage(path) {
164
- return goStdlib[path] !== undefined;
165
+ return path in goStdlib;
165
166
  }
166
167
  // All known package paths (for resolving cross-package type references).
167
168
  export function allGoPaths() {
168
169
  return Object.keys(goStdlib);
169
170
  }
171
+ // Package path of an emitted qualifier ('dwarf' → 'debug/dwarf'), bound by
172
+ // the bridge: annotated types (`let d: dwarf.Data`) carry the local form.
173
+ let qualifierPath = (_qualifier) => '';
174
+ export function bindQualifierPath(fn) {
175
+ qualifierPath = fn;
176
+ }
170
177
  // Resolve a qualified Go type to its type info.
171
178
  export function goTypeInfo(goType) {
172
179
  let base = goType;
@@ -175,11 +182,13 @@ export function goTypeInfo(goType) {
175
182
  const dot = base.lastIndexOf('.');
176
183
  if (dot < 0)
177
184
  return null;
178
- const path = base.slice(0, dot);
185
+ let path = base.slice(0, dot);
179
186
  let name = base.slice(dot + 1);
180
187
  const bracket = name.indexOf('[');
181
188
  if (bracket >= 0)
182
189
  name = name.slice(0, bracket);
190
+ if (!hasGoPackage(path) && qualifierPath(path) !== '')
191
+ path = qualifierPath(path);
183
192
  const info = goPackage(path);
184
193
  if (!info)
185
194
  return null;
@@ -49,12 +49,10 @@ export const goPathAliases = {
49
49
  'github.com/ncruces/go-sqlite3': 'sqlite3'
50
50
  };
51
51
  export const goExcluded = {
52
- plugin: 'cgo, `-buildmode=plugin`',
53
- unsafe: 'raw pointers',
54
- 'runtime/race': 'needs `-race`',
55
- 'runtime/coverage': 'needs `-cover`',
56
- 'runtime/cgo': 'needs cgo',
57
- embed: 'needs a `//go:embed` directive; a later phase'
52
+ plugin: 'Loads plugins with `dlopen`: needs cgo and `-buildmode=plugin` (no Windows support)',
53
+ unsafe: 'Raw pointer arithmetic and memory reinterpretation; TS values have no addresses',
54
+ 'runtime/race': 'No public API: the race detector is a build mode (`-race`) that needs cgo',
55
+ 'runtime/cgo': 'Links only with cgo and a C toolchain; `Handle` exists to pass Go values to C'
58
56
  };
59
57
  // Whether a call taking a callback invokes it synchronously.
60
58
  export function isSyncCallback(pkgPath, funcName) {