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/util.js CHANGED
@@ -192,7 +192,13 @@ func (ins *tnInspector) format(v interface{}, depth int) string {
192
192
  return x.String() + "n"
193
193
  case []byte:
194
194
  return TnBufferInspect(x)
195
+ case interface{ TnTypedInspect() (string, []float64) }:
196
+ name, values := x.TnTypedInspect()
197
+ return name + " " + ins.format(values, depth)
195
198
  case time.Time:
199
+ if x.IsZero() {
200
+ return "Invalid Date"
201
+ }
196
202
  return x.UTC().Format("2006-01-02T15:04:05.000Z07:00")
197
203
  case *regexp.Regexp:
198
204
  if x == nil {
@@ -324,8 +330,16 @@ func (ins *tnInspector) formatCompound(v interface{}, rv reflect.Value, depth in
324
330
  isTop := depth == 0
325
331
  if withEntries, ok := v.(interface{ Entries() [][]interface{} }); ok {
326
332
  entries = withEntries.Entries()
327
- if tnInspectSetLike(rv) {
333
+ // new Map() / new Set() are tagged; untagged maps are records unless a
334
+ // key is not a string
335
+ jsKind := uint8(0)
336
+ if tagged, ok := v.(interface{ TnJSKind() uint8 }); ok {
337
+ jsKind = tagged.TnJSKind()
338
+ }
339
+ if jsKind == 2 || (jsKind == 0 && tnInspectSetLike(rv)) {
328
340
  kind = "set"
341
+ } else if jsKind == 1 {
342
+ kind = "map"
329
343
  } else {
330
344
  kind = "map"
331
345
  stringKeys := true
@@ -759,6 +773,12 @@ func TnUtilFormat(args ...interface{}) string {
759
773
  } else {
760
774
  args[i] = *p
761
775
  }
776
+ case string:
777
+ default:
778
+ // String enum members (type E string) print as strings
779
+ if rv := reflect.ValueOf(a); rv.Kind() == reflect.String {
780
+ args[i] = rv.String()
781
+ }
762
782
  }
763
783
  }
764
784
  first, isString := args[0].(string)
@@ -253,31 +253,13 @@ func tnArgEntries(v interface{}) [][2]interface{} {
253
253
 
254
254
  // --- system errors ---
255
255
 
256
- var tnSystemErrors = map[string]syscall.Errno{
257
- "E2BIG": syscall.E2BIG, "EACCES": syscall.EACCES, "EADDRINUSE": syscall.EADDRINUSE, "EADDRNOTAVAIL": syscall.EADDRNOTAVAIL,
258
- "EAFNOSUPPORT": syscall.EAFNOSUPPORT, "EAGAIN": syscall.EAGAIN, "EALREADY": syscall.EALREADY, "EBADF": syscall.EBADF,
259
- "EBUSY": syscall.EBUSY, "ECANCELED": syscall.ECANCELED, "ECONNABORTED": syscall.ECONNABORTED, "ECONNREFUSED": syscall.ECONNREFUSED,
260
- "ECONNRESET": syscall.ECONNRESET, "EDESTADDRREQ": syscall.EDESTADDRREQ, "EEXIST": syscall.EEXIST, "EFAULT": syscall.EFAULT,
261
- "EFBIG": syscall.EFBIG, "EHOSTUNREACH": syscall.EHOSTUNREACH, "EINTR": syscall.EINTR, "EINVAL": syscall.EINVAL,
262
- "EIO": syscall.EIO, "EISCONN": syscall.EISCONN, "EISDIR": syscall.EISDIR, "ELOOP": syscall.ELOOP, "EMFILE": syscall.EMFILE,
263
- "EMLINK": syscall.EMLINK, "EMSGSIZE": syscall.EMSGSIZE, "ENAMETOOLONG": syscall.ENAMETOOLONG, "ENETDOWN": syscall.ENETDOWN,
264
- "ENETUNREACH": syscall.ENETUNREACH, "ENFILE": syscall.ENFILE, "ENOBUFS": syscall.ENOBUFS, "ENODEV": syscall.ENODEV,
265
- "ENOENT": syscall.ENOENT, "ENOMEM": syscall.ENOMEM, "ENOSPC": syscall.ENOSPC, "ENOSYS": syscall.ENOSYS,
266
- "ENOTCONN": syscall.ENOTCONN, "ENOTDIR": syscall.ENOTDIR, "ENOTEMPTY": syscall.ENOTEMPTY, "ENOTSOCK": syscall.ENOTSOCK,
267
- "ENOTSUP": syscall.ENOTSUP, "ENXIO": syscall.ENXIO, "EPERM": syscall.EPERM, "EPIPE": syscall.EPIPE,
268
- "EPROTO": syscall.EPROTO, "EPROTONOSUPPORT": syscall.EPROTONOSUPPORT, "EPROTOTYPE": syscall.EPROTOTYPE,
269
- "ERANGE": syscall.ERANGE, "EROFS": syscall.EROFS, "ESPIPE": syscall.ESPIPE, "ESRCH": syscall.ESRCH,
270
- "ETIMEDOUT": syscall.ETIMEDOUT, "ETXTBSY": syscall.ETXTBSY, "EXDEV": syscall.EXDEV,
271
- }
272
-
273
256
  func tnSystemErrorEntry(errno float64) (string, string, bool) {
274
257
  if errno >= 0 || errno != float64(int64(errno)) {
275
258
  panic(TnNodeError("RangeError", "ERR_OUT_OF_RANGE", "The value of \\"err\\" is out of range. It must be a negative integer. Received "+TnNumStr(errno)))
276
259
  }
277
- target := syscall.Errno(int64(-errno))
278
- for name, e := range tnSystemErrors {
279
- if e == target {
280
- return name, e.Error(), true
260
+ for _, e := range tnUvErrorList {
261
+ if tnUvErrnos[e[0]] == errno {
262
+ return e[0], e[1], true
281
263
  }
282
264
  }
283
265
  return "", "", false
@@ -301,14 +283,8 @@ func TnGetSystemErrorMessage(errno float64) string {
301
283
 
302
284
  func TnGetSystemErrorMap() *TnMap[float64, []string] {
303
285
  m := TnNewMap[float64, []string]()
304
- names := make([]string, 0, len(tnSystemErrors))
305
- for name := range tnSystemErrors {
306
- names = append(names, name)
307
- }
308
- sort.Slice(names, func(i, j int) bool { return tnSystemErrors[names[i]] < tnSystemErrors[names[j]] })
309
- for _, name := range names {
310
- e := tnSystemErrors[name]
311
- m.Set(-float64(e), []string{name, e.Error()})
286
+ for _, e := range tnUvErrorList {
287
+ m.Set(tnUvErrnos[e[0]], []string{e[0], e[1]})
312
288
  }
313
289
  return m
314
290
  }
@@ -560,7 +536,7 @@ func TnDebuglogEnabled(section string) bool { return tnDebugEnabled(section) }
560
536
  // toUSVString: invalid sequences become U+FFFD
561
537
  func TnToUSVString(s string) string { return strings.ToValidUTF8(s, "\uFFFD") }`;
562
538
  export function registerUtilExtra(r) {
563
- defineHelper(r, 'nodeUtilExtra', ['fmt', 'os', 'reflect', 'regexp', 'sort', 'strconv', 'strings', 'syscall', 'unsafe'], ['nodeUtil', 'dynamic', 'orderedMap', 'error', 'eventLoop', 'nodeEvents', 'fsErrors'], utilExtraHelper);
539
+ defineHelper(r, 'nodeUtilExtra', ['fmt', 'os', 'reflect', 'regexp', 'sort', 'strconv', 'strings', 'unsafe'], ['nodeUtil', 'dynamic', 'orderedMap', 'error', 'eventLoop', 'nodeEvents', 'fsErrors', 'uvErrno'], utilExtraHelper);
564
540
  const use = () => r.helper('nodeUtilExtra');
565
541
  const fn = (key, result, emit) => {
566
542
  r.functions[key] = (c) => {
@@ -6,8 +6,17 @@
6
6
  // workerData are set. MessageChannel / MessagePort / BroadcastChannel work
7
7
  // within one process. The worker's stdout / stderr are the parent's; an
8
8
  // uncaught exception in a worker becomes an 'error' event and exit code 1.
9
- import { defineClass, defineHelper, defineModule, setResults, isStringNode } from './registry.js';
9
+ import { defineClass, defineHelper, defineModule, setResults } from './registry.js';
10
10
  const cloneHelper = `// Structured clone (subset): values to and from JSON with type tags
11
+ // Objects keep their key order: {"$tn": "Object", "k": keys, "v": values}
12
+ func tnCloneObject(keys []string, values []interface{}) map[string]interface{} {
13
+ k := make([]interface{}, len(keys))
14
+ for i, key := range keys {
15
+ k[i] = key
16
+ }
17
+ return map[string]interface{}{"$tn": "Object", "k": k, "v": values}
18
+ }
19
+
11
20
  func tnCloneEncode(v interface{}) interface{} {
12
21
  switch x := v.(type) {
13
22
  case nil:
@@ -44,11 +53,16 @@ func tnCloneEncode(v interface{}) interface{} {
44
53
  }
45
54
  return map[string]interface{}{"$tn": "Error", "message": x.message, "code": x.code, "props": props}
46
55
  case map[string]interface{}:
47
- out := map[string]interface{}{}
48
- for k, val := range x {
49
- out[k] = tnCloneEncode(val)
56
+ keys := make([]string, 0, len(x))
57
+ for k := range x {
58
+ keys = append(keys, k)
50
59
  }
51
- return out
60
+ sort.Strings(keys)
61
+ values := make([]interface{}, len(keys))
62
+ for i, k := range keys {
63
+ values[i] = tnCloneEncode(x[k])
64
+ }
65
+ return tnCloneObject(keys, values)
52
66
  case []interface{}:
53
67
  out := make([]interface{}, len(x))
54
68
  for i, val := range x {
@@ -57,7 +71,30 @@ func tnCloneEncode(v interface{}) interface{} {
57
71
  return out
58
72
  }
59
73
  if withEntries, ok := v.(interface{ Entries() [][]interface{} }); ok {
60
- if _, isSet := v.(interface{ IsSet() bool }); isSet {
74
+ kind := uint8(0)
75
+ if tagged, ok := v.(interface{ TnJSKind() uint8 }); ok {
76
+ kind = tagged.TnJSKind()
77
+ }
78
+ // a record (string keys, not made by new Map()) is a plain object
79
+ if kind == 0 {
80
+ entries := withEntries.Entries()
81
+ keys := make([]string, 0, len(entries))
82
+ values := make([]interface{}, 0, len(entries))
83
+ plain := true
84
+ for _, e := range entries {
85
+ k, isString := e[0].(string)
86
+ if !isString {
87
+ plain = false
88
+ break
89
+ }
90
+ keys = append(keys, k)
91
+ values = append(values, tnCloneEncode(e[1]))
92
+ }
93
+ if plain {
94
+ return tnCloneObject(keys, values)
95
+ }
96
+ }
97
+ if kind == 2 {
61
98
  values := []interface{}{}
62
99
  for _, e := range withEntries.Entries() {
63
100
  values = append(values, tnCloneEncode(e[0]))
@@ -92,16 +129,18 @@ func tnCloneEncode(v interface{}) interface{} {
92
129
  }
93
130
  if rv.Elem().Kind() == reflect.Struct {
94
131
  sv := rv.Elem()
95
- out := map[string]interface{}{}
132
+ keys := []string{}
133
+ values := []interface{}{}
96
134
  for i := 0; i < sv.NumField(); i++ {
97
135
  f := sv.Field(i)
98
136
  if f.Kind() == reflect.Func {
99
137
  continue
100
138
  }
101
139
  value := reflect.NewAt(f.Type(), unsafe.Pointer(f.UnsafeAddr())).Elem().Interface()
102
- out[strings.TrimSuffix(sv.Type().Field(i).Name, "_")] = tnCloneEncode(value)
140
+ keys = append(keys, strings.TrimSuffix(sv.Type().Field(i).Name, "_"))
141
+ values = append(values, tnCloneEncode(value))
103
142
  }
104
- return out
143
+ return tnCloneObject(keys, values)
105
144
  }
106
145
  return tnCloneEncode(rv.Elem().Interface())
107
146
  case reflect.Float32, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
@@ -141,7 +180,7 @@ func tnCloneDecode(v interface{}) interface{} {
141
180
  }
142
181
  return e
143
182
  case "Map":
144
- m := TnNewMap[interface{}, interface{}]()
183
+ m := TnJSCollection(TnNewMap[interface{}, interface{}](), 1)
145
184
  if pairs, ok := x["v"].([]interface{}); ok {
146
185
  for _, p := range pairs {
147
186
  if pair, ok := p.([]interface{}); ok && len(pair) == 2 {
@@ -150,8 +189,19 @@ func tnCloneDecode(v interface{}) interface{} {
150
189
  }
151
190
  }
152
191
  return m
192
+ case "Object":
193
+ // an ordered record, as plain objects print and stringify in order
194
+ m := TnNewMap[string, interface{}]()
195
+ keys, _ := x["k"].([]interface{})
196
+ values, _ := x["v"].([]interface{})
197
+ for i, k := range keys {
198
+ if i < len(values) {
199
+ m.Set(TnJSString(k), tnCloneDecode(values[i]))
200
+ }
201
+ }
202
+ return m
153
203
  case "Set":
154
- m := TnNewMap[interface{}, interface{}]()
204
+ m := TnJSCollection(TnNewMap[interface{}, interface{}](), 2)
155
205
  if values, ok := x["v"].([]interface{}); ok {
156
206
  for _, val := range values {
157
207
  d := tnCloneDecode(val)
@@ -410,8 +460,10 @@ func init() {
410
460
  var setup map[string]interface{}
411
461
  json.Unmarshal(payload, &setup)
412
462
  TnWorkerData = tnCloneDecode(setup["workerData"])
413
- if env, ok := tnCloneDecode(setup["environmentData"]).(map[string]interface{}); ok {
414
- tnEnvironmentData = env
463
+ if env, ok := tnCloneDecode(setup["environmentData"]).(*TnMap[string, interface{}]); ok {
464
+ for _, k := range env.Keys() {
465
+ tnEnvironmentData[k] = env.Get(k)
466
+ }
415
467
  }
416
468
  TnThreadID, _ = setup["threadId"].(float64)
417
469
  port := tnNewPort()
@@ -463,6 +515,13 @@ type TnWorker struct {
463
515
 
464
516
  func (w *TnWorker) Get_threadId() float64 { return w.threadId }
465
517
 
518
+ // new Worker('./w.ts'): runs the entry point compiled from that file
519
+ func TnNewWorkerAt(entry string, filename interface{}, options ...interface{}) *TnWorker {
520
+ tnNextEntry = entry
521
+ defer func() { tnNextEntry = "" }()
522
+ return TnNewWorker(filename, options...)
523
+ }
524
+
466
525
  func TnNewWorker(filename interface{}, options ...interface{}) *TnWorker {
467
526
  tnNextThreadID++
468
527
  w := &TnWorker{threadId: tnNextThreadID}
@@ -505,6 +564,7 @@ func TnNewWorker(filename interface{}, options ...interface{}) *TnWorker {
505
564
  }
506
565
  }
507
566
  }
567
+ env = tnSpawnEntryEnv(env)
508
568
  env = append(env, "TN_WORKER_ADDR="+ln.Addr().String(), "TN_WORKER_TOKEN="+token)
509
569
  setup, err := json.Marshal(map[string]interface{}{
510
570
  "workerData": tnCloneEncode(workerData),
@@ -658,8 +718,8 @@ func (w *TnWorker) unref() *TnWorker {
658
718
  const EMITTER = 'on=*TnEventEmitter; once=*TnEventEmitter; addListener=*TnEventEmitter; off=*TnEventEmitter; removeListener=*TnEventEmitter; removeAllListeners=*TnEventEmitter; emit=bool; listenerCount=float64';
659
719
  export function registerWorkerThreads(r) {
660
720
  defineModule(r, 'worker_threads');
661
- defineHelper(r, 'nodeClone', ['encoding/base64', 'encoding/json', 'fmt', 'math/big', 'reflect', 'strings', 'time', 'unsafe'], ['dynamic', 'orderedMap', 'error'], cloneHelper);
662
- defineHelper(r, 'nodeWorker', ['bufio', 'crypto/rand', 'encoding/hex', 'encoding/json', 'fmt', 'net', 'os', 'os/exec', 'reflect', 'strings', 'sync', 'time'], ['nodeClone', 'nodeIpc', 'nodeEvents', 'eventLoop', 'nodeInvoke', 'dynamic', 'nodeChild'], workerHelper);
721
+ defineHelper(r, 'nodeClone', ['encoding/base64', 'encoding/json', 'fmt', 'math/big', 'reflect', 'sort', 'strings', 'time', 'unsafe'], ['dynamic', 'orderedMap', 'error'], cloneHelper);
722
+ defineHelper(r, 'nodeWorker', ['bufio', 'crypto/rand', 'encoding/hex', 'encoding/json', 'fmt', 'net', 'os', 'os/exec', 'reflect', 'strings', 'sync', 'time'], ['nodeClone', 'nodeIpc', 'nodeEvents', 'eventLoop', 'nodeInvoke', 'dynamic', 'nodeChild', 'entryPoints'], workerHelper);
663
723
  const use = () => r.helper('nodeWorker');
664
724
  defineClass(r, 'worker_threads.Worker', '*TnWorker', 'class', `${EMITTER}; postMessage=; terminate=chan float64; ref=*TnWorker; unref=*TnWorker`, '', 'threadId=float64', '');
665
725
  defineClass(r, 'worker_threads.MessagePort', '*TnMessagePort', 'class', `${EMITTER}; postMessage=; start=; close=; ref=*TnMessagePort; unref=*TnMessagePort; hasRef=bool`, '', 'onmessage=interface{}', 'onmessage');
@@ -686,10 +746,10 @@ export function registerWorkerThreads(r) {
686
746
  r.paramTypers['worker_threads.BroadcastChannel#addEventListener'] = (_n) => ['*TnMessageEvent'];
687
747
  r.constructors['worker_threads.Worker'] = (c) => {
688
748
  use();
689
- // The worker runs this program again: other files can't be loaded at runtime
690
- if (isStringNode(c.nodes[0]) && /\.(m?[jt]s|tsx?)$/.test(String(c.nodes[0].text))) {
691
- console.warn(`[TypeNative] new Worker('${c.nodes[0].text}') runs the current program; use new Worker(__filename) / new URL(import.meta.url) and branch on isMainThread`);
692
- }
749
+ // new Worker('./w.ts'): that file is compiled in as a second entry point
750
+ const entry = r.entryPoint(c.nodes[0]);
751
+ if (entry !== '')
752
+ return `TnNewWorkerAt(${JSON.stringify(entry)}, ${c.args.join(', ')})`;
693
753
  return `TnNewWorker(${c.args.join(', ')})`;
694
754
  };
695
755
  r.constructors['worker_threads.MessageChannel'] = (_c) => {
package/bin/node/zlib.js CHANGED
@@ -1,5 +1,6 @@
1
- // node:zlib — synchronous gzip / deflate (zlib format) / raw deflate, unzip
2
- // (auto-detect), crc32. Brotli has no Go standard-library codec.
1
+ // node:zlib — gzip / deflate (zlib format) / raw deflate, unzip (auto-detect),
2
+ // crc32 on Go's compress/*, and Brotli on the vendored
3
+ // github.com/andybalholm/brotli (pure Go; linked only into programs that use it).
3
4
  import { defineHelper, defineModule, setResults } from './registry.js';
4
5
  const zlibHelper = `// node:zlib
5
6
  func tnZlibInput(v interface{}) []byte {
@@ -40,7 +41,16 @@ func tnZlibError(err error) *TnError {
40
41
  return e
41
42
  }
42
43
 
43
- func tnCompress(format string, data []byte, level int) []byte {
44
+ // Set by the nodeBrotli helper, so the Brotli codec (a vendored module) is
45
+ // linked only into programs that use it
46
+ var tnBrotliEncode func(data []byte, options []interface{}) []byte
47
+ var tnBrotliDecode func(data []byte) []byte
48
+
49
+ func tnCompress(format string, data []byte, options []interface{}) []byte {
50
+ if format == "brotli" {
51
+ return tnBrotliEncode(data, options)
52
+ }
53
+ level := tnZlibLevel(options)
44
54
  var buf bytes.Buffer
45
55
  var w io.WriteCloser
46
56
  var err error
@@ -61,6 +71,9 @@ func tnCompress(format string, data []byte, level int) []byte {
61
71
  }
62
72
 
63
73
  func tnDecompress(format string, data []byte) []byte {
74
+ if format == "brotli" {
75
+ return tnBrotliDecode(data)
76
+ }
64
77
  var r io.Reader
65
78
  var err error
66
79
  if format == "unzip" {
@@ -95,7 +108,7 @@ func tnDecompress(format string, data []byte) []byte {
95
108
  }
96
109
 
97
110
  func TnZlibCompress(format string, data interface{}, options ...interface{}) []byte {
98
- return tnCompress(format, tnZlibInput(data), tnZlibLevel(options))
111
+ return tnCompress(format, tnZlibInput(data), options)
99
112
  }
100
113
 
101
114
  func TnZlibDecompress(format string, data interface{}, options ...interface{}) []byte {
@@ -107,7 +120,6 @@ func TnZlibAsync(compress bool, format string, data interface{}, rest ...interfa
107
120
  cb := rest[len(rest)-1]
108
121
  options := rest[:len(rest)-1]
109
122
  input := tnZlibInput(data)
110
- level := tnZlibLevel(options)
111
123
  ctx := TnAsyncSnapshot()
112
124
  TnLoopRef()
113
125
  go func() {
@@ -120,7 +132,7 @@ func TnZlibAsync(compress bool, format string, data interface{}, rest ...interfa
120
132
  }
121
133
  }()
122
134
  if compress {
123
- result = tnCompress(format, input, level)
135
+ result = tnCompress(format, input, options)
124
136
  } else {
125
137
  result = tnDecompress(format, input)
126
138
  }
@@ -142,7 +154,6 @@ func TnZlibAsync(compress bool, format string, data interface{}, rest ...interfa
142
154
  func TnZlibPromise(compress bool, format string, data interface{}, options ...interface{}) chan []byte {
143
155
  ch := make(chan []byte, 1)
144
156
  input := tnZlibInput(data)
145
- level := tnZlibLevel(options)
146
157
  TnLoopRef()
147
158
  go func() {
148
159
  var result []byte
@@ -154,7 +165,7 @@ func TnZlibPromise(compress bool, format string, data interface{}, options ...in
154
165
  }
155
166
  }()
156
167
  if compress {
157
- result = tnCompress(format, input, level)
168
+ result = tnCompress(format, input, options)
158
169
  } else {
159
170
  result = tnDecompress(format, input)
160
171
  }
@@ -178,6 +189,72 @@ func TnCrc32(data interface{}, value ...float64) float64 {
178
189
  }
179
190
  return float64(crc32.Update(crc, crc32.IEEETable, tnZlibInput(data)))
180
191
  }`;
192
+ const brotliHelper = `// node:zlib Brotli (github.com/andybalholm/brotli)
193
+ func init() {
194
+ tnBrotliEncode = tnBrotliCompress
195
+ tnBrotliDecode = tnBrotliDecompress
196
+ }
197
+
198
+ // Options: { params: { [BROTLI_PARAM_QUALITY]: q, [BROTLI_PARAM_LGWIN]: w } };
199
+ // out-of-range values are clamped, as in Node
200
+ func tnBrotliCompress(data []byte, options []interface{}) []byte {
201
+ opts := brotli.WriterOptions{Quality: 11}
202
+ if len(options) > 0 && options[0] != nil {
203
+ if params := TnGet(options[0], "params"); params != nil {
204
+ if q, ok := TnGet(params, "1").(float64); ok {
205
+ opts.Quality = min(max(int(q), 0), 11)
206
+ }
207
+ if w, ok := TnGet(params, "2").(float64); ok {
208
+ opts.LGWin = min(max(int(w), 10), 24)
209
+ }
210
+ }
211
+ }
212
+ var buf bytes.Buffer
213
+ w := brotli.NewWriterOptions(&buf, opts)
214
+ w.Write(data)
215
+ w.Close()
216
+ return buf.Bytes()
217
+ }
218
+
219
+ // Decoder error names (the library's) → Node's code suffix and errno
220
+ var tnBrotliErrors = map[string]int{
221
+ "EXUBERANT_NIBBLE": -1, "RESERVED": -2, "EXUBERANT_META_NIBBLE": -3, "SIMPLE_HUFFMAN_ALPHABET": -4,
222
+ "SIMPLE_HUFFMAN_SAME": -5, "CL_SPACE": -6, "HUFFMAN_SPACE": -7, "CONTEXT_MAP_REPEAT": -8,
223
+ "BLOCK_LENGTH_1": -9, "BLOCK_LENGTH_2": -10, "TRANSFORM": -11, "DICTIONARY": -12,
224
+ "WINDOW_BITS": -13, "PADDING_1": -14, "PADDING_2": -15, "DISTANCE": -16,
225
+ "DICTIONARY_NOT_SET": -19, "INVALID_ARGUMENTS": -20, "CONTEXT_MODES": -21, "TREE_GROUPS": -22,
226
+ "CONTEXT_MAP": -25, "RING_BUFFER_1": -26, "RING_BUFFER_2": -27, "BLOCK_TYPE_TREES": -30,
227
+ "UNREACHABLE": -31,
228
+ }
229
+
230
+ func tnBrotliDecompress(data []byte) []byte {
231
+ out, err := io.ReadAll(brotli.NewReader(bytes.NewReader(data)))
232
+ if err == nil || err.Error() == "brotli: excessive input" {
233
+ // Node ignores bytes after the end of the stream
234
+ return out
235
+ }
236
+ if err == io.ErrUnexpectedEOF || err == io.EOF {
237
+ e := TnNodeError("Error", "Z_BUF_ERROR", "unexpected end of file")
238
+ e.props["errno"] = float64(-5)
239
+ panic(e)
240
+ }
241
+ name := strings.TrimPrefix(err.Error(), "brotli: ")
242
+ errno, known := tnBrotliErrors[name]
243
+ if !known {
244
+ name, errno = "UNREACHABLE", -31
245
+ }
246
+ switch {
247
+ case errno >= -16:
248
+ name = "ERROR_FORMAT_" + name
249
+ case errno >= -20 || errno == -31:
250
+ name = "ERROR_" + name
251
+ default:
252
+ name = "ERROR_ALLOC_" + name
253
+ }
254
+ e := TnNodeError("Error", "ERR__"+name, "Decompression failed")
255
+ e.props["errno"] = float64(errno)
256
+ panic(e)
257
+ }`;
181
258
  const ZLIB_CONSTANTS = {
182
259
  Z_NO_FLUSH: 0,
183
260
  Z_SYNC_FLUSH: 2,
@@ -192,18 +269,48 @@ const ZLIB_CONSTANTS = {
192
269
  Z_BEST_COMPRESSION: 9,
193
270
  Z_DEFAULT_COMPRESSION: -1
194
271
  };
272
+ // zlib.constants only (Node does not copy these onto the module)
273
+ const BROTLI_CONSTANTS = {
274
+ BROTLI_DECODE: 8,
275
+ BROTLI_ENCODE: 9,
276
+ BROTLI_OPERATION_PROCESS: 0,
277
+ BROTLI_OPERATION_FLUSH: 1,
278
+ BROTLI_OPERATION_FINISH: 2,
279
+ BROTLI_OPERATION_EMIT_METADATA: 3,
280
+ BROTLI_PARAM_MODE: 0,
281
+ BROTLI_MODE_GENERIC: 0,
282
+ BROTLI_MODE_TEXT: 1,
283
+ BROTLI_MODE_FONT: 2,
284
+ BROTLI_DEFAULT_MODE: 0,
285
+ BROTLI_PARAM_QUALITY: 1,
286
+ BROTLI_MIN_QUALITY: 0,
287
+ BROTLI_MAX_QUALITY: 11,
288
+ BROTLI_DEFAULT_QUALITY: 11,
289
+ BROTLI_PARAM_LGWIN: 2,
290
+ BROTLI_MIN_WINDOW_BITS: 10,
291
+ BROTLI_MAX_WINDOW_BITS: 24,
292
+ BROTLI_DEFAULT_WINDOW: 22,
293
+ BROTLI_PARAM_LGBLOCK: 3,
294
+ BROTLI_PARAM_SIZE_HINT: 5,
295
+ BROTLI_DECODER_RESULT_ERROR: 0,
296
+ BROTLI_DECODER_RESULT_SUCCESS: 1
297
+ };
195
298
  export function registerZlib(r) {
196
299
  defineModule(r, 'zlib');
197
300
  defineHelper(r, 'nodeZlib', ['bytes', 'compress/flate', 'compress/gzip', 'compress/zlib', 'hash/crc32', 'io', 'strings'], ['error', 'buffer', 'dynamic', 'eventLoop', 'promise', 'nodeInvoke'], zlibHelper);
301
+ defineHelper(r, 'nodeBrotli', ['bytes', 'github.com/andybalholm/brotli', 'io', 'strings'], ['nodeZlib'], brotliHelper);
302
+ // Brotli entries pull in the codec helper too
303
+ const use = (format) => r.helper(format === 'brotli' ? 'nodeBrotli' : 'nodeZlib');
198
304
  const formats = {
199
305
  gzipSync: 'gzip',
200
306
  deflateSync: 'deflate',
201
- deflateRawSync: 'deflateRaw'
307
+ deflateRawSync: 'deflateRaw',
308
+ brotliCompressSync: 'brotli'
202
309
  };
203
310
  for (const name of Object.keys(formats)) {
204
311
  const format = formats[name];
205
312
  r.functions[`zlib.${name}`] = (call) => {
206
- r.helper('nodeZlib');
313
+ use(format);
207
314
  return `TnZlibCompress(${JSON.stringify(format)}, ${call.args.join(', ')})`;
208
315
  };
209
316
  r.results[`zlib.${name}`] = '[]byte';
@@ -212,12 +319,13 @@ export function registerZlib(r) {
212
319
  gunzipSync: 'gunzip',
213
320
  inflateSync: 'inflate',
214
321
  inflateRawSync: 'inflateRaw',
215
- unzipSync: 'unzip'
322
+ unzipSync: 'unzip',
323
+ brotliDecompressSync: 'brotli'
216
324
  };
217
325
  for (const name of Object.keys(decoders)) {
218
326
  const format = decoders[name];
219
327
  r.functions[`zlib.${name}`] = (call) => {
220
- r.helper('nodeZlib');
328
+ use(format);
221
329
  return `TnZlibDecompress(${JSON.stringify(format)}, ${call.args.join(', ')})`;
222
330
  };
223
331
  r.results[`zlib.${name}`] = '[]byte';
@@ -230,19 +338,21 @@ export function registerZlib(r) {
230
338
  gunzip: 'gunzip',
231
339
  inflate: 'inflate',
232
340
  inflateRaw: 'inflateRaw',
233
- unzip: 'unzip'
341
+ unzip: 'unzip',
342
+ brotliCompress: 'brotli',
343
+ brotliDecompress: 'brotli'
234
344
  };
235
345
  for (const name of Object.keys(asyncForms)) {
236
346
  const format = asyncForms[name];
237
- const compress = name === 'gzip' || name === 'deflate' || name === 'deflateRaw' ? 'true' : 'false';
347
+ const compress = name === 'gzip' || name === 'deflate' || name === 'deflateRaw' || name === 'brotliCompress' ? 'true' : 'false';
238
348
  r.functions[`zlib.${name}`] = (call) => {
239
- r.helper('nodeZlib');
349
+ use(format);
240
350
  return `TnZlibAsync(${compress}, ${JSON.stringify(format)}, ${call.args.join(', ')})`;
241
351
  };
242
352
  r.results[`zlib.${name}`] = '';
243
353
  r.paramTypers[`zlib.${name}`] = (_n) => ['*TnError', '[]byte'];
244
354
  r.functions[`zlib.${name}.__promisify__`] = (call) => {
245
- r.helper('nodeZlib');
355
+ use(format);
246
356
  return `TnZlibPromise(${compress}, ${JSON.stringify(format)}, ${call.args.join(', ')})`;
247
357
  };
248
358
  r.results[`zlib.${name}.__promisify__`] = 'chan []byte';
@@ -260,4 +370,9 @@ export function registerZlib(r) {
260
370
  r.values[`zlib.${name}`] = r.values[`zlib.constants.${name}`];
261
371
  r.valueTypes[`zlib.${name}`] = 'float64';
262
372
  }
373
+ for (const name of Object.keys(BROTLI_CONSTANTS)) {
374
+ const value = BROTLI_CONSTANTS[name];
375
+ r.values[`zlib.constants.${name}`] = (_c) => `float64(${value})`;
376
+ r.valueTypes[`zlib.constants.${name}`] = 'float64';
377
+ }
263
378
  }