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.
Files changed (170) hide show
  1. package/.github/workflows/ci.yml +2 -0
  2. package/CHANGELOG.md +258 -0
  3. package/CONTRIBUTION.md +1 -1
  4. package/README.md +17 -1
  5. package/bin/cli.js +26 -11
  6. package/bin/go/bridge.js +74 -14
  7. package/bin/go/convert.js +59 -1
  8. package/bin/go/metadata.js +13 -4
  9. package/bin/go/overrides.js +4 -6
  10. package/bin/go/stdlib.generated.js +2 -0
  11. package/bin/index.js +338 -47
  12. package/bin/main.js +36 -14
  13. package/bin/node/assert.js +2 -2
  14. package/bin/node/buffer.js +9 -0
  15. package/bin/node/child_process.js +51 -3
  16. package/bin/node/cluster.js +41 -3
  17. package/bin/node/core.js +1 -1
  18. package/bin/node/crypto.js +205 -4
  19. package/bin/node/dgram.js +230 -6
  20. package/bin/node/dns.js +471 -8
  21. package/bin/node/errno_tables.js +445 -0
  22. package/bin/node/events.js +1 -1
  23. package/bin/node/fs.js +22 -15
  24. package/bin/node/fs_watch.js +407 -0
  25. package/bin/node/http.js +128 -30
  26. package/bin/node/http2.js +37 -7
  27. package/bin/node/module_v8.js +142 -0
  28. package/bin/node/net.js +9 -6
  29. package/bin/node/process.js +242 -0
  30. package/bin/node/readline.js +272 -1
  31. package/bin/node/registry.js +3 -1
  32. package/bin/node/sqlite.js +60 -12
  33. package/bin/node/stream.js +145 -10
  34. package/bin/node/test.js +311 -19
  35. package/bin/node/timers.js +1 -1
  36. package/bin/node/typed_arrays.js +608 -0
  37. package/bin/node/url.js +23 -5
  38. package/bin/node/util.js +21 -1
  39. package/bin/node/util_extra.js +6 -30
  40. package/bin/node/worker_threads.js +79 -19
  41. package/bin/node/zlib.js +131 -16
  42. package/bin/transpiler.js +4729 -616
  43. package/bin/typecheck-node.js +1 -0
  44. package/bin/version.js +1 -1
  45. package/conformance.md +1030 -877
  46. package/examples/README.md +54 -0
  47. package/examples/fibonacci/README.md +89 -0
  48. package/examples/fibonacci/bench.mjs +87 -0
  49. package/examples/fibonacci/main.ts +21 -0
  50. package/examples/hello-world/README.md +62 -0
  51. package/examples/hello-world/bench.mjs +66 -0
  52. package/examples/hello-world/main.ts +7 -0
  53. package/examples/json-server/README.md +127 -0
  54. package/examples/json-server/bench.mjs +263 -0
  55. package/examples/json-server/main.ts +67 -0
  56. package/govendor/github.com/andybalholm/brotli/LICENSE +19 -0
  57. package/govendor/github.com/andybalholm/brotli/README.md +19 -0
  58. package/govendor/github.com/andybalholm/brotli/backward_references.go +185 -0
  59. package/govendor/github.com/andybalholm/brotli/backward_references_hq.go +796 -0
  60. package/govendor/github.com/andybalholm/brotli/bit_cost.go +436 -0
  61. package/govendor/github.com/andybalholm/brotli/bit_reader.go +266 -0
  62. package/govendor/github.com/andybalholm/brotli/bitwriter.go +56 -0
  63. package/govendor/github.com/andybalholm/brotli/block_splitter.go +144 -0
  64. package/govendor/github.com/andybalholm/brotli/block_splitter_command.go +434 -0
  65. package/govendor/github.com/andybalholm/brotli/block_splitter_distance.go +433 -0
  66. package/govendor/github.com/andybalholm/brotli/block_splitter_literal.go +433 -0
  67. package/govendor/github.com/andybalholm/brotli/brotli_bit_stream.go +1435 -0
  68. package/govendor/github.com/andybalholm/brotli/cluster.go +30 -0
  69. package/govendor/github.com/andybalholm/brotli/cluster_command.go +164 -0
  70. package/govendor/github.com/andybalholm/brotli/cluster_distance.go +326 -0
  71. package/govendor/github.com/andybalholm/brotli/cluster_literal.go +326 -0
  72. package/govendor/github.com/andybalholm/brotli/command.go +254 -0
  73. package/govendor/github.com/andybalholm/brotli/compress_fragment.go +834 -0
  74. package/govendor/github.com/andybalholm/brotli/compress_fragment_two_pass.go +775 -0
  75. package/govendor/github.com/andybalholm/brotli/constants.go +77 -0
  76. package/govendor/github.com/andybalholm/brotli/context.go +2176 -0
  77. package/govendor/github.com/andybalholm/brotli/decode.go +2570 -0
  78. package/govendor/github.com/andybalholm/brotli/dictionary.go +122890 -0
  79. package/govendor/github.com/andybalholm/brotli/dictionary_hash.go +32779 -0
  80. package/govendor/github.com/andybalholm/brotli/encode.go +1220 -0
  81. package/govendor/github.com/andybalholm/brotli/encoder.go +177 -0
  82. package/govendor/github.com/andybalholm/brotli/encoder_dict.go +22 -0
  83. package/govendor/github.com/andybalholm/brotli/encoder_fast.go +201 -0
  84. package/govendor/github.com/andybalholm/brotli/entropy_encode.go +592 -0
  85. package/govendor/github.com/andybalholm/brotli/entropy_encode_static.go +4399 -0
  86. package/govendor/github.com/andybalholm/brotli/fast_log.go +290 -0
  87. package/govendor/github.com/andybalholm/brotli/find_match_length.go +45 -0
  88. package/govendor/github.com/andybalholm/brotli/go.mod +3 -0
  89. package/govendor/github.com/andybalholm/brotli/h10.go +287 -0
  90. package/govendor/github.com/andybalholm/brotli/h5.go +214 -0
  91. package/govendor/github.com/andybalholm/brotli/h6.go +216 -0
  92. package/govendor/github.com/andybalholm/brotli/hash.go +342 -0
  93. package/govendor/github.com/andybalholm/brotli/hash_composite.go +93 -0
  94. package/govendor/github.com/andybalholm/brotli/hash_forgetful_chain.go +252 -0
  95. package/govendor/github.com/andybalholm/brotli/hash_longest_match_quickly.go +214 -0
  96. package/govendor/github.com/andybalholm/brotli/hash_rolling.go +168 -0
  97. package/govendor/github.com/andybalholm/brotli/histogram.go +226 -0
  98. package/govendor/github.com/andybalholm/brotli/http.go +201 -0
  99. package/govendor/github.com/andybalholm/brotli/huffman.go +653 -0
  100. package/govendor/github.com/andybalholm/brotli/literal_cost.go +182 -0
  101. package/govendor/github.com/andybalholm/brotli/matchfinder/bargain1.go +212 -0
  102. package/govendor/github.com/andybalholm/brotli/matchfinder/bargain2.go +248 -0
  103. package/govendor/github.com/andybalholm/brotli/matchfinder/bargain3.go +278 -0
  104. package/govendor/github.com/andybalholm/brotli/matchfinder/emitter.go +34 -0
  105. package/govendor/github.com/andybalholm/brotli/matchfinder/m0.go +175 -0
  106. package/govendor/github.com/andybalholm/brotli/matchfinder/m4.go +339 -0
  107. package/govendor/github.com/andybalholm/brotli/matchfinder/matchfinder.go +103 -0
  108. package/govendor/github.com/andybalholm/brotli/matchfinder/pathfinder.go +328 -0
  109. package/govendor/github.com/andybalholm/brotli/matchfinder/textencoder.go +53 -0
  110. package/govendor/github.com/andybalholm/brotli/matchfinder/trio.go +327 -0
  111. package/govendor/github.com/andybalholm/brotli/matchfinder/zdfast.go +258 -0
  112. package/govendor/github.com/andybalholm/brotli/matchfinder/zfast.go +206 -0
  113. package/govendor/github.com/andybalholm/brotli/matchfinder/zm.go +302 -0
  114. package/govendor/github.com/andybalholm/brotli/memory.go +66 -0
  115. package/govendor/github.com/andybalholm/brotli/metablock.go +574 -0
  116. package/govendor/github.com/andybalholm/brotli/metablock_command.go +165 -0
  117. package/govendor/github.com/andybalholm/brotli/metablock_distance.go +165 -0
  118. package/govendor/github.com/andybalholm/brotli/metablock_literal.go +165 -0
  119. package/govendor/github.com/andybalholm/brotli/params.go +37 -0
  120. package/govendor/github.com/andybalholm/brotli/platform.go +103 -0
  121. package/govendor/github.com/andybalholm/brotli/prefix.go +30 -0
  122. package/govendor/github.com/andybalholm/brotli/prefix_dec.go +723 -0
  123. package/govendor/github.com/andybalholm/brotli/quality.go +196 -0
  124. package/govendor/github.com/andybalholm/brotli/reader.go +127 -0
  125. package/govendor/github.com/andybalholm/brotli/ringbuffer.go +134 -0
  126. package/govendor/github.com/andybalholm/brotli/state.go +313 -0
  127. package/govendor/github.com/andybalholm/brotli/static_dict.go +662 -0
  128. package/govendor/github.com/andybalholm/brotli/static_dict_lut.go +75094 -0
  129. package/govendor/github.com/andybalholm/brotli/symbol_list.go +22 -0
  130. package/govendor/github.com/andybalholm/brotli/transform.go +641 -0
  131. package/govendor/github.com/andybalholm/brotli/utf8_util.go +70 -0
  132. package/govendor/github.com/andybalholm/brotli/util.go +7 -0
  133. package/govendor/github.com/andybalholm/brotli/write_bits.go +52 -0
  134. package/govendor/github.com/andybalholm/brotli/writer.go +162 -0
  135. package/govendor/github.com/fsnotify/fsnotify/.mailmap +2 -0
  136. package/govendor/github.com/fsnotify/fsnotify/CHANGELOG.md +651 -0
  137. package/govendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md +147 -0
  138. package/govendor/github.com/fsnotify/fsnotify/LICENSE +25 -0
  139. package/govendor/github.com/fsnotify/fsnotify/README.md +214 -0
  140. package/govendor/github.com/fsnotify/fsnotify/backend_fen.go +469 -0
  141. package/govendor/github.com/fsnotify/fsnotify/backend_inotify.go +597 -0
  142. package/govendor/github.com/fsnotify/fsnotify/backend_kqueue.go +735 -0
  143. package/govendor/github.com/fsnotify/fsnotify/backend_other.go +22 -0
  144. package/govendor/github.com/fsnotify/fsnotify/backend_windows.go +702 -0
  145. package/govendor/github.com/fsnotify/fsnotify/fsnotify.go +526 -0
  146. package/govendor/github.com/fsnotify/fsnotify/go.mod +3 -0
  147. package/govendor/github.com/fsnotify/fsnotify/internal/darwin.go +20 -0
  148. package/govendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go +15 -0
  149. package/govendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go +15 -0
  150. package/govendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go +20 -0
  151. package/govendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go +32 -0
  152. package/govendor/github.com/fsnotify/fsnotify/internal/debug_linux.go +56 -0
  153. package/govendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go +15 -0
  154. package/govendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go +16 -0
  155. package/govendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go +45 -0
  156. package/govendor/github.com/fsnotify/fsnotify/internal/debug_windows.go +40 -0
  157. package/govendor/github.com/fsnotify/fsnotify/internal/freebsd.go +20 -0
  158. package/govendor/github.com/fsnotify/fsnotify/internal/internal.go +2 -0
  159. package/govendor/github.com/fsnotify/fsnotify/internal/unix.go +20 -0
  160. package/govendor/github.com/fsnotify/fsnotify/internal/unix2.go +25 -0
  161. package/govendor/github.com/fsnotify/fsnotify/internal/windows.go +40 -0
  162. package/govendor/github.com/fsnotify/fsnotify/shared.go +64 -0
  163. package/govendor/github.com/fsnotify/fsnotify/staticcheck.conf +3 -0
  164. package/govendor/github.com/fsnotify/fsnotify/system_bsd.go +7 -0
  165. package/govendor/github.com/fsnotify/fsnotify/system_darwin.go +8 -0
  166. package/govendor/manifest.txt +3 -1
  167. package/package.json +1 -1
  168. package/types/typenative-go.d.ts +23 -0
  169. package/types/typenative-npm.d.ts +241 -5
  170. package/types/typenative.d.ts +302 -12
package/bin/node/http2.js CHANGED
@@ -25,6 +25,8 @@ type TnHttp2Session struct {
25
25
  active int
26
26
  nextID float64
27
27
  socket *TnSocket
28
+
29
+ connectEmitted bool
28
30
  }
29
31
 
30
32
  func (s *TnHttp2Session) Get_closed() bool { return s.closed }
@@ -51,6 +53,21 @@ func (s *TnHttp2Session) unref() *TnHttp2Session {
51
53
 
52
54
  func (s *TnHttp2Session) setTimeout(ms float64, cb ...interface{}) *TnHttp2Session { return s }
53
55
 
56
+ // 'connect' fires once, when the session's first connection is up; guarded on
57
+ // the loop so the eager probe dial and the transport's own dials can both call
58
+ // it without racing
59
+ func (s *TnHttp2Session) emitConnect(conn net.Conn) {
60
+ TnLoopPost(func() {
61
+ if s.connectEmitted || s.destroyed {
62
+ return
63
+ }
64
+ s.connectEmitted = true
65
+ s.socket = tnInfoSocket(conn.LocalAddr(), conn.RemoteAddr().String())
66
+ s.socket.encrypted = s.encrypted
67
+ s.emit("connect", s, s.socket)
68
+ })
69
+ }
70
+
54
71
  func (s *TnHttp2Session) maybeFinish() {
55
72
  if !s.closed || s.active > 0 || s.finished {
56
73
  return
@@ -140,6 +157,17 @@ func TnHttp2Connect(authority interface{}, args ...interface{}) *TnHttp2Session
140
157
  t.Protocols = protocols
141
158
  s.transport = t
142
159
  s.client = &http.Client{Transport: t, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
160
+ // The transport dials through here (https too, there is no custom DialTLS),
161
+ // so 'connect' is posted before that request's response can be
162
+ dialer := &net.Dialer{Timeout: 10 * time.Second}
163
+ t.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
164
+ conn, err := dialer.DialContext(ctx, network, addr)
165
+ if err != nil {
166
+ return nil, err
167
+ }
168
+ s.emitConnect(conn)
169
+ return conn, nil
170
+ }
143
171
  if listener != nil {
144
172
  s.TnEventEmitter.once("connect", listener)
145
173
  }
@@ -149,6 +177,9 @@ func TnHttp2Connect(authority interface{}, args ...interface{}) *TnHttp2Session
149
177
  conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), 10*time.Second)
150
178
  TnLoopPost(func() {
151
179
  if err != nil {
180
+ if s.connectEmitted || s.destroyed {
181
+ return
182
+ }
152
183
  p, _ := strconv.ParseFloat(port, 64)
153
184
  target := host
154
185
  if ip := tnDialedIP(err); ip != "" {
@@ -157,12 +188,8 @@ func TnHttp2Connect(authority interface{}, args ...interface{}) *TnHttp2Session
157
188
  s.destroy(TnNetError(err, "connect", target, p))
158
189
  return
159
190
  }
160
- s.socket = tnInfoSocket(conn.LocalAddr(), conn.RemoteAddr().String())
161
- s.socket.encrypted = s.encrypted
191
+ s.emitConnect(conn)
162
192
  conn.Close()
163
- if !s.destroyed {
164
- s.emit("connect", s, s.socket)
165
- }
166
193
  })
167
194
  }()
168
195
  return s
@@ -297,7 +324,10 @@ func (st *TnHttp2Stream) respond(args ...interface{}) {
297
324
  }
298
325
  }
299
326
  st.res.statusCode = float64(status)
300
- st.res.post(st.res.headerOp())
327
+ // respond() sends the HEADERS frame right away
328
+ op := st.res.headerOp()
329
+ op.flush = true
330
+ st.res.post(op)
301
331
  st.headersSent = true
302
332
  st.sentHeaders = sent
303
333
  if len(args) > 1 && args[1] != nil {
@@ -617,7 +647,7 @@ const HTTP2_NUMBERS = {
617
647
  };
618
648
  export function registerHttp2(r) {
619
649
  defineModule(r, 'http2');
620
- defineHelper(r, 'nodeHttp2', ['bytes', 'crypto/tls', 'fmt', 'io', 'net', 'net/http', 'net/url', 'os', 'sort', 'strconv', 'strings', 'time'], ['nodeHttp', 'nodeNet', 'netErrors', 'nodeStream', 'nodeEvents', 'eventLoop', 'nodeInvoke', 'dynamic', 'orderedMap', 'tlsConfig', 'fsErrors'], http2Helper);
650
+ defineHelper(r, 'nodeHttp2', ['bytes', 'context', 'crypto/tls', 'fmt', 'io', 'net', 'net/http', 'net/url', 'os', 'sort', 'strconv', 'strings', 'time'], ['nodeHttp', 'nodeNet', 'netErrors', 'nodeStream', 'nodeEvents', 'eventLoop', 'nodeInvoke', 'dynamic', 'orderedMap', 'tlsConfig', 'fsErrors'], http2Helper);
621
651
  const use = () => r.helper('nodeHttp2');
622
652
  defineClass(r, 'http2.Http2Stream', '*TnHttp2Stream', 'class', STREAM_METHODS + '; respond=; respondWithFile=; close=; pushStream=; additionalHeaders=', '', STREAM_GETTERS + '; id=float64; session=*TnHttp2Session; sentHeaders=*TnMap[string, interface{}]; headersSent=bool; pushAllowed=bool; endAfterHeaders=bool; rstCode=float64; aborted=bool', '');
623
653
  for (const name of ['ServerHttp2Stream', 'ClientHttp2Stream'])
@@ -0,0 +1,142 @@
1
+ // node:module (builtinModules, isBuiltin), node:v8 (heap statistics from Go's
2
+ // runtime, serialize / deserialize over the worker structured-clone codec) and
3
+ // node:sea (every TypeNative binary is a single executable)
4
+ import { defineClass, defineHelper, defineModule } from './registry.js';
5
+ // require('node:module').builtinModules in Node 22 (node:-only modules such as
6
+ // node:test are left out, as in Node)
7
+ const moduleHelper = `// node:module
8
+ var tnBuiltinModules = []string{
9
+ "_http_agent", "_http_client", "_http_common", "_http_incoming", "_http_outgoing", "_http_server",
10
+ "_stream_duplex", "_stream_passthrough", "_stream_readable", "_stream_transform", "_stream_wrap",
11
+ "_stream_writable", "_tls_common", "_tls_wrap", "assert", "assert/strict", "async_hooks",
12
+ "buffer", "child_process", "cluster", "console", "constants", "crypto", "dgram",
13
+ "diagnostics_channel", "dns", "dns/promises", "domain", "events", "fs", "fs/promises", "http",
14
+ "http2", "https", "inspector", "inspector/promises", "module", "net", "os", "path", "path/posix",
15
+ "path/win32", "perf_hooks", "process", "punycode", "querystring", "readline", "readline/promises",
16
+ "repl", "stream", "stream/consumers", "stream/promises", "stream/web", "string_decoder", "sys",
17
+ "timers", "timers/promises", "tls", "trace_events", "tty", "url", "util", "util/types", "v8",
18
+ "vm", "wasi", "worker_threads", "zlib",
19
+ }
20
+
21
+ // isBuiltin('fs') / isBuiltin('node:fs'); node:test, node:sqlite and node:sea
22
+ // exist only with the node: scheme
23
+ func TnIsBuiltin(name string) bool {
24
+ switch name {
25
+ case "node:sea", "node:sqlite", "node:test", "node:test/reporters":
26
+ return true
27
+ }
28
+ bare := strings.TrimPrefix(name, "node:")
29
+ for _, m := range tnBuiltinModules {
30
+ if m == bare {
31
+ return true
32
+ }
33
+ }
34
+ return false
35
+ }`;
36
+ const v8Helper = `// node:v8 heap statistics, from Go's runtime.MemStats
37
+ type TnHeapStatistics struct {
38
+ total_heap_size float64
39
+ total_heap_size_executable float64
40
+ total_physical_size float64
41
+ total_available_size float64
42
+ used_heap_size float64
43
+ heap_size_limit float64
44
+ malloced_memory float64
45
+ peak_malloced_memory float64
46
+ does_zap_garbage float64
47
+ number_of_native_contexts float64
48
+ number_of_detached_contexts float64
49
+ total_global_handles_size float64
50
+ used_global_handles_size float64
51
+ external_memory float64
52
+ }
53
+
54
+ // The heap limit: GOMEMLIMIT / debug.SetMemoryLimit when set, else 4 GiB
55
+ // (V8's default on 64-bit systems)
56
+ func tnHeapLimit() float64 {
57
+ if limit := debug.SetMemoryLimit(-1); limit < math.MaxInt64 {
58
+ return float64(limit)
59
+ }
60
+ return 4 * 1024 * 1024 * 1024
61
+ }
62
+
63
+ func TnV8HeapStatistics() *TnHeapStatistics {
64
+ var m runtime.MemStats
65
+ runtime.ReadMemStats(&m)
66
+ limit := tnHeapLimit()
67
+ return &TnHeapStatistics{
68
+ total_heap_size: float64(m.HeapSys), total_physical_size: float64(m.HeapInuse),
69
+ total_available_size: math.Max(0, limit-float64(m.HeapAlloc)), used_heap_size: float64(m.HeapAlloc),
70
+ heap_size_limit: limit, malloced_memory: float64(m.OtherSys), peak_malloced_memory: float64(m.OtherSys),
71
+ number_of_native_contexts: 1,
72
+ }
73
+ }
74
+
75
+ // v8.serialize / deserialize: the structured-clone codec workers use (JSON
76
+ // with type tags, behind a 0xFF version byte), not V8's wire format
77
+ func TnV8Serialize(v interface{}) []byte {
78
+ data, err := json.Marshal(tnCloneEncode(v))
79
+ if err != nil {
80
+ panic(TnNodeError("Error", "ERR_INVALID_ARG_TYPE", err.Error()))
81
+ }
82
+ return append([]byte{0xFF}, data...)
83
+ }
84
+
85
+ func TnV8Deserialize(buf []byte) interface{} {
86
+ var v interface{}
87
+ if len(buf) == 0 || buf[0] != 0xFF || json.Unmarshal(buf[1:], &v) != nil {
88
+ panic(TnNodeError("Error", "", "Unable to deserialize cloned data."))
89
+ }
90
+ return tnCloneDecode(v)
91
+ }`;
92
+ const seaHelper = `// node:sea: a TypeNative binary is a single executable without assets
93
+ func TnSeaGetAsset(key string, encoding ...string) interface{} {
94
+ panic(TnNodeError("Error", "ERR_SINGLE_EXECUTABLE_APPLICATION_ASSET_NOT_FOUND", "Cannot find asset "+key+" for the single executable application"))
95
+ }`;
96
+ export function registerModuleV8(r) {
97
+ defineModule(r, 'module');
98
+ defineHelper(r, 'nodeModule', ['strings'], [], moduleHelper);
99
+ r.values['module.builtinModules'] = (_c) => {
100
+ r.helper('nodeModule');
101
+ return 'append([]string{}, tnBuiltinModules...)';
102
+ };
103
+ r.valueTypes['module.builtinModules'] = '[]string';
104
+ r.functions['module.isBuiltin'] = (c) => {
105
+ r.helper('nodeModule');
106
+ return `TnIsBuiltin(${c.args[0]})`;
107
+ };
108
+ r.results['module.isBuiltin'] = 'bool';
109
+ // const require = createRequire(import.meta.url) is handled by the
110
+ // transpiler (require('./x.json') reads the file at compile time)
111
+ r.functions['module.createRequire'] = (_c) => 'nil';
112
+ r.results['module.createRequire'] = 'interface{}';
113
+ defineModule(r, 'v8');
114
+ defineHelper(r, 'nodeV8', ['encoding/json', 'math', 'runtime', 'runtime/debug'], ['nodeClone', 'error'], v8Helper);
115
+ defineClass(r, 'v8.HeapInfo', '*TnHeapStatistics', 'class', '', 'total_heap_size=float64; total_heap_size_executable=float64; total_physical_size=float64; total_available_size=float64; used_heap_size=float64; heap_size_limit=float64; malloced_memory=float64; peak_malloced_memory=float64; does_zap_garbage=float64; number_of_native_contexts=float64; number_of_detached_contexts=float64; total_global_handles_size=float64; used_global_handles_size=float64; external_memory=float64', '', '');
116
+ r.functions['v8.getHeapStatistics'] = (_c) => {
117
+ r.helper('nodeV8');
118
+ return 'TnV8HeapStatistics()';
119
+ };
120
+ r.results['v8.getHeapStatistics'] = '*TnHeapStatistics';
121
+ r.functions['v8.serialize'] = (c) => {
122
+ r.helper('nodeV8');
123
+ return `TnV8Serialize(${c.args[0]})`;
124
+ };
125
+ r.results['v8.serialize'] = '[]byte';
126
+ r.functions['v8.deserialize'] = (c) => {
127
+ r.helper('nodeV8');
128
+ return `TnV8Deserialize(${c.args[0]})`;
129
+ };
130
+ r.results['v8.deserialize'] = 'interface{}';
131
+ defineModule(r, 'sea');
132
+ r.functions['sea.isSea'] = (_c) => 'true';
133
+ r.results['sea.isSea'] = 'bool';
134
+ defineHelper(r, 'nodeSea', [], ['error'], seaHelper);
135
+ for (const name of ['getAsset', 'getRawAsset', 'getAssetAsBlob']) {
136
+ r.functions[`sea.${name}`] = (c) => {
137
+ r.helper('nodeSea');
138
+ return `TnSeaGetAsset(${c.args.join(', ')})`;
139
+ };
140
+ r.results[`sea.${name}`] = 'interface{}';
141
+ }
142
+ }
package/bin/node/net.js CHANGED
@@ -5,11 +5,14 @@
5
5
  import { defineClass, defineHelper, defineModule, setResults } from './registry.js';
6
6
  import { STREAM_METHODS, STREAM_GETTERS, streamListenerTypes } from './stream.js';
7
7
  const netErrorsHelper = `// Node-style network errors: connect ECONNREFUSED 127.0.0.1:80
8
- var tnNetErrnos = map[string]float64{
9
- "ECONNREFUSED": -111, "EADDRINUSE": -98, "EADDRNOTAVAIL": -99, "ECONNRESET": -104, "EPIPE": -32,
10
- "ETIMEDOUT": -110, "EACCES": -13, "ENOTFOUND": -3008, "EAI_AGAIN": -3001, "ENETUNREACH": -101,
11
- "EHOSTUNREACH": -113, "ECONNABORTED": -103, "EINVAL": -22, "ENOENT": -2,
12
- }
8
+ // Node's errno numbers, plus ENOTFOUND (getaddrinfo's EAI_NONAME)
9
+ var tnNetErrnos = func() map[string]float64 {
10
+ m := map[string]float64{"ENOTFOUND": -3008}
11
+ for code, errno := range tnUvErrnos {
12
+ m[code] = errno
13
+ }
14
+ return m
15
+ }()
13
16
 
14
17
  func tnNetCode(err error) string {
15
18
  var dnsErr *net.DNSError
@@ -1046,7 +1049,7 @@ func (b *TnBlockList) Get_rules() []string {
1046
1049
  }`;
1047
1050
  export function registerNet(r) {
1048
1051
  defineModule(r, 'net');
1049
- defineHelper(r, 'netErrors', ['errors', 'net', 'os', 'reflect', 'strconv', 'strings', 'syscall'], ['error', 'dynamic'], netErrorsHelper);
1052
+ defineHelper(r, 'netErrors', ['errors', 'net', 'os', 'reflect', 'strconv', 'strings', 'syscall'], ['error', 'dynamic', 'uvErrno'], netErrorsHelper);
1050
1053
  defineHelper(r, 'nodeNet', ['errors', 'io', 'net', 'strconv', 'strings', 'time'], ['netErrors', 'nodeStream', 'nodeEvents', 'eventLoop', 'nodeInvoke', 'dynamic'], netHelper);
1051
1054
  const use = () => r.helper('nodeNet');
1052
1055
  defineClass(r, 'net.AddressInfo', '*TnAddressInfo', 'class', '', 'address=string; family=string; port=float64', '', '');
@@ -32,9 +32,15 @@ func tnRunBeforeExit(code float64) {
32
32
  }
33
33
  }
34
34
 
35
+ // Set by process.stdin.setRawMode: puts the terminal back as it was, as Node does at exit
36
+ var tnResetStdio func()
37
+
35
38
  // The end of main: exit with process.exitCode
36
39
  func TnProcessExit() {
37
40
  tnRunBeforeExit(tnExitCode)
41
+ if tnResetStdio != nil {
42
+ tnResetStdio()
43
+ }
38
44
  if tnExitCode != 0 {
39
45
  os.Exit(int(tnExitCode))
40
46
  }
@@ -46,6 +52,9 @@ func TnProcessExitWith(code ...float64) {
46
52
  tnExitCode = code[0]
47
53
  }
48
54
  tnRunBeforeExit(tnExitCode)
55
+ if tnResetStdio != nil {
56
+ tnResetStdio()
57
+ }
49
58
  os.Exit(int(tnExitCode))
50
59
  }
51
60
 
@@ -171,6 +180,197 @@ func TnHasEnv(name string) bool {
171
180
  _, ok := os.LookupEnv(name)
172
181
  return ok
173
182
  }`;
183
+ // Terminal size, raw mode and umask: one variant per target OS (nodeTtyOS@os)
184
+ const ttyHelper = `var tnStdinRaw bool
185
+
186
+ // process.stdout.columns / rows: 0 when the stream is not a terminal
187
+ func TnTtyColumns(f *os.File) float64 {
188
+ cols, _, _ := tnTerminalSize(f)
189
+ return float64(cols)
190
+ }
191
+
192
+ func TnTtyRows(f *os.File) float64 {
193
+ _, rows, _ := tnTerminalSize(f)
194
+ return float64(rows)
195
+ }
196
+
197
+ func TnTtyWindowSize(f *os.File) []float64 {
198
+ cols, rows, _ := tnTerminalSize(f)
199
+ return []float64{float64(cols), float64(rows)}
200
+ }
201
+
202
+ // process.stdin.setRawMode(mode): libuv's raw mode; throws when stdin is not a terminal
203
+ func TnTtySetRawMode(mode bool) {
204
+ if !tnSetRawMode(os.Stdin, mode) {
205
+ panic(TnNodeError("Error", "EINVAL", "setRawMode EINVAL"))
206
+ }
207
+ tnStdinRaw = mode
208
+ tnResetStdio = func() { tnSetRawMode(os.Stdin, false) }
209
+ }
210
+
211
+ // process.umask(mask?): the previous mask (a number or an octal string)
212
+ func TnProcessUmask(mask ...interface{}) float64 {
213
+ if len(mask) == 0 || mask[0] == nil {
214
+ old := tnUmask(0)
215
+ tnUmask(old)
216
+ return float64(old)
217
+ }
218
+ var m int
219
+ switch x := mask[0].(type) {
220
+ case string:
221
+ n, err := strconv.ParseInt(x, 8, 32)
222
+ if err != nil {
223
+ panic(TnNodeError("TypeError", "ERR_INVALID_ARG_VALUE", "The argument 'mask' must be a 32-bit unsigned integer or an octal string. Received '" + x + "'"))
224
+ }
225
+ m = int(n)
226
+ default:
227
+ m = int(TnNumber(x))
228
+ }
229
+ return float64(tnUmask(m & 0o777))
230
+ }`;
231
+ // Linux: the asm-generic termios ioctls and flags (std syscall only has them
232
+ // for some architectures); PowerPC and MIPS number them differently
233
+ const linuxTtyHelper = `type tnWinsize struct {
234
+ Row, Col, X, Y uint16
235
+ }
236
+
237
+ func tnTerminalSize(f *os.File) (int, int, bool) {
238
+ var ws tnWinsize
239
+ _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&ws)))
240
+ if errno != 0 || ws.Col == 0 {
241
+ return 0, 0, false
242
+ }
243
+ return int(ws.Col), int(ws.Row), true
244
+ }
245
+
246
+ var tnSavedTermios *syscall.Termios
247
+
248
+ func tnSetRawMode(f *os.File, raw bool) bool {
249
+ if strings.HasPrefix(runtime.GOARCH, "ppc") || strings.HasPrefix(runtime.GOARCH, "mips") {
250
+ return false
251
+ }
252
+ var t syscall.Termios
253
+ if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), 0x5401, uintptr(unsafe.Pointer(&t))); errno != 0 {
254
+ return false
255
+ }
256
+ if raw {
257
+ if tnSavedTermios == nil {
258
+ saved := t
259
+ tnSavedTermios = &saved
260
+ }
261
+ t.Iflag &^= 0x2 | 0x100 | 0x10 | 0x20 | 0x400
262
+ t.Oflag |= 0x4
263
+ t.Cflag |= 0x30
264
+ t.Lflag &^= 0x8 | 0x2 | 0x8000 | 0x1
265
+ t.Cc[6], t.Cc[5] = 1, 0
266
+ } else if tnSavedTermios != nil {
267
+ t = *tnSavedTermios
268
+ }
269
+ _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), 0x5402, uintptr(unsafe.Pointer(&t)))
270
+ return errno == 0
271
+ }
272
+
273
+ func tnUmask(mask int) int {
274
+ return syscall.Umask(mask)
275
+ }`;
276
+ // macOS and FreeBSD: TIOCGETA / TIOCSETA
277
+ const bsdTtyHelper = `type tnWinsize struct {
278
+ Row, Col, X, Y uint16
279
+ }
280
+
281
+ func tnTerminalSize(f *os.File) (int, int, bool) {
282
+ var ws tnWinsize
283
+ _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(&ws)))
284
+ if errno != 0 || ws.Col == 0 {
285
+ return 0, 0, false
286
+ }
287
+ return int(ws.Col), int(ws.Row), true
288
+ }
289
+
290
+ var tnSavedTermios *syscall.Termios
291
+
292
+ func tnSetRawMode(f *os.File, raw bool) bool {
293
+ var t syscall.Termios
294
+ if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), uintptr(syscall.TIOCGETA), uintptr(unsafe.Pointer(&t))); errno != 0 {
295
+ return false
296
+ }
297
+ if raw {
298
+ if tnSavedTermios == nil {
299
+ saved := t
300
+ tnSavedTermios = &saved
301
+ }
302
+ t.Iflag &^= syscall.BRKINT | syscall.ICRNL | syscall.INPCK | syscall.ISTRIP | syscall.IXON
303
+ t.Oflag |= syscall.ONLCR
304
+ t.Cflag |= syscall.CS8
305
+ t.Lflag &^= syscall.ECHO | syscall.ICANON | syscall.IEXTEN | syscall.ISIG
306
+ t.Cc[syscall.VMIN], t.Cc[syscall.VTIME] = 1, 0
307
+ } else if tnSavedTermios != nil {
308
+ t = *tnSavedTermios
309
+ }
310
+ _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), uintptr(syscall.TIOCSETA), uintptr(unsafe.Pointer(&t)))
311
+ return errno == 0
312
+ }
313
+
314
+ func tnUmask(mask int) int {
315
+ return syscall.Umask(mask)
316
+ }`;
317
+ // Windows: the console API (there is no umask; Node returns 0)
318
+ const windowsTtyHelper = `var (
319
+ tnTtyKernel32 = syscall.NewLazyDLL("kernel32.dll")
320
+ tnGetConsoleScreenBufferInfo = tnTtyKernel32.NewProc("GetConsoleScreenBufferInfo")
321
+ tnSetConsoleMode = tnTtyKernel32.NewProc("SetConsoleMode")
322
+ tnSavedConsoleMode uint32
323
+ tnConsoleModeSaved bool
324
+ )
325
+
326
+ type tnConsoleScreenBufferInfo struct {
327
+ Size, CursorPosition [2]int16
328
+ Attributes uint16
329
+ Left, Top, Right, Bottom int16
330
+ MaximumWindowSize [2]int16
331
+ }
332
+
333
+ func tnTerminalSize(f *os.File) (int, int, bool) {
334
+ var info tnConsoleScreenBufferInfo
335
+ ok, _, _ := tnGetConsoleScreenBufferInfo.Call(f.Fd(), uintptr(unsafe.Pointer(&info)))
336
+ if ok == 0 {
337
+ return 0, 0, false
338
+ }
339
+ return int(info.Right-info.Left) + 1, int(info.Bottom-info.Top) + 1, true
340
+ }
341
+
342
+ func tnSetRawMode(f *os.File, raw bool) bool {
343
+ var mode uint32
344
+ if syscall.GetConsoleMode(syscall.Handle(f.Fd()), &mode) != nil {
345
+ return false
346
+ }
347
+ if raw {
348
+ if !tnConsoleModeSaved {
349
+ tnSavedConsoleMode, tnConsoleModeSaved = mode, true
350
+ }
351
+ // no ENABLE_ECHO_INPUT / LINE_INPUT / PROCESSED_INPUT; ENABLE_VIRTUAL_TERMINAL_INPUT
352
+ mode = mode&^(0x4|0x2|0x1) | 0x200
353
+ } else if tnConsoleModeSaved {
354
+ mode = tnSavedConsoleMode
355
+ }
356
+ ok, _, _ := tnSetConsoleMode.Call(f.Fd(), uintptr(mode))
357
+ return ok != 0
358
+ }
359
+
360
+ func tnUmask(mask int) int {
361
+ return 0
362
+ }`;
363
+ const otherTtyHelper = `func tnTerminalSize(f *os.File) (int, int, bool) {
364
+ return 0, 0, false
365
+ }
366
+
367
+ func tnSetRawMode(f *os.File, raw bool) bool {
368
+ return false
369
+ }
370
+
371
+ func tnUmask(mask int) int {
372
+ return 0
373
+ }`;
174
374
  export function registerProcess(r) {
175
375
  defineModule(r, 'process');
176
376
  r.globals['process'] = 'process';
@@ -182,6 +382,13 @@ export function registerProcess(r) {
182
382
  defineHelper(r, 'nodeProcess', ['fmt', 'math/big', 'os', 'runtime', 'strings', 'syscall', 'time'], ['error', 'orderedMap'], processHelper);
183
383
  defineClass(r, 'process.MemoryUsage', '*TnMemoryUsage', 'class', '', 'rss=float64; heapTotal=float64; heapUsed=float64; external=float64; arrayBuffers=float64', '', '');
184
384
  const use = () => r.helper('nodeProcess');
385
+ defineHelper(r, 'nodeTtyOS@linux', ['os', 'runtime', 'strings', 'syscall', 'unsafe'], [], linuxTtyHelper);
386
+ for (const goos of ['darwin', 'freebsd'])
387
+ defineHelper(r, `nodeTtyOS@${goos}`, ['os', 'syscall', 'unsafe'], [], bsdTtyHelper);
388
+ defineHelper(r, 'nodeTtyOS@windows', ['os', 'syscall', 'unsafe'], [], windowsTtyHelper);
389
+ defineHelper(r, 'nodeTtyOS@other', ['os'], [], otherTtyHelper);
390
+ defineHelper(r, 'nodeTty', ['os', 'strconv'], ['nodeTtyOS@os', 'nodeProcess', 'error', 'dynamic'], ttyHelper);
391
+ const tty = () => r.helper('nodeTty');
185
392
  const value = (name, type, emit) => {
186
393
  r.values[`process.${name}`] = (_c) => emit();
187
394
  r.valueTypes[`process.${name}`] = type;
@@ -241,6 +448,26 @@ export function registerProcess(r) {
241
448
  use();
242
449
  return 'TnIsTTY(os.Stdin)';
243
450
  });
451
+ value('stdout.columns', 'float64', () => {
452
+ tty();
453
+ return 'TnTtyColumns(os.Stdout)';
454
+ });
455
+ value('stdout.rows', 'float64', () => {
456
+ tty();
457
+ return 'TnTtyRows(os.Stdout)';
458
+ });
459
+ value('stderr.columns', 'float64', () => {
460
+ tty();
461
+ return 'TnTtyColumns(os.Stderr)';
462
+ });
463
+ value('stderr.rows', 'float64', () => {
464
+ tty();
465
+ return 'TnTtyRows(os.Stderr)';
466
+ });
467
+ value('stdin.isRaw', 'bool', () => {
468
+ tty();
469
+ return 'tnStdinRaw';
470
+ });
244
471
  value('stdout.fd', 'float64', () => 'float64(1)');
245
472
  value('stderr.fd', 'float64', () => 'float64(2)');
246
473
  value('stdin.fd', 'float64', () => 'float64(0)');
@@ -292,6 +519,21 @@ export function registerProcess(r) {
292
519
  use();
293
520
  return `TnProcessWrite(os.Stderr, ${call.args[0]})`;
294
521
  });
522
+ for (const stream of ['stdout', 'stderr']) {
523
+ const f = stream === 'stdout' ? 'os.Stdout' : 'os.Stderr';
524
+ fn(`${stream}.getWindowSize`, '[]float64', (_c) => {
525
+ tty();
526
+ return `TnTtyWindowSize(${f})`;
527
+ });
528
+ }
529
+ fn('stdin.setRawMode', '', (call) => {
530
+ tty();
531
+ return `TnTtySetRawMode(${call.args[0]})`;
532
+ });
533
+ fn('umask', 'float64', (call) => {
534
+ tty();
535
+ return `TnProcessUmask(${call.args.slice(0, 1).join(', ')})`;
536
+ });
295
537
  fn('nextTick', '', (call) => {
296
538
  r.helper('timerWait');
297
539
  const rest = call.args.slice(1).join(', ');