typenative 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +17 -1
  3. package/bin/cli.js +25 -11
  4. package/bin/go/convert.js +11 -1
  5. package/bin/index.js +221 -47
  6. package/bin/main.js +35 -14
  7. package/bin/node/assert.js +2 -2
  8. package/bin/node/buffer.js +9 -0
  9. package/bin/node/dns.js +1 -1
  10. package/bin/node/events.js +1 -1
  11. package/bin/node/fs.js +1 -1
  12. package/bin/node/fs_watch.js +407 -0
  13. package/bin/node/http2.js +33 -6
  14. package/bin/node/readline.js +1 -1
  15. package/bin/node/registry.js +2 -1
  16. package/bin/node/stream.js +6 -3
  17. package/bin/node/timers.js +1 -1
  18. package/bin/node/typed_arrays.js +608 -0
  19. package/bin/node/util.js +3 -0
  20. package/bin/node/zlib.js +131 -16
  21. package/bin/transpiler.js +635 -44
  22. package/bin/version.js +1 -1
  23. package/conformance.md +16 -4
  24. package/examples/README.md +54 -0
  25. package/examples/fibonacci/README.md +89 -0
  26. package/examples/fibonacci/bench.mjs +87 -0
  27. package/examples/fibonacci/main.ts +21 -0
  28. package/examples/hello-world/README.md +62 -0
  29. package/examples/hello-world/bench.mjs +66 -0
  30. package/examples/hello-world/main.ts +7 -0
  31. package/examples/json-server/README.md +125 -0
  32. package/examples/json-server/bench.mjs +171 -0
  33. package/examples/json-server/main.ts +67 -0
  34. package/govendor/github.com/andybalholm/brotli/LICENSE +19 -0
  35. package/govendor/github.com/andybalholm/brotli/README.md +19 -0
  36. package/govendor/github.com/andybalholm/brotli/backward_references.go +185 -0
  37. package/govendor/github.com/andybalholm/brotli/backward_references_hq.go +796 -0
  38. package/govendor/github.com/andybalholm/brotli/bit_cost.go +436 -0
  39. package/govendor/github.com/andybalholm/brotli/bit_reader.go +266 -0
  40. package/govendor/github.com/andybalholm/brotli/bitwriter.go +56 -0
  41. package/govendor/github.com/andybalholm/brotli/block_splitter.go +144 -0
  42. package/govendor/github.com/andybalholm/brotli/block_splitter_command.go +434 -0
  43. package/govendor/github.com/andybalholm/brotli/block_splitter_distance.go +433 -0
  44. package/govendor/github.com/andybalholm/brotli/block_splitter_literal.go +433 -0
  45. package/govendor/github.com/andybalholm/brotli/brotli_bit_stream.go +1435 -0
  46. package/govendor/github.com/andybalholm/brotli/cluster.go +30 -0
  47. package/govendor/github.com/andybalholm/brotli/cluster_command.go +164 -0
  48. package/govendor/github.com/andybalholm/brotli/cluster_distance.go +326 -0
  49. package/govendor/github.com/andybalholm/brotli/cluster_literal.go +326 -0
  50. package/govendor/github.com/andybalholm/brotli/command.go +254 -0
  51. package/govendor/github.com/andybalholm/brotli/compress_fragment.go +834 -0
  52. package/govendor/github.com/andybalholm/brotli/compress_fragment_two_pass.go +775 -0
  53. package/govendor/github.com/andybalholm/brotli/constants.go +77 -0
  54. package/govendor/github.com/andybalholm/brotli/context.go +2176 -0
  55. package/govendor/github.com/andybalholm/brotli/decode.go +2570 -0
  56. package/govendor/github.com/andybalholm/brotli/dictionary.go +122890 -0
  57. package/govendor/github.com/andybalholm/brotli/dictionary_hash.go +32779 -0
  58. package/govendor/github.com/andybalholm/brotli/encode.go +1220 -0
  59. package/govendor/github.com/andybalholm/brotli/encoder.go +177 -0
  60. package/govendor/github.com/andybalholm/brotli/encoder_dict.go +22 -0
  61. package/govendor/github.com/andybalholm/brotli/encoder_fast.go +201 -0
  62. package/govendor/github.com/andybalholm/brotli/entropy_encode.go +592 -0
  63. package/govendor/github.com/andybalholm/brotli/entropy_encode_static.go +4399 -0
  64. package/govendor/github.com/andybalholm/brotli/fast_log.go +290 -0
  65. package/govendor/github.com/andybalholm/brotli/find_match_length.go +45 -0
  66. package/govendor/github.com/andybalholm/brotli/go.mod +3 -0
  67. package/govendor/github.com/andybalholm/brotli/h10.go +287 -0
  68. package/govendor/github.com/andybalholm/brotli/h5.go +214 -0
  69. package/govendor/github.com/andybalholm/brotli/h6.go +216 -0
  70. package/govendor/github.com/andybalholm/brotli/hash.go +342 -0
  71. package/govendor/github.com/andybalholm/brotli/hash_composite.go +93 -0
  72. package/govendor/github.com/andybalholm/brotli/hash_forgetful_chain.go +252 -0
  73. package/govendor/github.com/andybalholm/brotli/hash_longest_match_quickly.go +214 -0
  74. package/govendor/github.com/andybalholm/brotli/hash_rolling.go +168 -0
  75. package/govendor/github.com/andybalholm/brotli/histogram.go +226 -0
  76. package/govendor/github.com/andybalholm/brotli/http.go +201 -0
  77. package/govendor/github.com/andybalholm/brotli/huffman.go +653 -0
  78. package/govendor/github.com/andybalholm/brotli/literal_cost.go +182 -0
  79. package/govendor/github.com/andybalholm/brotli/matchfinder/bargain1.go +212 -0
  80. package/govendor/github.com/andybalholm/brotli/matchfinder/bargain2.go +248 -0
  81. package/govendor/github.com/andybalholm/brotli/matchfinder/bargain3.go +278 -0
  82. package/govendor/github.com/andybalholm/brotli/matchfinder/emitter.go +34 -0
  83. package/govendor/github.com/andybalholm/brotli/matchfinder/m0.go +175 -0
  84. package/govendor/github.com/andybalholm/brotli/matchfinder/m4.go +339 -0
  85. package/govendor/github.com/andybalholm/brotli/matchfinder/matchfinder.go +103 -0
  86. package/govendor/github.com/andybalholm/brotli/matchfinder/pathfinder.go +328 -0
  87. package/govendor/github.com/andybalholm/brotli/matchfinder/textencoder.go +53 -0
  88. package/govendor/github.com/andybalholm/brotli/matchfinder/trio.go +327 -0
  89. package/govendor/github.com/andybalholm/brotli/matchfinder/zdfast.go +258 -0
  90. package/govendor/github.com/andybalholm/brotli/matchfinder/zfast.go +206 -0
  91. package/govendor/github.com/andybalholm/brotli/matchfinder/zm.go +302 -0
  92. package/govendor/github.com/andybalholm/brotli/memory.go +66 -0
  93. package/govendor/github.com/andybalholm/brotli/metablock.go +574 -0
  94. package/govendor/github.com/andybalholm/brotli/metablock_command.go +165 -0
  95. package/govendor/github.com/andybalholm/brotli/metablock_distance.go +165 -0
  96. package/govendor/github.com/andybalholm/brotli/metablock_literal.go +165 -0
  97. package/govendor/github.com/andybalholm/brotli/params.go +37 -0
  98. package/govendor/github.com/andybalholm/brotli/platform.go +103 -0
  99. package/govendor/github.com/andybalholm/brotli/prefix.go +30 -0
  100. package/govendor/github.com/andybalholm/brotli/prefix_dec.go +723 -0
  101. package/govendor/github.com/andybalholm/brotli/quality.go +196 -0
  102. package/govendor/github.com/andybalholm/brotli/reader.go +127 -0
  103. package/govendor/github.com/andybalholm/brotli/ringbuffer.go +134 -0
  104. package/govendor/github.com/andybalholm/brotli/state.go +313 -0
  105. package/govendor/github.com/andybalholm/brotli/static_dict.go +662 -0
  106. package/govendor/github.com/andybalholm/brotli/static_dict_lut.go +75094 -0
  107. package/govendor/github.com/andybalholm/brotli/symbol_list.go +22 -0
  108. package/govendor/github.com/andybalholm/brotli/transform.go +641 -0
  109. package/govendor/github.com/andybalholm/brotli/utf8_util.go +70 -0
  110. package/govendor/github.com/andybalholm/brotli/util.go +7 -0
  111. package/govendor/github.com/andybalholm/brotli/write_bits.go +52 -0
  112. package/govendor/github.com/andybalholm/brotli/writer.go +162 -0
  113. package/govendor/github.com/fsnotify/fsnotify/.mailmap +2 -0
  114. package/govendor/github.com/fsnotify/fsnotify/CHANGELOG.md +651 -0
  115. package/govendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md +147 -0
  116. package/govendor/github.com/fsnotify/fsnotify/LICENSE +25 -0
  117. package/govendor/github.com/fsnotify/fsnotify/README.md +214 -0
  118. package/govendor/github.com/fsnotify/fsnotify/backend_fen.go +469 -0
  119. package/govendor/github.com/fsnotify/fsnotify/backend_inotify.go +597 -0
  120. package/govendor/github.com/fsnotify/fsnotify/backend_kqueue.go +735 -0
  121. package/govendor/github.com/fsnotify/fsnotify/backend_other.go +22 -0
  122. package/govendor/github.com/fsnotify/fsnotify/backend_windows.go +702 -0
  123. package/govendor/github.com/fsnotify/fsnotify/fsnotify.go +526 -0
  124. package/govendor/github.com/fsnotify/fsnotify/go.mod +3 -0
  125. package/govendor/github.com/fsnotify/fsnotify/internal/darwin.go +20 -0
  126. package/govendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go +15 -0
  127. package/govendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go +15 -0
  128. package/govendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go +20 -0
  129. package/govendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go +32 -0
  130. package/govendor/github.com/fsnotify/fsnotify/internal/debug_linux.go +56 -0
  131. package/govendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go +15 -0
  132. package/govendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go +16 -0
  133. package/govendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go +45 -0
  134. package/govendor/github.com/fsnotify/fsnotify/internal/debug_windows.go +40 -0
  135. package/govendor/github.com/fsnotify/fsnotify/internal/freebsd.go +20 -0
  136. package/govendor/github.com/fsnotify/fsnotify/internal/internal.go +2 -0
  137. package/govendor/github.com/fsnotify/fsnotify/internal/unix.go +20 -0
  138. package/govendor/github.com/fsnotify/fsnotify/internal/unix2.go +25 -0
  139. package/govendor/github.com/fsnotify/fsnotify/internal/windows.go +40 -0
  140. package/govendor/github.com/fsnotify/fsnotify/shared.go +64 -0
  141. package/govendor/github.com/fsnotify/fsnotify/staticcheck.conf +3 -0
  142. package/govendor/github.com/fsnotify/fsnotify/system_bsd.go +7 -0
  143. package/govendor/github.com/fsnotify/fsnotify/system_darwin.go +8 -0
  144. package/govendor/manifest.txt +3 -1
  145. package/package.json +1 -1
  146. package/types/typenative-npm.d.ts +72 -0
  147. package/types/typenative.d.ts +117 -1
package/bin/transpiler.js CHANGED
@@ -18,6 +18,8 @@ import { registerStringDecoder } from './node/string_decoder.js';
18
18
  import { registerCrypto } from './node/crypto.js';
19
19
  import { registerCryptoKeys } from './node/crypto_keys.js';
20
20
  import { registerZlib } from './node/zlib.js';
21
+ import { registerFsWatch } from './node/fs_watch.js';
22
+ import { registerTypedArrays, isTypedArrayGoType } from './node/typed_arrays.js';
21
23
  import { registerTimers } from './node/timers.js';
22
24
  import { registerEvents } from './node/events.js';
23
25
  import { registerStream } from './node/stream.js';
@@ -348,6 +350,9 @@ const generatorFunctionNames = new Set();
348
350
  // While emitting an async/generator function body: `return`/`yield` send here
349
351
  let asyncChannelVar;
350
352
  let asyncFunctionNode;
353
+ // True while emitting the body of an async function (not a generator): its
354
+ // return settles the promise (ordered wake); a generator's sends stay raw
355
+ let asyncChannelIsAsync = false;
351
356
  // Variables holding JS arrays: stored as *[]T so aliasing shares the slice
352
357
  // header (push/splice through any alias are visible everywhere)
353
358
  const referenceArrays = new Set();
@@ -503,6 +508,9 @@ function sourceFileIndexOf(node) {
503
508
  // A line holding only this sentinel becomes //line <go file>:<next line>,
504
509
  // which returns the following generated code (helpers) to its real Go position
505
510
  const LINE_RESET = '/*tn@' + 'reset*/';
511
+ // First line of every generated Go file (Go's convention for generated code;
512
+ // the CLI only deletes stale .go files that start with it)
513
+ export const GENERATED_HEADER = '// Code generated by TypeNative. DO NOT EDIT.';
506
514
  function lineMarker(node) {
507
515
  if (!node?.line)
508
516
  return '';
@@ -1021,6 +1029,7 @@ export function transpileToNative(code, options) {
1021
1029
  usedHelpers.clear();
1022
1030
  helperProvidedPackages.clear();
1023
1031
  mainPackageVariables.length = 0;
1032
+ goInterfaceAdapters.clear();
1024
1033
  const transpiledCode = visit(sourceFile, { addFunctionOutside: true });
1025
1034
  const transpiledCodeOutside = outsideNodes.map((n) => withLineMarker(n, visit(n, { isOutside: true }))).join('\n');
1026
1035
  // Keep the process alive until detached async work and timers settle
@@ -1056,7 +1065,9 @@ export function transpileToNative(code, options) {
1056
1065
  : goImportLine(pkg);
1057
1066
  // process.on('uncaughtException'): a throw in the top-level code is handed to it too
1058
1067
  const body = usedHelpers.has('nodeUncaught') ? `func() {\n\tdefer TnMainRecover()\n\t${mainCode.trim()}\n\t}()` : mainCode.trim();
1059
- const main = `package main
1068
+ const main = `${GENERATED_HEADER}
1069
+
1070
+ package main
1060
1071
 
1061
1072
  ${mainImports.sort().map((pkg) => importLine(pkg)).join('\n')}
1062
1073
 
@@ -1280,11 +1291,21 @@ function visit(node, options = {}) {
1280
1291
  if (isStringLiteral(node.argumentExpression)) {
1281
1292
  return `${visit(node.expression)}[${visit(node.argumentExpression)}]`;
1282
1293
  }
1294
+ // Typed array elements read as numbers (out of range: 0)
1295
+ if (isTypedArrayGoType(targetType) && !isAssignmentTarget(node)) {
1296
+ return `${visit(node.expression)}.Get(${visit(node.argumentExpression)})`;
1297
+ }
1283
1298
  // Buffer / Uint8Array elements read as numbers
1284
1299
  if (targetType === '[]byte' && !isAssignmentTarget(node)) {
1285
1300
  useHelper('dynamic');
1286
1301
  return `float64(TnAt(${visit(node.expression)}, ${visit(node.argumentExpression)}))`;
1287
1302
  }
1303
+ // pair[0] on a [string, number] tuple ([]interface{}): the element's type
1304
+ const tupleElement = tupleElementGoType(node);
1305
+ if (tupleElement && !isAssignmentTarget(node)) {
1306
+ useHelper('dynamic');
1307
+ return `TnAs[${tupleElement}](TnAt(${visit(node.expression)}, ${visit(node.argumentExpression)}))`;
1308
+ }
1288
1309
  // Reading past the end of an array gives undefined in JS: the zero value here
1289
1310
  if (targetType?.startsWith('[]') && !isAssignmentTarget(node)) {
1290
1311
  useHelper('dynamic');
@@ -1514,6 +1535,10 @@ function visit(node, options = {}) {
1514
1535
  variableTypeNodes.set(node.name.text, node.type);
1515
1536
  else
1516
1537
  variableTypeNodes.delete(node.name.text);
1538
+ if (node.initializer && isArrayBufferExpression(node.initializer))
1539
+ arrayBufferVariables.add(node.name.text);
1540
+ else
1541
+ arrayBufferVariables.delete(node.name.text);
1517
1542
  if (node.initializer && isGoRefCall(node.initializer))
1518
1543
  goRefVariables.add(node.name.text);
1519
1544
  else
@@ -1626,6 +1651,9 @@ function visit(node, options = {}) {
1626
1651
  return visitNullablePrimitiveOptionalCall(node, visit(node.expression.expression), receiverType);
1627
1652
  }
1628
1653
  }
1654
+ const typedArrayCall = visitTypedArrayCall(node);
1655
+ if (typedArrayCall !== undefined)
1656
+ return typedArrayCall;
1629
1657
  const nodeCall = visitNodeCall(node);
1630
1658
  if (nodeCall !== undefined)
1631
1659
  return nodeCall;
@@ -1714,6 +1742,9 @@ function visit(node, options = {}) {
1714
1742
  node.expression.expression.text === 'Array' &&
1715
1743
  node.expression.name.text === 'from') {
1716
1744
  const sourceNode = (node.arguments ?? [])[0];
1745
+ if (isTypedArrayGoType(inferExpressionType(sourceNode)) && (node.arguments ?? []).length === 1) {
1746
+ return `${visit(sourceNode)}.tnFloats()`;
1747
+ }
1717
1748
  const callbackNode = (node.arguments ?? [])[1];
1718
1749
  const paramTypes = ['interface{}', 'float64'];
1719
1750
  if (callbackNode && (isArrowFunction(callbackNode) || isFunctionExpression(callbackNode))) {
@@ -1818,6 +1849,14 @@ function visit(node, options = {}) {
1818
1849
  useHelper('error');
1819
1850
  return `TnIsErrorOf(${visit(node.left)}, ${toGoStringLiteral(node.right.text)})`;
1820
1851
  }
1852
+ if (node.operatorToken.kind === 'InstanceOfKeyword' && isIdentifier(node.right) && !classNames.has(node.right.text)) {
1853
+ // x instanceof Int32Array / URL / …: a Node global class's Go type
1854
+ const nodeClassKey = nodeClassKeyOfName(node.right.text);
1855
+ const nodeClass = nodeClassKey ? nodeRegistry.classes[nodeClassKey] : undefined;
1856
+ if (nodeClass) {
1857
+ return `func() bool { _, ok := interface{}(${visit(node.left)}).(${nodeClass.goType}); return ok }()`;
1858
+ }
1859
+ }
1821
1860
  if (node.operatorToken.kind === 'InstanceOfKeyword' && isIdentifier(node.right)) {
1822
1861
  // x instanceof C: the runtime type is C's pointer type
1823
1862
  return `func() bool { _, ok := interface{}(${visit(node.left)}).(*${getSafeName(node.right.text)}); return ok }()`;
@@ -1995,6 +2034,12 @@ function visit(node, options = {}) {
1995
2034
  const goFieldAssignment = visitGoFieldAssignment(node, op);
1996
2035
  if (goFieldAssignment !== undefined)
1997
2036
  return goFieldAssignment;
2037
+ // ta[i] = v / ta[i] op= v on a typed array: Set converts to the element type
2038
+ if (isElementAccessExpression(node.left) && isTypedArrayGoType(inferExpressionType(node.left.expression))) {
2039
+ const typedAssignment = visitTypedArrayAssignment(node.left, op, node.right);
2040
+ if (typedAssignment !== undefined)
2041
+ return typedAssignment;
2042
+ }
1998
2043
  // buf[i] = v on a Buffer / Uint8Array: bytes wrap modulo 256
1999
2044
  if (op === '=' && isElementAccessExpression(node.left) && inferExpressionType(node.left.expression) === '[]byte') {
2000
2045
  useHelper('buffer');
@@ -2079,10 +2124,17 @@ function visit(node, options = {}) {
2079
2124
  return '';
2080
2125
  }
2081
2126
  else if (isAwaitExpression(node)) {
2082
- // Promises are channels: TnAwait keeps the event loop running while it waits
2083
- // (a bare receive would block it, e.g. in async callbacks)
2127
+ // Promises are channels: the await keeps the event loop running while it
2128
+ // waits (a bare receive would block it). Inside an async function body —
2129
+ // a goroutine of its own — TnAwait parks for the ordered wake (promise
2130
+ // continuations resume in settlement order); an await in code running
2131
+ // inline on the loop goroutine (an async callback) must keep draining the
2132
+ // loop itself
2084
2133
  useHelper('promise');
2085
- return `TnAwait(${visit(node.expression)})`;
2134
+ const awaitFn = asyncChannelVar && asyncChannelIsAsync && getEnclosingFunction(node) === asyncFunctionNode
2135
+ ? 'TnAwait'
2136
+ : 'TnAwaitInline';
2137
+ return `${awaitFn}(${visit(node.expression)})`;
2086
2138
  }
2087
2139
  else if (isVariableDeclarationList(node)) {
2088
2140
  return ((node.declarations ?? []).map((n) => visit(n)).join(options.inline ? ';' : ';\n\t') +
@@ -2242,6 +2294,11 @@ function visit(node, options = {}) {
2242
2294
  if (asyncChannelVar && getEnclosingFunction(node) === asyncFunctionNode) {
2243
2295
  if (!node.expression)
2244
2296
  return 'return';
2297
+ // An async return settles its promise (ordered wake); a generator's
2298
+ // sends stay raw (their consumers receive raw)
2299
+ if (asyncChannelIsAsync) {
2300
+ return `TnAsyncSend(${asyncChannelVar}, ${visit(node.expression)}); return` + (options.inline ? '' : ';\n\t');
2301
+ }
2245
2302
  return `${asyncChannelVar} <- ${visit(node.expression)}; return` + (options.inline ? '' : ';\n\t');
2246
2303
  }
2247
2304
  const enclosingFn = getEnclosingFunction(node);
@@ -2589,9 +2646,14 @@ function visit(node, options = {}) {
2589
2646
  result += `func New${name}${typeParams}(message string) *${name}${typeParamNames} {\n\t\tself := &${name}${typeParamNames}{}\n\t\tself.message = message\n\t\t${fieldInitializers(node)}return self\n\t}\n\n`;
2590
2647
  }
2591
2648
  else {
2592
- const parentInit = parentClass && !extendsError ? `self.${goFieldName(parentClass)} = *${parentConstructorCall(parentClass, [])}\n\t\t` : '';
2649
+ // No constructor: JS's implicit constructor(...args) { super(...args) }
2650
+ // takes the nearest ancestor constructor's parameters
2651
+ const inherited = parentClass && !extendsError ? inheritedConstructorParameters(parentClass) : null;
2652
+ const signature = inherited ? inherited.signature : '';
2653
+ const forwarded = inherited ? inherited.forward : [];
2654
+ const parentInit = parentClass && !extendsError ? `self.${goFieldName(parentClass)} = *${parentConstructorCall(parentClass, forwarded)}\n\t\t` : '';
2593
2655
  const ctorBody = `{\n\t\tself := &${name}${typeParamNames}{}\n\t\t${parentInit}${fieldInitializers(node)}${nodeSelfLink(parentClass, node)}return self\n\t}`;
2594
- result += emitConstructor(name, typeParams, typeParamNames, '', ctorBody);
2656
+ result += emitConstructor(name, typeParams, typeParamNames, signature, ctorBody);
2595
2657
  }
2596
2658
  // Inherited concrete methods are copied onto the subclass: Go embedding
2597
2659
  // promotes the parent's receiver, which would break `this` dispatch
@@ -2674,12 +2736,15 @@ function visit(node, options = {}) {
2674
2736
  const yieldType = getGeneratorYieldType(member);
2675
2737
  const prevChannel = asyncChannelVar;
2676
2738
  const prevFn = asyncFunctionNode;
2739
+ const prevIsAsync = asyncChannelIsAsync;
2677
2740
  asyncChannelVar = '__ch';
2678
2741
  asyncFunctionNode = member;
2742
+ asyncChannelIsAsync = false;
2679
2743
  const methodParameterInfo = getFunctionParametersInfo(member.parameters ?? []);
2680
2744
  const genBody = visit(member.body, { prefixBlockContent: methodParameterInfo.prefixBlockContent });
2681
2745
  asyncChannelVar = prevChannel;
2682
2746
  asyncFunctionNode = prevFn;
2747
+ asyncChannelIsAsync = prevIsAsync;
2683
2748
  result += `${lineMarker(member)}func (self *${name}${typeParamNames}) ${genName}(${methodParameterInfo.signature}) chan ${yieldType} {\n\t__ch := make(chan ${yieldType})\n\tgo func() {\n\t\tdefer close(__ch)\n\t\t${genBody.trim()}\n\t}()\n\treturn __ch\n}\n\n`;
2684
2749
  }
2685
2750
  continue;
@@ -2800,7 +2865,17 @@ function visit(node, options = {}) {
2800
2865
  return `make([]${elementType}, int(${length}))`;
2801
2866
  }
2802
2867
  const typeArgs = getTypeArguments((node.typeArguments ?? []));
2803
- const args = node.arguments ? (node.arguments ?? []).map((a) => visit(a)) : [];
2868
+ // Array-reference parameters (*[]T) box their array arguments
2869
+ const ctorParams = classNames.has(className) ? constructorParameterNodes(className) : [];
2870
+ const args = (node.arguments ?? []).map((a, i) => {
2871
+ const param = i < ctorParams.length ? ctorParams[i] : undefined;
2872
+ if (param && !param.dotDotDotToken && !param.initializer && isIdentifier(param.name)) {
2873
+ const paramType = getParameterGoType(param);
2874
+ if (paramType.startsWith('*[]'))
2875
+ return toGoValueOfType(a, paramType);
2876
+ }
2877
+ return visit(a);
2878
+ });
2804
2879
  // new F(…) where F holds a constructor function (construct signature)
2805
2880
  if (!classNames.has(className) && inferExpressionType(node.expression)?.startsWith('func(')) {
2806
2881
  return `${className}(${args.join(', ')})`;
@@ -2817,14 +2892,14 @@ function visit(node, options = {}) {
2817
2892
  return `TnAssign(__obj, ${visit(p.expression)})`;
2818
2893
  if (isShorthandPropertyAssignment(p))
2819
2894
  return `__obj[${mapKeyText(p.name)}] = ${visit(p.name)}`;
2820
- return `__obj[${mapKeyText(p.name)}] = ${visit(p.initializer)}`;
2895
+ return `__obj[${propertyKeyString(p.name)}] = ${visit(p.initializer)}`;
2821
2896
  });
2822
2897
  return `func() map[string]interface{} { __obj := map[string]interface{}{}; ${steps.join('; ')}; return __obj }()`;
2823
2898
  }
2824
2899
  const entries = (node.properties ?? [])
2825
2900
  .map((p) => {
2826
2901
  if (isPropertyAssignment(p))
2827
- return `${mapKeyText(p.name)}: ${visit(p.initializer)}`;
2902
+ return `${propertyKeyString(p.name)}: ${visit(p.initializer)}`;
2828
2903
  if (isShorthandPropertyAssignment(p))
2829
2904
  return `${mapKeyText(p.name)}: ${visit(p.name)}`;
2830
2905
  return '';
@@ -2918,6 +2993,10 @@ function visit(node, options = {}) {
2918
2993
  // Visits a value going into a slot of Go type `goType`; non-nil values for
2919
2994
  // nullable primitives (*string/*float64/*bool) are boxed into pointers
2920
2995
  function toGoValueOfType(expr, goType) {
2996
+ // (x as Task) on an any value stays dynamic; a typed slot asserts it
2997
+ if (goType && goType !== 'interface{}' && isAsExpression(expr) && getAsExpressionType(expr) === 'interface{}' && isDynamicValue(expr.expression)) {
2998
+ expr = expr.expression;
2999
+ }
2921
3000
  if (goType === 'string' && inferExpressionType(expr) === 'TnJsxNode')
2922
3001
  return `string(${visit(expr)})`;
2923
3002
  if (goType &&
@@ -3185,7 +3264,11 @@ function visitUsingDeclaration(statement, rest) {
3185
3264
  const hasAsync = (classNode?.members ?? []).some((m) => m.name?.text === '__asyncDispose');
3186
3265
  if (isAwait && hasAsync)
3187
3266
  useHelper('promise');
3188
- const call = isAwait && hasAsync ? `TnAwait(${name}.__asyncDispose())` : `${name}.__dispose()`;
3267
+ // The disposal may run on an async fn's goroutine or inline in a callback
3268
+ const awaitFn = asyncChannelVar && asyncChannelIsAsync && getEnclosingFunction(statement) === asyncFunctionNode
3269
+ ? 'TnAwait'
3270
+ : 'TnAwaitInline';
3271
+ const call = isAwait && hasAsync ? `${awaitFn}(${name}.__asyncDispose())` : `${name}.__dispose()`;
3189
3272
  return `defer func() { if ${name} != nil { ${call} } }()`;
3190
3273
  })
3191
3274
  .reverse();
@@ -3519,6 +3602,49 @@ function nodeParentGoName(expr) {
3519
3602
  nodeParentClassKeys.set(goName, key);
3520
3603
  return goName;
3521
3604
  }
3605
+ // The constructor parameters of a user class: its own, else the nearest
3606
+ // ancestor's (the implicit constructor forwards them)
3607
+ function constructorParameterNodes(className) {
3608
+ let current = className;
3609
+ for (let depth = 0; depth < 50 && current; depth++) {
3610
+ const classNode = declaredClasses.get(current);
3611
+ if (!classNode)
3612
+ return [];
3613
+ const ctor = (classNode.members ?? []).find((m) => isConstructorDeclaration(m));
3614
+ if (ctor)
3615
+ return ctor.parameters ?? [];
3616
+ current = classParentNames.get(current) ?? '';
3617
+ }
3618
+ return [];
3619
+ }
3620
+ // The parameters of the nearest user-class ancestor with a constructor, as a
3621
+ // Go signature and the argument list forwarding them (null when none, or when
3622
+ // they need destructuring)
3623
+ function inheritedConstructorParameters(parentClass) {
3624
+ let current = parentClass;
3625
+ for (let depth = 0; depth < 50 && current; depth++) {
3626
+ const classNode = declaredClasses.get(current);
3627
+ if (!classNode)
3628
+ return null;
3629
+ const ctor = (classNode.members ?? []).find((m) => isConstructorDeclaration(m));
3630
+ if (ctor) {
3631
+ const params = ctor.parameters ?? [];
3632
+ if (params.length === 0 || params.some((p) => !isIdentifier(p.name)))
3633
+ return null;
3634
+ const info = getFunctionParametersInfo(params);
3635
+ const forward = [];
3636
+ for (const part of splitGoParameters(info.signature)) {
3637
+ const trimmed = part.trim();
3638
+ const space = trimmed.indexOf(' ');
3639
+ const paramName = trimmed.substring(0, space);
3640
+ forward.push(trimmed.substring(space + 1).trim().startsWith('...') ? `${paramName}...` : paramName);
3641
+ }
3642
+ return { signature: info.signature, forward: forward };
3643
+ }
3644
+ current = classParentNames.get(current) ?? '';
3645
+ }
3646
+ return null;
3647
+ }
3522
3648
  function parentConstructorCall(parentClass, args) {
3523
3649
  if (nodeParentClassKeys.has(parentClass)) {
3524
3650
  const key = nodeParentClassKeys.get(parentClass) ?? '';
@@ -3653,6 +3779,15 @@ function isIncrementOrDecrement(node) {
3653
3779
  // x++ / ++x: Go only has the statement form, so used as a value they become
3654
3780
  // a closure returning the old (postfix) or new (prefix) value
3655
3781
  function visitIncrementOrDecrement(node, isPrefix) {
3782
+ // ta[i]++ on a typed array: read, convert back on Set
3783
+ if (isElementAccessExpression(node.operand) && isTypedArrayGoType(inferExpressionType(node.operand.expression))) {
3784
+ const sign = node.operator === 'PlusPlusToken' ? '+' : '-';
3785
+ const arr = getTempName('ta');
3786
+ const index = getTempName('i');
3787
+ const old = getTempName('old');
3788
+ const result = isPrefix ? `${arr}.Get(${index})` : old;
3789
+ return `func() float64 { ${arr}, ${index} := ${visit(node.operand.expression)}, ${visit(node.operand.argumentExpression)}; ${old} := ${arr}.Get(${index}); ${arr}.Set(${index}, ${old} ${sign} 1); return ${result} }()`;
3790
+ }
3656
3791
  const target = visit(node.operand, { inline: true });
3657
3792
  const op = node.operator === 'PlusPlusToken' ? '++' : '--';
3658
3793
  const parent = node.parent;
@@ -3663,6 +3798,185 @@ function visitIncrementOrDecrement(node, isPrefix) {
3663
3798
  return `func() float64 { ${target}${op}; return ${target} }()`;
3664
3799
  return `func() float64 { __old := ${target}; ${target}${op}; return __old }()`;
3665
3800
  }
3801
+ // Expression replacing the receiver of the typed-array call being inlined by
3802
+ // visitArrayHigherOrderCall ('' otherwise)
3803
+ let typedArrayReceiverExpr = '';
3804
+ // Variables holding an ArrayBuffer (typed-array constructors view these)
3805
+ const arrayBufferVariables = new Set();
3806
+ const TYPED_ARRAY_CALLBACK_METHODS = [
3807
+ 'map', 'filter', 'forEach', 'some', 'every', 'find', 'findIndex', 'findLast', 'findLastIndex', 'reduce',
3808
+ 'reduceRight', 'entries'
3809
+ ];
3810
+ // Whether a []byte expression is an ArrayBuffer rather than a Uint8Array /
3811
+ // Buffer: new ArrayBuffer(n), x.buffer, an ArrayBuffer-typed variable, and
3812
+ // slices of those
3813
+ function isArrayBufferExpression(node) {
3814
+ if (!node)
3815
+ return false;
3816
+ const expr = unwrapParentheses(node);
3817
+ if (isAsExpression(expr))
3818
+ return isArrayBufferTypeNode(expr.type) || isArrayBufferExpression(expr.expression);
3819
+ if (isNewExpression(expr) && isIdentifier(expr.expression)) {
3820
+ return expr.expression.text === 'ArrayBuffer' || expr.expression.text === 'SharedArrayBuffer';
3821
+ }
3822
+ if (isPropertyAccessExpression(expr))
3823
+ return expr.name.text === 'buffer';
3824
+ if (isCallExpression(expr) && isPropertyAccessExpression(expr.expression) && expr.expression.name.text === 'slice') {
3825
+ return isArrayBufferExpression(expr.expression.expression);
3826
+ }
3827
+ if (isIdentifier(expr)) {
3828
+ return arrayBufferVariables.has(expr.text) || isArrayBufferTypeNode(variableTypeNodes.get(expr.text));
3829
+ }
3830
+ return false;
3831
+ }
3832
+ function isArrayBufferTypeNode(typeNode) {
3833
+ if (!typeNode || !isTypeReferenceNode(typeNode) || !isIdentifier(typeNode.typeName))
3834
+ return false;
3835
+ const name = typeNode.typeName.text;
3836
+ return name === 'ArrayBuffer' || name === 'SharedArrayBuffer' || name === 'ArrayBufferLike';
3837
+ }
3838
+ // ta[i] = v / ta[i] op= v: one Set with the value converted like JS
3839
+ function visitTypedArrayAssignment(target, op, right) {
3840
+ const value = visit(right);
3841
+ if (op === '=')
3842
+ return `${visit(target.expression)}.Set(${visit(target.argumentExpression)}, ${value})`;
3843
+ const arr = getTempName('ta');
3844
+ const index = getTempName('i');
3845
+ const current = `${arr}.Get(${index})`;
3846
+ let combined = '';
3847
+ if (op === '+=' || op === '-=' || op === '*=' || op === '/=')
3848
+ combined = `${current} ${op[0]} (${value})`;
3849
+ else if (op === '%=') {
3850
+ importedPackages.add('math');
3851
+ combined = `math.Mod(${current}, ${value})`;
3852
+ }
3853
+ else if (op === '**=') {
3854
+ importedPackages.add('math');
3855
+ combined = `math.Pow(${current}, ${value})`;
3856
+ }
3857
+ else if (op === '&=' || op === '|=' || op === '^=') {
3858
+ useHelper('dynamic');
3859
+ combined = `float64(TnInt32(${current}) ${op[0]} TnInt32(${value}))`;
3860
+ }
3861
+ else if (op === '<<=' || op === '>>=') {
3862
+ useHelper('dynamic');
3863
+ combined = `float64(TnInt32(${current}) ${op.slice(0, 2)} (uint32(TnInt32(${value})) & 31))`;
3864
+ }
3865
+ else if (op === '>>>=') {
3866
+ useHelper('dynamic');
3867
+ combined = `float64(uint32(TnInt32(${current})) >> (uint32(TnInt32(${value})) & 31))`;
3868
+ }
3869
+ else
3870
+ return undefined;
3871
+ return `func() float64 { ${arr}, ${index} := ${visit(target.expression)}, ${visit(target.argumentExpression)}; return ${arr}.Set(${index}, ${combined}) }()`;
3872
+ }
3873
+ // Calls on typed arrays the Go type can't take: callback methods are inlined
3874
+ // over the elements as numbers (map / filter results become the same kind of
3875
+ // typed array); ArrayBuffer#slice copies
3876
+ function visitTypedArrayCall(node) {
3877
+ if (!isPropertyAccessExpression(node.expression))
3878
+ return undefined;
3879
+ const method = node.expression.name.text;
3880
+ const recvNode = node.expression.expression;
3881
+ if (method === 'slice' && isArrayBufferExpression(recvNode)) {
3882
+ useHelper('typedArrays');
3883
+ const args = (node.arguments ?? []).map((a) => `, ${visit(a)}`).join('');
3884
+ return `TnArrayBufferSlice(${visit(recvNode)}${args})`;
3885
+ }
3886
+ const recvType = inferExpressionType(recvNode);
3887
+ if (!isTypedArrayGoType(recvType) || !TYPED_ARRAY_CALLBACK_METHODS.includes(method))
3888
+ return undefined;
3889
+ const resultType = inferExpressionType(node) ?? '';
3890
+ const arr = getTempName('ta');
3891
+ const recv = visit(recvNode);
3892
+ typedArrayReceiverExpr = `${arr}.tnFloats()`;
3893
+ const inner = visitArrayHigherOrderCall(node);
3894
+ typedArrayReceiverExpr = '';
3895
+ if (!inner)
3896
+ return undefined;
3897
+ if (method === 'forEach')
3898
+ return `func() { ${arr} := ${recv}; ${inner} }()`;
3899
+ const value = method === 'map' || method === 'filter' ? `${arr}.tnLike(${inner})` : inner;
3900
+ return `func() ${resultType} { ${arr} := ${recv}; return ${value} }()`;
3901
+ }
3902
+ // Adapter types generated so far ('IntHeap__container_heap_Interface')
3903
+ const goInterfaceAdapters = new Set();
3904
+ // A class method declaration, searched up the inheritance chain
3905
+ function findClassMethod(className, methodName) {
3906
+ let name = className;
3907
+ for (let depth = 0; depth < 20 && name; depth++) {
3908
+ const cls = declaredClasses.get(name);
3909
+ if (!cls)
3910
+ return undefined;
3911
+ for (const member of cls.members ?? []) {
3912
+ if (member.kind === 'MethodDeclaration' && member.name && member.name.text === methodName)
3913
+ return member;
3914
+ }
3915
+ name = classParentNames.get(name) ?? '';
3916
+ }
3917
+ return undefined;
3918
+ }
3919
+ // A Go value of type `from` as a class method parameter of type `to`
3920
+ function adaptGoValue(expr, from, to) {
3921
+ if (from === to || to === 'interface{}' || to === 'any' || !to)
3922
+ return expr;
3923
+ if (from === 'any' || from === 'interface{}')
3924
+ return `${expr}.(${goLocalType(to)})`;
3925
+ if (to === 'float64' && isGoNumericKind(from))
3926
+ return `float64(${expr})`;
3927
+ return expr;
3928
+ }
3929
+ // heap.Push(h, x) with h an instance of `class IntHeap implements
3930
+ // heap.Interface`: Go needs Len() int, the class has Len(): number. The
3931
+ // adapter struct holds the instance and gives each interface method the
3932
+ // exact Go signature, converting arguments and results.
3933
+ function adaptClassToGoInterface(expr, fromType, toType, iface) {
3934
+ const className = fromType.slice(1);
3935
+ if (!declaredClasses.has(className))
3936
+ return '';
3937
+ for (const m of iface.ifaceMethods) {
3938
+ if (!findClassMethod(className, m.name))
3939
+ return '';
3940
+ }
3941
+ const adapterName = `${className}__${toType.replace(/[^A-Za-z0-9]/g, '_')}`;
3942
+ if (!goInterfaceAdapters.has(adapterName)) {
3943
+ goInterfaceAdapters.add(adapterName);
3944
+ const methods = [];
3945
+ for (const m of iface.ifaceMethods) {
3946
+ const method = findClassMethod(className, m.name);
3947
+ const declared = method.parameters ?? [];
3948
+ const params = [];
3949
+ const args = [];
3950
+ m.params.forEach((p, i) => {
3951
+ ensureGoTypePackages(p.goType);
3952
+ const variadic = p.goType.startsWith('...');
3953
+ params.push(`p${i} ${goLocalType(p.goType)}`);
3954
+ if (i >= declared.length)
3955
+ return;
3956
+ const target = declared[i].type ? getType(declared[i].type) : 'interface{}';
3957
+ args.push(variadic ? `p${i}...` : adaptGoValue(`p${i}`, p.goType, target));
3958
+ });
3959
+ const call = `a.v.${getSafeName(m.name)}(${args.join(', ')})`;
3960
+ let body = call;
3961
+ let results = '';
3962
+ if (m.results.length === 1) {
3963
+ ensureGoTypePackages(m.results[0]);
3964
+ results = ` ${goLocalType(m.results[0])}`;
3965
+ // (a truthiness check: a missing Map entry is '' in the self-hosted build)
3966
+ const recorded = classMethodReturnTypes.get(className)?.get(m.name);
3967
+ const returned = method.type ? getType(method.type) : recorded ? recorded : 'interface{}';
3968
+ body = `return ${toGoType(call, returned, m.results[0])}`;
3969
+ }
3970
+ else if (m.results.length > 1) {
3971
+ results = ` (${m.results.map((r) => goLocalType(r)).join(', ')})`;
3972
+ body = `return ${call}`;
3973
+ }
3974
+ methods.push(`func (a *${adapterName}) ${m.name}(${params.join(', ')})${results} { ${body} }`);
3975
+ }
3976
+ mainPackageVariables.push(`// ${className} as a ${toType}\ntype ${adapterName} struct{ v *${className} }\n\n${methods.join('\n')}`);
3977
+ }
3978
+ return `&${adapterName}{v: ${expr}}`;
3979
+ }
3666
3980
  function compositeBody(rawEntries) {
3667
3981
  const entries = rawEntries.map((e) => e.trimEnd());
3668
3982
  if (!entries.some((e) => e.includes('\n')))
@@ -3733,6 +4047,11 @@ function getDictionaryValueType(node) {
3733
4047
  function isDynamicObjectLiteral(node) {
3734
4048
  if (isAnyContext(getContextualTypeNode(node)))
3735
4049
  return true;
4050
+ // { [key]: v } has no struct shape (a Record context makes a typed map instead)
4051
+ if ((node.properties ?? []).some((p) => p.name?.kind === 'ComputedPropertyName') &&
4052
+ !isRecordTypeNode(resolveTypeNode(getContextualTypeNode(node)))) {
4053
+ return true;
4054
+ }
3736
4055
  // { name: { … } } nested in a dynamic object (with no declared member type) is dynamic too
3737
4056
  const parent = node.parent;
3738
4057
  if (isPropertyAssignment(parent) &&
@@ -3780,7 +4099,9 @@ function getObjectLiteralGoType(node) {
3780
4099
  // Values typed `any`/`unknown` are handled at runtime (TnGet/TnSet/...),
3781
4100
  // never by guessing their type
3782
4101
  function isDynamicValue(expr) {
3783
- return inferExpressionType(expr) === 'interface{}';
4102
+ // Go bridge results spell it `any`
4103
+ const type = inferExpressionType(expr);
4104
+ return type === 'interface{}' || type === 'any';
3784
4105
  }
3785
4106
  // A value whose type is a type parameter (a: T in f<T>): its properties are read dynamically
3786
4107
  function isTypeParameterValue(expr) {
@@ -3873,6 +4194,13 @@ function mapKeyText(name) {
3873
4194
  return visit(name.expression);
3874
4195
  return visit(name);
3875
4196
  }
4197
+ // A key of a dynamic object (map[string]interface{}): computed keys become
4198
+ // strings the way JS property keys do ({ [1]: x } has the key "1")
4199
+ function propertyKeyString(name) {
4200
+ if (name.kind !== 'ComputedPropertyName')
4201
+ return mapKeyText(name);
4202
+ return jsStringOf(visit(name.expression), inferExpressionType(name.expression));
4203
+ }
3876
4204
  // { a: 1 } typed as Record<K, V> → map[K]V{"a": 1}
3877
4205
  // An ordered map built from "key, value" entries (in source order)
3878
4206
  function orderedMapLiteral(keyType, valueType, entries) {
@@ -4064,6 +4392,24 @@ function getEnclosingClassName(node) {
4064
4392
  }
4065
4393
  return undefined;
4066
4394
  }
4395
+ // The Go type of `this` inside a class body (methods, constructor, field
4396
+ // initializers, arrow functions within them): *ClassName / *Box[T]; undefined
4397
+ // inside function expressions and object literals, where `this` is something else
4398
+ function thisGoType(node) {
4399
+ let current = node.parent;
4400
+ while (current) {
4401
+ if (isClassDeclaration(current)) {
4402
+ if (!current.name || !isIdentifier(current.name))
4403
+ return undefined;
4404
+ const params = (current.typeParameters ?? []).map((tp) => tp.name.text);
4405
+ return `*${current.name.text}${params.length > 0 ? `[${params.join(', ')}]` : ''}`;
4406
+ }
4407
+ if (isFunctionExpression(current) || isFunctionDeclaration(current) || isObjectLiteralExpression(current))
4408
+ return undefined;
4409
+ current = current.parent;
4410
+ }
4411
+ return undefined;
4412
+ }
4067
4413
  // Declared return type of a function, unwrapping Promise<T> for async functions
4068
4414
  function getReturnTypeNode(fn) {
4069
4415
  const typeNode = fn?.type ?? (fn ? getContextualFunctionType(fn)?.type : undefined);
@@ -4173,8 +4519,26 @@ function getContextualTypeNode(node) {
4173
4519
  return getReturnTypeNode(getEnclosingFunction(parent));
4174
4520
  }
4175
4521
  if (isArrowFunction(parent) && parent.body === node) {
4176
- return getReturnTypeNode(parent);
4522
+ const declared = getReturnTypeNode(parent);
4523
+ if (declared)
4524
+ return declared;
4525
+ // rows.map((r) => ({ … })) where the result must be Note[]: each item is a Note
4526
+ const call = parent.parent;
4527
+ if (isCallExpression(call) &&
4528
+ (call.arguments ?? [])[0] === parent &&
4529
+ isPropertyAccessExpression(call.expression) &&
4530
+ call.expression.name.text === 'map') {
4531
+ const resultType = resolveTypeNode(getContextualTypeNode(call));
4532
+ if (isArrayTypeNode(resultType))
4533
+ return resultType.elementType;
4534
+ }
4535
+ // items.reduce((acc, x) => ({ … }), init): the accumulator is the result type
4536
+ if (isReduceCall(call) && (call.arguments ?? [])[0] === parent)
4537
+ return getContextualTypeNode(call);
4538
+ return undefined;
4177
4539
  }
4540
+ if (isReduceCall(parent) && (parent.arguments ?? [])[1] === node)
4541
+ return getContextualTypeNode(parent);
4178
4542
  if (isCallExpression(parent) && isIdentifier(parent.expression)) {
4179
4543
  const index = (parent.arguments ?? []).indexOf(node);
4180
4544
  const fn = declaredFunctions.get(parent.expression.text);
@@ -4228,6 +4592,8 @@ function getArrayLiteralElementType(node) {
4228
4592
  const spreadType = inferExpressionType(element.expression);
4229
4593
  if (spreadType?.startsWith('[]'))
4230
4594
  return spreadType.slice(2);
4595
+ if (isTypedArrayGoType(spreadType))
4596
+ return 'float64';
4231
4597
  if (spreadType === 'string')
4232
4598
  return 'string';
4233
4599
  if (spreadType?.startsWith('*TnMap[') && extractMapValueType(spreadType) === 'struct{}') {
@@ -4300,6 +4666,54 @@ function unwrapParentheses(expr) {
4300
4666
  expr = expr.expression;
4301
4667
  return expr;
4302
4668
  }
4669
+ function isReduceCall(node) {
4670
+ return (isCallExpression(node) &&
4671
+ isPropertyAccessExpression(node.expression) &&
4672
+ (node.expression.name.text === 'reduce' || node.expression.name.text === 'reduceRight'));
4673
+ }
4674
+ // The Go type of tuple[i] (a literal index into a tuple-typed value held as
4675
+ // []interface{}): '' when not a tuple read or the element is itself dynamic
4676
+ function tupleElementGoType(expr) {
4677
+ if (!isNumericLiteral(expr.argumentExpression))
4678
+ return '';
4679
+ if (inferExpressionType(expr.expression) !== '[]interface{}')
4680
+ return '';
4681
+ let typeNode = resolveTypeNode(getExpressionTypeNode(expr.expression));
4682
+ if (!typeNode && isIdentifier(expr.expression))
4683
+ typeNode = resolveTypeNode(callbackParameterTypeNode(expr.expression));
4684
+ if (!typeNode || typeNode.kind !== 'TupleType')
4685
+ return '';
4686
+ const element = (typeNode.elements ?? [])[Number(expr.argumentExpression.text)];
4687
+ if (!element)
4688
+ return '';
4689
+ const goType = getType(element.kind === 'NamedTupleMember' ? element.type : element);
4690
+ return !goType || goType === 'interface{}' || isUnboundGoType(goType) ? '' : goType;
4691
+ }
4692
+ // The declared element type of an untyped callback parameter of an array
4693
+ // method (pairs.sort((a, b) => …) with pairs: [string, number][])
4694
+ function callbackParameterTypeNode(name) {
4695
+ let fn = name.parent;
4696
+ while (fn && !isArrowFunction(fn) && !isFunctionExpression(fn))
4697
+ fn = fn.parent;
4698
+ if (!fn)
4699
+ return undefined;
4700
+ const index = (fn.parameters ?? []).findIndex((p) => isIdentifier(p.name) && p.name.text === name.text);
4701
+ if (index < 0 || fn.parameters[index].type)
4702
+ return undefined;
4703
+ const call = fn.parent;
4704
+ if (!isCallExpression(call) || !isPropertyAccessExpression(call.expression))
4705
+ return undefined;
4706
+ const method = call.expression.name.text;
4707
+ const elementParams = {
4708
+ sort: [0, 1], toSorted: [0, 1], map: [0], filter: [0], forEach: [0], some: [0], every: [0], find: [0],
4709
+ findIndex: [0], findLast: [0], findLastIndex: [0], flatMap: [0], reduce: [1], reduceRight: [1]
4710
+ };
4711
+ const slots = elementParams[method];
4712
+ if (!slots || !slots.includes(index) || (call.arguments ?? [])[0] !== fn)
4713
+ return undefined;
4714
+ const arrayType = resolveTypeNode(getExpressionTypeNode(call.expression.expression));
4715
+ return isArrayTypeNode(arrayType) ? arrayType.elementType : undefined;
4716
+ }
4303
4717
  function getTupleElementType(tuple) {
4304
4718
  const types = (tuple.elements ?? []).map((t) => getType(t.kind === 'NamedTupleMember' ? t.type : t));
4305
4719
  return types.length > 0 && types.every((t) => t === types[0]) ? types[0] : 'interface{}';
@@ -4332,6 +4746,8 @@ function visitSpreadSource(expr) {
4332
4746
  if (sourceType === 'string') {
4333
4747
  return `func() []string { __parts := []string{}; for _, __r := range ${visit(expr)} { __parts = append(__parts, string(__r)) }; return __parts }()`;
4334
4748
  }
4749
+ if (isTypedArrayGoType(sourceType))
4750
+ return `${visit(expr)}.tnFloats()`;
4335
4751
  return visit(expr);
4336
4752
  }
4337
4753
  function visitSpreadArrayLiteral(node, elemType) {
@@ -4513,6 +4929,8 @@ function isMockAccess(node) {
4513
4929
  function inferExpressionType(expr) {
4514
4930
  if (isMockAccess(expr))
4515
4931
  return '*TnMockFunctionContext';
4932
+ if (expr?.kind === 'ThisKeyword')
4933
+ return thisGoType(expr);
4516
4934
  if (isAwaitExpression(expr)) {
4517
4935
  // await unwraps the promise channel
4518
4936
  const inner = inferExpressionType(expr.expression);
@@ -4625,11 +5043,16 @@ function inferExpressionType(expr) {
4625
5043
  }
4626
5044
  }
4627
5045
  if (isElementAccessExpression(expr)) {
5046
+ const tupleElement = tupleElementGoType(expr);
5047
+ if (tupleElement)
5048
+ return tupleElement;
4628
5049
  const objectType = inferExpressionType(expr.expression);
4629
5050
  if (objectType === 'string')
4630
5051
  return 'string';
4631
5052
  if (objectType?.startsWith('[]'))
4632
5053
  return objectType.slice(2);
5054
+ if (isTypedArrayGoType(objectType))
5055
+ return 'float64';
4633
5056
  if (objectType?.startsWith('*TnMap['))
4634
5057
  return extractMapValueType(objectType);
4635
5058
  const declared = getExpressionTypeNode(expr);
@@ -4892,6 +5315,25 @@ function inferExpressionType(expr) {
4892
5315
  return isStructGoType(valueType) ? `*${valueType}` : valueType;
4893
5316
  }
4894
5317
  }
5318
+ if (isTypedArrayGoType(ownerType)) {
5319
+ if (methodName === 'map' || methodName === 'filter')
5320
+ return ownerType;
5321
+ if (methodName === 'some' || methodName === 'every')
5322
+ return 'bool';
5323
+ if (['find', 'findIndex', 'findLast', 'findLastIndex'].includes(methodName))
5324
+ return 'float64';
5325
+ if (methodName === 'reduce' || methodName === 'reduceRight') {
5326
+ return (expr.arguments?.[1] ? inferExpressionType(expr.arguments[1]) : undefined) ?? 'float64';
5327
+ }
5328
+ if (methodName === 'entries')
5329
+ return '[][]interface{}';
5330
+ }
5331
+ if (methodName === 'from' &&
5332
+ isIdentifier(expr.expression.expression) &&
5333
+ expr.expression.expression.text === 'Array' &&
5334
+ isTypedArrayGoType(inferExpressionType(expr.arguments?.[0]))) {
5335
+ return '[]float64';
5336
+ }
4895
5337
  if (isArrayLikeGoType(ownerType)) {
4896
5338
  const elementType = getArrayElementTypeFromGoType(ownerType);
4897
5339
  if (methodName === 'map') {
@@ -5766,6 +6208,9 @@ function buildArrayCallbackInvocationReduce(callbackInfo, accVar, itemVar, index
5766
6208
  return `(${callbackInfo.fnExpr})(${args.join(', ')})`;
5767
6209
  }
5768
6210
  function visitArrayHigherOrderCall(node) {
6211
+ // Set by visitTypedArrayCall for this call only (callbacks may hold other calls)
6212
+ const typedReceiver = typedArrayReceiverExpr;
6213
+ typedArrayReceiverExpr = '';
5769
6214
  if (!isPropertyAccessExpression(node.expression))
5770
6215
  return undefined;
5771
6216
  const methodName = node.expression.name.text;
@@ -5773,8 +6218,8 @@ function visitArrayHigherOrderCall(node) {
5773
6218
  return undefined;
5774
6219
  }
5775
6220
  const arrayExprNode = node.expression.expression;
5776
- const arrayExpr = visit(arrayExprNode);
5777
- const ownerType = inferExpressionType(arrayExprNode);
6221
+ const arrayExpr = typedReceiver ? typedReceiver : visit(arrayExprNode);
6222
+ const ownerType = typedReceiver ? '[]float64' : inferExpressionType(arrayExprNode);
5778
6223
  const elementType = isArrayLikeGoType(ownerType)
5779
6224
  ? getArrayElementTypeFromGoType(ownerType)
5780
6225
  : 'interface{}';
@@ -6359,6 +6804,10 @@ function getAcessString(leftSide, rightSide, objectType) {
6359
6804
  return `float64(len(${leftSide}))`;
6360
6805
  }
6361
6806
  // Buffers / Uint8Arrays / ArrayBuffers are []byte
6807
+ if (rightSide === 'buffer' && objectType === 'Buffer')
6808
+ return leftSide;
6809
+ if (rightSide === 'byteOffset' && objectType === 'Buffer')
6810
+ return 'float64(0)';
6362
6811
  if (rightSide === 'byteLength' && objectType === 'Buffer') {
6363
6812
  return `float64(len(${leftSide}))`;
6364
6813
  }
@@ -7817,7 +8266,13 @@ function getCollectionArgumentTypes(node) {
7817
8266
  if (!isPropertyAccessExpression(node.expression))
7818
8267
  return undefined;
7819
8268
  const method = node.expression.name.text;
7820
- const receiverType = inferExpressionType(node.expression.expression);
8269
+ let receiverType = inferExpressionType(node.expression.expression);
8270
+ // this.items.push(x): the field's declared type
8271
+ if (!receiverType) {
8272
+ const declared = getExpressionTypeNode(node.expression.expression);
8273
+ if (declared)
8274
+ receiverType = getType(declared);
8275
+ }
7821
8276
  if (receiverType?.startsWith('*TnMap[')) {
7822
8277
  const keyType = extractMapKeyType(receiverType);
7823
8278
  const valueType = extractMapValueType(receiverType);
@@ -8048,15 +8503,18 @@ function emitChannelFunction(node, isAsync) {
8048
8503
  const rejectOnPanic = isAsync ? `\n\t\tdefer TnRejectOnPanic(${channelVar})` : '';
8049
8504
  const prevChannel = asyncChannelVar;
8050
8505
  const prevFn = asyncFunctionNode;
8506
+ const prevIsAsync = asyncChannelIsAsync;
8051
8507
  asyncChannelVar = channelVar;
8052
8508
  asyncFunctionNode = node;
8509
+ asyncChannelIsAsync = isAsync;
8053
8510
  const body = visit(node.body, { prefixBlockContent: parameterInfo.prefixBlockContent });
8054
8511
  asyncChannelVar = prevChannel;
8055
8512
  asyncFunctionNode = prevFn;
8513
+ asyncChannelIsAsync = prevIsAsync;
8056
8514
  if (isAsync) {
8057
8515
  // The body runs synchronously until its first await, holding the JS baton
8058
8516
  useHelper('eventLoop');
8059
- return (`func ${name}${typeParams}(${parameterInfo.signature}) chan ${chanType} {\n\t${channelVar} := make(chan ${chanType}, 1)\n\tTnStartAsync(func() {\n\t\tdefer close(${channelVar})${rejectOnPanic}\n\t\t${body.trim()}\n\t})\n\treturn ${channelVar}\n}`);
8517
+ return (`func ${name}${typeParams}(${parameterInfo.signature}) chan ${chanType} {\n\t${channelVar} := make(chan ${chanType}, 1)\n\tTnStartAsync(func() {\n\t\tdefer TnAsyncClose(${channelVar})${rejectOnPanic}\n\t\t${body.trim()}\n\t})\n\treturn ${channelVar}\n}`);
8060
8518
  }
8061
8519
  return (`func ${name}${typeParams}(${parameterInfo.signature}) chan ${chanType} {\n\t${channelVar} := make(chan ${chanType})\n\tgo func() {\n\t\tdefer close(${channelVar})${rejectOnPanic}\n\t\t${body.trim()}\n\t}()\n\treturn ${channelVar}\n}`);
8062
8520
  }
@@ -8271,7 +8729,7 @@ function includeLocalImport(code, dir, goFileName, tsx = false, fileName = '') {
8271
8729
  .sort()
8272
8730
  .map((pkg) => goImportLine(pkg))
8273
8731
  .join('\n');
8274
- const parts = ['package main'];
8732
+ const parts = [GENERATED_HEADER, 'package main'];
8275
8733
  if (fileImports)
8276
8734
  parts.push(fileImports);
8277
8735
  if (fileInline.trim())
@@ -8451,11 +8909,13 @@ function bindNodeRegistryServices() {
8451
8909
  nodeRegistry.typeOf = (node) => inferExpressionType(node) ?? '';
8452
8910
  nodeRegistry.visit = (node) => visit(node);
8453
8911
  nodeRegistry.categoryOf = (node) => resolveExpressionType(node) ?? '';
8912
+ nodeRegistry.isArrayBuffer = (node) => isArrayBufferExpression(node);
8454
8913
  bindConvertServices({
8455
8914
  pkg: needPkg,
8456
8915
  helper: useHelper,
8457
8916
  typeOf: (node) => inferExpressionType(node) ?? '',
8458
- localType: goLocalType
8917
+ localType: goLocalType,
8918
+ adapt: adaptClassToGoInterface
8459
8919
  });
8460
8920
  bindBridgeServices({
8461
8921
  pkg: needPkg,
@@ -8475,6 +8935,7 @@ function bindNodeRegistryServices() {
8475
8935
  }
8476
8936
  registerCore(nodeRegistry);
8477
8937
  registerBuffer(nodeRegistry);
8938
+ registerTypedArrays(nodeRegistry);
8478
8939
  registerPath(nodeRegistry);
8479
8940
  registerFs(nodeRegistry);
8480
8941
  registerUrl(nodeRegistry);
@@ -8490,6 +8951,7 @@ registerStringDecoder(nodeRegistry);
8490
8951
  registerCrypto(nodeRegistry);
8491
8952
  registerCryptoKeys(nodeRegistry);
8492
8953
  registerZlib(nodeRegistry);
8954
+ registerFsWatch(nodeRegistry);
8493
8955
  registerTimers(nodeRegistry);
8494
8956
  registerEvents(nodeRegistry);
8495
8957
  registerStream(nodeRegistry);
@@ -10814,6 +11276,9 @@ func tnRunDueTimers() {
10814
11276
  __tnTimers.Done()
10815
11277
  }
10816
11278
  t.fn()
11279
+ // Microtasks (promise continuations) run after each timer callback,
11280
+ // before the next one fires — as Node does
11281
+ TnRunMicrotasks()
10817
11282
  }
10818
11283
  }
10819
11284
 
@@ -11146,7 +11611,9 @@ func tnRunTask(fn func()) {
11146
11611
  func tnLoopIdle() bool {
11147
11612
  tnLoopMu.Lock()
11148
11613
  defer tnLoopMu.Unlock()
11149
- return len(tnLoopTasks) == 0 && atomic.LoadInt64(&tnLoopRefs) <= 0
11614
+ tnMicrotasksMu.Lock()
11615
+ defer tnMicrotasksMu.Unlock()
11616
+ return len(tnLoopTasks) == 0 && len(tnMicrotasks) == 0 && atomic.LoadInt64(&tnLoopRefs) <= 0
11150
11617
  }
11151
11618
 
11152
11619
  // The end of main: run until nothing is pending
@@ -11174,8 +11641,86 @@ func TnRunLoop() {
11174
11641
  }
11175
11642
  }
11176
11643
 
11177
- // (baton holder) Receives from a channel, running loop tasks while waiting
11644
+ // Parked awaits, keyed by promise channel. A promise resolution (TnAsyncSend /
11645
+ // TnAsyncClose) delivers under tnWakeMu and queues an ordered wakeup instead of
11646
+ // waking the awaiter directly: continuations must resume in the order their
11647
+ // promises settled, like Node's microtasks — awaiters racing for the baton
11648
+ // would resume out of order on a starved machine.
11649
+ var tnWakeMu sync.Mutex
11650
+ var tnAwaiting = map[any]chan struct{}{}
11651
+
11652
+ // (baton holder) hands the baton to a parked awaiter and waits for it to park
11653
+ // again (or finish): JS keeps running one thing at a time
11654
+ func tnDeliver(tok chan struct{}) {
11655
+ back := make(chan struct{})
11656
+ tnLendStack = append(tnLendStack, back)
11657
+ close(tok)
11658
+ <-back
11659
+ }
11660
+
11661
+ // Queues the ordered wakeup of a parked awaiter (nil tok: nobody parked)
11662
+ func tnWakeQueue(tok chan struct{}) {
11663
+ if tok == nil {
11664
+ return
11665
+ }
11666
+ tnMicrotasksMu.Lock()
11667
+ tnMicrotasks = append(tnMicrotasks, func() { tnDeliver(tok) })
11668
+ tnMicrotasksMu.Unlock()
11669
+ tnLoopNotify()
11670
+ }
11671
+
11672
+ // (baton holder) Receives from a channel, running loop tasks while waiting;
11673
+ // once nothing is left it parks. A promise wake resumes in settlement order
11674
+ // with the baton handed over; a raw send (a generator yield) resumes the old
11675
+ // way, racing for the baton
11178
11676
  func TnLoopReceive[T any](ch chan T) (T, bool) {
11677
+ ctx := tnAsyncCtx
11678
+ defer func() { tnAsyncCtx = ctx }()
11679
+ for {
11680
+ select {
11681
+ case v, ok := <-ch:
11682
+ return v, ok
11683
+ default:
11684
+ }
11685
+ TnRunMicrotasks()
11686
+ if TnLoopRunPending() {
11687
+ continue
11688
+ }
11689
+ tok := make(chan struct{})
11690
+ tnWakeMu.Lock()
11691
+ select {
11692
+ case v, ok := <-ch:
11693
+ tnWakeMu.Unlock()
11694
+ return v, ok
11695
+ default:
11696
+ tnAwaiting[any(ch)] = tok
11697
+ }
11698
+ tnWakeMu.Unlock()
11699
+ tnRelease()
11700
+ select {
11701
+ case v, ok := <-ch:
11702
+ // The value is taken; when a promise wake was queued (the token
11703
+ // is gone) it hands the baton over, else take the baton ourselves
11704
+ tnWakeMu.Lock()
11705
+ _, raw := tnAwaiting[any(ch)]
11706
+ if raw {
11707
+ delete(tnAwaiting, any(ch))
11708
+ }
11709
+ tnWakeMu.Unlock()
11710
+ if raw {
11711
+ tnAcquire()
11712
+ } else {
11713
+ <-tok
11714
+ }
11715
+ return v, ok
11716
+ case <-tok:
11717
+ }
11718
+ }
11719
+ }
11720
+
11721
+ // (baton holder) Receives from a channel of raw sends (generator yields),
11722
+ // running loop tasks while waiting
11723
+ func tnRawReceive[T any](ch chan T) (T, bool) {
11179
11724
  ctx := tnAsyncCtx
11180
11725
  defer func() { tnAsyncCtx = ctx }()
11181
11726
  for {
@@ -11473,12 +12018,48 @@ func TnRejectExecutor[T any](ch chan T) {
11473
12018
  }
11474
12019
  }
11475
12020
 
11476
- func TnResolveZero[T any](ch chan T) {
11477
- var zero T
12021
+ // Promise resolution: the value (or rejection) is sent and the parked awaiter
12022
+ // woken in settlement order — Node runs promise continuations as ordered
12023
+ // microtasks; a bare channel wake would race for the baton and resume out of
12024
+ // order on a starved machine
12025
+ func TnAsyncSend[T any](ch chan T, v T) {
12026
+ tok := make(chan struct{})
12027
+ handoff := false
12028
+ tnWakeMu.Lock()
11478
12029
  select {
11479
- case ch <- zero:
12030
+ case ch <- v:
11480
12031
  default:
11481
12032
  }
12033
+ if t, parked := tnAwaiting[any(ch)]; parked {
12034
+ delete(tnAwaiting, any(ch))
12035
+ tok = t
12036
+ handoff = true
12037
+ }
12038
+ tnWakeMu.Unlock()
12039
+ if handoff {
12040
+ tnWakeQueue(tok)
12041
+ }
12042
+ }
12043
+
12044
+ func TnAsyncClose[T any](ch chan T) {
12045
+ tok := make(chan struct{})
12046
+ handoff := false
12047
+ tnWakeMu.Lock()
12048
+ close(ch)
12049
+ if t, parked := tnAwaiting[any(ch)]; parked {
12050
+ delete(tnAwaiting, any(ch))
12051
+ tok = t
12052
+ handoff = true
12053
+ }
12054
+ tnWakeMu.Unlock()
12055
+ if handoff {
12056
+ tnWakeQueue(tok)
12057
+ }
12058
+ }
12059
+
12060
+ func TnResolveZero[T any](ch chan T) {
12061
+ var zero T
12062
+ TnAsyncSend(ch, zero)
11482
12063
  }
11483
12064
 
11484
12065
  // resolve / reject of a Promise executor used as values
@@ -11490,10 +12071,7 @@ func TnResolver[T any](ch chan T) func(...interface{}) {
11490
12071
  v = x
11491
12072
  }
11492
12073
  }
11493
- select {
11494
- case ch <- v:
11495
- default:
11496
- }
12074
+ TnAsyncSend(ch, v)
11497
12075
  }
11498
12076
  }
11499
12077
 
@@ -11512,7 +12090,7 @@ func TnRejecter[T any](ch chan T) func(...interface{}) {
11512
12090
 
11513
12091
  func TnReject[T any](ch chan T, reason interface{}) {
11514
12092
  tnRejections.Store(ch, reason)
11515
- close(ch)
12093
+ TnAsyncClose(ch)
11516
12094
  }
11517
12095
 
11518
12096
  // A detached call (\`main();\`): the process waits for it; a rejection is fatal
@@ -11566,6 +12144,18 @@ func TnAwait[T any](ch chan T) T {
11566
12144
  return v
11567
12145
  }
11568
12146
 
12147
+ // await in code running inline on the loop goroutine (an async callback — an
12148
+ // arrow, an event handler): the self-draining receive — this goroutine is the
12149
+ // loop, so it must keep running tasks while it waits
12150
+ func TnAwaitInline[T any](ch chan T) T {
12151
+ received, ok := tnRawReceive(ch)
12152
+ v, reason, rejected := tnSettled(ch, received, ok)
12153
+ if rejected {
12154
+ panic(reason)
12155
+ }
12156
+ return v
12157
+ }
12158
+
11569
12159
  func TnPromiseReject[T any](reason interface{}) chan T {
11570
12160
  ch := make(chan T)
11571
12161
  TnReject(ch, reason)
@@ -11581,8 +12171,8 @@ func TnPromiseCatch[T any, E any](p chan T, onRejected func(E)) chan T {
11581
12171
  e, _ := reason.(E)
11582
12172
  TnLoopCall(func() { TnAsyncRun(ctx, func() { onRejected(e) }) })
11583
12173
  }
11584
- out <- v
11585
- close(out)
12174
+ TnAsyncSend(out, v)
12175
+ TnAsyncClose(out)
11586
12176
  }()
11587
12177
  return out
11588
12178
  }
@@ -11596,8 +12186,8 @@ func TnPromiseCatchValue[T any, E any](p chan T, onRejected func(E) T) chan T {
11596
12186
  e, _ := reason.(E)
11597
12187
  TnLoopCall(func() { TnAsyncRun(ctx, func() { v = onRejected(e) }) })
11598
12188
  }
11599
- out <- v
11600
- close(out)
12189
+ TnAsyncSend(out, v)
12190
+ TnAsyncClose(out)
11601
12191
  }()
11602
12192
  return out
11603
12193
  }
@@ -11612,8 +12202,8 @@ func TnPromiseFinally[T any](p chan T, onFinally func()) chan T {
11612
12202
  TnReject(out, reason)
11613
12203
  return
11614
12204
  }
11615
- out <- v
11616
- close(out)
12205
+ TnAsyncSend(out, v)
12206
+ TnAsyncClose(out)
11617
12207
  }()
11618
12208
  return out
11619
12209
  }
@@ -11630,8 +12220,8 @@ func TnPromiseRace[T any](chs []chan T) chan T {
11630
12220
  TnReject(out, reason)
11631
12221
  return
11632
12222
  }
11633
- out <- v
11634
- close(out)
12223
+ TnAsyncSend(out, v)
12224
+ TnAsyncClose(out)
11635
12225
  })
11636
12226
  }(ch)
11637
12227
  }
@@ -11656,8 +12246,8 @@ func TnPromiseAllSettled[T any](chs []chan T) chan []*TnSettled[T] {
11656
12246
  results[i] = &TnSettled[T]{status: "fulfilled", value: v}
11657
12247
  }
11658
12248
  }
11659
- out <- results
11660
- close(out)
12249
+ TnAsyncSend(out, results)
12250
+ TnAsyncClose(out)
11661
12251
  }()
11662
12252
  return out
11663
12253
  }
@@ -11681,8 +12271,8 @@ func TnPromiseAny[T any](chs []chan T) chan T {
11681
12271
  for range chs {
11682
12272
  select {
11683
12273
  case v := <-values:
11684
- out <- v
11685
- close(out)
12274
+ TnAsyncSend(out, v)
12275
+ TnAsyncClose(out)
11686
12276
  return
11687
12277
  case <-failures:
11688
12278
  }
@@ -11693,7 +12283,7 @@ func TnPromiseAny[T any](chs []chan T) chan T {
11693
12283
  }`,
11694
12284
  promiseAll: `// Promise.all: every channel drained in order, results collected
11695
12285
  func TnPromiseAll[T any](chs []chan T) chan []T {
11696
- out := make(chan []T)
12286
+ out := make(chan []T, 1)
11697
12287
  go func() {
11698
12288
  results := make([]T, len(chs))
11699
12289
  for i, ch := range chs {
@@ -11704,8 +12294,8 @@ func TnPromiseAll[T any](chs []chan T) chan []T {
11704
12294
  }
11705
12295
  results[i] = v
11706
12296
  }
11707
- out <- results
11708
- close(out)
12297
+ TnAsyncSend(out, results)
12298
+ TnAsyncClose(out)
11709
12299
  }()
11710
12300
  return out
11711
12301
  }`,
@@ -12545,7 +13135,8 @@ function visitForOfSequence(node, iterExpr, iterType) {
12545
13135
  registerLocalVariable(declaration.name.text, elemType);
12546
13136
  // A rejected iterator (a stream error) throws out of the loop
12547
13137
  useHelper('promise');
12548
- let awaitPrefix = `${valueVar}, __ok := TnLoopReceive(${chanVar})\n\t\tif !__ok {\n\t\t\tif __reason, __rejected := tnRejections.Load(${chanVar}); __rejected {\n\t\t\t\tpanic(__reason)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t_ = ${valueVar}\n\t\t`;
13138
+ // Raw receive: iterator channels are fed by raw sends (generator yields)
13139
+ let awaitPrefix = `${valueVar}, __ok := tnRawReceive(${chanVar})\n\t\tif !__ok {\n\t\t\tif __reason, __rejected := tnRejections.Load(${chanVar}); __rejected {\n\t\t\t\tpanic(__reason)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t_ = ${valueVar}\n\t\t`;
12549
13140
  if (declaration && isArrayBindingPattern(declaration.name)) {
12550
13141
  const memberType = elemType.startsWith('[]') ? elemType.slice(2) : undefined;
12551
13142
  useHelper('dynamic');