typenative 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/bin/node/assert.js +2 -2
  2. package/bin/node/child_process.js +66 -8
  3. package/bin/node/fs.js +1012 -4
  4. package/bin/node/histogram.js +1991 -0
  5. package/bin/node/process.js +14 -2
  6. package/bin/node/sqlite.js +1488 -5
  7. package/bin/node/stream.js +2 -1
  8. package/bin/node/system_extra.js +3 -270
  9. package/bin/node/test.js +39 -1
  10. package/bin/node/test_report.js +47 -1
  11. package/bin/node/test_run.js +57 -2
  12. package/bin/node/util.js +8 -5
  13. package/bin/node/webassembly.js +20 -5
  14. package/bin/node/webview.js +3257 -244
  15. package/bin/node/zlib.js +118 -14
  16. package/bin/node/zlib_iter.js +585 -0
  17. package/bin/transpiler.js +1370 -258
  18. package/bin/version.js +1 -1
  19. package/govendor/software.sslmate.com/src/go-pkcs12/.gitattributes +10 -0
  20. package/govendor/software.sslmate.com/src/go-pkcs12/LICENSE +28 -0
  21. package/govendor/software.sslmate.com/src/go-pkcs12/README.md +31 -0
  22. package/govendor/software.sslmate.com/src/go-pkcs12/bmp-string.go +63 -0
  23. package/govendor/software.sslmate.com/src/go-pkcs12/crypto.go +331 -0
  24. package/govendor/software.sslmate.com/src/go-pkcs12/errors.go +23 -0
  25. package/govendor/software.sslmate.com/src/go-pkcs12/go.mod +3 -0
  26. package/govendor/software.sslmate.com/src/go-pkcs12/internal/rc2/rc2.go +271 -0
  27. package/govendor/software.sslmate.com/src/go-pkcs12/mac.go +202 -0
  28. package/govendor/software.sslmate.com/src/go-pkcs12/pbkdf.go +184 -0
  29. package/govendor/software.sslmate.com/src/go-pkcs12/pkcs12.go +1000 -0
  30. package/govendor/software.sslmate.com/src/go-pkcs12/safebags.go +107 -0
  31. package/package.json +10 -1
  32. package/types/tsconfig.json +17 -0
  33. package/types/typenative-npm.d.ts +492 -12
  34. package/types/typenative.d.ts +88 -2
  35. package/.gitattributes +0 -1
  36. package/.github/workflows/ci.yml +0 -68
  37. package/.github/workflows/npm-publish-github-packages.yml +0 -88
  38. package/CHANGELOG.md +0 -1746
  39. package/CONTRIBUTION.md +0 -133
  40. package/conformance.md +0 -1497
  41. package/examples/README.md +0 -114
  42. package/examples/angular-templates/README.md +0 -141
  43. package/examples/angular-templates/bench.mjs +0 -173
  44. package/examples/angular-templates/dom-type-globals.d.ts +0 -21
  45. package/examples/angular-templates/dom-type-stubs.ts +0 -21
  46. package/examples/angular-templates/main.ts +0 -135
  47. package/examples/angular-templates/parity.mjs +0 -157
  48. package/examples/angular-templates/run-node.mjs +0 -69
  49. package/examples/angular-templates/vendor/angular/compiler/LICENSE +0 -21
  50. package/examples/desktop-notes/README.md +0 -106
  51. package/examples/desktop-notes/bench.mjs +0 -125
  52. package/examples/desktop-notes/main.ts +0 -131
  53. package/examples/desktop-notes/package-lock.json +0 -726
  54. package/examples/desktop-notes/package.json +0 -9
  55. package/examples/desktop-notes/ui.ts +0 -176
  56. package/examples/dupe-finder/README.md +0 -78
  57. package/examples/dupe-finder/bench.mjs +0 -120
  58. package/examples/dupe-finder/main.ts +0 -87
  59. package/examples/fibonacci/README.md +0 -89
  60. package/examples/fibonacci/bench.mjs +0 -87
  61. package/examples/fibonacci/main.ts +0 -21
  62. package/examples/hello-world/README.md +0 -62
  63. package/examples/hello-world/bench.mjs +0 -66
  64. package/examples/hello-world/main.ts +0 -7
  65. package/examples/json-server/README.md +0 -132
  66. package/examples/json-server/bench.mjs +0 -263
  67. package/examples/json-server/main.ts +0 -67
  68. package/examples/mandelbrot-png/README.md +0 -63
  69. package/examples/mandelbrot-png/bench.mjs +0 -95
  70. package/examples/mandelbrot-png/main.ts +0 -98
  71. package/examples/mandelbrot-png/preview.png +0 -0
  72. package/examples/marked-cli/README.md +0 -174
  73. package/examples/marked-cli/bench.mjs +0 -178
  74. package/examples/marked-cli/main.ts +0 -410
  75. package/examples/marked-cli/parity.mjs +0 -185
  76. package/examples/marked-cli/vendor/marked/LICENSE +0 -44
  77. package/examples/marked-cli/vendor/marked/VENDOR.md +0 -26
  78. package/examples/openai-chat/README.md +0 -148
  79. package/examples/openai-chat/bench.mjs +0 -175
  80. package/examples/openai-chat/main.ts +0 -488
  81. package/examples/react-compiler/README.md +0 -185
  82. package/examples/react-compiler/bench.mjs +0 -181
  83. package/examples/react-compiler/main.ts +0 -324
  84. package/examples/react-compiler/parity.mjs +0 -362
  85. package/examples/react-compiler/run-node.mjs +0 -90
  86. package/examples/react-compiler/vendor/babel/LICENSE +0 -22
  87. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-lower.json +0 -15
  88. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-upper.json +0 -51
  89. package/examples/react-compiler/vendor/charcodes/package.json +0 -25
  90. package/examples/react-compiler/vendor/invariant/LICENSE +0 -21
  91. package/examples/react-compiler/vendor/invariant/invariant.cjs +0 -51
  92. package/examples/react-compiler/vendor/invariant/invariant.d.cts +0 -11
  93. package/examples/react-compiler/vendor/invariant/types/LICENSE +0 -21
  94. package/examples/react-compiler/vendor/jridgewell/gen-mapping/LICENSE +0 -19
  95. package/examples/react-compiler/vendor/jridgewell/resolve-uri/LICENSE +0 -19
  96. package/examples/react-compiler/vendor/jridgewell/sourcemap-codec/LICENSE +0 -19
  97. package/examples/react-compiler/vendor/jridgewell/trace-mapping/LICENSE +0 -19
  98. package/examples/react-compiler/vendor/js-tokens/LICENSE +0 -21
  99. package/examples/react-compiler/vendor/js-tokens/index.cjs +0 -23
  100. package/examples/react-compiler/vendor/js-tokens/index.d.cts +0 -13
  101. package/examples/react-compiler/vendor/jsesc/LICENSE-MIT.txt +0 -20
  102. package/examples/react-compiler/vendor/jsesc/jsesc.cjs +0 -337
  103. package/examples/react-compiler/vendor/jsesc/jsesc.d.cts +0 -384
  104. package/examples/react-compiler/vendor/jsesc/types/LICENSE +0 -21
  105. package/examples/react-compiler/vendor/picocolors/LICENSE +0 -15
  106. package/examples/react-compiler/vendor/picocolors/picocolors.cjs +0 -75
  107. package/examples/react-compiler/vendor/picocolors/picocolors.d.cts +0 -5
  108. package/examples/react-compiler/vendor/picocolors/types.d.ts +0 -51
  109. package/examples/react-compiler/vendor/react-compiler/LICENSE +0 -21
  110. package/examples/react-compiler/vendor/stubs/babel-core.ts +0 -31
  111. package/examples/react-compiler/vendor/stubs/debug.ts +0 -18
  112. package/examples/react-compiler/vendor/stubs/js-tokens.d.ts +0 -13
  113. package/examples/react-compiler/vendor/stubs/pretty-format.ts +0 -18
  114. package/examples/react-compiler/vendor/zod/LICENSE +0 -21
  115. package/examples/react-compiler/vendor/zod-validation-error/LICENSE +0 -9
  116. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/NonEmptyArray.ts +0 -5
  117. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinPath.ts +0 -49
  118. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinValues.ts +0 -48
  119. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/stringify.ts +0 -50
  120. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/titleCase.ts +0 -6
  121. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/MessageBuilder.ts +0 -126
  122. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/ValidationError.ts +0 -39
  123. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/custom.ts +0 -12
  124. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/errorMap.ts +0 -78
  125. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/index.ts +0 -2
  126. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidElement.ts +0 -12
  127. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidKey.ts +0 -12
  128. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidStringFormat.ts +0 -131
  129. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidType.ts +0 -54
  130. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidUnion.ts +0 -12
  131. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidValue.ts +0 -40
  132. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/notMultipleOf.ts +0 -12
  133. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooBig.ts +0 -76
  134. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooSmall.ts +0 -76
  135. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/types.ts +0 -27
  136. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/unrecognizedKeys.ts +0 -27
  137. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromError.ts +0 -13
  138. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodError.ts +0 -61
  139. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodIssue.ts +0 -38
  140. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/index.ts +0 -20
  141. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationError.ts +0 -5
  142. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationErrorLike.ts +0 -8
  143. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isZodErrorLike.ts +0 -11
  144. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/toValidationError.ts +0 -20
  145. package/examples/react-compiler/vendor.mjs +0 -688
  146. package/examples/todo-cli/README.md +0 -69
  147. package/examples/todo-cli/bench.mjs +0 -89
  148. package/examples/todo-cli/main.ts +0 -92
  149. package/examples/yaml-cli/README.md +0 -152
  150. package/examples/yaml-cli/bench.mjs +0 -265
  151. package/examples/yaml-cli/main.ts +0 -251
  152. package/examples/yaml-cli/parity.mjs +0 -156
  153. package/examples/yaml-cli/vendor/yaml/LICENSE +0 -13
  154. package/examples/yaml-cli/vendor/yaml/VENDOR.md +0 -25
  155. package/performance/README.md +0 -248
  156. package/performance/any-dynamic.ts +0 -21
  157. package/performance/any-record-view.ts +0 -20
  158. package/performance/arr-for-of.ts +0 -29
  159. package/performance/arr-hof.ts +0 -21
  160. package/performance/arr-push-index.ts +0 -15
  161. package/performance/arr-push-local.ts +0 -39
  162. package/performance/arr-slice-concat.ts +0 -24
  163. package/performance/arr-sort.ts +0 -21
  164. package/performance/async-await.ts +0 -24
  165. package/performance/async-promise-all.ts +0 -38
  166. package/performance/bigint-arith.ts +0 -36
  167. package/performance/buf-encode.ts +0 -29
  168. package/performance/class-accessors.ts +0 -48
  169. package/performance/class-dispatch.ts +0 -52
  170. package/performance/date-format.ts +0 -18
  171. package/performance/events-emit.ts +0 -27
  172. package/performance/exc-throw-rare.ts +0 -25
  173. package/performance/exc-try-catch.ts +0 -26
  174. package/performance/fn-closures.ts +0 -29
  175. package/performance/fn-recursion-tree.ts +0 -31
  176. package/performance/fn-rest-spread.ts +0 -43
  177. package/performance/gen-for-of.ts +0 -46
  178. package/performance/gen-next.ts +0 -32
  179. package/performance/iter-helpers.ts +0 -38
  180. package/performance/json-any.ts +0 -30
  181. package/performance/json-roundtrip.ts +0 -27
  182. package/performance/map-delete.ts +0 -24
  183. package/performance/map-iterate.ts +0 -26
  184. package/performance/map-number-keys.ts +0 -37
  185. package/performance/map-string-keys.ts +0 -22
  186. package/performance/num-arith-loop.ts +0 -14
  187. package/performance/num-bitwise.ts +0 -21
  188. package/performance/num-hash-imul.ts +0 -36
  189. package/performance/num-mod-int.ts +0 -16
  190. package/performance/num-to-string.ts +0 -16
  191. package/performance/obj-alloc.ts +0 -32
  192. package/performance/obj-keys-entries.ts +0 -44
  193. package/performance/obj-optional-chain.ts +0 -42
  194. package/performance/obj-record-dict.ts +0 -24
  195. package/performance/obj-spread-destructure.ts +0 -40
  196. package/performance/regex-exec.ts +0 -29
  197. package/performance/regex-replace-fn.ts +0 -24
  198. package/performance/regex-site.ts +0 -28
  199. package/performance/set-ops.ts +0 -20
  200. package/performance/str-char-scan.ts +0 -35
  201. package/performance/str-concat-plus.ts +0 -18
  202. package/performance/str-concat.ts +0 -24
  203. package/performance/str-methods.ts +0 -24
  204. package/performance/str-short-scan.ts +0 -26
  205. package/performance/str-split-join.ts +0 -23
  206. package/performance/str-switch-compare.ts +0 -50
  207. package/performance/str-template.ts +0 -16
  208. package/performance/str-unicode.ts +0 -25
  209. package/performance/typed-array.ts +0 -30
  210. package/performance/union-switch.ts +0 -57
  211. package/performance/union-typeof.ts +0 -40
  212. package/performance/wasm-call.ts +0 -63
  213. package/tsparser/check.go +0 -158
  214. package/tsparser/go.mod +0 -14
  215. package/tsparser/go.sum +0 -22
  216. package/tsparser/main.go +0 -363
  217. package/tsparser/tsparser.exe +0 -4
package/bin/transpiler.js CHANGED
@@ -386,6 +386,7 @@ let asyncFunctionNode;
386
386
  // True while emitting the body of an async function (not a generator): its
387
387
  // return settles the promise (ordered wake); a generator's sends stay raw
388
388
  let asyncChannelIsAsync = false;
389
+ let asyncChannelYieldType = 'interface{}';
389
390
  // Variables holding JS arrays: stored as *[]T so aliasing shares the slice
390
391
  // header (push/splice through any alias are visible everywhere)
391
392
  const referenceArrays = new Set();
@@ -553,6 +554,12 @@ const classStaticMethods = new Set();
553
554
  const classStaticProps = new Set();
554
555
  // Static getters (`static get tagName()`): reads call C_Get_tagName()
555
556
  const classStaticGetters = new Set();
557
+ // Static setters (`static set tagName(v)` / `static accessor x`): writes call C_Set_tagName(v)
558
+ const classStaticSetters = new Set();
559
+ // Classes with instance-level addInitializer callbacks (method/getter/setter)
560
+ const classesWithInstanceInits = new Set();
561
+ // Classes whose __metadata package variable has been emitted
562
+ const emittedClassMetadata = new Set();
556
563
  // The Go parameter list of each class's NewC constructor
557
564
  const classConstructorSignatures = new Map();
558
565
  // Set when the program uses classes as values (TnClass descriptors are emitted)
@@ -3761,6 +3768,9 @@ export function transpileToNative(code, options) {
3761
3768
  classStaticMethods.clear();
3762
3769
  classStaticProps.clear();
3763
3770
  classStaticGetters.clear();
3771
+ classStaticSetters.clear();
3772
+ classesWithInstanceInits.clear();
3773
+ emittedClassMetadata.clear();
3764
3774
  classConstructorSignatures.clear();
3765
3775
  classValuesUsed = false;
3766
3776
  emittedClasses.clear();
@@ -4625,6 +4635,10 @@ function visitNode(node, options = {}) {
4625
4635
  if (hasQuestionDot(node)) {
4626
4636
  return visitOptionalElementAccess(node);
4627
4637
  }
4638
+ // C[Symbol.metadata]: the class's decorator metadata object
4639
+ if (isIdentifier(node.expression) && classNames.has(node.expression.text) && isSymbolMetadata(node.argumentExpression)) {
4640
+ return ensureClassMetadata(getSafeName(node.expression.text));
4641
+ }
4628
4642
  // Enum['Member'] is the member; NumericEnum[value] its name (reverse mapping)
4629
4643
  if (isIdentifier(node.expression) && enumNames.has(node.expression.text)) {
4630
4644
  const enumGoName = getSafeName(node.expression.text);
@@ -4840,11 +4854,15 @@ function visitNode(node, options = {}) {
4840
4854
  useHelper('isArray');
4841
4855
  return 'func(__v interface{}) bool { return TnIsArray(__v) }';
4842
4856
  }
4843
- // Symbol.hasInstance as a value: the well-known symbol
4857
+ // Symbol.hasInstance / Symbol.metadata as values: well-known symbols
4844
4858
  if (isIdentifier(node.expression) && node.expression.text === 'Symbol' && node.name.text === 'hasInstance' && !variableGoTypes.has('Symbol')) {
4845
4859
  useHelper('symbol');
4846
4860
  return 'TnSymbolHasInstance';
4847
4861
  }
4862
+ if (isIdentifier(node.expression) && node.expression.text === 'Symbol' && node.name.text === 'metadata' && !variableGoTypes.has('Symbol')) {
4863
+ useHelper('symbol');
4864
+ return 'TnSymbolMetadata';
4865
+ }
4848
4866
  // fn.prototype on a function value (not a class): its prototype object
4849
4867
  if (node.name.text === 'prototype' && !isCallee(node) && !isAssignmentTarget(node) && !(isIdentifier(node.expression) && classNames.has(node.expression.text)) &&
4850
4868
  inferExpressionType(node.expression)?.startsWith('func(')) {
@@ -5760,25 +5778,29 @@ function visitNode(node, options = {}) {
5760
5778
  }
5761
5779
  }
5762
5780
  useHelper('asyncWait');
5781
+ useHelper('promise');
5763
5782
  const recv = visit(node.expression.expression);
5764
5783
  const cbs = (node.arguments ?? []).map((a) => visit(a));
5765
5784
  const cbExpr = cbs[0] ?? 'func(interface{}) {}';
5766
5785
  useHelper('eventLoop');
5767
5786
  // A callback without parameters (then(() => …)) takes no value
5768
5787
  const takesValue = !(cb && (isArrowFunction(cb) || isFunctionExpression(cb)) && (cb.parameters ?? []).length === 0);
5769
- const receive = takesValue ? `__v := <-__tnP` : `<-__tnP`;
5788
+ const receive = takesValue
5789
+ ? `__received, __ok := TnLoopReceive(__tnP); __v, __reason, __rejected := tnSettled(__tnP, __received, __ok); _ = __reason`
5790
+ : `__received, __ok := TnLoopReceive(__tnP); _, __reason, __rejected := tnSettled(__tnP, __received, __ok); _ = __reason`;
5770
5791
  const invoke = takesValue ? `(${cbExpr})(__v)` : `(${cbExpr})()`;
5771
5792
  // (used as a value — proms.push(p.then(cb)) —: the promise of the
5772
5793
  // callback's result, a channel that receives it once the callback ran)
5773
5794
  if (!isExpressionStatement(unwrapParenthesesUp(node).parent)) {
5774
5795
  const returns = !!cb && (isArrowFunction(cb) || isFunctionExpression(cb)) && !!inferFunctionBodyReturnType(cb);
5775
5796
  const outType = thenResultType(node)?.slice(5) ?? 'interface{}';
5776
- const settle = returns ? `__out <- ${invoke}` : `${invoke}; __out <- *new(${outType})`;
5777
- return `func() chan ${outType} {\n\t\t__out := make(chan ${outType}, 1)\n\t\t__tnWaitGroup.Add(1)\n\t\tgo func(__tnCtx TnAsyncContext, __tnP ${recvType}) {\n\t\t\t${receive}\n\t\t\tTnLoopPost(func() {\n\t\t\t\tdefer __tnWaitGroup.Done()\n\t\t\t\tTnAsyncRun(__tnCtx, func() { ${settle} })\n\t\t\t})\n\t\t}(TnAsyncSnapshot(), ${recv})\n\t\treturn __out\n\t}()`;
5797
+ const settle = returns ? `TnAsyncSend(__out, ${invoke})` : `${invoke}; TnResolveZero(__out)`;
5798
+ return `func(__tnP ${recvType}) chan ${outType} {\n\t\t__out := make(chan ${outType}, 1)\n\t\t__tnWaitGroup.Add(1)\n\t\tTnStartAsync(func() {\n\t\t\tdefer __tnWaitGroup.Done()\n\t\t\tdefer TnAsyncClose(__out)\n\t\t\tdefer TnRejectOnPanic(__out)\n\t\t\t${receive}\n\t\t\tif __rejected {\n\t\t\t\ttnRejections.Store(__out, __reason)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t${settle}\n\t\t})\n\t\treturn __out\n\t}(${recv})`;
5778
5799
  }
5779
- // The promise expression is a go-statement argument: it runs now, with
5780
- // the baton (exec() registering its listeners off the loop would race it)
5781
- return `__tnWaitGroup.Add(1)\n\t\tgo func(__tnCtx TnAsyncContext, __tnP ${recvType}) {\n\t\t\t${receive}\n\t\t\tTnLoopPost(func() {\n\t\t\t\tdefer __tnWaitGroup.Done()\n\t\t\t\tTnAsyncRun(__tnCtx, func() { ${invoke} })\n\t\t\t})\n\t\t}(TnAsyncSnapshot(), ${recv})`;
5800
+ // The promise expression is evaluated now, with the baton (exec()
5801
+ // registering its listeners off the loop would race it); the callback
5802
+ // runs as a microtask once the promise settles
5803
+ return `func(__tnP ${recvType}) {\n\t\t__tnWaitGroup.Add(1)\n\t\tTnStartAsync(func() {\n\t\t\tdefer __tnWaitGroup.Done()\n\t\t\t${receive}\n\t\t\tif __rejected {\n\t\t\t\treturn\n\t\t\t}\n\t\t\t${invoke}\n\t\t})\n\t}(${recv})`;
5782
5804
  }
5783
5805
  }
5784
5806
  // Array.from(arrayLike, mapFn) — array-likes are { length } structs
@@ -6614,8 +6636,15 @@ function visitNode(node, options = {}) {
6614
6636
  return `${visit(node.left.expression)}.Set(${toGoStringLiteral(node.left.name.text)}, ${toGoValueOfType(node.right, extractMapValueType(recordType))})`;
6615
6637
  }
6616
6638
  }
6617
- // Class setter writes are accessor calls: c.v = x → c.Set_v(x)
6639
+ // Class setter writes are accessor calls: c.v = x → c.Set_v(x), C.v = x → C_Set_v(x)
6618
6640
  if (op === '=' && isPropertyAccessExpression(node.left)) {
6641
+ if (isIdentifier(node.left.expression) && !hasQuestionDot(node.left)) {
6642
+ const staticSetterName = memberKey(node.left.name);
6643
+ const staticOwner = staticMemberOwner(node.left.expression.text, staticSetterName);
6644
+ if (staticOwner && classStaticSetters.has(`${staticOwner}.${staticSetterName}`)) {
6645
+ return `${staticOwner}_Set_${goFieldName(staticSetterName)}(${visit(node.right)})`;
6646
+ }
6647
+ }
6619
6648
  const ownerGoType = inferExpressionType(node.left.expression);
6620
6649
  // Object-literal setters are Set_x closure fields
6621
6650
  const literalSetter = `Set_${goFieldName(node.left.name.text)} func(`;
@@ -6732,16 +6761,16 @@ function visitNode(node, options = {}) {
6732
6761
  // Inside a generator: yield sends the value over the generator's channel
6733
6762
  if (asyncChannelVar && getEnclosingFunction(node) === asyncFunctionNode) {
6734
6763
  // (the value converted to what the generator's channel carries)
6735
- const yieldType = asyncFunctionNode ? getGeneratorYieldType(asyncFunctionNode) : 'interface{}';
6764
+ const yieldType = asyncChannelYieldType;
6736
6765
  if (generatorSeqMode)
6737
6766
  return visitSeqYield(node, yieldType);
6767
+ const isAsyncGen = (asyncFunctionNode?.modifiers ?? []).some((m) => m.kind === 'AsyncKeyword');
6738
6768
  if (node.asteriskToken) {
6739
6769
  // yield* other(): forward every value of the delegated generator
6740
6770
  // (each in step with this generator's consumer)
6741
6771
  const delegatedType = inferExpressionType(node.expression) ?? '';
6742
6772
  const elementType = delegatedType.startsWith('chan ') ? delegatedType.slice(5) : '';
6743
6773
  useHelper('dynamic');
6744
- const forwarded = elementType === yieldType ? '__yv' : yieldType === 'interface{}' ? 'interface{}(__yv)' : `TnAs[${yieldType}](interface{}(__yv))`;
6745
6774
  // yield* xs of an array (or of any value: its elements, an array's
6746
6775
  // or another iterable's)
6747
6776
  if (!delegatedType.startsWith('chan ')) {
@@ -6750,23 +6779,49 @@ function visitNode(node, options = {}) {
6750
6779
  if (!arrayElement)
6751
6780
  useHelper('arraySubclass');
6752
6781
  const value = (arrayElement || 'interface{}') === yieldType ? '__yv' : yieldType === 'interface{}' ? 'interface{}(__yv)' : `TnAs[${yieldType}](interface{}(__yv))`;
6753
- if (!asyncChannelIsAsync)
6782
+ if (!isAsyncGen) {
6754
6783
  useHelper('generatorStep');
6755
- return `for _, __yv := range ${source} {\n\t\t\t${asyncChannelVar} <- ${value}${asyncChannelIsAsync ? '' : `; TnGenStep(${asyncChannelVar})`}\n\t\t}`;
6784
+ const loop = `for _, __yv := range ${source} {\n\t\t\tTnGenYield[${yieldType}](${asyncChannelVar}, ${value})\n\t\t}`;
6785
+ return isExpressionStatement(node.parent) ? `func() {\n\t\t${loop}\n\t}()` : `func() interface{} {\n\t\t${loop}\n\t\treturn nil\n\t}()`;
6786
+ }
6787
+ useHelper('eventLoop');
6788
+ return `for _, __yv := range ${source} {\n\t\t\tTnAsyncYield(${asyncChannelVar}, ${value})\n\t\t}`;
6756
6789
  }
6757
- if (!asyncChannelIsAsync) {
6790
+ if (!isAsyncGen) {
6758
6791
  useHelper('generatorStep');
6759
- return `func() { __yg := TnGenLockstep(${visit(node.expression)}); for __yfirst := true; ; __yfirst = false { if !__yfirst { TnGenAck(__yg) }; __yv, __yok := <-__yg; if !__yok { TnGenDone(__yg); return }; ${asyncChannelVar} <- ${forwarded}; TnGenStep(${asyncChannelVar}) } }()`;
6792
+ useHelper('iterators');
6793
+ const conv = elementType === yieldType
6794
+ ? `func(__yv ${elementType}) ${yieldType} { return __yv }`
6795
+ : yieldType === 'interface{}'
6796
+ ? `func(__yv ${elementType}) interface{} { return __yv }`
6797
+ : `func(__yv ${elementType}) ${yieldType} { return TnAs[${yieldType}](interface{}(__yv)) }`;
6798
+ const call = `TnGenDelegate(${asyncChannelVar}, ${visit(node.expression)}, ${conv})`;
6799
+ const retType = delegatedGeneratorReturnType(node.expression);
6800
+ if (!isExpressionStatement(node.parent) && retType && retType !== 'interface{}') {
6801
+ return `TnAs[${retType}](${call})`;
6802
+ }
6803
+ return call;
6760
6804
  }
6761
- return `for __yv := range ${visit(node.expression)} {\n\t\t\t${asyncChannelVar} <- ${forwarded}\n\t\t}`;
6805
+ useHelper('eventLoop');
6806
+ const forwarded = elementType === yieldType ? '__yv' : yieldType === 'interface{}' ? 'interface{}(__yv)' : `TnAs[${yieldType}](interface{}(__yv))`;
6807
+ return `for {\n\t\t\t__yv, __ok := tnRawReceive(${visit(node.expression)})\n\t\t\tif !__ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tTnAsyncYield(${asyncChannelVar}, ${forwarded})\n\t\t}`;
6762
6808
  }
6763
- const yielded = node.expression ? toGoValueOfType(node.expression, yieldType) : 'nil';
6764
- // (a generator resumes only once its consumer has run: see TnGenStep)
6765
- if (!asyncChannelIsAsync) {
6809
+ const yielded = node.expression
6810
+ ? toGoValueOfType(node.expression, yieldType)
6811
+ : (yieldType === 'interface{}' ? 'nil' : `*new(${yieldType})`);
6812
+ // (a generator resumes only once its consumer has run: see TnGenYield / TnGenStep)
6813
+ if (!isAsyncGen) {
6766
6814
  useHelper('generatorStep');
6767
- return `${asyncChannelVar} <- ${yielded}; TnGenStep(${asyncChannelVar})`;
6815
+ const call = `TnGenYield[${yieldType}](${asyncChannelVar}, ${yielded})`;
6816
+ const nextType = getGeneratorNextType(asyncFunctionNode);
6817
+ if (!isExpressionStatement(node.parent) && nextType !== 'interface{}') {
6818
+ useHelper('dynamic');
6819
+ return `TnAs[${nextType}](${call})`;
6820
+ }
6821
+ return call;
6768
6822
  }
6769
- return `${asyncChannelVar} <- ${yielded}`;
6823
+ useHelper('eventLoop');
6824
+ return `TnAsyncYield(${asyncChannelVar}, ${yielded})`;
6770
6825
  }
6771
6826
  return '';
6772
6827
  }
@@ -7167,8 +7222,10 @@ function visitNode(node, options = {}) {
7167
7222
  }
7168
7223
  // Inside an async function or generator the channel carries the result
7169
7224
  if (asyncChannelVar && getEnclosingFunction(node) === asyncFunctionNode) {
7225
+ const inTryReturn = tryReturn && getEnclosingFunction(node) === tryReturn.fn;
7226
+ const genExit = inTryReturn ? tryAwareReturn('') : 'return';
7170
7227
  if (!node.expression)
7171
- return 'return';
7228
+ return genExit + (options.inline ? '' : ';\n\t');
7172
7229
  // An async return settles its promise (ordered wake); a generator's
7173
7230
  // sends stay raw (their consumers receive raw)
7174
7231
  if (asyncChannelIsAsync) {
@@ -7193,7 +7250,12 @@ function visitNode(node, options = {}) {
7193
7250
  }
7194
7251
  return `TnAsyncSend[${chanType}](${asyncChannelVar}, ${returned}); return` + (options.inline ? '' : ';\n\t');
7195
7252
  }
7196
- return `${asyncChannelVar} <- ${visit(node.expression)}; return` + (options.inline ? '' : ';\n\t');
7253
+ const isAsyncGen = (asyncFunctionNode?.modifiers ?? []).some((m) => m.kind === 'AsyncKeyword');
7254
+ if (isAsyncGen) {
7255
+ return `${asyncChannelVar} <- ${visit(node.expression)}; ${genExit}` + (options.inline ? '' : ';\n\t');
7256
+ }
7257
+ useHelper('generatorStep');
7258
+ return `TnGenSetReturn(${asyncChannelVar}, ${visit(node.expression)}); ${genExit}` + (options.inline ? '' : ';\n\t');
7197
7259
  }
7198
7260
  const enclosingFn = getEnclosingFunction(node);
7199
7261
  const isAsync = enclosingFn?.modifiers?.some((m) => m.kind === 'AsyncKeyword');
@@ -7591,9 +7653,10 @@ function visitNode(node, options = {}) {
7591
7653
  // (an abstract one is no field either: the subclasses declare it, as a
7592
7654
  // field or an accessor)
7593
7655
  if (isPropertyDeclaration(member) && !(member.modifiers ?? []).some((m) => m.kind === 'StaticKeyword' || m.kind === 'AbstractKeyword')) {
7594
- const fieldName = member.name?.kind === 'PrivateIdentifier'
7656
+ const rawFieldName = member.name?.kind === 'PrivateIdentifier'
7595
7657
  ? privateGoName(member.name.text)
7596
7658
  : visit(member.name);
7659
+ const fieldName = isAutoAccessor(member) ? `__accessor_${rawFieldName}` : rawFieldName;
7597
7660
  let fieldType;
7598
7661
  if (member.type && isArrayTypeNode(member.type)) {
7599
7662
  fieldType = `[]${getType(member.type, true)}`;
@@ -7848,7 +7911,9 @@ function visitNode(node, options = {}) {
7848
7911
  continue;
7849
7912
  ownAccessorKeys.add(accessorKey);
7850
7913
  emittedMethodNames.add(memberKey(member.name) ?? '');
7851
- copiedMethods.push(emitAccessor(member, `${name}${typeParamNames}`, mockSlots));
7914
+ copiedMethods.push(getDecorators(member).length > 0
7915
+ ? emitDecoratedAccessor(name, typeParamNames, member, visit(ancestor.name))
7916
+ : emitAccessor(member, `${name}${typeParamNames}`, mockSlots));
7852
7917
  continue;
7853
7918
  }
7854
7919
  if (!isMethodDeclaration(member))
@@ -7997,7 +8062,13 @@ function visitNode(node, options = {}) {
7997
8062
  }
7998
8063
  }
7999
8064
  else if (isGetAccessor(member) || isSetAccessor(member)) {
8000
- result += emitAccessor(member, `${name}${typeParamNames}`, mockSlots);
8065
+ result +=
8066
+ getDecorators(member).length > 0
8067
+ ? emitDecoratedAccessor(name, typeParamNames, member, name)
8068
+ : emitAccessor(member, `${name}${typeParamNames}`, mockSlots);
8069
+ }
8070
+ else if (isAutoAccessor(member)) {
8071
+ result += emitAutoAccessor(name, typeParamNames, member, name);
8001
8072
  }
8002
8073
  }
8003
8074
  // an interface method the class never declares: a stub that throws when
@@ -8020,11 +8091,12 @@ function visitNode(node, options = {}) {
8020
8091
  // (a mixin's super.m() goes through __super: no copies)
8021
8092
  if (!mixinOf)
8022
8093
  result += emitSuperCopies(name, typeParamNames, node);
8023
- // Static property declarations → package-level vars named ClassName_propName
8094
+ // Static property declarations → package-level vars named ClassName_propName (or ClassName__accessor_propName)
8024
8095
  for (const member of (node.members ?? [])) {
8025
8096
  if (isPropertyDeclaration(member) &&
8026
8097
  member.modifiers?.some((m) => m.kind === 'StaticKeyword')) {
8027
- const fieldName = visit(member.name);
8098
+ const rawFieldName = visit(member.name);
8099
+ const fieldName = isAutoAccessor(member) ? `_accessor_${rawFieldName}` : rawFieldName;
8028
8100
  const fieldType = member.type
8029
8101
  ? getOptionalNodeType(member.type, !!member.questionToken)
8030
8102
  : toFieldGoType(member.initializer ? inferExpressionType(member.initializer) : undefined);
@@ -8326,7 +8398,11 @@ function visitNode(node, options = {}) {
8326
8398
  if (isRecordTypeNode(contextualType)) {
8327
8399
  return visitMapLiteral(node, contextualType);
8328
8400
  }
8329
- let typeName = contextualType ? getTypeText(contextualType) : '';
8401
+ let typeName = contextualType && isTypeReferenceNode(contextualType) && isIdentifier(contextualType.typeName) && contextualType.typeName.text === 'ClassAccessorDecoratorResult'
8402
+ ? ''
8403
+ : contextualType
8404
+ ? getTypeText(contextualType)
8405
+ : '';
8330
8406
  // { ...ctx, indent: x }: a copy of ctx's object type, when it has every key
8331
8407
  const firstProp = (node.properties ?? [])[0];
8332
8408
  if ((!typeName || typeName === 'interface{}') && firstProp?.kind === 'SpreadAssignment') {
@@ -9855,7 +9931,8 @@ function visitUsingDeclaration(statement, rest) {
9855
9931
  const goType = inferExpressionType(d.initializer) ?? '';
9856
9932
  const className = goType.replace(/^\*/, '').replace(/\[.*$/, '');
9857
9933
  const classNode = declaredClasses.get(className);
9858
- const hasAsync = (classNode?.members ?? []).some((m) => m.name?.text === '__asyncDispose');
9934
+ const hasAsync = (classNode?.members ?? []).some((m) => m.name?.text === '__asyncDispose') ||
9935
+ !!nodeRegistry.classes[nodeRegistry.classByGoType[goType]]?.methods['__asyncDispose'];
9859
9936
  if (isAwait && hasAsync)
9860
9937
  useHelper('promise');
9861
9938
  // The disposal may run on an async fn's goroutine or inline in a callback
@@ -10983,6 +11060,14 @@ function widenToInterfaceParams(className, member, signature, prefix) {
10983
11060
  }
10984
11061
  return { signature, prefix };
10985
11062
  }
11063
+ function emitGeneratorGoroutineBody(chanType, channelVar, prologue, body, isAsyncGen) {
11064
+ if (isAsyncGen) {
11065
+ useHelper('eventLoop');
11066
+ return `${prologue}${channelVar} := make(chan ${chanType})\n\tTnStartAsync(func() {\n\t\tdefer close(${channelVar})\n\t\t${body.trim()}\n\t})\n\treturn ${channelVar}`;
11067
+ }
11068
+ useHelper('generatorStep');
11069
+ return `${prologue}${channelVar} := make(chan ${chanType})\n\t__ctrl := TnGenStart(${channelVar})\n\tgo func() {\n\t\tdefer close(${channelVar})\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tif ret, ok := r.(tnGenReturn); ok {\n\t\t\t\t\t__ctrl.finishReturn(ret.val)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t__ctrl.finishError(r)\n\t\t\t} else {\n\t\t\t\t__ctrl.finishDone()\n\t\t\t}\n\t\t}()\n\t\tif !__ctrl.awaitStart() {\n\t\t\treturn\n\t\t}\n\t\t${body.trim()}\n\t}()\n\treturn ${channelVar}`;
11070
+ }
10986
11071
  // A generator method: a Go method returning the channel its body sends on
10987
11072
  // (registered for dispatch on any values; copied into subclasses as other
10988
11073
  // methods are, so `this` is the subclass there)
@@ -10991,20 +11076,24 @@ function emitGeneratorMethod(className, typeParamNames, member, genName) {
10991
11076
  const prevChannel = asyncChannelVar;
10992
11077
  const prevFn = asyncFunctionNode;
10993
11078
  const prevIsAsync = asyncChannelIsAsync;
11079
+ const prevYieldType = asyncChannelYieldType;
10994
11080
  asyncChannelVar = '__ch';
10995
11081
  asyncFunctionNode = member;
10996
11082
  asyncChannelIsAsync = false;
11083
+ asyncChannelYieldType = yieldType;
10997
11084
  const methodParameterInfo = getFunctionParametersInfo(member.parameters ?? []);
10998
11085
  const genBody = visit(member.body, { prefixBlockContent: methodParameterInfo.prefixBlockContent });
10999
11086
  asyncChannelVar = prevChannel;
11000
11087
  asyncFunctionNode = prevFn;
11001
11088
  asyncChannelIsAsync = prevIsAsync;
11089
+ asyncChannelYieldType = prevYieldType;
11002
11090
  if (genName !== 'Symbol_iterator')
11003
11091
  recordMethodSignature(className, memberKey(member.name) ?? genName, genName, methodParameterInfo.signature, `chan ${yieldType}`);
11004
11092
  const seq = generatorSeqEligible(member)
11005
11093
  ? `${lineMarker(member)}${emitGeneratorSeq(member, `func (self *${className}${typeParamNames}) ${genName}__seq`, methodParameterInfo, '')}\n\n`
11006
11094
  : '';
11007
- return `${lineMarker(member)}func (self *${className}${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${seq}`;
11095
+ const isAsyncGen = (member.modifiers ?? []).some((m) => m.kind === 'AsyncKeyword');
11096
+ return `${lineMarker(member)}func (self *${className}${typeParamNames}) ${genName}(${methodParameterInfo.signature}) chan ${yieldType} {\n\t${emitGeneratorGoroutineBody(yieldType, '__ch', '', genBody, isAsyncGen)}\n}\n\n${seq}`;
11008
11097
  }
11009
11098
  // A sync generator a for…of can run without a goroutine: its push form
11010
11099
  // name__seq(args) is a Go range function whose yield runs the loop body (so
@@ -11048,10 +11137,12 @@ function emitGeneratorSeq(fn, header, parameterInfo, prologue) {
11048
11137
  const prevChannel = asyncChannelVar;
11049
11138
  const prevFn = asyncFunctionNode;
11050
11139
  const prevIsAsync = asyncChannelIsAsync;
11140
+ const prevYieldType = asyncChannelYieldType;
11051
11141
  const prevSeq = generatorSeqMode;
11052
11142
  asyncChannelVar = '__ch';
11053
11143
  asyncFunctionNode = fn;
11054
11144
  asyncChannelIsAsync = false;
11145
+ asyncChannelYieldType = yieldType;
11055
11146
  generatorSeqMode = true;
11056
11147
  let body;
11057
11148
  try {
@@ -11061,15 +11152,23 @@ function emitGeneratorSeq(fn, header, parameterInfo, prologue) {
11061
11152
  asyncChannelVar = prevChannel;
11062
11153
  asyncFunctionNode = prevFn;
11063
11154
  asyncChannelIsAsync = prevIsAsync;
11155
+ asyncChannelYieldType = prevYieldType;
11064
11156
  generatorSeqMode = prevSeq;
11065
11157
  }
11066
11158
  useHelper('generatorStep');
11067
11159
  return `${header}(${parameterInfo.signature}) func(func(${yieldType}) bool) {\n\t${prologue}return func(__yield func(${yieldType}) bool) {\n\t\t__stop := new(tnGenStop)\n\t\t__yc := false\n\t\t_, _ = __stop, __yc\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil && r != interface{}(__stop) {\n\t\t\t\tpanic(r)\n\t\t\t}\n\t\t}()\n\t\t${body.trim()}\n\t}\n}`;
11068
11160
  }
11069
- // A catch clause in a generator's push form: a panic raised while the
11070
- // consumer's loop body ran (or the stop of a break) is not the generator's
11161
+ // A catch clause in a generator's push form or coroutine: a panic raised
11162
+ // while the consumer's loop body ran, or a generator return() unwind, is not
11163
+ // for the generator's catch clause
11071
11164
  function seqCatchGuard() {
11072
- return generatorSeqMode ? 'if __yc {\n\t\t\t\t\tpanic(r)\n\t\t\t\t}\n\t\t\t\t' : '';
11165
+ if (generatorSeqMode)
11166
+ return 'if __yc {\n\t\t\t\t\tpanic(r)\n\t\t\t\t}\n\t\t\t\t';
11167
+ if (asyncChannelVar && !asyncChannelIsAsync && !(asyncFunctionNode?.modifiers ?? []).some((m) => m.kind === 'AsyncKeyword')) {
11168
+ useHelper('generatorStep');
11169
+ return 'if _, __isGenRet := r.(tnGenReturn); __isGenRet {\n\t\t\t\t\tpanic(r)\n\t\t\t\t}\n\t\t\t\t';
11170
+ }
11171
+ return '';
11073
11172
  }
11074
11173
  // One yield of a generator's push form: the consumer's loop body runs for the
11075
11174
  // value; false (a break, a return out of the loop) stops the generator
@@ -11318,8 +11417,10 @@ function visitGeneratorItems(node) {
11318
11417
  useHelper('generatorSeq');
11319
11418
  return found.elem === elem ? `tnSeqCollect(${found.seq})` : `tnSeqCollect(tnSeqAs[${elem}](${found.seq}))`;
11320
11419
  }
11321
- if (node.chanType)
11322
- return `func() []${elem} { __out := []${elem}{}; for __v := range ${code} { __out = append(__out, __v) }; return __out }()`;
11420
+ if (node.chanType) {
11421
+ useHelper('iterators');
11422
+ return `TnIterToArray(${code})`;
11423
+ }
11323
11424
  useHelper('arraySubclass');
11324
11425
  return `TnToArray(${code})`;
11325
11426
  }
@@ -12158,14 +12259,26 @@ function emitConstructor(name, typeParams, typeParamNames, signature, body) {
12158
12259
  }
12159
12260
  function fieldInitializers(classNode) {
12160
12261
  const counted = typeof classNode.covFields === 'number' ? `${coverageCount(classNode.covFields)}\n\t\t` : '';
12161
- return counted + (classNode.members ?? [])
12262
+ const className = classNode.name ? visit(classNode.name) : '';
12263
+ const instanceInits = className && classesWithInstanceInits.has(className) ? `TnRunInitializers(self, ${className}__instanceInits)\n\t\t` : '';
12264
+ return counted + instanceInits + (classNode.members ?? [])
12162
12265
  .filter((m) => isPropertyDeclaration(m) &&
12163
- m.initializer &&
12266
+ (m.initializer || getDecorators(m).length > 0) &&
12164
12267
  (isIdentifier(m.name) || m.name?.kind === 'PrivateIdentifier') &&
12165
12268
  !(m.modifiers ?? []).some((mod) => mod.kind === 'StaticKeyword'))
12166
12269
  .map((m) => {
12167
12270
  const fieldName = memberKey(m.name);
12168
- return `self.${goFieldName(fieldName)} = ${toGoValueOfType(m.initializer, getPropertyDeclarationType(m))}\n\t\t`;
12271
+ const goName = goFieldName(fieldName);
12272
+ const targetField = isAutoAccessor(m) ? `__accessor_${goName}` : goName;
12273
+ const fieldType = getPropertyDeclarationType(m);
12274
+ if (getDecorators(m).length > 0) {
12275
+ useHelper('decorators');
12276
+ useHelper('dynamic');
12277
+ const initExpr = m.initializer ? toGoValueOfType(m.initializer, fieldType) : 'nil';
12278
+ return (`self.${targetField} = TnAs[${fieldType}](TnRunFieldInitializers(self, ${className}_${goName}__fieldInits, ${initExpr}))\n\t\t` +
12279
+ `TnRunInitializers(self, ${className}_${goName}__extraInits)\n\t\t`);
12280
+ }
12281
+ return `self.${targetField} = ${toGoValueOfType(m.initializer, fieldType)}\n\t\t`;
12169
12282
  })
12170
12283
  .join('');
12171
12284
  }
@@ -12718,7 +12831,7 @@ function visitObjectMemberAccess(node, goType) {
12718
12831
  const fallback = resultType === 'interface{}' ? 'TnGet(o, k)' : `TnAs[${resultType}](TnGet(o, k))`;
12719
12832
  return `func(o ${goType}, k string) ${resultType} { if __v, __ok := tnExpandoGet(o, k); __ok { return ${asResult} }; switch k { ${cases.join('; ')} }; return ${fallback} }(${object}, ${toGoValueOfType(key, 'string')})`;
12720
12833
  }
12721
- const ITERATOR_HELPERS = new Set(['next', 'map', 'filter', 'flatMap', 'take', 'drop', 'toArray', 'forEach', 'some', 'every', 'find', 'reduce']);
12834
+ const ITERATOR_HELPERS = new Set(['next', 'return', 'throw', 'map', 'filter', 'flatMap', 'take', 'drop', 'toArray', 'forEach', 'some', 'every', 'find', 'reduce']);
12722
12835
  // A callback of an iterator helper as func(T, float64) R (its own arity may be smaller)
12723
12836
  function iteratorCallbackAdapter(callbackNode, callback, elementType, resultType) {
12724
12837
  const fnType = callbackNode ? functionValueGoType(callbackNode) : '';
@@ -12732,12 +12845,24 @@ function iteratorCallbackAdapter(callbackNode, callback, elementType, resultType
12732
12845
  }
12733
12846
  // gen.map(fn) / filter / take / drop / flatMap / toArray / forEach / some /
12734
12847
  // every / find / reduce / next() on a generator's channel
12735
- function visitIteratorHelper(receiver, method, elementType, args, callbackNode, extraArgs) {
12848
+ function visitIteratorHelper(receiver, method, elementType, args, callbackNode, extraArgs, receiverNode) {
12736
12849
  useHelper('iterators');
12737
12850
  const callbackResult = goFuncReturnType(callbackNode ? functionValueGoType(callbackNode) : '') ?? 'interface{}';
12851
+ const useAny = (method === 'next' || method === 'return' || method === 'throw') &&
12852
+ generatorResultElementType(receiverNode, elementType, method, callbackNode) === 'interface{}';
12738
12853
  switch (method) {
12739
12854
  case 'next':
12740
- return `TnIterNext(${receiver})`;
12855
+ if (useAny)
12856
+ return `TnIterNextAny(${receiver}, ${args[0] ?? 'nil'})`;
12857
+ return args.length > 0 ? `TnIterNextVal(${receiver}, ${args[0]})` : `TnIterNext(${receiver})`;
12858
+ case 'return':
12859
+ if (useAny)
12860
+ return `TnIterReturnAny(${receiver}, ${args[0] ?? 'nil'}, ${args.length > 0})`;
12861
+ return `TnIterReturn(${receiver}, ${args[0] ?? 'nil'}, ${args.length > 0})`;
12862
+ case 'throw':
12863
+ if (useAny)
12864
+ return `TnIterThrowAny(${receiver}, ${args[0] ?? 'nil'})`;
12865
+ return `TnIterThrow(${receiver}, ${args[0] ?? 'nil'})`;
12741
12866
  case 'map':
12742
12867
  return `TnIterMap(${receiver}, ${iteratorCallbackAdapter(callbackNode, args[0], elementType, callbackResult)})`;
12743
12868
  case 'flatMap':
@@ -12795,7 +12920,11 @@ function iteratorHelperGoType(expr, receiverType, method) {
12795
12920
  const callbackResult = expr.arguments?.[0] ? goFuncReturnType(functionValueGoType(expr.arguments[0])) : undefined;
12796
12921
  switch (method) {
12797
12922
  case 'next':
12798
- return `*TnIterResult[${elementType}]`;
12923
+ case 'return':
12924
+ case 'throw': {
12925
+ const resElem = generatorResultElementType(expr.expression?.expression, elementType, method, expr.arguments?.[0]);
12926
+ return `*TnIterResult[${resElem}]`;
12927
+ }
12799
12928
  case 'map':
12800
12929
  return `chan ${callbackResult ?? 'interface{}'}`;
12801
12930
  case 'flatMap':
@@ -13580,7 +13709,12 @@ function visitRecordFunctionCall(node) {
13580
13709
  const call = getRecordFunctionCall(node);
13581
13710
  if (!call)
13582
13711
  return undefined;
13583
- const args = (node.arguments ?? []).map((a) => visit(a)).join(', ');
13712
+ // (arguments as the function type's parameters: an array by its reference)
13713
+ const fnType = extractMapValueType(call.mapType);
13714
+ const paramTypes = goFuncParamTypes(fnType);
13715
+ const argNodes = node.arguments ?? [];
13716
+ const typed = !paramTypes.some((t) => t.startsWith('...')) && !argNodes.some((a) => isSpreadElement(a)) && argNodes.length <= paramTypes.length;
13717
+ const args = argNodes.map((a, i) => (typed ? toGoValueOfType(a, paramTypes[i]) : visit(a))).join(', ');
13584
13718
  return `${visit(call.receiver)}.Get(${toGoStringLiteral(node.expression.name.text)})(${args})`;
13585
13719
  }
13586
13720
  function isRecordTypeNode(typeNode) {
@@ -13760,7 +13894,9 @@ function methodFuncType(member) {
13760
13894
  const params = paramTypes.join(', ');
13761
13895
  const ret = member.type
13762
13896
  ? getType(member.type)
13763
- : inferFunctionBodyReturnType(member) ?? '';
13897
+ : isDescriptorMethod(member) && (member.name?.text === 'get' || member.name?.text === 'init')
13898
+ ? 'interface{}'
13899
+ : inferFunctionBodyReturnType(member) ?? '';
13764
13900
  return `func(${params})${ret ? ` ${ret}` : ''}`;
13765
13901
  }
13766
13902
  // A method or accessor of a dynamic object literal as a Go func literal, its
@@ -14652,7 +14788,8 @@ function iterableClassValues(code, iterable, limit) {
14652
14788
  return `func() []${elemType} { _ = ${code}; return []${elemType}{} }()`;
14653
14789
  return `func() []${elemType} { __out := []${elemType}{}; for __v := range ${code}.Symbol_iterator__seq() { __out = append(__out, __v); if len(__out) == ${limit} { break } }; return __out }()`;
14654
14790
  }
14655
- return `func() []${elemType} { __out := []${elemType}{}; for __v := range ${code}.Symbol_iterator() { __out = append(__out, __v) }; return __out }()`;
14791
+ useHelper('iterators');
14792
+ return `TnIterToArray(${code}.Symbol_iterator())`;
14656
14793
  }
14657
14794
  // bag[Symbol.iterator]() of a class with *[Symbol.iterator](): its class
14658
14795
  // and what it yields (undefined for any other expression)
@@ -14719,7 +14856,8 @@ function visitSpreadSource(expr) {
14719
14856
  // [...generator()]: every value it yields
14720
14857
  if (sourceType?.startsWith('chan ')) {
14721
14858
  const element = sourceType.slice(5);
14722
- return `func() []${element} { __out := []${element}{}; for __v := range ${visit(expr)} { __out = append(__out, __v) }; return __out }()`;
14859
+ useHelper('iterators');
14860
+ return `TnIterToArray(${visit(expr)})`;
14723
14861
  }
14724
14862
  // a dynamic value: its elements (any iterable)
14725
14863
  if (!sourceType || sourceType === 'interface{}') {
@@ -14921,6 +15059,8 @@ function inferExpectedTypeFromContext(node) {
14921
15059
  isMethodDeclaration(scope) ||
14922
15060
  isFunctionExpression(scope) ||
14923
15061
  isArrowFunction(scope)) {
15062
+ if (scope.asteriskToken)
15063
+ return getGeneratorReturnType(scope);
14924
15064
  if (scope.type)
14925
15065
  return getType(scope.type);
14926
15066
  break;
@@ -15899,8 +16039,10 @@ function inferExpressionTypeOf(expr) {
15899
16039
  return 'interface{}';
15900
16040
  if (isPropertyAccessExpression(expr) && isIdentifier(expr.expression) && expr.expression.text === 'Array' && expr.name.text === 'isArray' && !isCallee(expr) && !variableGoTypes.has('Array') && !classNames.has('Array'))
15901
16041
  return 'func(interface{}) bool';
15902
- if (isPropertyAccessExpression(expr) && isIdentifier(expr.expression) && expr.expression.text === 'Symbol' && expr.name.text === 'hasInstance' && !variableGoTypes.has('Symbol'))
16042
+ if (isPropertyAccessExpression(expr) && isIdentifier(expr.expression) && expr.expression.text === 'Symbol' && (expr.name.text === 'hasInstance' || expr.name.text === 'metadata') && !variableGoTypes.has('Symbol'))
15903
16043
  return '*TnSymbol';
16044
+ if (isElementAccessExpression(expr) && isIdentifier(expr.expression) && classNames.has(expr.expression.text) && isSymbolMetadata(expr.argumentExpression))
16045
+ return '*TnMap[string, interface{}]';
15904
16046
  if (isPropertyAccessExpression(expr) && expr.name.text === 'prototype' && !(isIdentifier(expr.expression) && classNames.has(expr.expression.text)) && inferExpressionType(expr.expression)?.startsWith('func('))
15905
16047
  return 'interface{}';
15906
16048
  if (isIdentifier(expr) && isAbsentGlobal(expr))
@@ -15951,6 +16093,12 @@ function inferExpressionTypeOf(expr) {
15951
16093
  return inferArrowFunctionGoType(staticMethod);
15952
16094
  }
15953
16095
  }
16096
+ if (expr.kind === 'YieldExpression') {
16097
+ if (expr.asteriskToken) {
16098
+ return delegatedGeneratorReturnType(expr.expression) ?? 'interface{}';
16099
+ }
16100
+ return getGeneratorNextType(getEnclosingFunction(expr));
16101
+ }
15954
16102
  if (isAwaitExpression(expr)) {
15955
16103
  // await unwraps the promise channel
15956
16104
  const inner = inferExpressionType(expr.expression);
@@ -16362,8 +16510,31 @@ function inferExpressionTypeOf(expr) {
16362
16510
  const regexPropertyType = inferRegexPropertyType(expr);
16363
16511
  if (regexPropertyType)
16364
16512
  return regexPropertyType;
16365
- if (isPropertyAccessExpression(expr) && inferExpressionType(expr.expression) === '*TnDecoratorContext') {
16366
- return ['static', 'private'].includes(expr.name.text) ? 'bool' : 'string';
16513
+ if (isPropertyAccessExpression(expr)) {
16514
+ const ownerType = inferExpressionType(expr.expression);
16515
+ if (ownerType === '*TnDecoratorContext') {
16516
+ if (['static', 'private'].includes(expr.name.text))
16517
+ return 'bool';
16518
+ if (expr.name.text === 'metadata')
16519
+ return '*TnMap[string, interface{}]';
16520
+ if (expr.name.text === 'access')
16521
+ return '*TnDecoratorAccess';
16522
+ return 'string';
16523
+ }
16524
+ if (ownerType === '*TnDecoratorAccess') {
16525
+ if (expr.name.text === 'has')
16526
+ return 'func(interface{}) bool';
16527
+ if (expr.name.text === 'get')
16528
+ return 'func(interface{}) interface{}';
16529
+ if (expr.name.text === 'set')
16530
+ return 'func(interface{}, interface{})';
16531
+ }
16532
+ if (ownerType === '*TnAccessorTarget') {
16533
+ if (expr.name.text === 'get')
16534
+ return 'func() interface{}';
16535
+ if (expr.name.text === 'set')
16536
+ return 'func(interface{})';
16537
+ }
16367
16538
  }
16368
16539
  if (isPropertyAccessExpression(expr) && expr.name.text === 'length' && hasDynamicProperties(expr.expression)) {
16369
16540
  // n?.length on an any value: undefined when n is nullish or has no length
@@ -19638,6 +19809,20 @@ function getType(typeNode, getArrayType = false) {
19638
19809
  useHelper('decorators');
19639
19810
  return '*TnDecoratorContext';
19640
19811
  }
19812
+ if (isTypeReferenceNode(typeNode) && isIdentifier(typeNode.typeName)) {
19813
+ if (typeNode.typeName.text === 'ClassAccessorDecoratorTarget') {
19814
+ useHelper('decorators');
19815
+ return '*TnAccessorTarget';
19816
+ }
19817
+ if (typeNode.typeName.text === 'ClassAccessorDecoratorResult') {
19818
+ useHelper('decorators');
19819
+ return 'interface{}';
19820
+ }
19821
+ if (typeNode.typeName.text === 'DecoratorMetadata' || typeNode.typeName.text === 'DecoratorMetadataObject') {
19822
+ useHelper('orderedMap');
19823
+ return '*TnMap[string, interface{}]';
19824
+ }
19825
+ }
19641
19826
  if (isTypeReferenceNode(typeNode) &&
19642
19827
  typeNode.typeName?.kind === 'QualifiedName' &&
19643
19828
  typeNode.typeName.left?.text === 'JSX' &&
@@ -19789,15 +19974,11 @@ function getType(typeNode, getArrayType = false) {
19789
19974
  }
19790
19975
  if (isFunctionTypeNode(typeNode)) {
19791
19976
  // (...args: T[]) => R is variadic: func(...T) R
19792
- // (parameters as declarations emit them — optional ones nullable pointers —
19793
- // except that a function type's arrays are plain slices: function literals
19794
- // stored in the slot take them that way, see functionSlotParamType)
19977
+ // (parameters as declarations emit them — optional ones nullable pointers,
19978
+ // arrays as references)
19795
19979
  const params = (typeNode.parameters ?? [])
19796
19980
  .map((p) => {
19797
- let paramType = p.type ? getParameterGoType({ ...p, parent: typeNode }) : 'interface{}';
19798
- // (a method signature's are its Go method's: references)
19799
- if (paramType.startsWith('*[]') && !isMethodSignature(typeNode.parent))
19800
- paramType = paramType.slice(1);
19981
+ const paramType = p.type ? getParameterGoType({ ...p, parent: typeNode }) : 'interface{}';
19801
19982
  if (p.dotDotDotToken && paramType.startsWith('[]'))
19802
19983
  return `...${paramType.slice(2)}`;
19803
19984
  return paramType;
@@ -20015,6 +20196,20 @@ function getType(typeNode, getArrayType = false) {
20015
20196
  if (typeNode.kind === 'IndexedAccessType') {
20016
20197
  const index = typeNode.indexType;
20017
20198
  const key = index?.kind === 'LiteralType' && isStringLiteral(index.literal) ? index.literal.text : undefined;
20199
+ if (key && isTypeReferenceNode(typeNode.objectType) && isIdentifier(typeNode.objectType.typeName) && /DecoratorContext$/.test(typeNode.objectType.typeName.text)) {
20200
+ if (key === 'access') {
20201
+ useHelper('decorators');
20202
+ return '*TnDecoratorAccess';
20203
+ }
20204
+ if (key === 'metadata') {
20205
+ useHelper('orderedMap');
20206
+ return '*TnMap[string, interface{}]';
20207
+ }
20208
+ if (key === 'kind' || key === 'name')
20209
+ return 'string';
20210
+ if (key === 'static' || key === 'private')
20211
+ return 'bool';
20212
+ }
20018
20213
  const member = key ? getMemberTypeNode(typeNode.objectType, key) : undefined;
20019
20214
  return member ? getType(member, getArrayType) || 'interface{}' : 'interface{}';
20020
20215
  }
@@ -20497,8 +20692,9 @@ const callHandlers = {
20497
20692
  return `func() chan ${t} { ch := make(chan ${t}, 1); func() { defer TnRejectExecutor(ch); ${settle} }(); return ch }()`;
20498
20693
  },
20499
20694
  'Promise.resolve': (_caller, args, _typeArgs) => {
20695
+ useHelper('promise');
20500
20696
  const valueType = currentCallArgTypes[0] && currentCallArgTypes[0] !== 'nil' ? currentCallArgTypes[0] : 'interface{}';
20501
- return `func() chan ${valueType} { __ch := make(chan ${valueType}, 1); __ch <- ${args[0] ?? 'nil'}; return __ch }()`;
20697
+ return `TnPromiseResolve[${valueType}](${args[0] ?? 'nil'})`;
20502
20698
  },
20503
20699
  structuredClone: (_caller, args, _typeArgs) => {
20504
20700
  useHelper('structuredClone');
@@ -21729,7 +21925,8 @@ function getDynamicCallHandler(caller, objectType) {
21729
21925
  const elementType = currentReceiverGoType.slice(5);
21730
21926
  const callbackNode = currentCallArgNodes[0];
21731
21927
  const extraArgs = currentCallArgNodes.slice(1);
21732
- return (c, args, _typeArgs) => visitIteratorHelper(c.substring(0, dotIndex), helperName, elementType, args, callbackNode, extraArgs);
21928
+ const receiverNode = currentCallNode?.expression?.expression;
21929
+ return (c, args, _typeArgs) => visitIteratorHelper(c.substring(0, dotIndex), helperName, elementType, args, callbackNode, extraArgs, receiverNode);
21733
21930
  }
21734
21931
  if (currentReceiverGoType?.startsWith('*TnWeakRef[') && methodName === 'deref') {
21735
21932
  return (c, _args, _typeArgs) => `${c.substring(0, dotIndex)}.deref()`;
@@ -22660,6 +22857,21 @@ function visitJsx(node) {
22660
22857
  function getDecorators(node) {
22661
22858
  return (node.modifiers ?? []).filter((m) => m.kind === 'Decorator');
22662
22859
  }
22860
+ function isAutoAccessor(member) {
22861
+ return isPropertyDeclaration(member) && (member.modifiers ?? []).some((m) => m.kind === 'AccessorKeyword');
22862
+ }
22863
+ function isSymbolMetadata(node) {
22864
+ return !!node && isPropertyAccessExpression(node) && isIdentifier(node.expression) && node.expression.text === 'Symbol' && node.name.text === 'metadata' && !variableGoTypes.has('Symbol');
22865
+ }
22866
+ function ensureClassMetadata(className) {
22867
+ const varName = `${className}__metadata`;
22868
+ if (!emittedClassMetadata.has(className)) {
22869
+ emittedClassMetadata.add(className);
22870
+ useHelper('orderedMap');
22871
+ mainPackageVariables.push(`var ${varName} *TnMap[string, interface{}]`);
22872
+ }
22873
+ return varName;
22874
+ }
22663
22875
  // `this` inside a function / function expression (not a class member, not an arrow's)
22664
22876
  // The plain function whose `this` a this expression is (arrows see their
22665
22877
  // enclosing function's), or undefined (a method's, a class's, top level)
@@ -22683,11 +22895,22 @@ function plainFunctionOfThis(node) {
22683
22895
  function isDescriptorMethod(n) {
22684
22896
  if (!n || !(isMethodDeclaration(n) || isGetAccessor(n) || isSetAccessor(n)) || !isObjectLiteralExpression(n.parent) || !isIdentifier(n.name))
22685
22897
  return false;
22686
- if (!['get', 'set'].includes(n.name.text))
22898
+ if (!['get', 'set', 'init'].includes(n.name.text))
22687
22899
  return false;
22688
22900
  const call = n.parent.parent;
22689
- return !!call && isCallExpression(call) && isPropertyAccessExpression(call.expression) && isIdentifier(call.expression.expression) &&
22690
- call.expression.expression.text === 'Object' && call.expression.name.text === 'defineProperty' && (call.arguments ?? [])[2] === n.parent;
22901
+ if (!!call && isCallExpression(call) && isPropertyAccessExpression(call.expression) && isIdentifier(call.expression.expression) &&
22902
+ call.expression.expression.text === 'Object' && call.expression.name.text === 'defineProperty' && (call.arguments ?? [])[2] === n.parent) {
22903
+ return true;
22904
+ }
22905
+ // Accessor decorator result ({ get() { ... this ... }, set(v) { ... }, init(v) { ... } })
22906
+ const fn = getEnclosingFunction(n.parent);
22907
+ if (fn) {
22908
+ const hasAccessorCtx = (fn.parameters ?? []).some((p) => p.type && isTypeReferenceNode(p.type) && isIdentifier(p.type.typeName) && p.type.typeName.text === 'ClassAccessorDecoratorContext');
22909
+ const returnsAccessorRes = !!fn.type && isTypeReferenceNode(fn.type) && isIdentifier(fn.type.typeName) && fn.type.typeName.text === 'ClassAccessorDecoratorResult';
22910
+ if (hasAccessorCtx || returnsAccessorRes)
22911
+ return true;
22912
+ }
22913
+ return false;
22691
22914
  }
22692
22915
  // A plain function's this: its `this: T` annotation's Go type, else any
22693
22916
  function plainFunctionThisType(fn) {
@@ -22923,6 +23146,41 @@ function visitFunctionCallApply(node) {
22923
23146
  : `func() struct{} { if __of := ${fn}; __of != nil { ${plainCall} }; return struct{}{} }()`;
22924
23147
  return withThis(guarded, result);
22925
23148
  }
23149
+ function adaptDecoratorTarget(varName, decorator) {
23150
+ let fnType = inferExpressionType(decorator.expression);
23151
+ const expr = decorator.expression;
23152
+ if (isCallExpression(expr) && isIdentifier(expr.expression)) {
23153
+ const factory = declaredFunctions.get(expr.expression.text);
23154
+ if (factory)
23155
+ fnType = factory.type ? getType(factory.type) : inferFunctionBodyReturnType(factory);
23156
+ }
23157
+ else if (isIdentifier(expr)) {
23158
+ const fn = declaredFunctions.get(expr.text);
23159
+ const firstParamNode = (fn?.parameters ?? [])[0];
23160
+ if (firstParamNode?.type)
23161
+ fnType = `func(${getType(firstParamNode.type)})`;
23162
+ }
23163
+ if (!fnType)
23164
+ return varName;
23165
+ if (fnType.startsWith('func[')) {
23166
+ const bracketEnd = fnType.indexOf('](');
23167
+ if (bracketEnd > -1)
23168
+ fnType = 'func(' + fnType.slice(bracketEnd + 2);
23169
+ }
23170
+ if (!fnType.startsWith('func('))
23171
+ return varName;
23172
+ const firstParam = goFuncParamTypes(fnType)[0];
23173
+ if (!firstParam || !firstParam.startsWith('func(') || firstParam === 'func(...interface{}) interface{}')
23174
+ return varName;
23175
+ const pTypes = goFuncParamTypes(firstParam);
23176
+ if (pTypes.some((p) => p.startsWith('...')))
23177
+ return varName;
23178
+ const retType = goFuncReturnType(firstParam);
23179
+ const decls = pTypes.map((t, i) => `__dp${i} ${t}`).join(', ');
23180
+ const args = pTypes.map((_, i) => `__dp${i}`).join(', ');
23181
+ const body = retType ? `return TnAs[${retType}](__prev(${args}))` : `__prev(${args})`;
23182
+ return `func(__prev func(...interface{}) interface{}) func(${decls})${retType ? ` ${retType}` : ''} { return func(${decls})${retType ? ` ${retType}` : ''} { ${body} } }(${varName})`;
23183
+ }
22926
23184
  // Whether a decorator call returns a value (a replacement), or only has effects
22927
23185
  function decoratorReturnsValue(decorator) {
22928
23186
  let fnType = inferExpressionType(decorator.expression);
@@ -22962,46 +23220,242 @@ function emitDecoratedMethod(className, typeParamNames, member, ownerClass) {
22962
23220
  return (`func (self *${className}${typeParamNames}) ${methodName}__undecorated(${info.signature})${result} ${body}\n\n` +
22963
23221
  `func (self *${className}${typeParamNames}) ${methodName}(${info.signature})${result} {\n\t\t__prevThis := TnThis\n\t\tTnThis = self\n\t\tdefer func() { TnThis = __prevThis }()\n\t\t${invoke}\n\t}\n\n`);
22964
23222
  }
22965
- // Applies a class's decorators where it is defined (in source order): each decorated
22966
- // method's function is wrapped bottom-up, then class decorators run
23223
+ function emitDecoratedAccessor(className, typeParamNames, member, ownerClass) {
23224
+ useHelper('decorators');
23225
+ useHelper('dynamic');
23226
+ const accessorName = isIdentifier(member.name) ? goFieldName(member.name.text) : visit(member.name);
23227
+ const isStatic = (member.modifiers ?? []).some((m) => m.kind === 'StaticKeyword');
23228
+ if (isGetAccessor(member)) {
23229
+ const returnType = member.type ? getType(member.type) : methodReturnGoType(member) || 'interface{}';
23230
+ const body = visit(member.body);
23231
+ if (isStatic) {
23232
+ return (`func ${className}_Get_${accessorName}__undecorated() ${returnType} ${body}\n\n` +
23233
+ `func ${className}_Get_${accessorName}() ${returnType} {\n\t\treturn TnAs[${returnType}](${ownerClass}_Get_${accessorName}__decorated())\n\t}\n\n`);
23234
+ }
23235
+ return (`func (self *${className}${typeParamNames}) Get_${accessorName}__undecorated() ${returnType} ${body}\n\n` +
23236
+ `func (self *${className}${typeParamNames}) Get_${accessorName}() ${returnType} {\n\t\t__prevThis := TnThis\n\t\tTnThis = self\n\t\tdefer func() { TnThis = __prevThis }()\n\t\treturn TnAs[${returnType}](${ownerClass}_Get_${accessorName}__decorated())\n\t}\n\n`);
23237
+ }
23238
+ const parameterInfo = getFunctionParametersInfo(member.parameters ?? []);
23239
+ const names = splitGoParameters(parameterInfo.signature).map((p) => p.slice(0, p.indexOf(' ')));
23240
+ const body = visit(member.body, { prefixBlockContent: parameterInfo.prefixBlockContent });
23241
+ const call = `${ownerClass}_Set_${accessorName}__decorated(${names.join(', ')})`;
23242
+ if (isStatic) {
23243
+ return (`func ${className}_Set_${accessorName}__undecorated(${parameterInfo.signature}) ${body}\n\n` +
23244
+ `func ${className}_Set_${accessorName}(${parameterInfo.signature}) {\n\t\t${call}\n\t}\n\n`);
23245
+ }
23246
+ return (`func (self *${className}${typeParamNames}) Set_${accessorName}__undecorated(${parameterInfo.signature}) ${body}\n\n` +
23247
+ `func (self *${className}${typeParamNames}) Set_${accessorName}(${parameterInfo.signature}) {\n\t\t__prevThis := TnThis\n\t\tTnThis = self\n\t\tdefer func() { TnThis = __prevThis }()\n\t\t${call}\n\t}\n\n`);
23248
+ }
23249
+ function emitAutoAccessor(className, typeParamNames, member, ownerClass) {
23250
+ const rawName = member.name?.kind === 'PrivateIdentifier' ? privateGoName(member.name.text) : isIdentifier(member.name) ? goFieldName(member.name.text) : visit(member.name);
23251
+ const accessorName = isIdentifier(member.name) ? goFieldName(member.name.text) : visit(member.name);
23252
+ const fieldType = getPropertyDeclarationType(member);
23253
+ const isStatic = (member.modifiers ?? []).some((m) => m.kind === 'StaticKeyword');
23254
+ const decorated = getDecorators(member).length > 0;
23255
+ if (!decorated) {
23256
+ if (isStatic) {
23257
+ return (`func ${className}_Get_${accessorName}() ${fieldType} { return ${className}__accessor_${rawName} }\n\n` +
23258
+ `func ${className}_Set_${accessorName}(__v ${fieldType}) { ${className}__accessor_${rawName} = __v }\n\n`);
23259
+ }
23260
+ return (`func (self *${className}${typeParamNames}) Get_${accessorName}() ${fieldType} { return self.__accessor_${rawName} }\n\n` +
23261
+ `func (self *${className}${typeParamNames}) Set_${accessorName}(__v ${fieldType}) { self.__accessor_${rawName} = __v }\n\n`);
23262
+ }
23263
+ useHelper('decorators');
23264
+ useHelper('dynamic');
23265
+ if (isStatic) {
23266
+ return (`func ${className}_Get_${accessorName}() ${fieldType} {\n\t\treturn TnAs[${fieldType}](${ownerClass}_Get_${accessorName}__decorated())\n\t}\n\n` +
23267
+ `func ${className}_Set_${accessorName}(__v ${fieldType}) {\n\t\t${ownerClass}_Set_${accessorName}__decorated(__v)\n\t}\n\n`);
23268
+ }
23269
+ return (`func (self *${className}${typeParamNames}) Get_${accessorName}() ${fieldType} {\n\t\t__prevThis := TnThis\n\t\tTnThis = self\n\t\tdefer func() { TnThis = __prevThis }()\n\t\treturn TnAs[${fieldType}](${ownerClass}_Get_${accessorName}__decorated())\n\t}\n\n` +
23270
+ `func (self *${className}${typeParamNames}) Set_${accessorName}(__v ${fieldType}) {\n\t\t__prevThis := TnThis\n\t\tTnThis = self\n\t\tdefer func() { TnThis = __prevThis }()\n\t\t${ownerClass}_Set_${accessorName}__decorated(__v)\n\t}\n\n`);
23271
+ }
23272
+ // Applies a class's decorators where it is defined (in source order): parameter,
23273
+ // method/getter/setter/field/accessor decorators bottom-up, then class decorators,
23274
+ // then static & class initializers.
22967
23275
  function visitClassDecorators(node) {
22968
23276
  const className = visit(node.name);
23277
+ const classDecorators = getDecorators(node);
23278
+ const hasAnyMemberDecorator = (node.members ?? []).some((m) => getDecorators(m).length > 0 || (m.parameters ?? []).some((p) => getDecorators(p).length > 0));
23279
+ if (classDecorators.length === 0 && !hasAnyMemberDecorator)
23280
+ return '';
23281
+ useHelper('decorators');
23282
+ useHelper('dynamic');
23283
+ const metadataVar = ensureClassMetadata(className);
22969
23284
  const statements = [];
23285
+ // Inherit metadata from parent class if any
23286
+ const parentClause = (node.heritageClauses ?? []).find((c) => c.token === 'ExtendsKeyword');
23287
+ const parentClass = parentClause ? (nodeParentGoName(parentClause.types[0].expression) || visit(parentClause.types[0].expression)) : '';
23288
+ if (parentClass && parentClass !== 'Error' && parentClass !== 'Array') {
23289
+ const parentMetaVar = ensureClassMetadata(parentClass);
23290
+ statements.push(`${metadataVar} = TnInheritMetadata(${parentMetaVar})`);
23291
+ }
23292
+ else {
23293
+ statements.push(`${metadataVar} = TnNewMap[string, interface{}]()`);
23294
+ }
23295
+ const staticInitsVar = `${className}__staticInits`;
23296
+ const classInitsVar = `${className}__classInits`;
23297
+ const instanceInitsVar = `${className}__instanceInits`;
23298
+ statements.push(`var ${staticInitsVar} []interface{}`);
23299
+ statements.push(`var ${classInitsVar} []interface{}`);
23300
+ let declaredInstanceInits = false;
23301
+ const ensureInstanceInits = () => {
23302
+ if (!declaredInstanceInits) {
23303
+ declaredInstanceInits = true;
23304
+ classesWithInstanceInits.add(className);
23305
+ mainPackageVariables.push(`var ${instanceInitsVar} []interface{}`);
23306
+ }
23307
+ return instanceInitsVar;
23308
+ };
23309
+ const staticFieldRunners = [];
22970
23310
  for (const member of node.members ?? []) {
23311
+ const isStatic = (member.modifiers ?? []).some((m) => m.kind === 'StaticKeyword');
23312
+ // Parameter decorators (legacy experimentalDecorators) on constructors & methods
23313
+ if (isConstructorDeclaration(member) || isMethodDeclaration(member)) {
23314
+ const params = member.parameters ?? [];
23315
+ const memberKeyStr = isConstructorDeclaration(member) ? 'nil' : toGoStringLiteral(memberKey(member.name) ?? visit(member.name));
23316
+ for (let pi = params.length - 1; pi >= 0; pi--) {
23317
+ const pDecs = getDecorators(params[pi]);
23318
+ for (const dec of [...pDecs].reverse()) {
23319
+ statements.push(`(${visit(dec.expression)})(New${className}, ${memberKeyStr}, float64(${pi}))`);
23320
+ }
23321
+ }
23322
+ }
22971
23323
  const decorators = getDecorators(member);
22972
23324
  if (decorators.length === 0)
22973
23325
  continue;
22974
- if (!isMethodDeclaration(member) || !member.body) {
22975
- reportError(member, `Unsupported decorator on ${className}: only method and class decorators are supported`);
23326
+ const isPrivate = member.name?.kind === 'PrivateIdentifier';
23327
+ const rawName = isPrivate ? privateGoName(member.name.text) : visit(member.name);
23328
+ const tsMemberName = isPrivate ? member.name.text : (memberKey(member.name) ?? rawName);
23329
+ if (isMethodDeclaration(member) && member.body) {
23330
+ const methodName = rawName;
23331
+ const params = splitGoParameters(getFunctionParametersInfo(member.parameters ?? []).signature);
23332
+ const paramTypes = params.map((p) => p.slice(p.indexOf(' ') + 1));
23333
+ const returnType = methodReturnGoType(member);
23334
+ const varName = `${className}_${methodName}__decorated`;
23335
+ mainPackageVariables.push(`var ${varName} func(...interface{}) interface{}`);
23336
+ const args = paramTypes.map((t, i) => `TnAs[${t}](__args[${i}])`).join(', ');
23337
+ const target = isStatic
23338
+ ? `${className}_${methodName}__undecorated(${args})`
23339
+ : `TnThis.(interface{ ${methodName}__undecorated(${paramTypes.join(', ')})${returnType ? ` ${returnType}` : ''} }).${methodName}__undecorated(${args})`;
23340
+ statements.push(`${varName} = func(__args ...interface{}) interface{} { ${returnType ? `return ${target}` : `${target}; return nil`} }`);
23341
+ const hasFn = isStatic ? 'func(__o interface{}) bool { return __o != nil }' : `func(__o interface{}) bool { _, ok := __o.(*${className}); return ok }`;
23342
+ const getFn = isStatic
23343
+ ? `func(__o interface{}) interface{} { return ${varName} }`
23344
+ : `func(__o interface{}) interface{} { return func(__args ...interface{}) interface{} { return TnWithThis(__o, func() interface{} { return ${varName}(__args...) }) } }`;
23345
+ const accessExpr = `&TnDecoratorAccess{has: ${hasFn}, get: ${getFn}}`;
23346
+ const initsRef = `&${isStatic ? staticInitsVar : ensureInstanceInits()}`;
23347
+ for (const decorator of [...decorators].reverse()) {
23348
+ const context = `&TnDecoratorContext{kind: "method", name: ${toGoStringLiteral(tsMemberName)}, static: ${isStatic}, private: ${isPrivate}, access: ${accessExpr}, metadata: ${metadataVar}, initializers: ${initsRef}}`;
23349
+ const call = `(${visit(decorator.expression)})(${adaptDecoratorTarget(varName, decorator)}, ${context})`;
23350
+ statements.push(decoratorReturnsValue(decorator) ? `${varName} = TnDecorate(${varName}, ${call})` : call);
23351
+ }
22976
23352
  continue;
22977
23353
  }
22978
- useHelper('decorators');
22979
- useHelper('dynamic');
22980
- const methodName = visit(member.name);
22981
- const isStatic = (member.modifiers ?? []).some((m) => m.kind === 'StaticKeyword');
22982
- const isPrivate = member.name?.kind === 'PrivateIdentifier';
22983
- const params = splitGoParameters(getFunctionParametersInfo(member.parameters ?? []).signature);
22984
- const paramTypes = params.map((p) => p.slice(p.indexOf(' ') + 1));
22985
- const returnType = methodReturnGoType(member);
22986
- const varName = `${className}_${methodName}__decorated`;
22987
- mainPackageVariables.push(`var ${varName} func(...interface{}) interface{}`);
22988
- const args = paramTypes.map((t, i) => `TnAs[${t}](__args[${i}])`).join(', ');
22989
- const target = isStatic
22990
- ? `${className}_${methodName}__undecorated(${args})`
22991
- : `TnThis.(interface{ ${methodName}__undecorated(${paramTypes.join(', ')})${returnType ? ` ${returnType}` : ''} }).${methodName}__undecorated(${args})`;
22992
- statements.push(`${varName} = func(__args ...interface{}) interface{} { ${returnType ? `return ${target}` : `${target}; return nil`} }`);
22993
- for (const decorator of [...decorators].reverse()) {
22994
- const context = `&TnDecoratorContext{kind: "method", name: ${toGoStringLiteral(isPrivate ? member.name.text : methodName)}, static: ${isStatic}, private: ${isPrivate}}`;
22995
- const call = `(${visit(decorator.expression)})(${varName}, ${context})`;
22996
- statements.push(decoratorReturnsValue(decorator) ? `${varName} = TnDecorate(${varName}, ${call})` : call);
22997
- }
22998
- }
22999
- for (const decorator of [...getDecorators(node)].reverse()) {
23000
- useHelper('decorators');
23001
- const context = `&TnDecoratorContext{kind: "class", name: ${toGoStringLiteral(className)}}`;
23354
+ if ((isGetAccessor(member) || isSetAccessor(member)) && member.body) {
23355
+ const accessorName = isIdentifier(member.name) ? goFieldName(member.name.text) : rawName;
23356
+ const isGetter = isGetAccessor(member);
23357
+ const varName = `${className}_${isGetter ? 'Get' : 'Set'}_${accessorName}__decorated`;
23358
+ mainPackageVariables.push(`var ${varName} func(...interface{}) interface{}`);
23359
+ if (isGetter) {
23360
+ const returnType = member.type ? getType(member.type) : methodReturnGoType(member) || 'interface{}';
23361
+ const target = isStatic
23362
+ ? `${className}_Get_${accessorName}__undecorated()`
23363
+ : `TnThis.(interface{ Get_${accessorName}__undecorated() ${returnType} }).Get_${accessorName}__undecorated()`;
23364
+ statements.push(`${varName} = func(__args ...interface{}) interface{} { return ${target} }`);
23365
+ }
23366
+ else {
23367
+ const params = splitGoParameters(getFunctionParametersInfo(member.parameters ?? []).signature);
23368
+ const paramTypes = params.map((p) => p.slice(p.indexOf(' ') + 1));
23369
+ const argType = paramTypes[0] || 'interface{}';
23370
+ const target = isStatic
23371
+ ? `${className}_Set_${accessorName}__undecorated(TnAs[${argType}](__args[0]))`
23372
+ : `TnThis.(interface{ Set_${accessorName}__undecorated(${argType}) }).Set_${accessorName}__undecorated(TnAs[${argType}](__args[0]))`;
23373
+ statements.push(`${varName} = func(__args ...interface{}) interface{} { ${target}; return nil }`);
23374
+ }
23375
+ const hasFn = isStatic ? 'func(__o interface{}) bool { return __o != nil }' : `func(__o interface{}) bool { _, ok := __o.(*${className}); return ok }`;
23376
+ const getFn = isGetter
23377
+ ? (isStatic ? `func(__o interface{}) interface{} { return ${className}_Get_${accessorName}() }` : `func(__o interface{}) interface{} { return __o.(*${className}).Get_${accessorName}() }`)
23378
+ : 'nil';
23379
+ const setArgType = !isGetter ? (splitGoParameters(getFunctionParametersInfo(member.parameters ?? []).signature).map((p) => p.slice(p.indexOf(' ') + 1))[0] || 'interface{}') : 'interface{}';
23380
+ const setFn = !isGetter
23381
+ ? (isStatic ? `func(__o interface{}, __v interface{}) { ${className}_Set_${accessorName}(TnAs[${setArgType}](__v)) }` : `func(__o interface{}, __v interface{}) { __o.(*${className}).Set_${accessorName}(TnAs[${setArgType}](__v)) }`)
23382
+ : 'nil';
23383
+ const accessExpr = `&TnDecoratorAccess{has: ${hasFn}, get: ${getFn}, set: ${setFn}}`;
23384
+ const initsRef = `&${isStatic ? staticInitsVar : ensureInstanceInits()}`;
23385
+ for (const decorator of [...decorators].reverse()) {
23386
+ const context = `&TnDecoratorContext{kind: "${isGetter ? 'getter' : 'setter'}", name: ${toGoStringLiteral(tsMemberName)}, static: ${isStatic}, private: ${isPrivate}, access: ${accessExpr}, metadata: ${metadataVar}, initializers: ${initsRef}}`;
23387
+ const call = `(${visit(decorator.expression)})(${adaptDecoratorTarget(varName, decorator)}, ${context})`;
23388
+ statements.push(decoratorReturnsValue(decorator) ? `${varName} = TnDecorate(${varName}, ${call})` : call);
23389
+ }
23390
+ continue;
23391
+ }
23392
+ if (isPropertyDeclaration(member) && isAutoAccessor(member)) {
23393
+ const goName = isPrivate ? privateGoName(member.name.text) : goFieldName(memberKey(member.name) ?? rawName);
23394
+ const accessorName = isIdentifier(member.name) ? goFieldName(member.name.text) : rawName;
23395
+ const fieldType = getPropertyDeclarationType(member);
23396
+ const getVar = `${className}_Get_${accessorName}__decorated`;
23397
+ const setVar = `${className}_Set_${accessorName}__decorated`;
23398
+ const fieldInitsVar = `${className}_${goName}__fieldInits`;
23399
+ const extraInitsVar = `${className}_${goName}__extraInits`;
23400
+ mainPackageVariables.push(`var ${getVar} func(...interface{}) interface{}`);
23401
+ mainPackageVariables.push(`var ${setVar} func(...interface{}) interface{}`);
23402
+ mainPackageVariables.push(`var ${fieldInitsVar} []interface{}`);
23403
+ mainPackageVariables.push(`var ${extraInitsVar} []interface{}`);
23404
+ if (isStatic) {
23405
+ statements.push(`${getVar} = func(__args ...interface{}) interface{} { return ${className}__accessor_${goName} }`);
23406
+ statements.push(`${setVar} = func(__args ...interface{}) interface{} { ${className}__accessor_${goName} = TnAs[${fieldType}](__args[0]); return nil }`);
23407
+ }
23408
+ else {
23409
+ statements.push(`${getVar} = func(__args ...interface{}) interface{} { return TnThis.(*${className}).__accessor_${goName} }`);
23410
+ statements.push(`${setVar} = func(__args ...interface{}) interface{} { TnThis.(*${className}).__accessor_${goName} = TnAs[${fieldType}](__args[0]); return nil }`);
23411
+ }
23412
+ const hasFn = isStatic ? 'func(__o interface{}) bool { return __o != nil }' : `func(__o interface{}) bool { _, ok := __o.(*${className}); return ok }`;
23413
+ const getFn = isStatic ? `func(__o interface{}) interface{} { return ${className}_Get_${accessorName}() }` : `func(__o interface{}) interface{} { return __o.(*${className}).Get_${accessorName}() }`;
23414
+ const setFn = isStatic ? `func(__o interface{}, __v interface{}) { ${className}_Set_${accessorName}(TnAs[${fieldType}](__v)) }` : `func(__o interface{}, __v interface{}) { __o.(*${className}).Set_${accessorName}(TnAs[${fieldType}](__v)) }`;
23415
+ const accessExpr = `&TnDecoratorAccess{has: ${hasFn}, get: ${getFn}, set: ${setFn}}`;
23416
+ for (const decorator of [...decorators].reverse()) {
23417
+ const context = `&TnDecoratorContext{kind: "accessor", name: ${toGoStringLiteral(tsMemberName)}, static: ${isStatic}, private: ${isPrivate}, access: ${accessExpr}, metadata: ${metadataVar}, initializers: &${extraInitsVar}}`;
23418
+ const targetArg = `&TnAccessorTarget{get: func() interface{} { return __prevGet() }, set: func(__v interface{}) { __prevSet(__v) }}`;
23419
+ const call = `(${visit(decorator.expression)})(${targetArg}, ${context})`;
23420
+ statements.push(`func() { __prevGet := ${getVar}; __prevSet := ${setVar}; _ = __prevGet; _ = __prevSet; ${decoratorReturnsValue(decorator) ? `TnDecorateAccessor(&${getVar}, &${setVar}, &${fieldInitsVar}, ${call})` : call} }()`);
23421
+ }
23422
+ if (isStatic) {
23423
+ staticFieldRunners.push(`${className}__accessor_${goName} = TnAs[${fieldType}](TnRunFieldInitializers(New${className}, ${fieldInitsVar}, ${className}__accessor_${goName}))`, `TnRunInitializers(New${className}, ${extraInitsVar})`);
23424
+ }
23425
+ continue;
23426
+ }
23427
+ if (isPropertyDeclaration(member)) {
23428
+ const goName = isPrivate ? privateGoName(member.name.text) : goFieldName(memberKey(member.name) ?? rawName);
23429
+ const fieldType = getPropertyDeclarationType(member);
23430
+ const fieldInitsVar = `${className}_${goName}__fieldInits`;
23431
+ const extraInitsVar = `${className}_${goName}__extraInits`;
23432
+ mainPackageVariables.push(`var ${fieldInitsVar} []interface{}`);
23433
+ mainPackageVariables.push(`var ${extraInitsVar} []interface{}`);
23434
+ const hasFn = isStatic ? 'func(__o interface{}) bool { return __o != nil }' : `func(__o interface{}) bool { _, ok := __o.(*${className}); return ok }`;
23435
+ const getFn = isStatic ? `func(__o interface{}) interface{} { return ${className}_${goName} }` : `func(__o interface{}) interface{} { return __o.(*${className}).${goName} }`;
23436
+ const setFn = isStatic ? `func(__o interface{}, __v interface{}) { ${className}_${goName} = TnAs[${fieldType}](__v) }` : `func(__o interface{}, __v interface{}) { __o.(*${className}).${goName} = TnAs[${fieldType}](__v) }`;
23437
+ const accessExpr = `&TnDecoratorAccess{has: ${hasFn}, get: ${getFn}, set: ${setFn}}`;
23438
+ for (const decorator of [...decorators].reverse()) {
23439
+ const context = `&TnDecoratorContext{kind: "field", name: ${toGoStringLiteral(tsMemberName)}, static: ${isStatic}, private: ${isPrivate}, access: ${accessExpr}, metadata: ${metadataVar}, initializers: &${extraInitsVar}}`;
23440
+ const call = `(${visit(decorator.expression)})(nil, ${context})`;
23441
+ statements.push(decoratorReturnsValue(decorator) ? `if __fi := interface{}(${call}); __fi != nil { ${fieldInitsVar} = append(${fieldInitsVar}, __fi) }` : call);
23442
+ }
23443
+ if (isStatic) {
23444
+ staticFieldRunners.push(`${className}_${goName} = TnAs[${fieldType}](TnRunFieldInitializers(New${className}, ${fieldInitsVar}, ${className}_${goName}))`, `TnRunInitializers(New${className}, ${extraInitsVar})`);
23445
+ }
23446
+ continue;
23447
+ }
23448
+ reportError(member, `Unsupported decorator on ${className}`);
23449
+ }
23450
+ for (const decorator of [...classDecorators].reverse()) {
23451
+ const context = `&TnDecoratorContext{kind: "class", name: ${toGoStringLiteral(className)}, metadata: ${metadataVar}, initializers: &${classInitsVar}}`;
23002
23452
  const call = `(${visit(decorator.expression)})(New${className}, ${context})`;
23003
23453
  statements.push(decoratorReturnsValue(decorator) ? `TnDecorateClass(${call})` : call);
23004
23454
  }
23455
+ statements.push(`TnRunInitializers(New${className}, ${staticInitsVar})`);
23456
+ for (const r of staticFieldRunners)
23457
+ statements.push(r);
23458
+ statements.push(`TnRunInitializers(New${className}, ${classInitsVar})`);
23005
23459
  return statements.map((statement) => `${statement};\n\t`).join('');
23006
23460
  }
23007
23461
  function isStringRawTag(tag) {
@@ -23112,7 +23566,20 @@ function registerClassMembers(node) {
23112
23566
  const isStatic = memberModifiers?.some((m) => m.kind === 'StaticKeyword');
23113
23567
  const memberName = memberKey(member.name);
23114
23568
  if (isPropertyDeclaration(member) && memberName) {
23115
- if (isStatic) {
23569
+ if (isAutoAccessor(member)) {
23570
+ const propType = getPropertyDeclarationType(member);
23571
+ if (isStatic) {
23572
+ classStaticProps.add(`${className}.${memberName}`);
23573
+ classStaticGetters.add(`${className}.${memberName}`);
23574
+ classStaticSetters.add(`${className}.${memberName}`);
23575
+ }
23576
+ else {
23577
+ classGetterMethods.add(`${className}.${memberName}`);
23578
+ classSetterMethods.add(`${className}.${memberName}`);
23579
+ properties.set(memberName, propType);
23580
+ }
23581
+ }
23582
+ else if (isStatic) {
23116
23583
  classStaticProps.add(`${className}.${memberName}`);
23117
23584
  }
23118
23585
  else {
@@ -23133,6 +23600,8 @@ function registerClassMembers(node) {
23133
23600
  classStaticProps.add(`${className}.${memberName}`);
23134
23601
  if (isGetAccessor(member))
23135
23602
  classStaticGetters.add(`${className}.${memberName}`);
23603
+ if (isSetAccessor(member))
23604
+ classStaticSetters.add(`${className}.${memberName}`);
23136
23605
  }
23137
23606
  if (isGetAccessor(member) && memberName && !isStatic) {
23138
23607
  classGetterMethods.add(`${className}.${memberName}`);
@@ -23897,8 +24366,8 @@ function getParameterGoType(param) {
23897
24366
  const isTaggedTemplateArray = isTypeReferenceNode(param.type) &&
23898
24367
  isIdentifier(param.type.typeName) &&
23899
24368
  param.type.typeName.text === 'TemplateStringsArray';
23900
- // (a function literal stored where a function type is expected takes
23901
- // that type's parameter: a function type's arrays are plain slices)
24369
+ // (a function literal stored where a plain-slice function type is expected
24370
+ // — e.g. a Go-bridge callback — takes that type's parameter)
23902
24371
  const slotType = isArrowFunction(param.parent) || isFunctionExpression(param.parent) ? functionSlotParamType(param) : undefined;
23903
24372
  if (!isUnboundGoType(explicitType.slice(2)) && !isTaggedTemplateArray && slotType !== explicitType) {
23904
24373
  explicitType = `*${explicitType}`;
@@ -23941,8 +24410,8 @@ function getParameterGoType(param) {
23941
24410
  const contextualParam = contextualFn.parameters?.[index];
23942
24411
  const contextualParamType = contextualParam?.type;
23943
24412
  if (contextualParamType) {
23944
- const contextualGoType = getType(contextualParamType);
23945
- return contextualParam.questionToken ? makeNullableType(contextualGoType) : contextualGoType;
24413
+ // (as the function type emits it: arrays as references)
24414
+ return functionTypeParamGoType(contextualParam, contextualFn);
23946
24415
  }
23947
24416
  }
23948
24417
  // f = (x) => …, where f holds a function: the parameter of f's Go type
@@ -23964,6 +24433,17 @@ function getParameterGoType(param) {
23964
24433
  }
23965
24434
  return 'interface{}';
23966
24435
  }
24436
+ // The Go type of a function type's parameter, as the function type emits it:
24437
+ // arrays are references (*[]T), so a function value called through the slot
24438
+ // shares the caller's array — a push in it reaches the caller (JS passes the
24439
+ // array itself)
24440
+ function functionTypeParamGoType(param, fnType) {
24441
+ if (param.dotDotDotToken) {
24442
+ const restType = getType(param.type);
24443
+ return param.questionToken ? makeNullableType(restType) : restType;
24444
+ }
24445
+ return getParameterGoType({ ...param, parent: fnType });
24446
+ }
23967
24447
  function adaptReferenceParams(expr, goType) {
23968
24448
  const own = functionValueGoType(unwrapParentheses(expr));
23969
24449
  if (!own?.startsWith('func(') || own === goType)
@@ -23995,8 +24475,9 @@ function functionSlotParamType(param) {
23995
24475
  const index = (fn?.parameters ?? []).indexOf(param);
23996
24476
  const contextualFn = getContextualFunctionType(fn);
23997
24477
  const contextualParam = contextualFn?.parameters?.[index];
24478
+ // (as the function type emits it: arrays as references)
23998
24479
  if (contextualParam?.type)
23999
- return getType(contextualParam.type);
24480
+ return functionTypeParamGoType(contextualParam, contextualFn);
24000
24481
  const slot = fn?.parent && isBinaryExpression(fn.parent) && fn.parent.operatorToken.kind === 'EqualsToken' && fn.parent.right === fn
24001
24482
  ? inferExpressionType(fn.parent.left)
24002
24483
  : undefined;
@@ -24767,7 +25248,7 @@ function visitCallArguments(node) {
24767
25248
  if (!fn) {
24768
25249
  // A function-valued variable or field without a declared type
24769
25250
  // (const f = (xs: number[]) => …): its Go func type's parameters
24770
- const calleeType = isIdentifier(node.expression) || isPropertyAccessExpression(node.expression) || isCallExpression(node.expression) || isParenthesizedExpression(node.expression)
25251
+ const calleeType = isIdentifier(node.expression) || isPropertyAccessExpression(node.expression) || isElementAccessExpression(node.expression) || isCallExpression(node.expression) || isParenthesizedExpression(node.expression)
24771
25252
  ? inferExpressionType(node.expression)
24772
25253
  : undefined;
24773
25254
  // (a variadic function value: its rest arguments converted to the element type)
@@ -25020,7 +25501,7 @@ function withContextualParameters(fn, info) {
25020
25501
  return info;
25021
25502
  const extra = contextualParams
25022
25503
  .slice(declaredCount)
25023
- .map((p) => `_ ${p.dotDotDotToken ? '...' : ''}${p.type ? (p.questionToken && !p.dotDotDotToken ? makeNullableType(getType(p.type)) : getType(p.type)) : 'interface{}'}`);
25504
+ .map((p) => `_ ${p.type ? getParameterGoType({ ...p, parent: contextualFn }) : (p.dotDotDotToken ? '...interface{}' : 'interface{}')}`);
25024
25505
  const signature = [info.signature, ...extra].filter((part) => part).join(', ');
25025
25506
  return { ...info, signature };
25026
25507
  }
@@ -25330,12 +25811,11 @@ function getPromiseChannelType(node) {
25330
25811
  }
25331
25812
  return 'interface{}';
25332
25813
  }
25333
- // An async function whose body never parks: it awaits only calls of other
25334
- // such functions (their promises are settled by the time they return, and
25335
- // TnAwait resumes on the spot on a settled promise), has no for await, and
25336
- // returns no promise (whose value it would await). Called, it runs to its end
25337
- // at once, so it runs on the caller's goroutine (TnRunAsyncInline) instead of
25338
- // a goroutine of its own handing the JS baton back and forth (TnStartAsync).
25814
+ // An async function whose body has no await, no for await, and returns no
25815
+ // promise (whose value it would await): called, it runs to its end at once on
25816
+ // the caller's goroutine (TnRunAsyncInline) instead of a goroutine of its own
25817
+ // handing the JS baton back and forth (TnStartAsync). Functions with await
25818
+ // must suspend at their await and resume as a microtask.
25339
25819
  const asyncInlineCache = new Map();
25340
25820
  function asyncInlineEligible(fn, visiting = new Set()) {
25341
25821
  const cached = asyncInlineCache.get(fn);
@@ -25389,13 +25869,8 @@ function asyncInlineEligible(fn, visiting = new Set()) {
25389
25869
  return true;
25390
25870
  if (n.kind === 'YieldExpression')
25391
25871
  return true;
25392
- if (n.kind === 'AwaitExpression') {
25393
- const operand = unwrapParentheses(n.expression);
25394
- if (!isCallExpression(operand) || operand.questionDotToken || !isIdentifier(operand.expression))
25395
- return true;
25396
- const decl = declaredFunctions.get(operand.expression.text);
25397
- return !decl || !isFunctionDeclaration(decl) || decl.parent?.kind !== 'SourceFile' || !asyncInlineEligible(decl, visiting);
25398
- }
25872
+ if (n.kind === 'AwaitExpression')
25873
+ return true;
25399
25874
  if (isReturnStatement(n) && n.expression && !plainValue(n.expression))
25400
25875
  return true;
25401
25876
  return false;
@@ -25427,13 +25902,16 @@ function emitChannelFunction(node, isAsync, header) {
25427
25902
  const prevChannel = asyncChannelVar;
25428
25903
  const prevFn = asyncFunctionNode;
25429
25904
  const prevIsAsync = asyncChannelIsAsync;
25905
+ const prevYieldType = asyncChannelYieldType;
25430
25906
  asyncChannelVar = channelVar;
25431
25907
  asyncFunctionNode = node;
25432
25908
  asyncChannelIsAsync = isAsync;
25909
+ asyncChannelYieldType = chanType;
25433
25910
  const body = visit(node.body, { prefixBlockContent: parameterInfo.prefixBlockContent });
25434
25911
  asyncChannelVar = prevChannel;
25435
25912
  asyncFunctionNode = prevFn;
25436
25913
  asyncChannelIsAsync = prevIsAsync;
25914
+ asyncChannelYieldType = prevYieldType;
25437
25915
  if (isAsync) {
25438
25916
  // The body runs synchronously until its first await, holding the JS baton
25439
25917
  // (a body that never parks runs on the caller's goroutine: see asyncInlineEligible)
@@ -25445,7 +25923,8 @@ function emitChannelFunction(node, isAsync, header) {
25445
25923
  const seq = !header && isFunctionDeclaration(node) && node.parent?.kind === 'SourceFile' && generatorSeqEligible(node)
25446
25924
  ? `\n\n${emitGeneratorSeq(node, `func ${name}__seq${typeParams}`, parameterInfo, prologue)}`
25447
25925
  : '';
25448
- return (`${declaration}(${parameterInfo.signature}) chan ${chanType} {\n\t${prologue}${channelVar} := make(chan ${chanType})\n\tgo func() {\n\t\tdefer close(${channelVar})${rejectOnPanic}\n\t\t${body.trim()}\n\t}()\n\treturn ${channelVar}\n}` + seq);
25926
+ const isAsyncGen = (node.modifiers ?? []).some((m) => m.kind === 'AsyncKeyword');
25927
+ return (`${declaration}(${parameterInfo.signature}) chan ${chanType} {\n\t${emitGeneratorGoroutineBody(chanType, channelVar, prologue, body, isAsyncGen)}\n}` + seq);
25449
25928
  }
25450
25929
  // The type a generator yields: from its first yield expression's operand
25451
25930
  // The generator functions whose yield type is being inferred
@@ -25488,6 +25967,105 @@ function getGeneratorYieldType(fn) {
25488
25967
  generatorYieldsInferring.delete(fn);
25489
25968
  return found && found !== 'nil' ? found : 'interface{}';
25490
25969
  }
25970
+ function generatorTypeArg(fn, index) {
25971
+ if (!fn)
25972
+ return undefined;
25973
+ const retType = fn.type ?? (isFunctionExpression(fn) ? resolveTypeNode(getContextualFunctionType(fn)?.type) : undefined);
25974
+ if (retType && isTypeReferenceNode(retType) && isIdentifier(retType.typeName) && ['Generator', 'AsyncGenerator'].includes(retType.typeName.text) && (retType.typeArguments ?? []).length > index) {
25975
+ const arg = retType.typeArguments[index];
25976
+ if (arg && !['UndefinedKeyword', 'VoidKeyword', 'UnknownKeyword', 'AnyKeyword'].includes(arg.kind)) {
25977
+ const goType = getType(arg);
25978
+ if (goType && goType !== ':')
25979
+ return goType;
25980
+ }
25981
+ }
25982
+ return undefined;
25983
+ }
25984
+ function getGeneratorNextType(fn) {
25985
+ return generatorTypeArg(fn, 2) ?? 'interface{}';
25986
+ }
25987
+ function getGeneratorReturnType(fn) {
25988
+ const annotated = generatorTypeArg(fn, 1);
25989
+ if (annotated)
25990
+ return annotated;
25991
+ if (!fn?.body)
25992
+ return undefined;
25993
+ let found;
25994
+ containsNode(fn.body, (n) => {
25995
+ if (isReturnStatement(n) && n.expression && getEnclosingFunction(n) === fn) {
25996
+ found = inferExpressionType(n.expression);
25997
+ return true;
25998
+ }
25999
+ return false;
26000
+ });
26001
+ return found;
26002
+ }
26003
+ function delegatedGeneratorReturnType(expr) {
26004
+ if (!expr)
26005
+ return undefined;
26006
+ const bare = unwrapParentheses(expr);
26007
+ if (isCallExpression(bare) && isIdentifier(bare.expression)) {
26008
+ const decl = declaredFunctions.get(bare.expression.text);
26009
+ if (decl?.asteriskToken)
26010
+ return getGeneratorReturnType(decl);
26011
+ }
26012
+ return undefined;
26013
+ }
26014
+ function generatorResultElementType(receiverNode, elementType, method, arg0) {
26015
+ if (elementType === 'interface{}')
26016
+ return 'interface{}';
26017
+ if (method === 'return' && arg0) {
26018
+ const argType = inferExpressionType(arg0);
26019
+ if (argType && argType !== elementType && argType !== 'nil')
26020
+ return 'interface{}';
26021
+ }
26022
+ if (receiverNode) {
26023
+ const bare = unwrapParentheses(receiverNode);
26024
+ let fnDecl;
26025
+ if (isCallExpression(bare) && isIdentifier(bare.expression)) {
26026
+ fnDecl = declaredFunctions.get(bare.expression.text);
26027
+ }
26028
+ else if (isIdentifier(bare)) {
26029
+ let decl;
26030
+ for (let p = bare.parent; p && !decl; p = p.parent) {
26031
+ if (isBlock(p) || p.kind === 'SourceFile') {
26032
+ for (const st of p.statements ?? []) {
26033
+ if (st.kind === 'VariableStatement') {
26034
+ for (const d of st.declarationList?.declarations ?? []) {
26035
+ if (isIdentifier(d.name) && d.name.text === bare.text) {
26036
+ decl = d;
26037
+ break;
26038
+ }
26039
+ }
26040
+ }
26041
+ if (decl)
26042
+ break;
26043
+ }
26044
+ }
26045
+ }
26046
+ decl = decl ?? declaredVariables.get(bare.text);
26047
+ if (decl?.type && isTypeReferenceNode(decl.type) && isIdentifier(decl.type.typeName) && ['Generator', 'AsyncGenerator'].includes(decl.type.typeName.text) && (decl.type.typeArguments ?? []).length > 1) {
26048
+ const retArg = decl.type.typeArguments[1];
26049
+ if (retArg && !['UndefinedKeyword', 'VoidKeyword'].includes(retArg.kind)) {
26050
+ const t = getType(retArg);
26051
+ if (t && t !== ':' && t !== elementType)
26052
+ return 'interface{}';
26053
+ }
26054
+ }
26055
+ else if (decl?.initializer && isCallExpression(unwrapParentheses(decl.initializer))) {
26056
+ const initCall = unwrapParentheses(decl.initializer);
26057
+ if (isIdentifier(initCall.expression))
26058
+ fnDecl = declaredFunctions.get(initCall.expression.text);
26059
+ }
26060
+ }
26061
+ if (fnDecl?.asteriskToken) {
26062
+ const retType = getGeneratorReturnType(fnDecl);
26063
+ if (retType && retType !== elementType && retType !== 'nil')
26064
+ return 'interface{}';
26065
+ }
26066
+ }
26067
+ return elementType;
26068
+ }
25491
26069
  function visitPromiseReturn(node, options) {
25492
26070
  const callback = node.arguments?.[0];
25493
26071
  if (!callback || (!isArrowFunction(callback) && !isFunctionExpression(callback))) {
@@ -27108,15 +27686,13 @@ function goFileImportLines(fileCode) {
27108
27686
  .map((pkg) => (pkg === 'embed' && blankEmbed ? 'import _ "embed"' : goImportLine(pkg)))
27109
27687
  .join('\n');
27110
27688
  }
27111
- // Every Go package some helper imports
27689
+ // Every Go package a used helper imports
27112
27690
  function allHelperPackages() {
27113
27691
  const all = new Set();
27114
- for (const pkgs of Object.values(helperPackages))
27115
- for (const pkg of pkgs)
27116
- all.add(pkg);
27117
- for (const pkgs of Object.values(nodeRegistry.helperPackages))
27118
- for (const pkg of pkgs)
27692
+ for (const id of usedHelpers) {
27693
+ for (const pkg of helperPackages[id] ?? nodeRegistry.helperPackages[id] ?? [])
27119
27694
  all.add(pkg);
27695
+ }
27120
27696
  return all;
27121
27697
  }
27122
27698
  // Whether Object.keys & co.'s argument is a Map / Record (an ordered map)
@@ -27224,6 +27800,8 @@ function needPkg(pkg) {
27224
27800
  // Marks a Go helper as used; also registers the packages the helper needs,
27225
27801
  // since the import list is serialized before helpers are emitted.
27226
27802
  const helperRequires = {
27803
+ generatorStep: ['dynamic', 'error'],
27804
+ iterators: ['generatorStep', 'dynamic'],
27227
27805
  generatorSeq: ['generatorStep', 'dynamic', 'arraySubclass'],
27228
27806
  regexReplaceFunc: ['strIndex'],
27229
27807
  replaceAny: ['fancyRegex', 'regexReplaceFunc', 'dynamic'],
@@ -27245,7 +27823,7 @@ const helperRequires = {
27245
27823
  builtins: ['error', 'dynamic', 'bigint'],
27246
27824
  date: ['error', 'dynamic'],
27247
27825
  goBlocking: ['error', 'eventLoop'],
27248
- decorators: ['functionThis'],
27826
+ decorators: ['functionThis', 'orderedMap', 'dynamic'],
27249
27827
  functionThis: [],
27250
27828
  jsx: [],
27251
27829
  objectIntegrity: [],
@@ -28157,19 +28735,157 @@ func tnSeqCollect[T any](s func(func(T) bool)) []T {
28157
28735
  // yield it waits until the loop body has run for that value (JS resumes a
28158
28736
  // generator only on next()), so the body sees the state the generator saw
28159
28737
  var tnGenAcks sync.Map
28738
+ var tnGenCtrls sync.Map
28739
+
28740
+ func init() {
28741
+ tnGenWakeFn = TnGenWake
28742
+ }
28160
28743
 
28161
28744
  // A generator push form's stop token (one per run: a nested generator's
28162
28745
  // stop passes through the outer one). Not zero-sized, so each is unique
28163
28746
  type tnGenStop struct{ _ byte }
28164
28747
 
28748
+ type tnGenCmdKind uint8
28749
+
28750
+ const (
28751
+ tnGenCmdNext tnGenCmdKind = iota
28752
+ tnGenCmdReturn
28753
+ tnGenCmdThrow
28754
+ )
28755
+
28756
+ type tnGenCmd struct {
28757
+ kind tnGenCmdKind
28758
+ val interface{}
28759
+ }
28760
+
28761
+ type tnGenReturn struct {
28762
+ val interface{}
28763
+ }
28764
+
28765
+ type tnGenCtrl struct {
28766
+ in chan tnGenCmd
28767
+ mu sync.Mutex
28768
+ done bool
28769
+ hasRet bool
28770
+ retVal interface{}
28771
+ hasErr bool
28772
+ errVal interface{}
28773
+ }
28774
+
28775
+ func TnGenStart[T any](ch chan T) *tnGenCtrl {
28776
+ ctrl := &tnGenCtrl{in: make(chan tnGenCmd)}
28777
+ tnGenCtrls.Store(ch, ctrl)
28778
+ return ctrl
28779
+ }
28780
+
28781
+ func TnGenWake(ch interface{}) {
28782
+ if c, ok := tnGenCtrls.Load(ch); ok {
28783
+ ctrl := c.(*tnGenCtrl)
28784
+ ctrl.mu.Lock()
28785
+ done := ctrl.done
28786
+ ctrl.mu.Unlock()
28787
+ if !done {
28788
+ ctrl.in <- tnGenCmd{kind: tnGenCmdNext}
28789
+ }
28790
+ }
28791
+ }
28792
+
28793
+ func (c *tnGenCtrl) awaitStart() bool {
28794
+ cmd := <-c.in
28795
+ switch cmd.kind {
28796
+ case tnGenCmdReturn:
28797
+ c.mu.Lock()
28798
+ c.hasRet = true
28799
+ c.retVal = cmd.val
28800
+ c.mu.Unlock()
28801
+ return false
28802
+ case tnGenCmdThrow:
28803
+ if cmd.val == nil {
28804
+ panic(tnGenNilErr{})
28805
+ }
28806
+ panic(cmd.val)
28807
+ default:
28808
+ return true
28809
+ }
28810
+ }
28811
+
28812
+ func (c *tnGenCtrl) finishDone() {
28813
+ c.mu.Lock()
28814
+ c.done = true
28815
+ c.mu.Unlock()
28816
+ }
28817
+
28818
+ func (c *tnGenCtrl) finishReturn(val interface{}) {
28819
+ c.mu.Lock()
28820
+ c.hasRet = true
28821
+ c.retVal = val
28822
+ c.done = true
28823
+ c.mu.Unlock()
28824
+ }
28825
+
28826
+ func (c *tnGenCtrl) finishError(err interface{}) {
28827
+ c.mu.Lock()
28828
+ c.hasErr = true
28829
+ c.errVal = err
28830
+ c.done = true
28831
+ c.mu.Unlock()
28832
+ }
28833
+
28834
+ func TnGenSetReturn[T any](ch chan T, val interface{}) {
28835
+ if c, ok := tnGenCtrls.Load(ch); ok {
28836
+ ctrl := c.(*tnGenCtrl)
28837
+ ctrl.mu.Lock()
28838
+ ctrl.hasRet = true
28839
+ ctrl.retVal = val
28840
+ ctrl.mu.Unlock()
28841
+ }
28842
+ }
28843
+
28844
+ func TnGenYieldCmd[T any](ch chan T, val T) tnGenCmd {
28845
+ ch <- val
28846
+ if c, ok := tnGenCtrls.Load(ch); ok {
28847
+ return <-c.(*tnGenCtrl).in
28848
+ }
28849
+ return tnGenCmd{kind: tnGenCmdNext}
28850
+ }
28851
+
28852
+ func TnGenYield[T any](ch chan T, val T) interface{} {
28853
+ cmd := TnGenYieldCmd(ch, val)
28854
+ switch cmd.kind {
28855
+ case tnGenCmdReturn:
28856
+ panic(tnGenReturn{val: cmd.val})
28857
+ case tnGenCmdThrow:
28858
+ if cmd.val == nil {
28859
+ panic(tnGenNilErr{})
28860
+ }
28861
+ panic(cmd.val)
28862
+ default:
28863
+ return cmd.val
28864
+ }
28865
+ }
28866
+
28867
+ func tnGenPull[T any](ch chan T) (T, bool) {
28868
+ TnGenWake(ch)
28869
+ v, ok := <-ch
28870
+ return v, ok
28871
+ }
28872
+
28165
28873
  // Marks a generator's channel as consumed in step (before its first receive)
28166
28874
  func TnGenLockstep[T any](ch chan T) chan T {
28875
+ if _, ok := tnGenCtrls.Load(ch); ok {
28876
+ TnGenWake(ch)
28877
+ return ch
28878
+ }
28167
28879
  tnGenAcks.Store(ch, make(chan struct{}, 1))
28168
28880
  return ch
28169
28881
  }
28170
28882
 
28171
28883
  // The loop body ran for the last value received: the generator may go on
28172
28884
  func TnGenAck[T any](ch chan T) {
28885
+ if _, ok := tnGenCtrls.Load(ch); ok {
28886
+ TnGenWake(ch)
28887
+ return
28888
+ }
28173
28889
  if ack, ok := tnGenAcks.Load(ch); ok {
28174
28890
  select {
28175
28891
  case ack.(chan struct{}) <- struct{}{}:
@@ -28203,10 +28919,141 @@ func TnIterFirst[T any](items []T) *TnIterResult[T] {
28203
28919
  return &TnIterResult[T]{value: items[0]}
28204
28920
  }
28205
28921
 
28206
- // it.next(): { value, done }
28207
- func TnIterNext[T any](ch chan T) *TnIterResult[T] {
28922
+ // it.next() / next(v) / return(v) / throw(e): { value, done }
28923
+ func tnIterStep[T any, R any](ch chan T, kind tnGenCmdKind, val interface{}, hasVal bool, toRes func(T) R, castRet func(interface{}) R) *TnIterResult[R] {
28924
+ if c, ok := tnGenCtrls.Load(ch); ok {
28925
+ ctrl := c.(*tnGenCtrl)
28926
+ ctrl.mu.Lock()
28927
+ if ctrl.done {
28928
+ ctrl.mu.Unlock()
28929
+ if kind == tnGenCmdThrow {
28930
+ if val == nil {
28931
+ panic(nil)
28932
+ }
28933
+ panic(val)
28934
+ }
28935
+ if kind == tnGenCmdReturn && hasVal {
28936
+ return &TnIterResult[R]{value: castRet(val), done: true}
28937
+ }
28938
+ return &TnIterResult[R]{done: true}
28939
+ }
28940
+ ctrl.mu.Unlock()
28941
+ ctrl.in <- tnGenCmd{kind: kind, val: val}
28942
+ v, ok := <-ch
28943
+ if ok {
28944
+ return &TnIterResult[R]{value: toRes(v), done: false}
28945
+ }
28946
+ ctrl.mu.Lock()
28947
+ hasErr := ctrl.hasErr
28948
+ errVal := ctrl.errVal
28949
+ ctrl.hasErr = false
28950
+ hasRet := ctrl.hasRet
28951
+ retVal := ctrl.retVal
28952
+ ctrl.hasRet = false
28953
+ ctrl.mu.Unlock()
28954
+ if hasErr {
28955
+ if _, isNil := errVal.(tnGenNilErr); isNil {
28956
+ panic(nil)
28957
+ }
28958
+ panic(errVal)
28959
+ }
28960
+ if hasRet {
28961
+ return &TnIterResult[R]{value: castRet(retVal), done: true}
28962
+ }
28963
+ if kind == tnGenCmdReturn && hasVal {
28964
+ return &TnIterResult[R]{value: castRet(val), done: true}
28965
+ }
28966
+ return &TnIterResult[R]{done: true}
28967
+ }
28968
+ if kind == tnGenCmdThrow {
28969
+ panic(val)
28970
+ }
28971
+ if kind == tnGenCmdReturn {
28972
+ if hasVal {
28973
+ return &TnIterResult[R]{value: castRet(val), done: true}
28974
+ }
28975
+ return &TnIterResult[R]{done: true}
28976
+ }
28208
28977
  v, ok := <-ch
28209
- return &TnIterResult[T]{value: v, done: !ok}
28978
+ if ok {
28979
+ return &TnIterResult[R]{value: toRes(v), done: false}
28980
+ }
28981
+ return &TnIterResult[R]{done: true}
28982
+ }
28983
+
28984
+ func tnIterCast[R any](v interface{}) R {
28985
+ if v == nil {
28986
+ var zero R
28987
+ return zero
28988
+ }
28989
+ return TnAs[R](v)
28990
+ }
28991
+
28992
+ func tnIterToAny[T any](v T) interface{} { return v }
28993
+ func tnIterId[T any](v T) T { return v }
28994
+ func tnIterIdAny(v interface{}) interface{} { return v }
28995
+
28996
+ func TnIterNext[T any](ch chan T) *TnIterResult[T] {
28997
+ return tnIterStep[T, T](ch, tnGenCmdNext, nil, false, tnIterId[T], tnIterCast[T])
28998
+ }
28999
+
29000
+ func TnIterNextVal[T any](ch chan T, val interface{}) *TnIterResult[T] {
29001
+ return tnIterStep[T, T](ch, tnGenCmdNext, val, true, tnIterId[T], tnIterCast[T])
29002
+ }
29003
+
29004
+ func TnIterReturn[T any](ch chan T, val interface{}, hasVal bool) *TnIterResult[T] {
29005
+ return tnIterStep[T, T](ch, tnGenCmdReturn, val, hasVal, tnIterId[T], tnIterCast[T])
29006
+ }
29007
+
29008
+ func TnIterThrow[T any](ch chan T, err interface{}) *TnIterResult[T] {
29009
+ return tnIterStep[T, T](ch, tnGenCmdThrow, err, true, tnIterId[T], tnIterCast[T])
29010
+ }
29011
+
29012
+ func TnIterNextAny[T any](ch chan T, val interface{}) *TnIterResult[interface{}] {
29013
+ return tnIterStep[T, interface{}](ch, tnGenCmdNext, val, false, tnIterToAny[T], tnIterIdAny)
29014
+ }
29015
+
29016
+ func TnIterReturnAny[T any](ch chan T, val interface{}, hasVal bool) *TnIterResult[interface{}] {
29017
+ return tnIterStep[T, interface{}](ch, tnGenCmdReturn, val, hasVal, tnIterToAny[T], tnIterIdAny)
29018
+ }
29019
+
29020
+ func TnIterThrowAny[T any](ch chan T, err interface{}) *TnIterResult[interface{}] {
29021
+ return tnIterStep[T, interface{}](ch, tnGenCmdThrow, err, true, tnIterToAny[T], tnIterIdAny)
29022
+ }
29023
+
29024
+ func TnGenDelegate[T any, S any](outerCh chan T, innerCh chan S, convert func(S) T) interface{} {
29025
+ cmd := tnGenCmd{kind: tnGenCmdNext}
29026
+ for {
29027
+ var res *TnIterResult[interface{}]
29028
+ var panicErr interface{}
29029
+ var panicked bool
29030
+ func() {
29031
+ defer func() {
29032
+ if r := recover(); r != nil {
29033
+ panicErr = r
29034
+ panicked = true
29035
+ }
29036
+ }()
29037
+ switch cmd.kind {
29038
+ case tnGenCmdNext:
29039
+ res = TnIterNextAny(innerCh, cmd.val)
29040
+ case tnGenCmdReturn:
29041
+ res = TnIterReturnAny(innerCh, cmd.val, true)
29042
+ case tnGenCmdThrow:
29043
+ res = TnIterThrowAny(innerCh, cmd.val)
29044
+ }
29045
+ }()
29046
+ if panicked {
29047
+ panic(panicErr)
29048
+ }
29049
+ if res.done {
29050
+ if cmd.kind == tnGenCmdReturn {
29051
+ panic(tnGenReturn{val: res.value})
29052
+ }
29053
+ return res.value
29054
+ }
29055
+ cmd = TnGenYieldCmd(outerCh, convert(TnAs[S](res.value)))
29056
+ }
28210
29057
  }
28211
29058
 
28212
29059
  // Iterator.concat(a, b, …): each iterable's values in turn
@@ -28215,7 +29062,11 @@ func TnIterConcat[T any](chs ...chan T) chan T {
28215
29062
  go func() {
28216
29063
  defer close(ch)
28217
29064
  for _, src := range chs {
28218
- for v := range src {
29065
+ for {
29066
+ v, ok := tnGenPull(src)
29067
+ if !ok {
29068
+ break
29069
+ }
28219
29070
  ch <- v
28220
29071
  }
28221
29072
  }
@@ -28240,7 +29091,11 @@ func TnIterMap[T, U any](ch chan T, fn func(T, float64) U) chan U {
28240
29091
  go func() {
28241
29092
  defer close(out)
28242
29093
  i := 0.0
28243
- for v := range ch {
29094
+ for {
29095
+ v, ok := tnGenPull(ch)
29096
+ if !ok {
29097
+ break
29098
+ }
28244
29099
  out <- fn(v, i)
28245
29100
  i++
28246
29101
  }
@@ -28253,7 +29108,11 @@ func TnIterFilter[T any](ch chan T, fn func(T, float64) bool) chan T {
28253
29108
  go func() {
28254
29109
  defer close(out)
28255
29110
  i := 0.0
28256
- for v := range ch {
29111
+ for {
29112
+ v, ok := tnGenPull(ch)
29113
+ if !ok {
29114
+ break
29115
+ }
28257
29116
  if fn(v, i) {
28258
29117
  out <- v
28259
29118
  }
@@ -28268,7 +29127,11 @@ func TnIterFlatMap[T, U any](ch chan T, fn func(T, float64) []U) chan U {
28268
29127
  go func() {
28269
29128
  defer close(out)
28270
29129
  i := 0.0
28271
- for v := range ch {
29130
+ for {
29131
+ v, ok := tnGenPull(ch)
29132
+ if !ok {
29133
+ break
29134
+ }
28272
29135
  for _, u := range fn(v, i) {
28273
29136
  out <- u
28274
29137
  }
@@ -28286,7 +29149,11 @@ func TnIterTake[T any](ch chan T, n float64) chan T {
28286
29149
  return
28287
29150
  }
28288
29151
  count := 0.0
28289
- for v := range ch {
29152
+ for {
29153
+ v, ok := tnGenPull(ch)
29154
+ if !ok {
29155
+ break
29156
+ }
28290
29157
  out <- v
28291
29158
  count++
28292
29159
  if count >= n {
@@ -28302,7 +29169,11 @@ func TnIterDrop[T any](ch chan T, n float64) chan T {
28302
29169
  go func() {
28303
29170
  defer close(out)
28304
29171
  count := 0.0
28305
- for v := range ch {
29172
+ for {
29173
+ v, ok := tnGenPull(ch)
29174
+ if !ok {
29175
+ break
29176
+ }
28306
29177
  if count >= n {
28307
29178
  out <- v
28308
29179
  }
@@ -28314,7 +29185,11 @@ func TnIterDrop[T any](ch chan T, n float64) chan T {
28314
29185
 
28315
29186
  func TnIterToArray[T any](ch chan T) []T {
28316
29187
  out := []T{}
28317
- for v := range ch {
29188
+ for {
29189
+ v, ok := tnGenPull(ch)
29190
+ if !ok {
29191
+ break
29192
+ }
28318
29193
  out = append(out, v)
28319
29194
  }
28320
29195
  return out
@@ -28322,7 +29197,11 @@ func TnIterToArray[T any](ch chan T) []T {
28322
29197
 
28323
29198
  func TnIterForEach[T any](ch chan T, fn func(T, float64)) {
28324
29199
  i := 0.0
28325
- for v := range ch {
29200
+ for {
29201
+ v, ok := tnGenPull(ch)
29202
+ if !ok {
29203
+ break
29204
+ }
28326
29205
  fn(v, i)
28327
29206
  i++
28328
29207
  }
@@ -28330,7 +29209,11 @@ func TnIterForEach[T any](ch chan T, fn func(T, float64)) {
28330
29209
 
28331
29210
  func TnIterSome[T any](ch chan T, fn func(T, float64) bool) bool {
28332
29211
  i := 0.0
28333
- for v := range ch {
29212
+ for {
29213
+ v, ok := tnGenPull(ch)
29214
+ if !ok {
29215
+ break
29216
+ }
28334
29217
  if fn(v, i) {
28335
29218
  return true
28336
29219
  }
@@ -28341,7 +29224,11 @@ func TnIterSome[T any](ch chan T, fn func(T, float64) bool) bool {
28341
29224
 
28342
29225
  func TnIterEvery[T any](ch chan T, fn func(T, float64) bool) bool {
28343
29226
  i := 0.0
28344
- for v := range ch {
29227
+ for {
29228
+ v, ok := tnGenPull(ch)
29229
+ if !ok {
29230
+ break
29231
+ }
28345
29232
  if !fn(v, i) {
28346
29233
  return false
28347
29234
  }
@@ -28352,7 +29239,11 @@ func TnIterEvery[T any](ch chan T, fn func(T, float64) bool) bool {
28352
29239
 
28353
29240
  func TnIterFind[T any](ch chan T, fn func(T, float64) bool) T {
28354
29241
  i := 0.0
28355
- for v := range ch {
29242
+ for {
29243
+ v, ok := tnGenPull(ch)
29244
+ if !ok {
29245
+ break
29246
+ }
28356
29247
  if fn(v, i) {
28357
29248
  return v
28358
29249
  }
@@ -28364,7 +29255,11 @@ func TnIterFind[T any](ch chan T, fn func(T, float64) bool) T {
28364
29255
 
28365
29256
  func TnIterReduce[T, A any](ch chan T, fn func(A, T, float64) A, acc A, hasInitial bool) A {
28366
29257
  i := 0.0
28367
- for v := range ch {
29258
+ for {
29259
+ v, ok := tnGenPull(ch)
29260
+ if !ok {
29261
+ break
29262
+ }
28368
29263
  if !hasInitial {
28369
29264
  if a, ok := interface{}(v).(A); ok {
28370
29265
  acc = a
@@ -30329,6 +31224,7 @@ func TnProtoMember(obj interface{}, name string) interface{} {
30329
31224
  // function-valued property (an object literal's method, a record's function)
30330
31225
  // then / catch / finally on a promise held as any (set when promises are used)
30331
31226
  var tnDynamicPromiseMethod func(p reflect.Value, name string, args []interface{}) (interface{}, bool)
31227
+ var tnGenWakeFn func(interface{})
30332
31228
 
30333
31229
  func TnCallMember(obj interface{}, name string, args ...interface{}) interface{} {
30334
31230
  // a Map / Set's methods (Get, Set, Has … on the ordered map)
@@ -33912,10 +34808,26 @@ func TnToArray(v interface{}) []interface{} {
33912
34808
  if m := rv.MethodByName("Symbol_iterator"); m.IsValid() && m.Type().NumIn() == 0 && m.Type().NumOut() == 1 {
33913
34809
  return TnToArray(m.Call(nil)[0].Interface())
33914
34810
  }
34811
+ // (a Go iter.Seq[T] — func(func(T) bool): collect its yielded values)
34812
+ if rv.Kind() == reflect.Func && rv.Type().NumIn() == 1 && rv.Type().NumOut() == 0 {
34813
+ yt := rv.Type().In(0)
34814
+ if yt.Kind() == reflect.Func && yt.NumIn() == 1 && yt.NumOut() == 1 && yt.Out(0).Kind() == reflect.Bool {
34815
+ out := []interface{}{}
34816
+ yieldFn := reflect.MakeFunc(yt, func(args []reflect.Value) []reflect.Value {
34817
+ out = append(out, args[0].Interface())
34818
+ return []reflect.Value{reflect.ValueOf(true)}
34819
+ })
34820
+ rv.Call([]reflect.Value{yieldFn})
34821
+ return out
34822
+ }
34823
+ }
33915
34824
  // (a generator: its values until it returns)
33916
34825
  if rv.Kind() == reflect.Chan {
33917
34826
  out := []interface{}{}
33918
34827
  for {
34828
+ if tnGenWakeFn != nil {
34829
+ tnGenWakeFn(v)
34830
+ }
33919
34831
  x, ok := rv.Recv()
33920
34832
  if !ok {
33921
34833
  return out
@@ -38092,7 +39004,12 @@ var tnDOMExceptionCodes = map[string]float64{
38092
39004
  // A Node error: name ('TypeError', 'AssertionError'), code and message
38093
39005
  // A recovered panic as the value a JS catch receives: a Go runtime failure
38094
39006
  // (nil dereference, failed assertion …) is a TypeError
39007
+ type tnGenNilErr struct{}
39008
+
38095
39009
  func TnCaught(r interface{}) interface{} {
39010
+ if _, ok := r.(tnGenNilErr); ok {
39011
+ return nil
39012
+ }
38096
39013
  if e, ok := r.(runtime.Error); ok {
38097
39014
  return tnCaughtError(e.Error(), 2)
38098
39015
  }
@@ -38404,6 +39321,9 @@ func (s *TnSymbol) String() string { return "Symbol(" + s.description + ")" }
38404
39321
  // Symbol.hasInstance (x instanceof C asks C, when C defines it)
38405
39322
  var TnSymbolHasInstance = &TnSymbol{description: "Symbol.hasInstance"}
38406
39323
 
39324
+ // Symbol.metadata (class decorator metadata key)
39325
+ var TnSymbolMetadata = &TnSymbol{description: "Symbol.metadata"}
39326
+
38407
39327
  // Symbol.for(key) / Symbol.keyFor(sym): the global symbol registry
38408
39328
  var tnSymbolRegistry = map[string]*TnSymbol{}
38409
39329
 
@@ -38837,6 +39757,19 @@ func TnStartAsync(body func()) {
38837
39757
  tnAsyncCtx = ctx
38838
39758
  }
38839
39759
 
39760
+ // Yields from an async generator: releases the JS baton if the consumer isn't
39761
+ // waiting yet so the event loop can run while the send blocks
39762
+ func TnAsyncYield[T any](ch chan T, v T) {
39763
+ select {
39764
+ case ch <- v:
39765
+ return
39766
+ default:
39767
+ }
39768
+ tnRelease()
39769
+ ch <- v
39770
+ tnAcquire()
39771
+ }
39772
+
38840
39773
  func tnLoopNotify() {
38841
39774
  select {
38842
39775
  case tnLoopSignal <- struct{}{}:
@@ -39026,7 +39959,22 @@ func TnRunLoop() {
39026
39959
  // promises settled, like Node's microtasks — awaiters racing for the baton
39027
39960
  // would resume out of order on a starved machine.
39028
39961
  var tnWakeMu sync.Mutex
39029
- var tnAwaiting = map[any]chan struct{}{}
39962
+ var tnAwaiting = map[any][]chan struct{}{}
39963
+
39964
+ func tnCancelAwait(ch any, tok chan struct{}) bool {
39965
+ list := tnAwaiting[ch]
39966
+ for i, t := range list {
39967
+ if t == tok {
39968
+ if len(list) == 1 {
39969
+ delete(tnAwaiting, ch)
39970
+ } else {
39971
+ tnAwaiting[ch] = append(list[:i], list[i+1:]...)
39972
+ }
39973
+ return true
39974
+ }
39975
+ }
39976
+ return false
39977
+ }
39030
39978
 
39031
39979
  // (baton holder) hands the baton to a parked awaiter and waits for it to park
39032
39980
  // again (or finish): JS keeps running one thing at a time
@@ -39049,31 +39997,47 @@ func tnWakeQueue(tok chan struct{}) {
39049
39997
  tnLoopNotify()
39050
39998
  }
39051
39999
 
40000
+ // Yields one microtask tick while releasing the JS baton (used when awaiting
40001
+ // an already-settled promise or non-promise value inside an async function)
40002
+ func tnYieldMicrotask() {
40003
+ tok := make(chan struct{})
40004
+ tnWakeQueue(tok)
40005
+ tnRelease()
40006
+ <-tok
40007
+ }
40008
+
39052
40009
  // (baton holder) Receives from a channel, running loop tasks while waiting;
39053
- // once nothing is left it parks. A promise wake resumes in settlement order
39054
- // with the baton handed over; a raw send (a generator yield) resumes the old
39055
- // way, racing for the baton
40010
+ // once nothing is left it parks. An already-settled promise still yields one
40011
+ // microtask tick so the async function never resumes synchronously. A promise
40012
+ // wake resumes in settlement order with the baton handed over; a raw send (a
40013
+ // generator yield) resumes the old way, racing for the baton
39056
40014
  func TnLoopReceive[T any](ch chan T) (T, bool) {
39057
40015
  ctx := tnAsyncCtx
39058
40016
  defer func() { tnAsyncCtx = ctx }()
40017
+ select {
40018
+ case v, ok := <-ch:
40019
+ tnYieldMicrotask()
40020
+ return v, ok
40021
+ default:
40022
+ }
39059
40023
  for {
39060
- select {
39061
- case v, ok := <-ch:
39062
- return v, ok
39063
- default:
39064
- }
39065
- TnRunMicrotasks()
39066
- if TnLoopRunPending() {
39067
- continue
40024
+ if len(tnLendStack) == 0 {
40025
+ TnRunMicrotasks()
40026
+ if TnLoopRunPending() {
40027
+ continue
40028
+ }
39068
40029
  }
39069
40030
  tok := make(chan struct{})
39070
40031
  tnWakeMu.Lock()
39071
40032
  select {
39072
40033
  case v, ok := <-ch:
39073
40034
  tnWakeMu.Unlock()
40035
+ if len(tnLendStack) > 0 {
40036
+ tnYieldMicrotask()
40037
+ }
39074
40038
  return v, ok
39075
40039
  default:
39076
- tnAwaiting[any(ch)] = tok
40040
+ tnAwaiting[any(ch)] = append(tnAwaiting[any(ch)], tok)
39077
40041
  }
39078
40042
  tnWakeMu.Unlock()
39079
40043
  tnRelease()
@@ -39082,10 +40046,7 @@ func TnLoopReceive[T any](ch chan T) (T, bool) {
39082
40046
  // The value is taken; when a promise wake was queued (the token
39083
40047
  // is gone) it hands the baton over, else take the baton ourselves
39084
40048
  tnWakeMu.Lock()
39085
- _, raw := tnAwaiting[any(ch)]
39086
- if raw {
39087
- delete(tnAwaiting, any(ch))
39088
- }
40049
+ raw := tnCancelAwait(any(ch), tok)
39089
40050
  tnWakeMu.Unlock()
39090
40051
  if raw {
39091
40052
  tnAcquire()
@@ -39123,7 +40084,7 @@ func tnRawReceive[T any](ch chan T) (T, bool) {
39123
40084
  tnWakeMu.Unlock()
39124
40085
  return v, ok
39125
40086
  default:
39126
- tnAwaiting[any(ch)] = tok
40087
+ tnAwaiting[any(ch)] = append(tnAwaiting[any(ch)], tok)
39127
40088
  }
39128
40089
  tnWakeMu.Unlock()
39129
40090
  stop := make(chan struct{})
@@ -39135,10 +40096,7 @@ func tnRawReceive[T any](ch chan T) (T, bool) {
39135
40096
  // a promise wake was queued: wait for its hand-over (the stand-in
39136
40097
  // keeps draining until then — it may be what delivers it)
39137
40098
  tnWakeMu.Lock()
39138
- _, raw := tnAwaiting[any(ch)]
39139
- if raw {
39140
- delete(tnAwaiting, any(ch))
39141
- }
40099
+ raw := tnCancelAwait(any(ch), tok)
39142
40100
  tnWakeMu.Unlock()
39143
40101
  if raw {
39144
40102
  close(stop)
@@ -39492,15 +40450,37 @@ func TnWithThis[R any](this interface{}, f func() R) R {
39492
40450
  defer func() { TnThis = prev }()
39493
40451
  return f()
39494
40452
  }`,
39495
- decorators: `// The context a decorator receives (kind is "method" or "class")
40453
+ decorators: `// The access object a member decorator context receives
40454
+ type TnDecoratorAccess struct {
40455
+ has func(interface{}) bool
40456
+ get func(interface{}) interface{}
40457
+ set func(interface{}, interface{})
40458
+ }
40459
+
40460
+ // The context a decorator receives
39496
40461
  type TnDecoratorContext struct {
39497
- kind string
39498
- name string
39499
- static bool
39500
- private bool
40462
+ kind string
40463
+ name string
40464
+ static bool
40465
+ private bool
40466
+ access *TnDecoratorAccess
40467
+ metadata *TnMap[string, interface{}]
40468
+ initializers *[]interface{}
40469
+ }
40470
+
40471
+ func (c *TnDecoratorContext) addInitializer(fn interface{}) {
40472
+ if c.initializers != nil && fn != nil {
40473
+ *c.initializers = append(*c.initializers, fn)
40474
+ }
40475
+ }
40476
+
40477
+ // Target passed to an auto-accessor decorator
40478
+ type TnAccessorTarget struct {
40479
+ get func() interface{}
40480
+ set func(interface{})
39501
40481
  }
39502
40482
 
39503
- // A method decorator's result replaces the method; undefined keeps it
40483
+ // A method, getter, or setter decorator's result replaces the target; undefined keeps it
39504
40484
  func TnDecorate(prev func(...interface{}) interface{}, result interface{}) func(...interface{}) interface{} {
39505
40485
  if result == nil {
39506
40486
  return prev
@@ -39508,7 +40488,36 @@ func TnDecorate(prev func(...interface{}) interface{}, result interface{}) func(
39508
40488
  if f, ok := result.(func(...interface{}) interface{}); ok && f != nil {
39509
40489
  return f
39510
40490
  }
39511
- return prev
40491
+ return func(__args ...interface{}) interface{} {
40492
+ return TnCallValue(result, __args...)
40493
+ }
40494
+ }
40495
+
40496
+ // An auto-accessor decorator's result ({ get, set, init }) updates the getter/setter/initializer list
40497
+ func TnDecorateAccessor(getPtr *func(...interface{}) interface{}, setPtr *func(...interface{}) interface{}, initsPtr *[]interface{}, result interface{}) {
40498
+ if result == nil {
40499
+ return
40500
+ }
40501
+ if g := TnGet(result, "get"); g != nil {
40502
+ prevGet := *getPtr
40503
+ _ = prevGet
40504
+ *getPtr = func(__args ...interface{}) interface{} { return TnCallValue(g) }
40505
+ }
40506
+ if s := TnGet(result, "set"); s != nil {
40507
+ prevSet := *setPtr
40508
+ _ = prevSet
40509
+ *setPtr = func(__args ...interface{}) interface{} {
40510
+ var v interface{}
40511
+ if len(__args) > 0 {
40512
+ v = __args[0]
40513
+ }
40514
+ TnCallValue(s, v)
40515
+ return nil
40516
+ }
40517
+ }
40518
+ if initFn := TnGet(result, "init"); initFn != nil {
40519
+ *initsPtr = append(*initsPtr, initFn)
40520
+ }
39512
40521
  }
39513
40522
 
39514
40523
  // Class decorators may not replace a class (a Go type)
@@ -39516,6 +40525,36 @@ func TnDecorateClass(result interface{}) {
39516
40525
  if result != nil {
39517
40526
  panic("class decorators cannot replace the class")
39518
40527
  }
40528
+ }
40529
+
40530
+ func TnRunInitializers(thisVal interface{}, inits []interface{}) {
40531
+ for _, fn := range inits {
40532
+ if fn != nil {
40533
+ TnWithThis(thisVal, func() interface{} { return TnCallValue(fn) })
40534
+ }
40535
+ }
40536
+ }
40537
+
40538
+ func TnRunFieldInitializers(thisVal interface{}, inits []interface{}, initial interface{}) interface{} {
40539
+ val := initial
40540
+ for _, fn := range inits {
40541
+ if fn != nil {
40542
+ val = TnWithThis(thisVal, func() interface{} { return TnCallValue(fn, val) })
40543
+ }
40544
+ }
40545
+ return val
40546
+ }
40547
+
40548
+ func TnInheritMetadata(parent *TnMap[string, interface{}]) *TnMap[string, interface{}] {
40549
+ m := TnNewMap[string, interface{}]()
40550
+ if parent != nil {
40551
+ for _, k := range parent.Keys() {
40552
+ if v, ok := parent.Lookup(k); ok {
40553
+ m.Set(k, v)
40554
+ }
40555
+ }
40556
+ }
40557
+ return m
39519
40558
  }`,
39520
40559
  stringSearch: `// startsWith/endsWith/includes(search, position): the position clamped, as in JS
39521
40560
  // (a JS position: UTF-16 units, as a byte offset into the Go string)
@@ -39565,123 +40604,149 @@ func tnPromiseMethodDynamic(p reflect.Value, name string, args []interface{}) (i
39565
40604
  out := make(chan interface{}, 1)
39566
40605
  ctx := TnAsyncSnapshot()
39567
40606
  __tnWaitGroup.Add(1)
39568
- go func() {
40607
+ TnStartAsync(func() {
39569
40608
  defer __tnWaitGroup.Done()
39570
- received, ok := p.Recv()
39571
- var v interface{}
39572
- if received.IsValid() {
39573
- v = received.Interface()
39574
- }
39575
- var reason interface{}
40609
+ defer TnAsyncClose(out)
40610
+ defer TnRejectOnPanic(out)
40611
+ var v, reason interface{}
39576
40612
  rejected := false
39577
- if !ok {
39578
- reason, rejected = tnRejections.Load(p.Interface())
40613
+ if ch, isUntyped := p.Interface().(chan interface{}); isUntyped {
40614
+ received, ok := TnLoopReceive(ch)
40615
+ v, reason, rejected = tnSettled(ch, received, ok)
40616
+ } else if received, ok := p.TryRecv(); ok {
40617
+ if received.IsValid() {
40618
+ v = received.Interface()
40619
+ }
40620
+ tnYieldMicrotask()
40621
+ } else if val, resolved := tnResolved.Load(p.Interface()); resolved {
40622
+ v = val
40623
+ tnYieldMicrotask()
40624
+ } else if r, rej := tnRejections.Load(p.Interface()); rej {
40625
+ reason, rejected = r, true
40626
+ tnYieldMicrotask()
40627
+ } else {
40628
+ untyped := make(chan interface{}, 1)
40629
+ go func() {
40630
+ received, ok := p.Recv()
40631
+ if !ok {
40632
+ if val, resolved := tnResolved.Load(p.Interface()); resolved {
40633
+ TnAsyncSend(untyped, val)
40634
+ TnAsyncClose(untyped)
40635
+ return
40636
+ }
40637
+ if r, rej := tnRejections.Load(p.Interface()); rej {
40638
+ TnReject(untyped, r)
40639
+ return
40640
+ }
40641
+ TnAsyncClose(untyped)
40642
+ return
40643
+ }
40644
+ var val interface{}
40645
+ if received.IsValid() {
40646
+ val = received.Interface()
40647
+ }
40648
+ TnAsyncSend(untyped, val)
40649
+ TnAsyncClose(untyped)
40650
+ }()
40651
+ received, ok := TnLoopReceive(untyped)
40652
+ v, reason, rejected = tnSettled(untyped, received, ok)
39579
40653
  }
39580
40654
  if name == "finally" {
39581
40655
  if onFulfilled != nil {
39582
- TnLoopCall(func() { TnAsyncRun(ctx, func() { TnCallValue(onFulfilled) }) })
40656
+ TnAsyncRun(ctx, func() { TnCallValue(onFulfilled) })
39583
40657
  }
39584
40658
  } else if handler := map[bool]interface{}{false: onFulfilled, true: onRejected}[rejected]; handler != nil {
39585
40659
  input := v
39586
40660
  if rejected {
39587
40661
  input = reason
39588
40662
  }
39589
- var result, thrown interface{}
39590
- threw := false
39591
- TnLoopCall(func() {
39592
- TnAsyncRun(ctx, func() {
39593
- defer func() {
39594
- if r := recover(); r != nil {
39595
- thrown, threw = r, true
39596
- }
39597
- }()
39598
- result = TnCallValue(handler, input)
39599
- })
40663
+ var result interface{}
40664
+ TnAsyncRun(ctx, func() {
40665
+ result = TnCallValue(handler, input)
39600
40666
  })
39601
- if threw {
39602
- TnReject(out, thrown)
39603
- return
39604
- }
39605
40667
  // (a handler returning a promise: settled with it)
39606
40668
  if rv := reflect.ValueOf(result); rv.Kind() == reflect.Chan {
39607
- inner, innerOk := rv.Recv()
39608
- if !innerOk {
39609
- if r, innerRejected := tnRejections.Load(rv.Interface()); innerRejected {
39610
- TnReject(out, r)
39611
- return
39612
- }
39613
- }
39614
- result = nil
39615
- if inner.IsValid() {
39616
- result = inner.Interface()
39617
- }
40669
+ result = TnAwaitValue(result, false)
39618
40670
  }
39619
40671
  v, rejected = result, false
39620
40672
  }
39621
40673
  if rejected {
39622
- TnReject(out, reason)
40674
+ tnRejections.Store(out, reason)
39623
40675
  return
39624
40676
  }
39625
40677
  TnAsyncSend(out, v)
39626
- TnAsyncClose(out)
39627
- }()
40678
+ })
39628
40679
  return out, true
39629
40680
  }`,
39630
40681
  functionValue: `// The global Function used as a value: an opaque sentinel
39631
40682
  type tnFunctionConstructor struct{}
39632
40683
 
39633
40684
  var TnFunction interface{} = &tnFunctionConstructor{}`,
39634
- promise: `// Promises are channels; a rejected promise is a closed channel with a reason
40685
+ promise: `// Promises are channels; a settled promise is a closed channel with its value or reason
40686
+ var tnResolved sync.Map
39635
40687
  var tnRejections sync.Map
39636
40688
 
39637
40689
  // A throw inside a Promise executor rejects the promise
39638
40690
  func TnRejectExecutor[T any](ch chan T) {
39639
40691
  if r := recover(); r != nil {
39640
- if _, rejected := tnRejections.Load(ch); !rejected && len(ch) == 0 {
39641
- TnReject(ch, r)
39642
- }
40692
+ TnReject(ch, r)
39643
40693
  }
39644
40694
  }
39645
40695
 
39646
- // Promise resolution: the value (or rejection) is sent and the parked awaiter
40696
+ // Promise resolution: the value (or rejection) is stored and the channel closed
40697
+ // so any number of consumers (.then / await) can read it; parked awaiters are
39647
40698
  // woken in settlement order — Node runs promise continuations as ordered
39648
40699
  // microtasks; a bare channel wake would race for the baton and resume out of
39649
40700
  // order on a starved machine
39650
40701
  func TnAsyncSend[T any](ch chan T, v T) {
39651
- var tok chan struct{}
39652
- handoff := false
39653
40702
  tnWakeMu.Lock()
39654
40703
  select {
39655
- case ch <- v:
40704
+ case _, ok := <-ch:
40705
+ if !ok {
40706
+ tnWakeMu.Unlock()
40707
+ return
40708
+ }
39656
40709
  default:
39657
40710
  }
39658
- if t, parked := tnAwaiting[any(ch)]; parked {
40711
+ tnResolved.Store(any(ch), v)
40712
+ close(ch)
40713
+ toks := tnAwaiting[any(ch)]
40714
+ if len(toks) > 0 {
39659
40715
  delete(tnAwaiting, any(ch))
39660
- tok = t
39661
- handoff = true
39662
40716
  }
39663
40717
  tnWakeMu.Unlock()
39664
- if handoff {
40718
+ for _, tok := range toks {
39665
40719
  tnWakeQueue(tok)
39666
40720
  }
39667
40721
  }
39668
40722
 
39669
40723
  func TnAsyncClose[T any](ch chan T) {
39670
- var tok chan struct{}
39671
- handoff := false
39672
40724
  tnWakeMu.Lock()
40725
+ select {
40726
+ case _, ok := <-ch:
40727
+ if !ok {
40728
+ tnWakeMu.Unlock()
40729
+ return
40730
+ }
40731
+ default:
40732
+ }
39673
40733
  close(ch)
39674
- if t, parked := tnAwaiting[any(ch)]; parked {
40734
+ toks := tnAwaiting[any(ch)]
40735
+ if len(toks) > 0 {
39675
40736
  delete(tnAwaiting, any(ch))
39676
- tok = t
39677
- handoff = true
39678
40737
  }
39679
40738
  tnWakeMu.Unlock()
39680
- if handoff {
40739
+ for _, tok := range toks {
39681
40740
  tnWakeQueue(tok)
39682
40741
  }
39683
40742
  }
39684
40743
 
40744
+ func TnPromiseResolve[T any](v T) chan T {
40745
+ ch := make(chan T, 1)
40746
+ TnAsyncSend(ch, v)
40747
+ return ch
40748
+ }
40749
+
39685
40750
  func TnResolveZero[T any](ch chan T) {
39686
40751
  var zero T
39687
40752
  TnAsyncSend(ch, zero)
@@ -39706,16 +40771,30 @@ func TnRejecter[T any](ch chan T) func(...interface{}) {
39706
40771
  if len(args) > 0 {
39707
40772
  reason = args[0]
39708
40773
  }
39709
- if _, rejected := tnRejections.Load(ch); rejected || len(ch) > 0 {
39710
- return
39711
- }
39712
40774
  TnReject(ch, reason)
39713
40775
  }
39714
40776
  }
39715
40777
 
39716
40778
  func TnReject[T any](ch chan T, reason interface{}) {
40779
+ tnWakeMu.Lock()
40780
+ select {
40781
+ case _, ok := <-ch:
40782
+ if !ok {
40783
+ tnWakeMu.Unlock()
40784
+ return
40785
+ }
40786
+ default:
40787
+ }
39717
40788
  tnRejections.Store(ch, reason)
39718
- TnAsyncClose(ch)
40789
+ close(ch)
40790
+ toks := tnAwaiting[any(ch)]
40791
+ if len(toks) > 0 {
40792
+ delete(tnAwaiting, any(ch))
40793
+ }
40794
+ tnWakeMu.Unlock()
40795
+ for _, tok := range toks {
40796
+ tnWakeQueue(tok)
40797
+ }
39719
40798
  }
39720
40799
 
39721
40800
  // A detached call (\`main();\`): the process waits for it; a rejection is fatal
@@ -39752,6 +40831,12 @@ func TnRejectOnPanic[T any](ch chan T) {
39752
40831
 
39753
40832
  func tnSettled[T any](ch chan T, v T, ok bool) (T, interface{}, bool) {
39754
40833
  if !ok {
40834
+ if val, resolved := tnResolved.Load(any(ch)); resolved {
40835
+ if typed, ok := val.(T); ok {
40836
+ return typed, nil, false
40837
+ }
40838
+ return v, nil, false
40839
+ }
39755
40840
  if reason, rejected := tnRejections.Load(ch); rejected {
39756
40841
  return v, reason, true
39757
40842
  }
@@ -39790,22 +40875,28 @@ func TnAwaitValue(v interface{}, inline bool) interface{} {
39790
40875
  go func() {
39791
40876
  received, ok := rv.Recv()
39792
40877
  if !ok {
40878
+ if val, resolved := tnResolved.Load(rv.Interface()); resolved {
40879
+ TnAsyncSend(untyped, val)
40880
+ return
40881
+ }
39793
40882
  // (a rejected promise: a closed channel with its reason recorded)
39794
40883
  if r, rejected := tnRejections.Load(rv.Interface()); rejected {
39795
40884
  TnReject(untyped, r)
39796
40885
  return
39797
40886
  }
39798
- close(untyped)
40887
+ TnAsyncClose(untyped)
39799
40888
  return
39800
40889
  }
39801
- untyped <- received.Interface()
39802
- close(untyped)
40890
+ TnAsyncSend(untyped, received.Interface())
39803
40891
  }()
39804
40892
  if inline {
39805
40893
  return TnAwaitInline(untyped)
39806
40894
  }
39807
40895
  return TnAwait(untyped)
39808
40896
  }
40897
+ if !inline {
40898
+ tnYieldMicrotask()
40899
+ }
39809
40900
  return v
39810
40901
  }
39811
40902
 
@@ -39830,15 +40921,19 @@ func TnPromiseReject[T any](reason interface{}) chan T {
39830
40921
  func TnPromiseCatch[T any, E any](p chan T, onRejected func(E)) chan T {
39831
40922
  out := make(chan T, 1)
39832
40923
  ctx := TnAsyncSnapshot()
39833
- go func() {
39834
- v, reason, rejected := tnSettle(p)
40924
+ __tnWaitGroup.Add(1)
40925
+ TnStartAsync(func() {
40926
+ defer __tnWaitGroup.Done()
40927
+ defer TnAsyncClose(out)
40928
+ defer TnRejectOnPanic(out)
40929
+ received, ok := TnLoopReceive(p)
40930
+ v, reason, rejected := tnSettled(p, received, ok)
39835
40931
  if rejected {
39836
40932
  e, _ := reason.(E)
39837
- TnLoopCall(func() { TnAsyncRun(ctx, func() { onRejected(e) }) })
40933
+ TnAsyncRun(ctx, func() { onRejected(e) })
39838
40934
  }
39839
40935
  TnAsyncSend(out, v)
39840
- TnAsyncClose(out)
39841
- }()
40936
+ })
39842
40937
  return out
39843
40938
  }
39844
40939
 
@@ -39861,31 +40956,39 @@ func TnPromiseAs[T any](p chan interface{}, convert func(interface{}) T) chan T
39861
40956
  func TnPromiseCatchValue[T any, E any](p chan T, onRejected func(E) T) chan T {
39862
40957
  out := make(chan T, 1)
39863
40958
  ctx := TnAsyncSnapshot()
39864
- go func() {
39865
- v, reason, rejected := tnSettle(p)
40959
+ __tnWaitGroup.Add(1)
40960
+ TnStartAsync(func() {
40961
+ defer __tnWaitGroup.Done()
40962
+ defer TnAsyncClose(out)
40963
+ defer TnRejectOnPanic(out)
40964
+ received, ok := TnLoopReceive(p)
40965
+ v, reason, rejected := tnSettled(p, received, ok)
39866
40966
  if rejected {
39867
40967
  e, _ := reason.(E)
39868
- TnLoopCall(func() { TnAsyncRun(ctx, func() { v = onRejected(e) }) })
40968
+ TnAsyncRun(ctx, func() { v = onRejected(e) })
39869
40969
  }
39870
40970
  TnAsyncSend(out, v)
39871
- TnAsyncClose(out)
39872
- }()
40971
+ })
39873
40972
  return out
39874
40973
  }
39875
40974
 
39876
40975
  func TnPromiseFinally[T any](p chan T, onFinally func()) chan T {
39877
40976
  out := make(chan T, 1)
39878
40977
  onFinally = TnAsyncWrap(onFinally)
39879
- go func() {
39880
- v, reason, rejected := tnSettle(p)
39881
- TnLoopCall(onFinally)
40978
+ __tnWaitGroup.Add(1)
40979
+ TnStartAsync(func() {
40980
+ defer __tnWaitGroup.Done()
40981
+ defer TnAsyncClose(out)
40982
+ defer TnRejectOnPanic(out)
40983
+ received, ok := TnLoopReceive(p)
40984
+ v, reason, rejected := tnSettled(p, received, ok)
40985
+ onFinally()
39882
40986
  if rejected {
39883
- TnReject(out, reason)
40987
+ tnRejections.Store(out, reason)
39884
40988
  return
39885
40989
  }
39886
40990
  TnAsyncSend(out, v)
39887
- TnAsyncClose(out)
39888
- }()
40991
+ })
39889
40992
  return out
39890
40993
  }
39891
40994
 
@@ -39978,12 +41081,14 @@ func TnPromiseAllValues(values []interface{}) chan []interface{} {
39978
41081
  } else if rv := reflect.ValueOf(v); rv.IsValid() && rv.Kind() == reflect.Chan {
39979
41082
  r, ok := rv.Recv()
39980
41083
  if !ok {
39981
- // (a rejected promise: a closed channel with its reason recorded)
39982
- if reason, rejected := tnRejections.Load(rv.Interface()); rejected {
41084
+ if val, resolved := tnResolved.Load(rv.Interface()); resolved {
41085
+ results[i] = val
41086
+ } else if reason, rejected := tnRejections.Load(rv.Interface()); rejected {
39983
41087
  TnReject(out, reason)
39984
41088
  return
41089
+ } else {
41090
+ results[i] = nil
39985
41091
  }
39986
- results[i] = nil
39987
41092
  } else {
39988
41093
  results[i] = r.Interface()
39989
41094
  }
@@ -40024,8 +41129,7 @@ func TnFromAsyncChan[T any](ch chan T) chan []T {
40024
41129
  // Array.fromAsync over plain values: resolved with a copy of them
40025
41130
  func TnFromAsyncValues[T any](values []T) chan []T {
40026
41131
  out := make(chan []T, 1)
40027
- out <- append([]T{}, values...)
40028
- close(out)
41132
+ TnAsyncSend(out, append([]T{}, values...))
40029
41133
  return out
40030
41134
  }
40031
41135
 
@@ -41117,6 +42221,8 @@ function visitForOfSequence(node, iterExpr, iterType) {
41117
42221
  }
41118
42222
  if (declaration && isIdentifier(declaration.name)) {
41119
42223
  const loopVar = bindIterVar(declaration.name, goIterElem(iterType));
42224
+ if (loopVar !== '_' && !prefix)
42225
+ prefix = `_ = ${loopVar}\n\t\t`;
41120
42226
  return `for ${loopVar} := range ${iterExpr}${visitLoopBody(node.statement, prefix)}`;
41121
42227
  }
41122
42228
  return `for _ = range ${iterExpr}${visitLoopBody(node.statement)}`;
@@ -41126,19 +42232,25 @@ function visitForOfSequence(node, iterExpr, iterType) {
41126
42232
  const iterClass = iterType.slice(1).replace(/\[.*\]$/, '');
41127
42233
  const yieldType = classIteratorYieldType(iterClass);
41128
42234
  if (yieldType) {
41129
- const declaration = isVariableDeclarationList(node.initializer)
41130
- ? node.initializer.declarations[0]
41131
- : undefined;
41132
- if (declaration && isIdentifier(declaration.name)) {
41133
- registerLocalVariable(declaration.name.text, yieldType);
41134
- const iteratorMember = findClassGenerator(iterClass, 'Symbol_iterator');
41135
- if (iteratorMember && generatorSeqEligible(iteratorMember)) {
41136
- const loopVar = visit(declaration.name);
41137
- return `for ${loopVar} := range ${iterExpr}.Symbol_iterator__seq()${visitLoopBody(node.statement, `_ = ${loopVar}\n\t\t`)}`;
42235
+ if (node.awaitModifier) {
42236
+ iterExpr = `${iterExpr}.Symbol_iterator()`;
42237
+ iterType = `chan ${yieldType}`;
42238
+ }
42239
+ else {
42240
+ const declaration = isVariableDeclarationList(node.initializer)
42241
+ ? node.initializer.declarations[0]
42242
+ : undefined;
42243
+ if (declaration && isIdentifier(declaration.name)) {
42244
+ registerLocalVariable(declaration.name.text, yieldType);
42245
+ const iteratorMember = findClassGenerator(iterClass, 'Symbol_iterator');
42246
+ if (iteratorMember && generatorSeqEligible(iteratorMember)) {
42247
+ const loopVar = visit(declaration.name);
42248
+ return `for ${loopVar} := range ${iterExpr}.Symbol_iterator__seq()${visitLoopBody(node.statement, `_ = ${loopVar}\n\t\t`)}`;
42249
+ }
42250
+ return lockstepRange(visit(declaration.name), `${iterExpr}.Symbol_iterator()`, node.statement);
41138
42251
  }
41139
- return lockstepRange(visit(declaration.name), `${iterExpr}.Symbol_iterator()`, node.statement);
42252
+ return `for _ = range ${iterExpr}.Symbol_iterator()${visitLoopBody(node.statement)}`;
41140
42253
  }
41141
- return `for _ = range ${iterExpr}.Symbol_iterator()${visitLoopBody(node.statement)}`;
41142
42254
  }
41143
42255
  }
41144
42256
  if (iterType?.startsWith('chan ')) {