typenative 0.3.0 → 0.4.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 (148) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +17 -1
  3. package/bin/cli.js +25 -11
  4. package/bin/go/convert.js +11 -1
  5. package/bin/index.js +221 -44
  6. package/bin/main.js +35 -14
  7. package/bin/node/assert.js +2 -2
  8. package/bin/node/buffer.js +9 -0
  9. package/bin/node/dns.js +1 -1
  10. package/bin/node/events.js +1 -1
  11. package/bin/node/fs.js +1 -1
  12. package/bin/node/fs_watch.js +407 -0
  13. package/bin/node/http2.js +33 -6
  14. package/bin/node/readline.js +1 -1
  15. package/bin/node/registry.js +2 -1
  16. package/bin/node/stream.js +6 -3
  17. package/bin/node/timers.js +1 -1
  18. package/bin/node/tls.js +3 -1
  19. package/bin/node/typed_arrays.js +608 -0
  20. package/bin/node/util.js +3 -0
  21. package/bin/node/zlib.js +131 -16
  22. package/bin/transpiler.js +684 -62
  23. package/bin/version.js +1 -1
  24. package/conformance.md +16 -4
  25. package/examples/README.md +54 -0
  26. package/examples/fibonacci/README.md +89 -0
  27. package/examples/fibonacci/bench.mjs +87 -0
  28. package/examples/fibonacci/main.ts +21 -0
  29. package/examples/hello-world/README.md +62 -0
  30. package/examples/hello-world/bench.mjs +66 -0
  31. package/examples/hello-world/main.ts +7 -0
  32. package/examples/json-server/README.md +125 -0
  33. package/examples/json-server/bench.mjs +171 -0
  34. package/examples/json-server/main.ts +67 -0
  35. package/govendor/github.com/andybalholm/brotli/LICENSE +19 -0
  36. package/govendor/github.com/andybalholm/brotli/README.md +19 -0
  37. package/govendor/github.com/andybalholm/brotli/backward_references.go +185 -0
  38. package/govendor/github.com/andybalholm/brotli/backward_references_hq.go +796 -0
  39. package/govendor/github.com/andybalholm/brotli/bit_cost.go +436 -0
  40. package/govendor/github.com/andybalholm/brotli/bit_reader.go +266 -0
  41. package/govendor/github.com/andybalholm/brotli/bitwriter.go +56 -0
  42. package/govendor/github.com/andybalholm/brotli/block_splitter.go +144 -0
  43. package/govendor/github.com/andybalholm/brotli/block_splitter_command.go +434 -0
  44. package/govendor/github.com/andybalholm/brotli/block_splitter_distance.go +433 -0
  45. package/govendor/github.com/andybalholm/brotli/block_splitter_literal.go +433 -0
  46. package/govendor/github.com/andybalholm/brotli/brotli_bit_stream.go +1435 -0
  47. package/govendor/github.com/andybalholm/brotli/cluster.go +30 -0
  48. package/govendor/github.com/andybalholm/brotli/cluster_command.go +164 -0
  49. package/govendor/github.com/andybalholm/brotli/cluster_distance.go +326 -0
  50. package/govendor/github.com/andybalholm/brotli/cluster_literal.go +326 -0
  51. package/govendor/github.com/andybalholm/brotli/command.go +254 -0
  52. package/govendor/github.com/andybalholm/brotli/compress_fragment.go +834 -0
  53. package/govendor/github.com/andybalholm/brotli/compress_fragment_two_pass.go +775 -0
  54. package/govendor/github.com/andybalholm/brotli/constants.go +77 -0
  55. package/govendor/github.com/andybalholm/brotli/context.go +2176 -0
  56. package/govendor/github.com/andybalholm/brotli/decode.go +2570 -0
  57. package/govendor/github.com/andybalholm/brotli/dictionary.go +122890 -0
  58. package/govendor/github.com/andybalholm/brotli/dictionary_hash.go +32779 -0
  59. package/govendor/github.com/andybalholm/brotli/encode.go +1220 -0
  60. package/govendor/github.com/andybalholm/brotli/encoder.go +177 -0
  61. package/govendor/github.com/andybalholm/brotli/encoder_dict.go +22 -0
  62. package/govendor/github.com/andybalholm/brotli/encoder_fast.go +201 -0
  63. package/govendor/github.com/andybalholm/brotli/entropy_encode.go +592 -0
  64. package/govendor/github.com/andybalholm/brotli/entropy_encode_static.go +4399 -0
  65. package/govendor/github.com/andybalholm/brotli/fast_log.go +290 -0
  66. package/govendor/github.com/andybalholm/brotli/find_match_length.go +45 -0
  67. package/govendor/github.com/andybalholm/brotli/go.mod +3 -0
  68. package/govendor/github.com/andybalholm/brotli/h10.go +287 -0
  69. package/govendor/github.com/andybalholm/brotli/h5.go +214 -0
  70. package/govendor/github.com/andybalholm/brotli/h6.go +216 -0
  71. package/govendor/github.com/andybalholm/brotli/hash.go +342 -0
  72. package/govendor/github.com/andybalholm/brotli/hash_composite.go +93 -0
  73. package/govendor/github.com/andybalholm/brotli/hash_forgetful_chain.go +252 -0
  74. package/govendor/github.com/andybalholm/brotli/hash_longest_match_quickly.go +214 -0
  75. package/govendor/github.com/andybalholm/brotli/hash_rolling.go +168 -0
  76. package/govendor/github.com/andybalholm/brotli/histogram.go +226 -0
  77. package/govendor/github.com/andybalholm/brotli/http.go +201 -0
  78. package/govendor/github.com/andybalholm/brotli/huffman.go +653 -0
  79. package/govendor/github.com/andybalholm/brotli/literal_cost.go +182 -0
  80. package/govendor/github.com/andybalholm/brotli/matchfinder/bargain1.go +212 -0
  81. package/govendor/github.com/andybalholm/brotli/matchfinder/bargain2.go +248 -0
  82. package/govendor/github.com/andybalholm/brotli/matchfinder/bargain3.go +278 -0
  83. package/govendor/github.com/andybalholm/brotli/matchfinder/emitter.go +34 -0
  84. package/govendor/github.com/andybalholm/brotli/matchfinder/m0.go +175 -0
  85. package/govendor/github.com/andybalholm/brotli/matchfinder/m4.go +339 -0
  86. package/govendor/github.com/andybalholm/brotli/matchfinder/matchfinder.go +103 -0
  87. package/govendor/github.com/andybalholm/brotli/matchfinder/pathfinder.go +328 -0
  88. package/govendor/github.com/andybalholm/brotli/matchfinder/textencoder.go +53 -0
  89. package/govendor/github.com/andybalholm/brotli/matchfinder/trio.go +327 -0
  90. package/govendor/github.com/andybalholm/brotli/matchfinder/zdfast.go +258 -0
  91. package/govendor/github.com/andybalholm/brotli/matchfinder/zfast.go +206 -0
  92. package/govendor/github.com/andybalholm/brotli/matchfinder/zm.go +302 -0
  93. package/govendor/github.com/andybalholm/brotli/memory.go +66 -0
  94. package/govendor/github.com/andybalholm/brotli/metablock.go +574 -0
  95. package/govendor/github.com/andybalholm/brotli/metablock_command.go +165 -0
  96. package/govendor/github.com/andybalholm/brotli/metablock_distance.go +165 -0
  97. package/govendor/github.com/andybalholm/brotli/metablock_literal.go +165 -0
  98. package/govendor/github.com/andybalholm/brotli/params.go +37 -0
  99. package/govendor/github.com/andybalholm/brotli/platform.go +103 -0
  100. package/govendor/github.com/andybalholm/brotli/prefix.go +30 -0
  101. package/govendor/github.com/andybalholm/brotli/prefix_dec.go +723 -0
  102. package/govendor/github.com/andybalholm/brotli/quality.go +196 -0
  103. package/govendor/github.com/andybalholm/brotli/reader.go +127 -0
  104. package/govendor/github.com/andybalholm/brotli/ringbuffer.go +134 -0
  105. package/govendor/github.com/andybalholm/brotli/state.go +313 -0
  106. package/govendor/github.com/andybalholm/brotli/static_dict.go +662 -0
  107. package/govendor/github.com/andybalholm/brotli/static_dict_lut.go +75094 -0
  108. package/govendor/github.com/andybalholm/brotli/symbol_list.go +22 -0
  109. package/govendor/github.com/andybalholm/brotli/transform.go +641 -0
  110. package/govendor/github.com/andybalholm/brotli/utf8_util.go +70 -0
  111. package/govendor/github.com/andybalholm/brotli/util.go +7 -0
  112. package/govendor/github.com/andybalholm/brotli/write_bits.go +52 -0
  113. package/govendor/github.com/andybalholm/brotli/writer.go +162 -0
  114. package/govendor/github.com/fsnotify/fsnotify/.mailmap +2 -0
  115. package/govendor/github.com/fsnotify/fsnotify/CHANGELOG.md +651 -0
  116. package/govendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md +147 -0
  117. package/govendor/github.com/fsnotify/fsnotify/LICENSE +25 -0
  118. package/govendor/github.com/fsnotify/fsnotify/README.md +214 -0
  119. package/govendor/github.com/fsnotify/fsnotify/backend_fen.go +469 -0
  120. package/govendor/github.com/fsnotify/fsnotify/backend_inotify.go +597 -0
  121. package/govendor/github.com/fsnotify/fsnotify/backend_kqueue.go +735 -0
  122. package/govendor/github.com/fsnotify/fsnotify/backend_other.go +22 -0
  123. package/govendor/github.com/fsnotify/fsnotify/backend_windows.go +702 -0
  124. package/govendor/github.com/fsnotify/fsnotify/fsnotify.go +526 -0
  125. package/govendor/github.com/fsnotify/fsnotify/go.mod +3 -0
  126. package/govendor/github.com/fsnotify/fsnotify/internal/darwin.go +20 -0
  127. package/govendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go +15 -0
  128. package/govendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go +15 -0
  129. package/govendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go +20 -0
  130. package/govendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go +32 -0
  131. package/govendor/github.com/fsnotify/fsnotify/internal/debug_linux.go +56 -0
  132. package/govendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go +15 -0
  133. package/govendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go +16 -0
  134. package/govendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go +45 -0
  135. package/govendor/github.com/fsnotify/fsnotify/internal/debug_windows.go +40 -0
  136. package/govendor/github.com/fsnotify/fsnotify/internal/freebsd.go +20 -0
  137. package/govendor/github.com/fsnotify/fsnotify/internal/internal.go +2 -0
  138. package/govendor/github.com/fsnotify/fsnotify/internal/unix.go +20 -0
  139. package/govendor/github.com/fsnotify/fsnotify/internal/unix2.go +25 -0
  140. package/govendor/github.com/fsnotify/fsnotify/internal/windows.go +40 -0
  141. package/govendor/github.com/fsnotify/fsnotify/shared.go +64 -0
  142. package/govendor/github.com/fsnotify/fsnotify/staticcheck.conf +3 -0
  143. package/govendor/github.com/fsnotify/fsnotify/system_bsd.go +7 -0
  144. package/govendor/github.com/fsnotify/fsnotify/system_darwin.go +8 -0
  145. package/govendor/manifest.txt +3 -1
  146. package/package.json +1 -1
  147. package/types/typenative-npm.d.ts +72 -0
  148. package/types/typenative.d.ts +117 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,77 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.4.0] - 2026-10-19
11
+
12
+ A fuller CLI (`--target` cross-compilation, `--release`, `--emit-go`), typed arrays, Brotli and
13
+ `fs.watch`, and TS classes that satisfy Go interfaces such as `heap.Interface`. Three sample apps
14
+ now run as tests.
15
+
16
+ ### Added
17
+
18
+ - **CLI**: `--help`, `--version`, `--target <os/arch>` (cross-compiles through `GOOS` /
19
+ `GOARCH`; `--script` refuses foreign targets), `--release` (`-trimpath -ldflags="-s -w"`),
20
+ `--emit-go <dir>` (writes the Go sources and `go.mod` and stops), the entry file as a bare
21
+ argument, and `--flag=value`. Unknown options exit with code `2`, and a missing or older Go
22
+ toolchain (below 1.26) is reported before anything is built
23
+ - **Typed arrays**: `Int8Array`, `Uint8ClampedArray`, `Int16Array`, `Uint16Array`,
24
+ `Int32Array`, `Uint32Array`, `Float32Array`, `Float64Array` (indexing, `from` / `of`,
25
+ `fill` / `set` / `subarray` / `slice`, the callback methods, `sort`, `join`, iteration),
26
+ `ArrayBuffer` (`slice`, `isView`) and `DataView`. Views made on an `ArrayBuffer` share its
27
+ memory, and writes convert like JS; `new Uint8Array(arrayBuffer)` is a view too
28
+ - **Go interfaces**: a TS class passed where Go expects an interface (`heap.Interface`,
29
+ `sort.Interface`) gets an adapter with the exact Go method signatures, so `go:container/heap`
30
+ works and `sort.Sort` takes classes
31
+ - **Brotli** in `node:zlib`: `brotliCompressSync` / `brotliDecompressSync`, the callback and
32
+ promisified forms, `createBrotliCompress` / `createBrotliDecompress` and `constants.BROTLI_*`,
33
+ on the vendored `github.com/andybalholm/brotli` (byte-identical to Node's output)
34
+ - **`fs.watch`** (`recursive`, `persistent`, `signal`, `ref` / `unref`), `fs.watchFile` /
35
+ `unwatchFile` and `fs/promises` `watch`, on the vendored `github.com/fsnotify/fsnotify`
36
+ - `x instanceof Int32Array` / `URL` / any Node global class
37
+ - Three sample apps run as tests (`conformance/app-*.ts`): a `wc`-style CLI, a JSON API on
38
+ `node:http` + `node:sqlite`, and a stream pipeline with gzip / Brotli
39
+
40
+ ### Changed
41
+
42
+ - Every build goes through `dist/go.mod` (`go build -C dist`), and generated Go files start
43
+ with Go's `// Code generated … DO NOT EDIT.` header
44
+ - Vendored Go modules are linked only into programs that import them (`npm run vendor:go`
45
+ now vendors sqlite, Brotli and fsnotify)
46
+
47
+ ### Fixed
48
+
49
+ - A subclass without a constructor takes its parent's constructor arguments (it compiled to a
50
+ constructor with no parameters)
51
+ - `new C([1, 2])` passes array literals to constructors whose array parameter is a shared
52
+ reference
53
+ - `this.field` has the field's type inside class bodies, so `Map` / `Set` fields dispatch their
54
+ methods (`this.counts.set(k, v)` called a Go method `set` that doesn't exist)
55
+ - Tuple elements read with their declared types (`pair[0]` of a `[string, number]` is a
56
+ string), including in the callbacks of `sort` / `map` / … on tuple arrays
57
+ - `rows.map((r) => ({ … }))` and `reduce` accumulators take the contextual type (a function
58
+ returning `Note[]` builds `Note`s, not anonymous structs)
59
+ - Object literals with computed keys (`{ [constants.BROTLI_PARAM_QUALITY]: 4 }`) are objects keyed
60
+ by the computed value (they compiled to a struct field named `undefined`)
61
+ - `(x as T)` on a Go `any` result (`heap.Pop(h) as Task`) asserts the type, and so does
62
+ `this.items.push(x as T)`
63
+ - Timers fire in deadline order (then creation order) when several expire together, as in
64
+ Node; timer goroutines that woke at once on a busy loop or coarse OS clock could run out of
65
+ order
66
+
67
+ ## [0.3.1] - 2026-10-18
68
+
69
+ ### Fixed
70
+
71
+ - `node:tls` on macOS: an untrusted certificate chain reports Node's codes
72
+ (`DEPTH_ZERO_SELF_SIGNED_CERT`, `SELF_SIGNED_CERT_IN_CHAIN`,
73
+ `UNABLE_TO_GET_ISSUER_CERT_LOCALLY`) like on other platforms; the platform verifier returns
74
+ a plain error, not `UnknownAuthorityError`
75
+ - `go build` runs with `-trimpath`, so vendored packages (the ~5 MB sqlite driver) are cached
76
+ once instead of recompiled for every project directory, and builds are reproducible
77
+ - `conformance-parallel.mjs` builds one sqlite probe first so a cold cache doesn't time out
78
+ every sqlite probe at once on small runners; the `node:sqlite` `location()` probe compares
79
+ canonical paths (symlinks, Windows 8.3 short names)
80
+
10
81
  ## [0.3.0] - 2026-10-18
11
82
 
12
83
  Errors now point at your TypeScript. Programs are type-checked before they're transpiled, code
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), cleans stale `dist/*.go`, shells out to `go build -o dist/native(.exe)`, then either executes it (`--script`, stdio inherited) or copies it to `--output`. Third-party Go modules a program needs (`node:sqlite`'s driver, 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.
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 scriptMode = process.argv.findIndex((a) => a === '--script') > -1;
11
- const newCommand = process.argv.findIndex((a) => a === '--new') > -1;
12
- const noTypeCheck = process.argv.includes('--no-typecheck');
13
- const sourceIndex = process.argv.findIndex((a) => a === '--source');
14
- const source = sourceIndex > -1 ? process.argv[sourceIndex + 1] : null;
15
- const outputIndex = process.argv.findIndex((a) => a === '--output');
16
- const output = outputIndex > -1 ? process.argv[outputIndex + 1] : null;
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,10 @@ 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
+ emitGo: args.emitGo
67
81
  });
68
82
  })();
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);
package/bin/index.js CHANGED
@@ -9,8 +9,135 @@ import { platform } from 'node:os';
9
9
  // from Node's; under Node these functions are never called (the CLI wrapper does
10
10
  // not reach them), so they're accessed through `any` casts for type-checking.
11
11
  import * as childProcess from 'node:child_process';
12
- import { transpileToNative } from './transpiler.js';
12
+ import { transpileToNative, GENERATED_HEADER } from './transpiler.js';
13
13
  import { VERSION } from './version.js';
14
+ // The minimum Go toolchain generated code needs
15
+ const MIN_GO_MAJOR = 1;
16
+ const MIN_GO_MINOR = 26;
17
+ export function usage() {
18
+ return `Usage: typenative [options] [file.ts]
19
+
20
+ Compiles a TypeScript program to a native executable (through Go).
21
+
22
+ Options:
23
+ --source <file> The program's entry file (or pass it as the last argument)
24
+ --output <file> Where to write the executable
25
+ --script Build and run the program (prompts for code without --source)
26
+ --new Create a new TypeNative project
27
+ --target <os/arch> Cross-compile, e.g. linux/amd64, linux/arm64, darwin/arm64,
28
+ windows/amd64 ('go tool dist list' shows every pair)
29
+ --release Smaller binary: drop symbols and file paths
30
+ --emit-go <dir> Write the generated Go (and go.mod) to <dir> instead of building
31
+ --no-typecheck Skip type-checking
32
+ -h, --help Show this help
33
+ -v, --version Show the TypeNative version
34
+
35
+ Examples:
36
+ typenative --source main.ts --output bin/app
37
+ typenative main.ts --script
38
+ typenative --source main.ts --output app-linux --target linux/arm64 --release`;
39
+ }
40
+ // Parses argv (without the executable and script): --flag value and
41
+ // --flag=value; one bare argument is the entry file
42
+ export function parseCliArgs(argv) {
43
+ const args = {
44
+ help: false,
45
+ version: false,
46
+ newProject: false,
47
+ script: false,
48
+ noTypeCheck: false,
49
+ release: false,
50
+ source: null,
51
+ output: null,
52
+ target: null,
53
+ emitGo: null,
54
+ error: ''
55
+ };
56
+ for (let i = 0; i < argv.length; i++) {
57
+ let arg = argv[i];
58
+ let value = null;
59
+ const eq = arg.indexOf('=');
60
+ if (arg.startsWith('--') && eq > 0) {
61
+ value = arg.substring(eq + 1);
62
+ arg = arg.substring(0, eq);
63
+ }
64
+ if (arg === '-h' || arg === '--help')
65
+ args.help = true;
66
+ else if (arg === '-v' || arg === '--version')
67
+ args.version = true;
68
+ else if (arg === '--new')
69
+ args.newProject = true;
70
+ else if (arg === '--script')
71
+ args.script = true;
72
+ else if (arg === '--no-typecheck')
73
+ args.noTypeCheck = true;
74
+ else if (arg === '--release')
75
+ args.release = true;
76
+ else if (arg === '--source' || arg === '--output' || arg === '--target' || arg === '--emit-go') {
77
+ if (value === null) {
78
+ if (i + 1 >= argv.length || argv[i + 1].startsWith('--')) {
79
+ args.error = `${arg} needs a value`;
80
+ return args;
81
+ }
82
+ i++;
83
+ value = argv[i];
84
+ }
85
+ if (arg === '--source')
86
+ args.source = value;
87
+ else if (arg === '--output')
88
+ args.output = value;
89
+ else if (arg === '--target')
90
+ args.target = value;
91
+ else
92
+ args.emitGo = value;
93
+ }
94
+ else if (arg.startsWith('-')) {
95
+ args.error = `Unknown option: ${arg}`;
96
+ return args;
97
+ }
98
+ else if (args.source === null) {
99
+ // (a typed local: the self-hosted build boxes it into the string | null field)
100
+ const entry = arg;
101
+ args.source = entry;
102
+ }
103
+ else {
104
+ args.error = `Unexpected argument: ${arg}`;
105
+ return args;
106
+ }
107
+ }
108
+ if (args.target !== null && !/^[a-z0-9]+\/[a-z0-9]+$/.test(args.target)) {
109
+ args.error = `--target expects os/arch (like linux/arm64), got '${args.target}'`;
110
+ }
111
+ return args;
112
+ }
113
+ // This machine's os/arch, as Go names them
114
+ function hostTarget() {
115
+ const result = runCommand('go', ['env', 'GOHOSTOS', 'GOHOSTARCH']);
116
+ const lines = (result.stdout ?? '').trim().split('\n');
117
+ return lines.length === 2 ? `${lines[0].trim()}/${lines[1].trim()}` : '';
118
+ }
119
+ // Checks the Go toolchain on the PATH (and a --target against the pairs it
120
+ // supports); returns an error message, '' when usable
121
+ export function checkGo(target) {
122
+ const version = runCommand('go', ['version']);
123
+ const found = (version.stdout ?? '').match(/go(\d+)\.(\d+)/);
124
+ if (version.status !== 0 || !found) {
125
+ return `TypeNative needs Go ${MIN_GO_MAJOR}.${MIN_GO_MINOR} or newer on the PATH (https://go.dev/dl/)`;
126
+ }
127
+ const major = Number(found[1]);
128
+ const minor = Number(found[2]);
129
+ if (major < MIN_GO_MAJOR || (major === MIN_GO_MAJOR && minor < MIN_GO_MINOR)) {
130
+ return `TypeNative needs Go ${MIN_GO_MAJOR}.${MIN_GO_MINOR} or newer; found go${major}.${minor} (https://go.dev/dl/)`;
131
+ }
132
+ if (target !== null) {
133
+ const list = runCommand('go', ['tool', 'dist', 'list']);
134
+ const targets = (list.stdout ?? '').split('\n').map((line) => line.trim());
135
+ if (!targets.includes(target)) {
136
+ return `Go can't build for '${target}' ('go tool dist list' shows the os/arch pairs it supports)`;
137
+ }
138
+ }
139
+ return '';
140
+ }
14
141
  // A source path as diagnostics and Go line directives show it: relative to
15
142
  // the working directory when inside it, else absolute; forward slashes
16
143
  function displayPath(file) {
@@ -29,11 +156,11 @@ function plural(count, noun) {
29
156
  }
30
157
  // golang.org/x/text's transform and unicode/norm packages (String.normalize),
31
158
  // copied from GOROOT/src/vendor
32
- function vendorXText() {
159
+ function vendorXText(outDir) {
33
160
  const goroot = runCommand('go', ['env', 'GOROOT']).stdout.trim();
34
161
  const source = path.join(goroot, 'src', 'vendor', 'golang.org', 'x', 'text');
35
162
  for (const pkg of ['transform', path.join('unicode', 'norm')]) {
36
- const target = path.join('dist', 'tnvendor', 'x-text', pkg);
163
+ const target = path.join(outDir, 'tnvendor', 'x-text', pkg);
37
164
  fs.mkdirSync(target, { recursive: true });
38
165
  for (const file of fs.readdirSync(path.join(source, pkg))) {
39
166
  if (file.endsWith('.go') && !file.endsWith('_test.go')) {
@@ -41,17 +168,17 @@ function vendorXText() {
41
168
  }
42
169
  }
43
170
  }
44
- fs.writeFileSync(path.join('dist', 'tnvendor', 'x-text', 'go.mod'), 'module golang.org/x/text\n\ngo 1.23\n');
171
+ fs.writeFileSync(path.join(outDir, 'tnvendor', 'x-text', 'go.mod'), 'module golang.org/x/text\n\ngo 1.23\n');
45
172
  return { path: 'golang.org/x/text', version: 'v0.0.0', dir: './tnvendor/x-text' };
46
173
  }
47
- // node:sqlite's driver and its dependencies, copied from the package's
48
- // govendor/ (listed in govendor/manifest.txt); the copy is skipped while
49
- // dist/tnvendor already holds the same version. Returns the modules and the
50
- // Go version their go.mod files declare.
51
- function vendorGoModules(vendorDir) {
174
+ // node:sqlite's driver, the Brotli codec, fsnotify and their dependencies,
175
+ // copied from the package's govendor/ (listed in govendor/manifest.txt); the
176
+ // copy is skipped while dist/tnvendor already holds the same version. Returns
177
+ // the modules and the Go version their go.mod files declare.
178
+ function vendorGoModules(vendorDir, outDir) {
52
179
  const manifest = fs.readFileSync(path.join(vendorDir, 'manifest.txt'), 'utf-8');
53
180
  let version = '';
54
- let goVersion = '1.23';
181
+ let goVersion = `${MIN_GO_MAJOR}.${MIN_GO_MINOR}`;
55
182
  const modules = [];
56
183
  for (const line of manifest.split('\n')) {
57
184
  const parts = line.trim().split(' ');
@@ -63,11 +190,11 @@ function vendorGoModules(vendorDir) {
63
190
  modules.push({ path: parts[1], version: parts[2], dir: './tnvendor/' + parts[1] });
64
191
  }
65
192
  }
66
- const stamp = path.join('dist', 'tnvendor', 'govendor.version');
193
+ const stamp = path.join(outDir, 'tnvendor', 'govendor.version');
67
194
  const current = fs.existsSync(stamp) ? fs.readFileSync(stamp, 'utf-8') : '';
68
195
  if (current !== version) {
69
196
  for (const mod of modules) {
70
- const target = path.join('dist', 'tnvendor', mod.path);
197
+ const target = path.join(outDir, 'tnvendor', mod.path);
71
198
  fs.rmSync(target, { recursive: true, force: true });
72
199
  fs.cpSync(path.join(vendorDir, mod.path), target, { recursive: true });
73
200
  }
@@ -75,14 +202,28 @@ function vendorGoModules(vendorDir) {
75
202
  }
76
203
  return { modules: modules, goVersion: goVersion };
77
204
  }
78
- function writeGoMod(modules, goVersion) {
205
+ // Whether generated Go imports a package of a module in govendor/ (node:sqlite's
206
+ // driver, zlib's Brotli codec, fs.watch's fsnotify)
207
+ function importsVendoredModule(content, vendorDir) {
208
+ const manifest = fs.readFileSync(path.join(vendorDir, 'manifest.txt'), 'utf-8');
209
+ for (const line of manifest.split('\n')) {
210
+ const parts = line.trim().split(' ');
211
+ if (parts[0] !== 'module')
212
+ continue;
213
+ if (content.includes(`"${parts[1]}"`) || content.includes(`"${parts[1]}/`))
214
+ return true;
215
+ }
216
+ return false;
217
+ }
218
+ function writeGoMod(modules, goVersion, outDir) {
79
219
  let requires = '';
80
220
  let replaces = '';
81
221
  for (const mod of modules) {
82
222
  requires += `\t${mod.path} ${mod.version}\n`;
83
223
  replaces += `\t${mod.path} => ${mod.dir}\n`;
84
224
  }
85
- fs.writeFileSync(path.join('dist', 'go.mod'), `module tnapp\n\ngo ${goVersion}\n\nrequire (\n${requires})\n\nreplace (\n${replaces})\n`);
225
+ const deps = modules.length > 0 ? `\nrequire (\n${requires})\n\nreplace (\n${replaces})\n` : '';
226
+ fs.writeFileSync(path.join(outDir, 'go.mod'), `module tnapp\n\ngo ${goVersion}\n${deps}`);
86
227
  }
87
228
  // Run a command and capture its output. Uses Node's spawnSync under Node and a
88
229
  // Go helper (os/exec) once transpiled — both synchronous, same result shape.
@@ -118,6 +259,15 @@ export function createProject(projectName, installDependencies) {
118
259
  }
119
260
  }
120
261
  export function run(opts) {
262
+ const goError = checkGo(opts.target);
263
+ if (goError) {
264
+ console.error(`error: ${goError}`);
265
+ process.exit(1);
266
+ }
267
+ if (opts.target && opts.scriptMode && opts.target !== hostTarget()) {
268
+ console.error(`error: --script can't run a program built for ${opts.target} on ${hostTarget()}; use --output`);
269
+ process.exit(1);
270
+ }
121
271
  const sourcePath = opts.tsCode ? null : opts.source;
122
272
  const tsCode = opts.tsCode ? opts.tsCode : fs.readFileSync(sourcePath, 'utf-8');
123
273
  fs.mkdirSync('dist', { recursive: true });
@@ -136,14 +286,18 @@ export function run(opts) {
136
286
  }
137
287
  }
138
288
  const sourceDir = sourcePath ? path.dirname(path.resolve(sourcePath)) : null;
139
- // Node's platform names are GOOS names, except win32
289
+ // Node's platform names are GOOS names, except win32; OS-specific runtime
290
+ // helpers follow the --target
140
291
  const goos = platform() === 'win32' ? 'windows' : platform();
292
+ // (typed locals: the self-hosted build boxes them into the optional fields)
293
+ const goFile = displayPath(path.join(opts.emitGo ?? 'dist', 'code.go'));
294
+ const targetOs = opts.target ? opts.target.split('/')[0] : goos;
141
295
  const transpileOptions = {
142
296
  parse: opts.parse,
143
297
  tsx: !!sourcePath && sourcePath.endsWith('.tsx'),
144
298
  fileName: displayPath(entryPath),
145
- goFile: 'dist/code.go',
146
- goos: goos
299
+ goFile: goFile,
300
+ goos: targetOs
147
301
  };
148
302
  if (sourceDir) {
149
303
  transpileOptions.readFile = (specifier, fromDir) => {
@@ -197,47 +351,70 @@ export function run(opts) {
197
351
  console.error(`\n${plural(transpileResult.diagnostics.length, 'error')}: TypeNative can't compile this yet`);
198
352
  process.exit(1);
199
353
  }
200
- const exeName = platform() === 'win32' ? 'native.exe' : 'native';
201
- const exePath = `dist/${exeName}`;
202
- // Clean up stale Go files from previous runs before writing new ones
203
- for (const existing of fs.readdirSync('dist')) {
204
- if (existing.endsWith('.go') || existing === 'go.mod' || existing === 'go.sum')
205
- fs.rmSync(`dist/${existing}`);
354
+ // --emit-go writes to its own directory; builds happen in dist/
355
+ const outDir = opts.emitGo ?? 'dist';
356
+ fs.mkdirSync(outDir, { recursive: true });
357
+ if (opts.emitGo && fs.existsSync(path.join(outDir, 'go.mod'))) {
358
+ const existingMod = fs.readFileSync(path.join(outDir, 'go.mod'), 'utf-8');
359
+ if (!existingMod.startsWith('module tnapp')) {
360
+ console.error(`error: ${outDir}/go.mod belongs to another Go module; --emit-go needs a directory of its own`);
361
+ process.exit(1);
362
+ }
206
363
  }
207
- fs.writeFileSync('dist/code.go', transpileResult.main);
208
- const goFiles = ['dist/code.go'];
364
+ // Clean up stale Go files from previous runs before writing new ones (in an
365
+ // --emit-go directory, only files TypeNative generated)
366
+ for (const existing of fs.readdirSync(outDir)) {
367
+ const file = path.join(outDir, existing);
368
+ if (existing === 'go.mod' || existing === 'go.sum')
369
+ fs.rmSync(file);
370
+ else if (existing.endsWith('.go') && (!opts.emitGo || fs.readFileSync(file, 'utf-8').startsWith(GENERATED_HEADER)))
371
+ fs.rmSync(file);
372
+ }
373
+ fs.writeFileSync(path.join(outDir, 'code.go'), transpileResult.main);
374
+ const goFiles = ['code.go'];
209
375
  for (const [filename, content] of transpileResult.files) {
210
- fs.writeFileSync(`dist/${filename}`, content);
211
- goFiles.push(`dist/${filename}`);
376
+ fs.writeFileSync(path.join(outDir, filename), content);
377
+ goFiles.push(filename);
212
378
  }
213
379
  // Third-party Go modules the program imports (see vendorXText / vendorGoModules)
214
380
  const generated = [transpileResult.main];
215
381
  for (const content of transpileResult.files.values())
216
382
  generated.push(content);
217
383
  const xTextImport = /^import (\w+ )?"golang\.org\/x\/text\//m;
218
- const sqliteImport = /^import (\w+ )?"github\.com\/ncruces\/go-sqlite3"/m;
219
384
  const modules = [];
220
- let goVersion = '1.23';
385
+ let goVersion = `${MIN_GO_MAJOR}.${MIN_GO_MINOR}`;
221
386
  if (generated.some((content) => xTextImport.test(content)))
222
- modules.push(vendorXText());
223
- if (generated.some((content) => sqliteImport.test(content))) {
224
- const vendored = vendorGoModules(opts.vendorDir);
387
+ modules.push(vendorXText(outDir));
388
+ if (generated.some((content) => importsVendoredModule(content, opts.vendorDir))) {
389
+ const vendored = vendorGoModules(opts.vendorDir, outDir);
225
390
  for (const mod of vendored.modules)
226
391
  modules.push(mod);
227
392
  goVersion = vendored.goVersion;
228
393
  }
229
- if (modules.length > 0)
230
- writeGoMod(modules, goVersion);
231
- const buildResult = modules.length > 0
232
- ? runCommand('go', [
233
- 'build',
234
- '-C',
235
- 'dist',
236
- '-o',
237
- exeName,
238
- ...goFiles.map((f) => f.slice('dist/'.length))
239
- ])
240
- : runCommand('go', ['build', '-o', exePath, ...goFiles]);
394
+ writeGoMod(modules, goVersion, outDir);
395
+ if (opts.emitGo) {
396
+ console.log(`Wrote the Go sources to ${outDir} (build them with: go build -C ${outDir})`);
397
+ return;
398
+ }
399
+ // GOOS / GOARCH for --target: set on this process, which go build inherits
400
+ // (--script only runs host builds, so the program never sees them changed)
401
+ if (opts.target) {
402
+ const pair = opts.target.split('/');
403
+ process.env.GOOS = pair[0];
404
+ process.env.GOARCH = pair[1];
405
+ }
406
+ const exeName = targetOs === 'windows' ? 'native.exe' : 'native';
407
+ const exePath = `dist/${exeName}`;
408
+ const buildArgs = ['build', '-C', 'dist', '-o', exeName];
409
+ // -trimpath gives path-independent cache keys: the vendored packages (sqlite
410
+ // is ~5 MB of Go) compile once, not again for every project directory
411
+ if (opts.release || modules.length > 0)
412
+ buildArgs.push('-trimpath');
413
+ if (opts.release)
414
+ buildArgs.push('-ldflags=-s -w');
415
+ for (const file of goFiles)
416
+ buildArgs.push(file);
417
+ const buildResult = runCommand('go', buildArgs);
241
418
  if (buildResult.status !== 0) {
242
419
  // Positions in .ts files come from line directives in the generated Go
243
420
  console.error('go build failed:');
package/bin/main.js CHANGED
@@ -2,37 +2,58 @@
2
2
  // the native compiler binary. Interactive prompts use the transpilable
3
3
  // prompt module (sync stdin) instead of inquirer.
4
4
  import path from 'node:path';
5
- import { run, createProject } from './index.js';
5
+ import { run, createProject, parseCliArgs, usage } from './index.js';
6
6
  import { ask, askMultiline, confirm } from './prompt.js';
7
7
  import { parseAstJsonNative, typeCheckNative } from './parse-native.js';
8
+ import { VERSION } from './version.js';
8
9
  (function main() {
9
- const scriptMode = process.argv.findIndex((a) => a === '--script') > -1;
10
- const newCommand = process.argv.findIndex((a) => a === '--new') > -1;
11
- const noTypeCheck = process.argv.includes('--no-typecheck');
12
- const sourceIndex = process.argv.findIndex((a) => a === '--source');
13
- let source = sourceIndex > -1 ? process.argv[sourceIndex + 1] : null;
14
- const outputIndex = process.argv.findIndex((a) => a === '--output');
15
- let output = outputIndex > -1 ? process.argv[outputIndex + 1] : null;
16
- if (newCommand) {
10
+ const args = parseCliArgs(process.argv.slice(2));
11
+ if (args.error) {
12
+ console.error(`error: ${args.error}\nRun 'typenative --help' for the options.`);
13
+ process.exit(2);
14
+ }
15
+ if (args.help) {
16
+ console.log(usage());
17
+ return;
18
+ }
19
+ if (args.version) {
20
+ console.log(VERSION);
21
+ return;
22
+ }
23
+ const scriptMode = args.script;
24
+ let source = args.source;
25
+ let output = args.output;
26
+ if (args.newProject) {
17
27
  const projectName = ask('Enter Project Name:');
18
28
  const installDependencies = confirm('Do you want to install dependencies?');
19
29
  createProject(projectName, installDependencies);
20
30
  return;
21
31
  }
22
32
  let tsCode = null;
23
- if (!newCommand && !scriptMode && !source) {
33
+ if (!scriptMode && !source) {
24
34
  source = ask('Enter Path to typescript main file:');
25
35
  }
26
- if (!newCommand && !scriptMode && !output) {
36
+ if (!scriptMode && !output && !args.emitGo) {
27
37
  output = ask('Enter Output Path:');
28
38
  }
29
- if (!newCommand && scriptMode && !source) {
39
+ if (scriptMode && !source) {
30
40
  tsCode = askMultiline('Write your typescript code here:');
31
41
  }
32
42
  // The native compiler lives in native/, next to the package's govendor/ and types/
33
43
  const packageDir = path.join(path.dirname(path.resolve(process.argv[0])), '..');
34
44
  const vendorDir = path.join(packageDir, 'govendor');
35
45
  const typesDir = path.join(packageDir, 'types');
36
- const typeCheck = noTypeCheck ? null : (fileName) => typeCheckNative(fileName, typesDir);
37
- run({ source, output, scriptMode, tsCode, parse: parseAstJsonNative, typeCheck, vendorDir });
46
+ const typeCheck = args.noTypeCheck ? null : (fileName) => typeCheckNative(fileName, typesDir);
47
+ run({
48
+ source,
49
+ output,
50
+ scriptMode,
51
+ tsCode,
52
+ parse: parseAstJsonNative,
53
+ typeCheck,
54
+ vendorDir,
55
+ target: args.target,
56
+ release: args.release,
57
+ emitGo: args.emitGo
58
+ });
38
59
  })();
@@ -201,7 +201,7 @@ func TnAssertRejects[T any](p chan T, check func(interface{}) bool, msg ...inter
201
201
  if check != nil && !check(reason) {
202
202
  panic(reason)
203
203
  }
204
- out <- struct{}{}
204
+ TnAsyncSend(out, struct{}{})
205
205
  }()
206
206
  return out
207
207
  }
@@ -215,7 +215,7 @@ func TnAssertDoesNotReject[T any](p chan T, msg ...interface{}) chan struct{} {
215
215
  if rejected {
216
216
  panic(tnAssertionError(tnAssertMessage(msg), "Got unwanted rejection.\\nActual message: \\""+TnErrorText(reason)+"\\"", reason, nil, "doesNotReject"))
217
217
  }
218
- out <- struct{}{}
218
+ TnAsyncSend(out, struct{}{})
219
219
  }()
220
220
  return out
221
221
  }