typenative 0.4.0 → 0.5.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 (167) hide show
  1. package/.github/workflows/ci.yml +2 -0
  2. package/CHANGELOG.md +372 -0
  3. package/CONTRIBUTION.md +1 -1
  4. package/README.md +62 -22
  5. package/ROUND2-HANDOFF.md +200 -0
  6. package/bin/cli.js +2 -0
  7. package/bin/go/bridge.js +74 -14
  8. package/bin/go/convert.js +48 -0
  9. package/bin/go/metadata.js +13 -4
  10. package/bin/go/overrides.js +4 -6
  11. package/bin/go/stdlib.generated.js +2 -0
  12. package/bin/index.js +130 -2
  13. package/bin/main.js +2 -0
  14. package/bin/node/assert.js +2 -2
  15. package/bin/node/async_hooks.js +1 -1
  16. package/bin/node/buffer.js +16 -5
  17. package/bin/node/child_process.js +57 -9
  18. package/bin/node/cluster.js +44 -6
  19. package/bin/node/core.js +1 -1
  20. package/bin/node/crypto.js +205 -4
  21. package/bin/node/crypto_keys.js +21 -21
  22. package/bin/node/dgram.js +231 -7
  23. package/bin/node/diagnostics_channel.js +3 -3
  24. package/bin/node/dns.js +472 -9
  25. package/bin/node/errno_tables.js +445 -0
  26. package/bin/node/events.js +3 -3
  27. package/bin/node/fetch.js +2 -2
  28. package/bin/node/fs.js +24 -17
  29. package/bin/node/fs_watch.js +5 -5
  30. package/bin/node/http.js +131 -33
  31. package/bin/node/http2.js +7 -4
  32. package/bin/node/module_v8.js +142 -0
  33. package/bin/node/net.js +17 -14
  34. package/bin/node/path.js +17 -3
  35. package/bin/node/process.js +274 -9
  36. package/bin/node/readline.js +272 -1
  37. package/bin/node/registry.js +5 -1
  38. package/bin/node/sqlite.js +65 -17
  39. package/bin/node/stream.js +220 -22
  40. package/bin/node/stream_web.js +10 -10
  41. package/bin/node/system_extra.js +3 -3
  42. package/bin/node/test.js +834 -234
  43. package/bin/node/test_coverage.js +187 -0
  44. package/bin/node/test_report.js +1392 -0
  45. package/bin/node/test_run.js +575 -0
  46. package/bin/node/timers.js +4 -4
  47. package/bin/node/tls.js +5 -5
  48. package/bin/node/url.js +23 -5
  49. package/bin/node/util.js +49 -8
  50. package/bin/node/util_extra.js +13 -37
  51. package/bin/node/webview.js +654 -0
  52. package/bin/node/worker_threads.js +80 -20
  53. package/bin/node/zlib.js +3 -3
  54. package/bin/parse-node.js +4 -0
  55. package/bin/transpiler.js +14457 -1723
  56. package/bin/typecheck-node.js +1 -0
  57. package/bin/version.js +1 -1
  58. package/conformance.md +1153 -884
  59. package/examples/README.md +47 -10
  60. package/examples/desktop-notes/README.md +108 -0
  61. package/examples/desktop-notes/bench.mjs +125 -0
  62. package/examples/desktop-notes/main.ts +131 -0
  63. package/examples/desktop-notes/package-lock.json +726 -0
  64. package/examples/desktop-notes/package.json +9 -0
  65. package/examples/desktop-notes/ui.ts +176 -0
  66. package/examples/dupe-finder/README.md +76 -0
  67. package/examples/dupe-finder/bench.mjs +120 -0
  68. package/examples/dupe-finder/main.ts +87 -0
  69. package/examples/json-server/README.md +31 -29
  70. package/examples/json-server/bench.mjs +130 -38
  71. package/examples/mandelbrot-png/README.md +65 -0
  72. package/examples/mandelbrot-png/bench.mjs +95 -0
  73. package/examples/mandelbrot-png/main.ts +98 -0
  74. package/examples/mandelbrot-png/preview.png +0 -0
  75. package/examples/marked-cli/README.md +159 -0
  76. package/examples/marked-cli/bench.mjs +178 -0
  77. package/examples/marked-cli/main.ts +292 -0
  78. package/examples/marked-cli/parity.mjs +185 -0
  79. package/examples/marked-cli/vendor/marked/LICENSE +44 -0
  80. package/examples/marked-cli/vendor/marked/VENDOR.md +26 -0
  81. package/examples/todo-cli/README.md +69 -0
  82. package/examples/todo-cli/bench.mjs +89 -0
  83. package/examples/todo-cli/main.ts +92 -0
  84. package/examples/yaml-cli/README.md +136 -0
  85. package/examples/yaml-cli/bench.mjs +265 -0
  86. package/examples/yaml-cli/main.ts +29 -0
  87. package/examples/yaml-cli/parity.mjs +156 -0
  88. package/examples/yaml-cli/vendor/yaml/LICENSE +13 -0
  89. package/examples/yaml-cli/vendor/yaml/VENDOR.md +25 -0
  90. package/govendor/github.com/jchv/go-webview2/LICENSE +22 -0
  91. package/govendor/github.com/jchv/go-webview2/README.md +21 -0
  92. package/govendor/github.com/jchv/go-webview2/common.go +84 -0
  93. package/govendor/github.com/jchv/go-webview2/go.mod +3 -0
  94. package/govendor/github.com/jchv/go-webview2/internal/w32/w32.go +194 -0
  95. package/govendor/github.com/jchv/go-webview2/internal/w32/w32_386.go +14 -0
  96. package/govendor/github.com/jchv/go-webview2/internal/w32/w32_64bit.go +15 -0
  97. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_COLOR.go +8 -0
  98. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_HOST_RESOURCE_ACCESS_KIND.go +9 -0
  99. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_KEY_EVENT_KIND.go +10 -0
  100. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_MOVE_FOCUS_REASON.go +9 -0
  101. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_PHYSICAL_KEY_STATUS.go +10 -0
  102. package/govendor/github.com/jchv/go-webview2/pkg/edge/COREWEBVIEW2_WEB_RESOURCE_CONTEXT.go +23 -0
  103. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2AcceleratorKeyPressedEventArgs.go +78 -0
  104. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2AcceleratorKeyPressedEventHandler.go +52 -0
  105. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Controller.go +132 -0
  106. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Controller2.go +74 -0
  107. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2CreateCoreWebView2ControllerCompletedHandler.go +48 -0
  108. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2NavigationCompletedEventArgs.go +17 -0
  109. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2NavigationCompletedEventHandler.go +48 -0
  110. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2Settings.go +270 -0
  111. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequest.go +43 -0
  112. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequestedEventArgs.go +51 -0
  113. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceRequestedEventHandler.go +48 -0
  114. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2WebResourceResponse.go +21 -0
  115. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2_2.go +21 -0
  116. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebView2_3.go +60 -0
  117. package/govendor/github.com/jchv/go-webview2/pkg/edge/ICoreWebViewSettings.go +396 -0
  118. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium.go +361 -0
  119. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_386.go +24 -0
  120. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_amd64.go +22 -0
  121. package/govendor/github.com/jchv/go-webview2/pkg/edge/chromium_arm64.go +26 -0
  122. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc.go +13 -0
  123. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc_go17.go +51 -0
  124. package/govendor/github.com/jchv/go-webview2/pkg/edge/comproc_go18.go +16 -0
  125. package/govendor/github.com/jchv/go-webview2/pkg/edge/corewebview2.go +411 -0
  126. package/govendor/github.com/jchv/go-webview2/pkg/edge/guid.go +223 -0
  127. package/govendor/github.com/jchv/go-webview2/webview.go +482 -0
  128. package/govendor/github.com/jchv/go-webview2/webviewloader/README.md +3 -0
  129. package/govendor/github.com/jchv/go-webview2/webviewloader/module.go +153 -0
  130. package/govendor/github.com/jchv/go-webview2/webviewloader/module_386.go +6 -0
  131. package/govendor/github.com/jchv/go-webview2/webviewloader/module_amd64.go +6 -0
  132. package/govendor/github.com/jchv/go-webview2/webviewloader/module_arm64.go +6 -0
  133. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/arm64/WebView2Loader.dll +0 -0
  134. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/x64/WebView2Loader.dll +0 -0
  135. package/govendor/github.com/jchv/go-webview2/webviewloader/sdk/x86/WebView2Loader.dll +0 -0
  136. package/govendor/github.com/jchv/go-winloader/LICENSE.md +7 -0
  137. package/govendor/github.com/jchv/go-winloader/README.md +124 -0
  138. package/govendor/github.com/jchv/go-winloader/common.go +11 -0
  139. package/govendor/github.com/jchv/go-winloader/go.mod +3 -0
  140. package/govendor/github.com/jchv/go-winloader/internal/loader/loader.go +25 -0
  141. package/govendor/github.com/jchv/go-winloader/internal/loader/machine.go +53 -0
  142. package/govendor/github.com/jchv/go-winloader/internal/memloader/cache.go +42 -0
  143. package/govendor/github.com/jchv/go-winloader/internal/memloader/loader.go +253 -0
  144. package/govendor/github.com/jchv/go-winloader/internal/pe/export.go +76 -0
  145. package/govendor/github.com/jchv/go-winloader/internal/pe/format.go +522 -0
  146. package/govendor/github.com/jchv/go-winloader/internal/pe/import.go +106 -0
  147. package/govendor/github.com/jchv/go-winloader/internal/pe/module.go +91 -0
  148. package/govendor/github.com/jchv/go-winloader/internal/pe/reloc.go +177 -0
  149. package/govendor/github.com/jchv/go-winloader/internal/pe/util.go +40 -0
  150. package/govendor/github.com/jchv/go-winloader/internal/vmem/common.go +55 -0
  151. package/govendor/github.com/jchv/go-winloader/internal/vmem/memory_other.go +71 -0
  152. package/govendor/github.com/jchv/go-winloader/internal/vmem/memory_windows.go +179 -0
  153. package/govendor/github.com/jchv/go-winloader/internal/winloader/hacks_other.go +17 -0
  154. package/govendor/github.com/jchv/go-winloader/internal/winloader/hacks_windows.go +73 -0
  155. package/govendor/github.com/jchv/go-winloader/internal/winloader/loader_windows.go +64 -0
  156. package/govendor/github.com/jchv/go-winloader/internal/winloader/machine_windows.go +32 -0
  157. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_386.go +9 -0
  158. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_amd64.go +9 -0
  159. package/govendor/github.com/jchv/go-winloader/internal/winloader/nativearch_arm64.go +9 -0
  160. package/govendor/github.com/jchv/go-winloader/loader_other.go +24 -0
  161. package/govendor/github.com/jchv/go-winloader/loader_windows.go +33 -0
  162. package/govendor/manifest.txt +3 -1
  163. package/package.json +1 -1
  164. package/tsparser/main.go +4 -0
  165. package/types/typenative-go.d.ts +23 -0
  166. package/types/typenative-npm.d.ts +359 -7
  167. package/types/typenative.d.ts +283 -42
package/bin/node/http.js CHANGED
@@ -274,28 +274,43 @@ func tnNewIncoming() *TnIncomingMessage {
274
274
  return m
275
275
  }
276
276
 
277
- // Streams a body into the message on a goroutine; done runs (off the loop) at the end
278
- func tnPumpBody(body io.ReadCloser, m *TnIncomingMessage, done func()) {
277
+ // Read buffers of the body pumps (chunks are copied out of them)
278
+ var tnBodyBufs = sync.Pool{New: func() any { b := make([]byte, 32768); return &b }}
279
+
280
+ // Streams a body into the message on a goroutine; atEOF (optional) runs on the
281
+ // loop just before the end of the stream, done (off the loop) at the end
282
+ func tnPumpBody(body io.ReadCloser, m *TnIncomingMessage, atEOF func(), done func()) {
279
283
  go func() {
280
284
  defer done()
281
285
  defer body.Close()
282
- buf := make([]byte, 32768)
286
+ bp := tnBodyBufs.Get().(*[]byte)
287
+ defer tnBodyBufs.Put(bp)
283
288
  for {
284
- n, err := body.Read(buf)
289
+ n, err := body.Read(*bp)
290
+ var chunk []byte
285
291
  if n > 0 {
286
- chunk := append([]byte{}, buf[:n]...)
287
- TnLoopPost(func() {
288
- if !m.destroyed {
289
- m.push(chunk)
290
- }
291
- })
292
+ chunk = append([]byte{}, (*bp)[:n]...)
293
+ if err == nil {
294
+ tnLoopRunOrPost(func() {
295
+ if !m.destroyed {
296
+ m.push(chunk)
297
+ }
298
+ })
299
+ }
292
300
  }
293
301
  if err != nil {
294
- TnLoopPost(func() {
302
+ // The last chunk usually comes with the EOF: one task for both
303
+ tnLoopRunOrPost(func() {
295
304
  if m.destroyed {
296
305
  return
297
306
  }
307
+ if chunk != nil {
308
+ m.push(chunk)
309
+ }
298
310
  if err == io.EOF {
311
+ if atEOF != nil {
312
+ atEOF()
313
+ }
299
314
  m.complete = true
300
315
  m.push(nil)
301
316
  return
@@ -326,10 +341,13 @@ func tnInfoSocket(local net.Addr, remote string) *TnSocket {
326
341
 
327
342
  // One operation of a response, applied by the handler goroutine
328
343
  type tnResOp struct {
329
- status int
330
- header http.Header
344
+ status int
345
+ header http.Header
346
+ trailer http.Header
331
347
  data []byte
332
348
  end bool
349
+ // Header ops: send the headers now (flushHeaders) instead of with the body
350
+ flush bool
333
351
  done func(err error)
334
352
  }
335
353
 
@@ -346,16 +364,25 @@ type TnServerResponse struct {
346
364
  mu sync.Mutex
347
365
  ops []tnResOp
348
366
  signal chan struct{}
367
+ trailer http.Header
368
+ // end(chunk) is writing its chunk; endPosted: that write also ended the response
369
+ lastWrite bool
370
+ endPosted bool
349
371
  }
350
372
 
351
373
  func (res *TnServerResponse) Get_headersSent() bool { return res.headersSent }
352
374
  func (res *TnServerResponse) Get_req() *TnIncomingMessage { return res.req }
353
375
  func (res *TnServerResponse) Get_socket() *TnSocket { return res.req.socket }
354
376
 
355
- func (res *TnServerResponse) post(op tnResOp) {
377
+ // Queues an op without waking the handler goroutine (it goes out with the next post)
378
+ func (res *TnServerResponse) queue(op tnResOp) {
356
379
  res.mu.Lock()
357
380
  res.ops = append(res.ops, op)
358
381
  res.mu.Unlock()
382
+ }
383
+
384
+ func (res *TnServerResponse) post(op tnResOp) {
385
+ res.queue(op)
359
386
  select {
360
387
  case res.signal <- struct{}{}:
361
388
  default:
@@ -401,6 +428,19 @@ func (res *TnServerResponse) appendHeader(name string, value interface{}) *TnSer
401
428
  return res
402
429
  }
403
430
 
431
+ // addTrailers(headers): sent after a chunked body (Node, too, sends them only
432
+ // without a Content-Length)
433
+ func (res *TnServerResponse) addTrailers(headers interface{}) {
434
+ if res.trailer == nil {
435
+ res.trailer = http.Header{}
436
+ }
437
+ for _, e := range tnEntries(headers) {
438
+ for _, v := range tnHeaderStrings(e[1]) {
439
+ res.trailer.Add(fmt.Sprint(e[0]), v)
440
+ }
441
+ }
442
+ }
443
+
404
444
  func (res *TnServerResponse) getHeader(name string) interface{} { return res.store.get(name) }
405
445
  func (res *TnServerResponse) getHeaders() *TnMap[string, interface{}] { return res.store.record() }
406
446
  func (res *TnServerResponse) getHeaderNames() []string { return res.store.keys() }
@@ -422,13 +462,16 @@ func (res *TnServerResponse) writeHead(status float64, args ...interface{}) *TnS
422
462
  }
423
463
  }
424
464
  }
425
- res.post(res.headerOp())
465
+ // As in Node, the headers go out with the first write or end()
466
+ res.queue(res.headerOp())
426
467
  return res
427
468
  }
428
469
 
429
470
  func (res *TnServerResponse) flushHeaders() {
430
471
  if !res.headersSent {
431
- res.post(res.headerOp())
472
+ op := res.headerOp()
473
+ op.flush = true
474
+ res.post(op)
432
475
  }
433
476
  }
434
477
 
@@ -445,7 +488,11 @@ func (res *TnServerResponse) end(args ...interface{}) *TnServerResponse {
445
488
  if len(args) > 1 {
446
489
  enc, _ = args[1].(string)
447
490
  }
448
- size = len(TnBufferFromString(d, enc))
491
+ if tnEncoding(enc) == "utf8" {
492
+ size = len(d)
493
+ } else {
494
+ size = len(TnBufferFromString(d, enc))
495
+ }
449
496
  case []byte:
450
497
  size = len(d)
451
498
  }
@@ -454,6 +501,7 @@ func (res *TnServerResponse) end(args ...interface{}) *TnServerResponse {
454
501
  res.store.set("Content-Length", strconv.Itoa(size))
455
502
  }
456
503
  }
504
+ res.lastWrite = true
457
505
  res.TnStream.end(args...)
458
506
  return res
459
507
  }
@@ -469,7 +517,7 @@ func tnNewServerResponse(req *TnIncomingMessage) *TnServerResponse {
469
517
  res.tnSelf = res
470
518
  res.sink = func(chunk interface{}, done func(err interface{})) {
471
519
  if !res.headersSent {
472
- res.post(res.headerOp())
520
+ res.queue(res.headerOp())
473
521
  }
474
522
  var data []byte
475
523
  switch c := chunk.(type) {
@@ -479,7 +527,13 @@ func tnNewServerResponse(req *TnIncomingMessage) *TnServerResponse {
479
527
  data = []byte(c)
480
528
  }
481
529
  res.wroteData = true
482
- res.post(tnResOp{data: data, done: func(err error) {
530
+ // end(chunk)'s last chunk also ends the response: the handler goroutine
531
+ // finishes without another round trip through the loop
532
+ last := res.lastWrite && len(res.writeQueue) == 0
533
+ if last {
534
+ res.endPosted = true
535
+ }
536
+ res.post(tnResOp{data: data, end: last, trailer: res.trailer, done: func(err error) {
483
537
  TnLoopPost(func() {
484
538
  if err != nil {
485
539
  done(TnNetError(err, "write", "", -1))
@@ -490,10 +544,14 @@ func tnNewServerResponse(req *TnIncomingMessage) *TnServerResponse {
490
544
  }})
491
545
  }
492
546
  res.sinkFinal = func(done func(err interface{})) {
547
+ if res.endPosted {
548
+ done(nil)
549
+ return
550
+ }
493
551
  if !res.headersSent {
494
- res.post(res.headerOp())
552
+ res.queue(res.headerOp())
495
553
  }
496
- res.post(tnResOp{end: true, done: func(err error) {
554
+ res.post(tnResOp{end: true, trailer: res.trailer, done: func(err error) {
497
555
  TnLoopPost(func() { done(nil) })
498
556
  }})
499
557
  }
@@ -546,10 +604,20 @@ func (hs *TnHttpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
546
604
  return
547
605
  }
548
606
  http.NewResponseController(w).EnableFullDuplex()
549
- // The messages are created on the loop (streams capture its async context)
607
+ // The messages are created on the loop (streams capture its async context);
608
+ // when it is idle, right here
550
609
  created := make(chan *TnServerResponse, 1)
551
610
  bodyDone := make(chan struct{})
552
- TnLoopPost(func() {
611
+ // A small body that comes with the headers (a Content-Length, no Expect:
612
+ // 100-continue) is read here first, so the request needs no reader goroutine
613
+ var small []byte
614
+ var smallErr error
615
+ if r.ProtoMajor == 1 && r.ContentLength > 0 && r.ContentLength <= 65536 && r.Header.Get("Expect") == "" {
616
+ small = make([]byte, r.ContentLength)
617
+ _, smallErr = io.ReadFull(r.Body, small)
618
+ r.Body.Close()
619
+ }
620
+ tnLoopRunOrPost(func() {
553
621
  TnAsyncRun(hs.asyncCtx, func() {
554
622
  req := hs.incoming(r, local)
555
623
  req.socket = tnInfoSocket(local, r.RemoteAddr)
@@ -559,7 +627,24 @@ func (hs *TnHttpServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
559
627
  res := tnNewServerResponse(req)
560
628
  created <- res
561
629
  hs.emit("request", req, res)
562
- tnPumpBody(r.Body, req, func() { close(bodyDone) })
630
+ if small != nil {
631
+ if smallErr != nil {
632
+ req.aborted = true
633
+ req.destroy(TnNodeError("Error", "ECONNRESET", "aborted"))
634
+ } else {
635
+ req.push(small)
636
+ req.complete = true
637
+ req.push(nil)
638
+ }
639
+ close(bodyDone)
640
+ } else if r.Body == nil || r.Body == http.NoBody {
641
+ // No body: the request ends at once, without a reader goroutine
642
+ req.complete = true
643
+ req.push(nil)
644
+ close(bodyDone)
645
+ } else {
646
+ tnPumpBody(r.Body, req, nil, func() { close(bodyDone) })
647
+ }
563
648
  })
564
649
  })
565
650
  res := <-created
@@ -683,10 +768,21 @@ func tnServeOps(w http.ResponseWriter, r *http.Request, res *TnServerResponse, a
683
768
  }
684
769
  }
685
770
  w.WriteHeader(op.status)
686
- rc.Flush()
771
+ if op.flush {
772
+ rc.Flush()
773
+ }
687
774
  case op.end:
775
+ // end(chunk): its data goes out with the headers; net/http flushes
776
+ // once the handler returns
777
+ var err error
778
+ if len(op.data) > 0 {
779
+ _, err = w.Write(op.data)
780
+ }
781
+ for k, v := range op.trailer {
782
+ w.Header()[http.TrailerPrefix+k] = v
783
+ }
688
784
  ended = true
689
- op.done(nil)
785
+ op.done(err)
690
786
  default:
691
787
  _, err := w.Write(op.data)
692
788
  if err == nil {
@@ -799,7 +895,7 @@ func TnNewHttpAgent(options ...interface{}) *TnHttpAgent {
799
895
  a := &TnHttpAgent{maxSockets: math.Inf(1)}
800
896
  if len(options) > 0 && options[0] != nil {
801
897
  a.options = options[0]
802
- a.keepAlive, _ = TnGet(options[0], "keepAlive").(bool)
898
+ a.keepAlive, _ = TnGetValue(options[0], "keepAlive").(bool)
803
899
  if n, ok := tnNetNumber(TnGet(options[0], "maxSockets")); ok {
804
900
  a.maxSockets = n
805
901
  }
@@ -1215,12 +1311,14 @@ func (cr *TnClientRequest) start(body []byte, complete bool) {
1215
1311
  } else {
1216
1312
  res.resume()
1217
1313
  }
1314
+ // The trailers are read with the end of the body, before 'end'
1218
1315
  tnPumpBody(resp.Body, res, func() {
1316
+ for k, v := range resp.Trailer {
1317
+ res.trailers.Set(strings.ToLower(k), strings.Join(v, ", "))
1318
+ }
1319
+ }, func() {
1219
1320
  TnLoopPost(func() {
1220
1321
  defer TnLoopUnref()
1221
- for k, v := range resp.Trailer {
1222
- res.trailers.Set(strings.ToLower(k), strings.Join(v, ", "))
1223
- }
1224
1322
  cr.closeHeld = false
1225
1323
  cr.emitClose()
1226
1324
  })
@@ -1311,11 +1409,11 @@ func TnHttpRequest(secure bool, args ...interface{}) *TnClientRequest {
1311
1409
  cr.timeoutMs = n
1312
1410
  }
1313
1411
  cr.store.setAll(TnGet(options, "headers"))
1314
- if b, ok := TnGet(options, "rejectUnauthorized").(bool); ok && !b {
1412
+ if b, ok := TnGetValue(options, "rejectUnauthorized").(bool); ok && !b {
1315
1413
  insecure = true
1316
1414
  }
1317
1415
  ca = tnPemStrings(TnGet(options, "ca"))
1318
- if sig, ok := TnGet(options, "signal").(*TnAbortSignal); ok && sig != nil {
1416
+ if sig, ok := TnGetValue(options, "signal").(*TnAbortSignal); ok && sig != nil {
1319
1417
  cr.signal = sig
1320
1418
  }
1321
1419
  }
@@ -1397,7 +1495,7 @@ func TnHttpGet(secure bool, args ...interface{}) *TnClientRequest {
1397
1495
  const CLIENT_REQUEST_METHODS = STREAM_METHODS.replace('end=*TnStream', 'end=*TnClientRequest').replace('destroy=*TnStream', 'destroy=*TnClientRequest') +
1398
1496
  '; setHeader=*TnClientRequest; getHeader=interface{}; getHeaders=*TnMap[string, interface{}]; getHeaderNames=[]string; getRawHeaderNames=[]string; hasHeader=bool; removeHeader=; flushHeaders=; setTimeout=*TnClientRequest; setNoDelay=; setSocketKeepAlive=; abort=';
1399
1497
  const SERVER_RESPONSE_METHODS = STREAM_METHODS.replace('end=*TnStream', 'end=*TnServerResponse') +
1400
- '; setHeader=*TnServerResponse; setHeaders=*TnServerResponse; appendHeader=*TnServerResponse; getHeader=interface{}; getHeaders=*TnMap[string, interface{}]; getHeaderNames=[]string; hasHeader=bool; removeHeader=; writeHead=*TnServerResponse; flushHeaders=; writeContinue=; setTimeout=*TnServerResponse';
1498
+ '; setHeader=*TnServerResponse; setHeaders=*TnServerResponse; appendHeader=*TnServerResponse; getHeader=interface{}; getHeaders=*TnMap[string, interface{}]; getHeaderNames=[]string; hasHeader=bool; removeHeader=; addTrailers=; writeHead=*TnServerResponse; flushHeaders=; writeContinue=; setTimeout=*TnServerResponse';
1401
1499
  function eventName(nodes) {
1402
1500
  const event = nodes[0];
1403
1501
  return event && event.kind === 'StringLiteral' ? String(event.text) : '';
package/bin/node/http2.js CHANGED
@@ -324,11 +324,14 @@ func (st *TnHttp2Stream) respond(args ...interface{}) {
324
324
  }
325
325
  }
326
326
  st.res.statusCode = float64(status)
327
- 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)
328
331
  st.headersSent = true
329
332
  st.sentHeaders = sent
330
333
  if len(args) > 1 && args[1] != nil {
331
- if end, _ := TnGet(args[1], "endStream").(bool); end {
334
+ if end, _ := TnGetValue(args[1], "endStream").(bool); end {
332
335
  st.end()
333
336
  }
334
337
  }
@@ -460,7 +463,7 @@ func TnHttp2CreateServer(secure bool, args ...interface{}) *TnHttpServer {
460
463
  allowHTTP1 := false
461
464
  for _, a := range args {
462
465
  if a != nil && !tnIsFunc(a) {
463
- allowHTTP1, _ = TnGet(a, "allowHTTP1").(bool)
466
+ allowHTTP1, _ = TnGetValue(a, "allowHTTP1").(bool)
464
467
  }
465
468
  }
466
469
  if hs.tlsConfig == nil {
@@ -518,7 +521,7 @@ func (s *TnHttp2Session) request(headers interface{}, options ...interface{}) *T
518
521
  }
519
522
  endStream := false
520
523
  if len(options) > 0 && options[0] != nil {
521
- endStream, _ = TnGet(options[0], "endStream").(bool)
524
+ endStream, _ = TnGetValue(options[0], "endStream").(bool)
522
525
  }
523
526
  // Requests without a body go out right away, as Node sends their headers at once
524
527
  if endStream || st.method == "GET" || st.method == "HEAD" {
@@ -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
@@ -262,7 +265,7 @@ func TnNewSocket(options ...interface{}) *TnSocket {
262
265
  s.TnStream = *TnNewDuplex()
263
266
  s.tnSelf = s
264
267
  if len(options) > 0 && options[0] != nil {
265
- if b, ok := TnGet(options[0], "allowHalfOpen").(bool); ok {
268
+ if b, ok := TnGetValue(options[0], "allowHalfOpen").(bool); ok {
266
269
  s.allowHalfOpen = b
267
270
  }
268
271
  }
@@ -414,7 +417,7 @@ func (s *TnSocket) connect(args ...interface{}) *TnSocket {
414
417
  if p := tnNetString(TnGet(a, "path")); p != "" {
415
418
  path, network = p, "unix"
416
419
  }
417
- if b, ok := TnGet(a, "allowHalfOpen").(bool); ok {
420
+ if b, ok := TnGetValue(a, "allowHalfOpen").(bool); ok {
418
421
  s.allowHalfOpen = b
419
422
  }
420
423
  if n, ok := tnNetNumber(TnGet(a, "timeout")); ok {
@@ -621,10 +624,10 @@ func TnNewNetServer(args ...interface{}) *TnNetServer {
621
624
  if tnIsFunc(a) {
622
625
  srv.on(srv.connectionEvent, a)
623
626
  } else if a != nil {
624
- if b, ok := TnGet(a, "allowHalfOpen").(bool); ok {
627
+ if b, ok := TnGetValue(a, "allowHalfOpen").(bool); ok {
625
628
  srv.allowHalfOpen = b
626
629
  }
627
- if b, ok := TnGet(a, "pauseOnConnect").(bool); ok {
630
+ if b, ok := TnGetValue(a, "pauseOnConnect").(bool); ok {
628
631
  srv.pauseOnConnect = b
629
632
  }
630
633
  }
@@ -862,7 +865,7 @@ func TnNewSocketAddress(options ...interface{}) *TnSocketAddress {
862
865
  if len(options) > 0 {
863
866
  opts = options[0]
864
867
  }
865
- if f, ok := TnGet(opts, "family").(string); ok {
868
+ if f, ok := TnGetValue(opts, "family").(string); ok {
866
869
  sa.family = strings.ToLower(f)
867
870
  }
868
871
  if sa.family != "ipv4" && sa.family != "ipv6" {
@@ -872,13 +875,13 @@ func TnNewSocketAddress(options ...interface{}) *TnSocketAddress {
872
875
  if sa.family == "ipv6" {
873
876
  sa.address = "::"
874
877
  }
875
- if a, ok := TnGet(opts, "address").(string); ok {
878
+ if a, ok := TnGetValue(opts, "address").(string); ok {
876
879
  sa.address = a
877
880
  }
878
- if p, ok := TnGet(opts, "port").(float64); ok {
881
+ if p, ok := TnGetValue(opts, "port").(float64); ok {
879
882
  sa.port = p
880
883
  }
881
- if fl, ok := TnGet(opts, "flowlabel").(float64); ok {
884
+ if fl, ok := TnGetValue(opts, "flowlabel").(float64); ok {
882
885
  sa.flowlabel = fl
883
886
  }
884
887
  addr, err := netip.ParseAddr(sa.address)
@@ -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', '', '');
package/bin/node/path.js CHANGED
@@ -3,6 +3,14 @@
3
3
  // the platform's flavour, as in Node.
4
4
  import { defineClass, defineHelper, defineModule, setResults, isObjectLiteral, getOption } from './registry.js';
5
5
  const pathHelper = `// node:path — Node's posix and win32 algorithms (path is the platform's)
6
+ // A path argument held as any: a string, else Node's TypeError
7
+ func TnPathArg(v interface{}) string {
8
+ if s, ok := v.(string); ok {
9
+ return s
10
+ }
11
+ panic(TnNodeError("TypeError", "ERR_INVALID_ARG_TYPE", "The \\"path\\" argument must be of type string. Received "+TnTypeOf(v)))
12
+ }
13
+
6
14
  type tnPathStyle struct {
7
15
  win bool
8
16
  sep string
@@ -99,6 +107,10 @@ func tnGlobRegexp(g string, escapes bool) string {
99
107
  segStart = false
100
108
  switch {
101
109
  case c == '*' && i+1 < len(g) && g[i+1] == '*' && wasStart && (i+2 == len(g) || g[i+2] == '/'):
110
+ // a leading ** also matches an absolute path's root ('**/a.ts' matches '/x/a.ts')
111
+ if i == 0 {
112
+ b.WriteString("/?")
113
+ }
102
114
  if i+2 == len(g) {
103
115
  b.WriteString("(?:[^/.][^/]*(?:/[^/.][^/]*)*)?")
104
116
  i++
@@ -700,7 +712,7 @@ func TnParsedPathOf(v interface{}) *TnParsedPath {
700
712
  return p
701
713
  }
702
714
  str := func(key string) string {
703
- if s, ok := TnGet(v, key).(string); ok {
715
+ if s, ok := TnGetValue(v, key).(string); ok {
704
716
  return s
705
717
  }
706
718
  return ""
@@ -713,14 +725,16 @@ const PATH_STYLES = {
713
725
  'path/win32': 'TnPathWin32'
714
726
  };
715
727
  export function registerPath(r) {
716
- defineHelper(r, 'nodePath', ['os', 'regexp', 'runtime', 'strings'], ['dynamic'], pathHelper);
728
+ defineHelper(r, 'nodePath', ['os', 'regexp', 'runtime', 'strings'], ['dynamic', 'error', 'typeOf'], pathHelper);
717
729
  defineClass(r, 'path.ParsedPath', '*TnParsedPath', 'class', '', 'root=string; dir=string; base=string; ext=string; name=string', '', '');
718
730
  for (const mod of Object.keys(PATH_STYLES)) {
719
731
  const style = PATH_STYLES[mod];
720
732
  defineModule(r, mod);
721
733
  const fn = (name) => (call) => {
722
734
  r.helper('nodePath');
723
- return `${style}.${name}(${call.args.join(', ')})`;
735
+ // (a dynamic argument must hold a string, as Node checks)
736
+ const args = call.args.map((a, i) => (call.types[i] === 'interface{}' ? `TnPathArg(${a})` : a));
737
+ return `${style}.${name}(${args.join(', ')})`;
724
738
  };
725
739
  for (const name of ['join', 'resolve', 'normalize', 'relative', 'dirname', 'basename', 'extname', 'isAbsolute', 'parse', 'toNamespacedPath', 'matchesGlob']) {
726
740
  r.functions[`${mod}.${name}`] = fn(name);