typenative 0.3.1 → 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.
- package/.github/workflows/ci.yml +2 -0
- package/CHANGELOG.md +258 -0
- package/CONTRIBUTION.md +1 -1
- package/README.md +17 -1
- package/bin/cli.js +26 -11
- package/bin/go/bridge.js +74 -14
- package/bin/go/convert.js +59 -1
- package/bin/go/metadata.js +13 -4
- package/bin/go/overrides.js +4 -6
- package/bin/go/stdlib.generated.js +2 -0
- package/bin/index.js +338 -47
- package/bin/main.js +36 -14
- package/bin/node/assert.js +2 -2
- package/bin/node/buffer.js +9 -0
- package/bin/node/child_process.js +51 -3
- package/bin/node/cluster.js +41 -3
- package/bin/node/core.js +1 -1
- package/bin/node/crypto.js +205 -4
- package/bin/node/dgram.js +230 -6
- package/bin/node/dns.js +471 -8
- package/bin/node/errno_tables.js +445 -0
- package/bin/node/events.js +1 -1
- package/bin/node/fs.js +22 -15
- package/bin/node/fs_watch.js +407 -0
- package/bin/node/http.js +128 -30
- package/bin/node/http2.js +37 -7
- package/bin/node/module_v8.js +142 -0
- package/bin/node/net.js +9 -6
- package/bin/node/process.js +242 -0
- package/bin/node/readline.js +272 -1
- package/bin/node/registry.js +3 -1
- package/bin/node/sqlite.js +60 -12
- package/bin/node/stream.js +145 -10
- package/bin/node/test.js +311 -19
- package/bin/node/timers.js +1 -1
- package/bin/node/typed_arrays.js +608 -0
- package/bin/node/url.js +23 -5
- package/bin/node/util.js +21 -1
- package/bin/node/util_extra.js +6 -30
- package/bin/node/worker_threads.js +79 -19
- package/bin/node/zlib.js +131 -16
- package/bin/transpiler.js +4729 -616
- package/bin/typecheck-node.js +1 -0
- package/bin/version.js +1 -1
- package/conformance.md +1030 -877
- package/examples/README.md +54 -0
- package/examples/fibonacci/README.md +89 -0
- package/examples/fibonacci/bench.mjs +87 -0
- package/examples/fibonacci/main.ts +21 -0
- package/examples/hello-world/README.md +62 -0
- package/examples/hello-world/bench.mjs +66 -0
- package/examples/hello-world/main.ts +7 -0
- package/examples/json-server/README.md +127 -0
- package/examples/json-server/bench.mjs +263 -0
- package/examples/json-server/main.ts +67 -0
- package/govendor/github.com/andybalholm/brotli/LICENSE +19 -0
- package/govendor/github.com/andybalholm/brotli/README.md +19 -0
- package/govendor/github.com/andybalholm/brotli/backward_references.go +185 -0
- package/govendor/github.com/andybalholm/brotli/backward_references_hq.go +796 -0
- package/govendor/github.com/andybalholm/brotli/bit_cost.go +436 -0
- package/govendor/github.com/andybalholm/brotli/bit_reader.go +266 -0
- package/govendor/github.com/andybalholm/brotli/bitwriter.go +56 -0
- package/govendor/github.com/andybalholm/brotli/block_splitter.go +144 -0
- package/govendor/github.com/andybalholm/brotli/block_splitter_command.go +434 -0
- package/govendor/github.com/andybalholm/brotli/block_splitter_distance.go +433 -0
- package/govendor/github.com/andybalholm/brotli/block_splitter_literal.go +433 -0
- package/govendor/github.com/andybalholm/brotli/brotli_bit_stream.go +1435 -0
- package/govendor/github.com/andybalholm/brotli/cluster.go +30 -0
- package/govendor/github.com/andybalholm/brotli/cluster_command.go +164 -0
- package/govendor/github.com/andybalholm/brotli/cluster_distance.go +326 -0
- package/govendor/github.com/andybalholm/brotli/cluster_literal.go +326 -0
- package/govendor/github.com/andybalholm/brotli/command.go +254 -0
- package/govendor/github.com/andybalholm/brotli/compress_fragment.go +834 -0
- package/govendor/github.com/andybalholm/brotli/compress_fragment_two_pass.go +775 -0
- package/govendor/github.com/andybalholm/brotli/constants.go +77 -0
- package/govendor/github.com/andybalholm/brotli/context.go +2176 -0
- package/govendor/github.com/andybalholm/brotli/decode.go +2570 -0
- package/govendor/github.com/andybalholm/brotli/dictionary.go +122890 -0
- package/govendor/github.com/andybalholm/brotli/dictionary_hash.go +32779 -0
- package/govendor/github.com/andybalholm/brotli/encode.go +1220 -0
- package/govendor/github.com/andybalholm/brotli/encoder.go +177 -0
- package/govendor/github.com/andybalholm/brotli/encoder_dict.go +22 -0
- package/govendor/github.com/andybalholm/brotli/encoder_fast.go +201 -0
- package/govendor/github.com/andybalholm/brotli/entropy_encode.go +592 -0
- package/govendor/github.com/andybalholm/brotli/entropy_encode_static.go +4399 -0
- package/govendor/github.com/andybalholm/brotli/fast_log.go +290 -0
- package/govendor/github.com/andybalholm/brotli/find_match_length.go +45 -0
- package/govendor/github.com/andybalholm/brotli/go.mod +3 -0
- package/govendor/github.com/andybalholm/brotli/h10.go +287 -0
- package/govendor/github.com/andybalholm/brotli/h5.go +214 -0
- package/govendor/github.com/andybalholm/brotli/h6.go +216 -0
- package/govendor/github.com/andybalholm/brotli/hash.go +342 -0
- package/govendor/github.com/andybalholm/brotli/hash_composite.go +93 -0
- package/govendor/github.com/andybalholm/brotli/hash_forgetful_chain.go +252 -0
- package/govendor/github.com/andybalholm/brotli/hash_longest_match_quickly.go +214 -0
- package/govendor/github.com/andybalholm/brotli/hash_rolling.go +168 -0
- package/govendor/github.com/andybalholm/brotli/histogram.go +226 -0
- package/govendor/github.com/andybalholm/brotli/http.go +201 -0
- package/govendor/github.com/andybalholm/brotli/huffman.go +653 -0
- package/govendor/github.com/andybalholm/brotli/literal_cost.go +182 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/bargain1.go +212 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/bargain2.go +248 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/bargain3.go +278 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/emitter.go +34 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/m0.go +175 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/m4.go +339 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/matchfinder.go +103 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/pathfinder.go +328 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/textencoder.go +53 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/trio.go +327 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/zdfast.go +258 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/zfast.go +206 -0
- package/govendor/github.com/andybalholm/brotli/matchfinder/zm.go +302 -0
- package/govendor/github.com/andybalholm/brotli/memory.go +66 -0
- package/govendor/github.com/andybalholm/brotli/metablock.go +574 -0
- package/govendor/github.com/andybalholm/brotli/metablock_command.go +165 -0
- package/govendor/github.com/andybalholm/brotli/metablock_distance.go +165 -0
- package/govendor/github.com/andybalholm/brotli/metablock_literal.go +165 -0
- package/govendor/github.com/andybalholm/brotli/params.go +37 -0
- package/govendor/github.com/andybalholm/brotli/platform.go +103 -0
- package/govendor/github.com/andybalholm/brotli/prefix.go +30 -0
- package/govendor/github.com/andybalholm/brotli/prefix_dec.go +723 -0
- package/govendor/github.com/andybalholm/brotli/quality.go +196 -0
- package/govendor/github.com/andybalholm/brotli/reader.go +127 -0
- package/govendor/github.com/andybalholm/brotli/ringbuffer.go +134 -0
- package/govendor/github.com/andybalholm/brotli/state.go +313 -0
- package/govendor/github.com/andybalholm/brotli/static_dict.go +662 -0
- package/govendor/github.com/andybalholm/brotli/static_dict_lut.go +75094 -0
- package/govendor/github.com/andybalholm/brotli/symbol_list.go +22 -0
- package/govendor/github.com/andybalholm/brotli/transform.go +641 -0
- package/govendor/github.com/andybalholm/brotli/utf8_util.go +70 -0
- package/govendor/github.com/andybalholm/brotli/util.go +7 -0
- package/govendor/github.com/andybalholm/brotli/write_bits.go +52 -0
- package/govendor/github.com/andybalholm/brotli/writer.go +162 -0
- package/govendor/github.com/fsnotify/fsnotify/.mailmap +2 -0
- package/govendor/github.com/fsnotify/fsnotify/CHANGELOG.md +651 -0
- package/govendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md +147 -0
- package/govendor/github.com/fsnotify/fsnotify/LICENSE +25 -0
- package/govendor/github.com/fsnotify/fsnotify/README.md +214 -0
- package/govendor/github.com/fsnotify/fsnotify/backend_fen.go +469 -0
- package/govendor/github.com/fsnotify/fsnotify/backend_inotify.go +597 -0
- package/govendor/github.com/fsnotify/fsnotify/backend_kqueue.go +735 -0
- package/govendor/github.com/fsnotify/fsnotify/backend_other.go +22 -0
- package/govendor/github.com/fsnotify/fsnotify/backend_windows.go +702 -0
- package/govendor/github.com/fsnotify/fsnotify/fsnotify.go +526 -0
- package/govendor/github.com/fsnotify/fsnotify/go.mod +3 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/darwin.go +20 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go +15 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go +15 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go +20 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go +32 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_linux.go +56 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go +15 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go +16 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go +45 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/debug_windows.go +40 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/freebsd.go +20 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/internal.go +2 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/unix.go +20 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/unix2.go +25 -0
- package/govendor/github.com/fsnotify/fsnotify/internal/windows.go +40 -0
- package/govendor/github.com/fsnotify/fsnotify/shared.go +64 -0
- package/govendor/github.com/fsnotify/fsnotify/staticcheck.conf +3 -0
- package/govendor/github.com/fsnotify/fsnotify/system_bsd.go +7 -0
- package/govendor/github.com/fsnotify/fsnotify/system_darwin.go +8 -0
- package/govendor/manifest.txt +3 -1
- package/package.json +1 -1
- package/types/typenative-go.d.ts +23 -0
- package/types/typenative-npm.d.ts +241 -5
- package/types/typenative.d.ts +302 -12
package/.github/workflows/ci.yml
CHANGED
|
@@ -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,264 @@ 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
|
+
|
|
211
|
+
## [0.4.0] - 2026-10-19
|
|
212
|
+
|
|
213
|
+
A fuller CLI (`--target` cross-compilation, `--release`, `--emit-go`), typed arrays, Brotli and
|
|
214
|
+
`fs.watch`, and TS classes that satisfy Go interfaces such as `heap.Interface`. Three sample apps
|
|
215
|
+
now run as tests.
|
|
216
|
+
|
|
217
|
+
### Added
|
|
218
|
+
|
|
219
|
+
- **CLI**: `--help`, `--version`, `--target <os/arch>` (cross-compiles through `GOOS` /
|
|
220
|
+
`GOARCH`; `--script` refuses foreign targets), `--release` (`-trimpath -ldflags="-s -w"`),
|
|
221
|
+
`--emit-go <dir>` (writes the Go sources and `go.mod` and stops), the entry file as a bare
|
|
222
|
+
argument, and `--flag=value`. Unknown options exit with code `2`, and a missing or older Go
|
|
223
|
+
toolchain (below 1.26) is reported before anything is built
|
|
224
|
+
- **Typed arrays**: `Int8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`,
|
|
225
|
+
`Int32Array`, `Uint32Array`, `Float32Array`, `Float64Array` (indexing, `from` / `of`,
|
|
226
|
+
`fill` / `set` / `subarray` / `slice`, the callback methods, `sort`, `join`, iteration),
|
|
227
|
+
`ArrayBuffer` (`slice`, `isView`) and `DataView`. Views made on an `ArrayBuffer` share its
|
|
228
|
+
memory, and writes convert like JS; `new Uint8Array(arrayBuffer)` is a view too
|
|
229
|
+
- **Go interfaces**: a TS class passed where Go expects an interface (`heap.Interface`,
|
|
230
|
+
`sort.Interface`) gets an adapter with the exact Go method signatures, so `go:container/heap`
|
|
231
|
+
works and `sort.Sort` takes classes
|
|
232
|
+
- **Brotli** in `node:zlib`: `brotliCompressSync` / `brotliDecompressSync`, the callback and
|
|
233
|
+
promisified forms, `createBrotliCompress` / `createBrotliDecompress` and `constants.BROTLI_*`,
|
|
234
|
+
on the vendored `github.com/andybalholm/brotli` (byte-identical to Node's output)
|
|
235
|
+
- **`fs.watch`** (`recursive`, `persistent`, `signal`, `ref` / `unref`), `fs.watchFile` /
|
|
236
|
+
`unwatchFile` and `fs/promises` `watch`, on the vendored `github.com/fsnotify/fsnotify`
|
|
237
|
+
- `x instanceof Int32Array` / `URL` / any Node global class
|
|
238
|
+
- Three sample apps run as tests (`conformance/app-*.ts`): a `wc`-style CLI, a JSON API on
|
|
239
|
+
`node:http` + `node:sqlite`, and a stream pipeline with gzip / Brotli
|
|
240
|
+
|
|
241
|
+
### Changed
|
|
242
|
+
|
|
243
|
+
- Every build goes through `dist/go.mod` (`go build -C dist`), and generated Go files start
|
|
244
|
+
with Go's `// Code generated … DO NOT EDIT.` header
|
|
245
|
+
- Vendored Go modules are linked only into programs that import them (`npm run vendor:go`
|
|
246
|
+
now vendors sqlite, Brotli and fsnotify)
|
|
247
|
+
|
|
248
|
+
### Fixed
|
|
249
|
+
|
|
250
|
+
- A subclass without a constructor takes its parent's constructor arguments (it compiled to a
|
|
251
|
+
constructor with no parameters)
|
|
252
|
+
- `new C([1, 2])` passes array literals to constructors whose array parameter is a shared
|
|
253
|
+
reference
|
|
254
|
+
- `this.field` has the field's type inside class bodies, so `Map` / `Set` fields dispatch their
|
|
255
|
+
methods (`this.counts.set(k, v)` called a Go method `set` that doesn't exist)
|
|
256
|
+
- Tuple elements read with their declared types (`pair[0]` of a `[string, number]` is a
|
|
257
|
+
string), including in the callbacks of `sort` / `map` / … on tuple arrays
|
|
258
|
+
- `rows.map((r) => ({ … }))` and `reduce` accumulators take the contextual type (a function
|
|
259
|
+
returning `Note[]` builds `Note`s, not anonymous structs)
|
|
260
|
+
- Object literals with computed keys (`{ [constants.BROTLI_PARAM_QUALITY]: 4 }`) are objects keyed
|
|
261
|
+
by the computed value (they compiled to a struct field named `undefined`)
|
|
262
|
+
- `(x as T)` on a Go `any` result (`heap.Pop(h) as Task`) asserts the type, and so does
|
|
263
|
+
`this.items.push(x as T)`
|
|
264
|
+
- Timers fire in deadline order (then creation order) when several expire together, as in
|
|
265
|
+
Node; timer goroutines that woke at once on a busy loop or coarse OS clock could run out of
|
|
266
|
+
order
|
|
267
|
+
|
|
10
268
|
## [0.3.1] - 2026-10-18
|
|
11
269
|
|
|
12
270
|
### Fixed
|
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/README.md
CHANGED
|
@@ -123,6 +123,18 @@ Scaffolded `tsconfig.json` targets the TypeNative type surface:
|
|
|
123
123
|
| `--script` | run | Build to `dist/native(.exe)` and execute immediately with inherited stdio. Combine with `--source`, or omit `--source` to type code into the prompt. |
|
|
124
124
|
| `--new` | scaffold | Create a new project directory (`main.ts`, `package.json`, `tsconfig.json`, `README.md`, `.gitignore`). |
|
|
125
125
|
| `--no-typecheck` | build / script | Skip the type-check that runs before transpiling. |
|
|
126
|
+
| `--target <os/arch>` | build | Cross-compile for another platform (`linux/amd64`, `linux/arm64`, `darwin/arm64`, `windows/amd64`, … — `go tool dist list` shows every pair). `--script` only runs host builds. |
|
|
127
|
+
| `--release` | build / script | Smaller binary: strips symbols and file paths (`-trimpath -ldflags="-s -w"`). |
|
|
128
|
+
| `--emit-go <dir>` | build | Write the generated Go (`code.go`, `go.mod`, vendored modules) to `<dir>` instead of building; `go build -C <dir>` builds it. |
|
|
129
|
+
| `-h`, `--help` | | Print the options. |
|
|
130
|
+
| `-v`, `--version` | | Print the TypeNative version. |
|
|
131
|
+
|
|
132
|
+
The entry file can also be the last argument (`typenative main.ts --script`), and every option accepts `--flag=value`. Unknown options are an error (exit code `2`). Before building, the CLI checks that Go 1.26 or newer is on the `PATH`.
|
|
133
|
+
|
|
134
|
+
```sh
|
|
135
|
+
# A stripped Linux ARM64 binary, built on any OS
|
|
136
|
+
npx typenative --source main.ts --output bin/app-linux-arm64 --target linux/arm64 --release
|
|
137
|
+
```
|
|
126
138
|
|
|
127
139
|
Exit codes from `--script` are the exit code of your program. Before anything is built, the entry file and its imports are type-checked with the nearest `tsconfig.json` (or TypeNative's defaults: `lib: []` plus the `typenative` declarations); type errors print as `main.ts:4:7: error TS2322: …` and exit `1`. TypeScript TypeNative can't compile yet is an error too (`main.ts:2:1: error: Unsupported syntax: WithStatement`), not a guess. A non-zero `go build` prints `go build failed:` plus the compiler output and exits `1`.
|
|
128
140
|
|
|
@@ -235,6 +247,10 @@ c.inc();
|
|
|
235
247
|
console.log(`count=${c.count} seen=${seen.get('a')}`);
|
|
236
248
|
```
|
|
237
249
|
|
|
250
|
+
Complete, runnable projects — including Node-vs-TypeNative benchmarks for
|
|
251
|
+
each — live in [examples/](examples/): a hello world (startup), a recursive
|
|
252
|
+
fibonacci (CPU), and a JSON web server (`node:http` GET/POST).
|
|
253
|
+
|
|
238
254
|
## How it works
|
|
239
255
|
|
|
240
256
|
```text
|
|
@@ -244,7 +260,7 @@ main.ts --(type-check)--(parse)--> normalized JSON AST --(transpileToNative)-->
|
|
|
244
260
|
- **Type-check:** Node CLI builds a program with the `typescript` package (`src/typecheck-node.ts`); the self-hosted binary runs `tsparser --check`, the same check on typescript-go (`tsparser/check.go`).
|
|
245
261
|
- **Parse:** Node CLI uses the `typescript` npm package (`src/parse-node.ts`); the self-hosted binary spawns the Go `tsparser` tool (`src/parse-native.ts`). Both emit the same `{ kind: "Xxx", line, column, ... }` JSON shape so one transpiler consumes either.
|
|
246
262
|
- **Transpile:** `transpileToNative(code, { parse, readFile })` in `src/transpiler.ts` lowers the AST to Go, resolving relative and npm imports into additional Go files (`TranspileResult { main, files, diagnostics }`). Generated statements carry `/*line file.ts:line:col*/` directives; `diagnostics` lists source the transpiler can't compile.
|
|
247
|
-
- **Build:** `run()` in `src/index.ts` writes `dist/code.go` (+ one Go file per module)
|
|
263
|
+
- **Build:** `run()` in `src/index.ts` writes `dist/code.go` (+ one Go file per module) and `dist/go.mod`, cleans stale `dist/*.go`, shells out to `go build -C dist` (with `GOOS` / `GOARCH` for `--target`), then either executes it (`--script`, stdio inherited) or copies it to `--output`. Third-party Go modules a program needs (`node:sqlite`'s driver, zlib's Brotli codec and `fs.watch`'s fsnotify, shipped in `govendor/`; `golang.org/x/text`, copied from GOROOT) are copied under `dist/tnvendor` and wired in with `replace` directives in `dist/go.mod`, so builds stay offline.
|
|
248
264
|
|
|
249
265
|
## Testing and conformance
|
|
250
266
|
|
package/bin/cli.js
CHANGED
|
@@ -3,17 +3,28 @@
|
|
|
3
3
|
// the actual compiler logic lives in the transpilable src/index.ts.
|
|
4
4
|
import inquirer from 'inquirer';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
|
-
import { run, createProject } from './index.js';
|
|
6
|
+
import { run, createProject, parseCliArgs, usage } from './index.js';
|
|
7
7
|
import { parseAstJson } from './parse-node.js';
|
|
8
8
|
import { typeCheckNode } from './typecheck-node.js';
|
|
9
|
+
import { VERSION } from './version.js';
|
|
9
10
|
(async function main() {
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
11
|
+
const args = parseCliArgs(process.argv.slice(2));
|
|
12
|
+
if (args.error) {
|
|
13
|
+
console.error(`error: ${args.error}\nRun 'typenative --help' for the options.`);
|
|
14
|
+
process.exit(2);
|
|
15
|
+
}
|
|
16
|
+
if (args.help) {
|
|
17
|
+
console.log(usage());
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
if (args.version) {
|
|
21
|
+
console.log(VERSION);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
const scriptMode = args.script;
|
|
25
|
+
const newCommand = args.newProject;
|
|
26
|
+
const source = args.source;
|
|
27
|
+
const output = args.output;
|
|
17
28
|
const answers = await inquirer.prompt([
|
|
18
29
|
{
|
|
19
30
|
type: 'input',
|
|
@@ -39,7 +50,7 @@ import { typeCheckNode } from './typecheck-node.js';
|
|
|
39
50
|
type: 'input',
|
|
40
51
|
name: 'output',
|
|
41
52
|
message: 'Enter Output Path:',
|
|
42
|
-
when: !newCommand && !scriptMode && !output,
|
|
53
|
+
when: !newCommand && !scriptMode && !output && !args.emitGo,
|
|
43
54
|
validate: (input) => input.trim() !== ''
|
|
44
55
|
},
|
|
45
56
|
{
|
|
@@ -62,7 +73,11 @@ import { typeCheckNode } from './typecheck-node.js';
|
|
|
62
73
|
scriptMode,
|
|
63
74
|
tsCode: answers.tsCode ?? null,
|
|
64
75
|
parse: parseAstJson,
|
|
65
|
-
typeCheck: noTypeCheck ? null : (fileName) => typeCheckNode(fileName, typesDir),
|
|
66
|
-
vendorDir: fileURLToPath(new URL('../govendor', import.meta.url))
|
|
76
|
+
typeCheck: args.noTypeCheck ? null : (fileName) => typeCheckNode(fileName, typesDir),
|
|
77
|
+
vendorDir: fileURLToPath(new URL('../govendor', import.meta.url)),
|
|
78
|
+
target: args.target,
|
|
79
|
+
release: args.release,
|
|
80
|
+
cover: args.cover,
|
|
81
|
+
emitGo: args.emitGo
|
|
67
82
|
});
|
|
68
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
|
-
//
|
|
202
|
-
//
|
|
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
|
|
205
|
-
return
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
602
|
+
inner = services.visit(node.body);
|
|
581
603
|
}
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
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
|
|
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
|
@@ -12,7 +12,8 @@ let convertServices = {
|
|
|
12
12
|
pkg: (_name) => { },
|
|
13
13
|
helper: (_id) => { },
|
|
14
14
|
typeOf: (_node) => '',
|
|
15
|
-
localType: (goType) => goType
|
|
15
|
+
localType: (goType) => goType,
|
|
16
|
+
adapt: (_expr, _fromType, _toType, _iface) => ''
|
|
16
17
|
};
|
|
17
18
|
let convertKnownPaths = {};
|
|
18
19
|
export function initConvertPaths() {
|
|
@@ -91,6 +92,15 @@ export function toGo(expr, fromType, toType) {
|
|
|
91
92
|
return expr;
|
|
92
93
|
if (expr === 'nil')
|
|
93
94
|
return expr;
|
|
95
|
+
// A TS class implementing a Go interface (heap.Interface, sort.Interface)
|
|
96
|
+
if (fromType.startsWith('*')) {
|
|
97
|
+
const iface = goTypeInfo(toType);
|
|
98
|
+
if (iface !== null && iface.kind === 'interface' && iface.ifaceMethods.length > 0) {
|
|
99
|
+
const adapted = convertServices.adapt(expr, fromType, toType, iface);
|
|
100
|
+
if (adapted !== '')
|
|
101
|
+
return adapted;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
94
104
|
// Array references read as the slice they point to.
|
|
95
105
|
if (fromType.startsWith('*[]'))
|
|
96
106
|
fromType = fromType.slice(1);
|
|
@@ -130,6 +140,15 @@ export function toGo(expr, fromType, toType) {
|
|
|
130
140
|
}
|
|
131
141
|
return `func() ${convertServices.localType(toType)} { __v := ${expr}; return __v[:] }()`;
|
|
132
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
|
+
}
|
|
133
152
|
// Slices of numbers: tnGoNums[T](x) / element conversion.
|
|
134
153
|
// []byte ↔ []byte passes through (Uint8Array needs no conversion).
|
|
135
154
|
if (toType.startsWith('[]') && fromType.startsWith('[]')) {
|
|
@@ -177,6 +196,45 @@ export function toGo(expr, fromType, toType) {
|
|
|
177
196
|
}
|
|
178
197
|
return expr;
|
|
179
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
|
+
}
|
|
180
238
|
// Convert a Go expression back to a TS-facing value.
|
|
181
239
|
export function fromGo(expr, goType) {
|
|
182
240
|
if (!goType)
|