funkscript 0.0.0-stage → 0.2.4

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 (631) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +204 -2
  3. package/dist/Widget.tsx +9 -0
  4. package/dist/ast/types.d.ts +513 -0
  5. package/dist/ast/types.d.ts.map +1 -0
  6. package/dist/ast/types.js +5 -0
  7. package/dist/ast/types.js.map +1 -0
  8. package/dist/ast/walk.d.ts +8 -0
  9. package/dist/ast/walk.d.ts.map +1 -0
  10. package/dist/ast/walk.js +23 -0
  11. package/dist/ast/walk.js.map +1 -0
  12. package/dist/cli/build-bun.d.ts +24 -0
  13. package/dist/cli/build-bun.d.ts.map +1 -0
  14. package/dist/cli/build-bun.js +190 -0
  15. package/dist/cli/build-bun.js.map +1 -0
  16. package/dist/cli/build-watch.d.ts +21 -0
  17. package/dist/cli/build-watch.d.ts.map +1 -0
  18. package/dist/cli/build-watch.js +244 -0
  19. package/dist/cli/build-watch.js.map +1 -0
  20. package/dist/cli/build.d.ts +4 -0
  21. package/dist/cli/build.d.ts.map +1 -0
  22. package/dist/cli/build.js +338 -0
  23. package/dist/cli/build.js.map +1 -0
  24. package/dist/cli/check.d.ts +4 -0
  25. package/dist/cli/check.d.ts.map +1 -0
  26. package/dist/cli/check.js +278 -0
  27. package/dist/cli/check.js.map +1 -0
  28. package/dist/cli/commands.d.ts +13 -0
  29. package/dist/cli/commands.d.ts.map +1 -0
  30. package/dist/cli/commands.js +262 -0
  31. package/dist/cli/commands.js.map +1 -0
  32. package/dist/cli/doc.d.ts +3 -0
  33. package/dist/cli/doc.d.ts.map +1 -0
  34. package/dist/cli/doc.js +71 -0
  35. package/dist/cli/doc.js.map +1 -0
  36. package/dist/cli/doctor.d.ts +3 -0
  37. package/dist/cli/doctor.d.ts.map +1 -0
  38. package/dist/cli/doctor.js +121 -0
  39. package/dist/cli/doctor.js.map +1 -0
  40. package/dist/cli/emit.d.ts +4 -0
  41. package/dist/cli/emit.d.ts.map +1 -0
  42. package/dist/cli/emit.js +87 -0
  43. package/dist/cli/emit.js.map +1 -0
  44. package/dist/cli/explain.d.ts +3 -0
  45. package/dist/cli/explain.d.ts.map +1 -0
  46. package/dist/cli/explain.js +103 -0
  47. package/dist/cli/explain.js.map +1 -0
  48. package/dist/cli/fmt.d.ts +3 -0
  49. package/dist/cli/fmt.d.ts.map +1 -0
  50. package/dist/cli/fmt.js +146 -0
  51. package/dist/cli/fmt.js.map +1 -0
  52. package/dist/cli/index.d.ts +3 -0
  53. package/dist/cli/index.d.ts.map +1 -0
  54. package/dist/cli/index.js +186 -0
  55. package/dist/cli/index.js.map +1 -0
  56. package/dist/cli/init.d.ts +10 -0
  57. package/dist/cli/init.d.ts.map +1 -0
  58. package/dist/cli/init.js +412 -0
  59. package/dist/cli/init.js.map +1 -0
  60. package/dist/cli/io.d.ts +9 -0
  61. package/dist/cli/io.d.ts.map +1 -0
  62. package/dist/cli/io.js +113 -0
  63. package/dist/cli/io.js.map +1 -0
  64. package/dist/cli/output-collisions.d.ts +2 -0
  65. package/dist/cli/output-collisions.d.ts.map +1 -0
  66. package/dist/cli/output-collisions.js +39 -0
  67. package/dist/cli/output-collisions.js.map +1 -0
  68. package/dist/cli/pipeline-style.d.ts +3 -0
  69. package/dist/cli/pipeline-style.d.ts.map +1 -0
  70. package/dist/cli/pipeline-style.js +45 -0
  71. package/dist/cli/pipeline-style.js.map +1 -0
  72. package/dist/cli/repl.d.ts +37 -0
  73. package/dist/cli/repl.d.ts.map +1 -0
  74. package/dist/cli/repl.js +334 -0
  75. package/dist/cli/repl.js.map +1 -0
  76. package/dist/cli/run.d.ts +4 -0
  77. package/dist/cli/run.d.ts.map +1 -0
  78. package/dist/cli/run.js +185 -0
  79. package/dist/cli/run.js.map +1 -0
  80. package/dist/cli/test.d.ts +3 -0
  81. package/dist/cli/test.d.ts.map +1 -0
  82. package/dist/cli/test.js +124 -0
  83. package/dist/cli/test.js.map +1 -0
  84. package/dist/cli/tsc.d.ts +3 -0
  85. package/dist/cli/tsc.d.ts.map +1 -0
  86. package/dist/cli/tsc.js +143 -0
  87. package/dist/cli/tsc.js.map +1 -0
  88. package/dist/cli/typecheck.d.ts +23 -0
  89. package/dist/cli/typecheck.d.ts.map +1 -0
  90. package/dist/cli/typecheck.js +65 -0
  91. package/dist/cli/typecheck.js.map +1 -0
  92. package/dist/compiler/ast-inspection.d.ts +18 -0
  93. package/dist/compiler/ast-inspection.d.ts.map +1 -0
  94. package/dist/compiler/ast-inspection.js +96 -0
  95. package/dist/compiler/ast-inspection.js.map +1 -0
  96. package/dist/compiler/boolean-operators.d.ts +8 -0
  97. package/dist/compiler/boolean-operators.d.ts.map +1 -0
  98. package/dist/compiler/boolean-operators.js +84 -0
  99. package/dist/compiler/boolean-operators.js.map +1 -0
  100. package/dist/compiler/check.d.ts +87 -0
  101. package/dist/compiler/check.d.ts.map +1 -0
  102. package/dist/compiler/check.js +1830 -0
  103. package/dist/compiler/check.js.map +1 -0
  104. package/dist/compiler/diagnostics.d.ts +6 -0
  105. package/dist/compiler/diagnostics.d.ts.map +1 -0
  106. package/dist/compiler/diagnostics.js +136 -0
  107. package/dist/compiler/diagnostics.js.map +1 -0
  108. package/dist/compiler/effect-mutation-rule.d.ts +4 -0
  109. package/dist/compiler/effect-mutation-rule.d.ts.map +1 -0
  110. package/dist/compiler/effect-mutation-rule.js +348 -0
  111. package/dist/compiler/effect-mutation-rule.js.map +1 -0
  112. package/dist/compiler/entry-rules.d.ts +5 -0
  113. package/dist/compiler/entry-rules.d.ts.map +1 -0
  114. package/dist/compiler/entry-rules.js +89 -0
  115. package/dist/compiler/entry-rules.js.map +1 -0
  116. package/dist/compiler/imported-record-functions.d.ts +4 -0
  117. package/dist/compiler/imported-record-functions.d.ts.map +1 -0
  118. package/dist/compiler/imported-record-functions.js +706 -0
  119. package/dist/compiler/imported-record-functions.js.map +1 -0
  120. package/dist/compiler/imported-schemas.d.ts +21 -0
  121. package/dist/compiler/imported-schemas.d.ts.map +1 -0
  122. package/dist/compiler/imported-schemas.js +461 -0
  123. package/dist/compiler/imported-schemas.js.map +1 -0
  124. package/dist/compiler/incremental-build.d.ts +23 -0
  125. package/dist/compiler/incremental-build.d.ts.map +1 -0
  126. package/dist/compiler/incremental-build.js +90 -0
  127. package/dist/compiler/incremental-build.js.map +1 -0
  128. package/dist/compiler/incremental-dependencies.d.ts +7 -0
  129. package/dist/compiler/incremental-dependencies.d.ts.map +1 -0
  130. package/dist/compiler/incremental-dependencies.js +190 -0
  131. package/dist/compiler/incremental-dependencies.js.map +1 -0
  132. package/dist/compiler/js-interop-nullability.d.ts +9 -0
  133. package/dist/compiler/js-interop-nullability.d.ts.map +1 -0
  134. package/dist/compiler/js-interop-nullability.js +57 -0
  135. package/dist/compiler/js-interop-nullability.js.map +1 -0
  136. package/dist/compiler/module-resolution.d.ts +6 -0
  137. package/dist/compiler/module-resolution.d.ts.map +1 -0
  138. package/dist/compiler/module-resolution.js +44 -0
  139. package/dist/compiler/module-resolution.js.map +1 -0
  140. package/dist/compiler/modules/output-collisions.d.ts +2 -0
  141. package/dist/compiler/modules/output-collisions.d.ts.map +1 -0
  142. package/dist/compiler/modules/output-collisions.js +39 -0
  143. package/dist/compiler/modules/output-collisions.js.map +1 -0
  144. package/dist/compiler/modules/output-plan.d.ts +7 -0
  145. package/dist/compiler/modules/output-plan.d.ts.map +1 -0
  146. package/dist/compiler/modules/output-plan.js +37 -0
  147. package/dist/compiler/modules/output-plan.js.map +1 -0
  148. package/dist/compiler/modules/resolution.d.ts +8 -0
  149. package/dist/compiler/modules/resolution.d.ts.map +1 -0
  150. package/dist/compiler/modules/resolution.js +48 -0
  151. package/dist/compiler/modules/resolution.js.map +1 -0
  152. package/dist/compiler/numeric-comparisons.d.ts +9 -0
  153. package/dist/compiler/numeric-comparisons.d.ts.map +1 -0
  154. package/dist/compiler/numeric-comparisons.js +153 -0
  155. package/dist/compiler/numeric-comparisons.js.map +1 -0
  156. package/dist/compiler/optional-arguments.d.ts +11 -0
  157. package/dist/compiler/optional-arguments.d.ts.map +1 -0
  158. package/dist/compiler/optional-arguments.js +246 -0
  159. package/dist/compiler/optional-arguments.js.map +1 -0
  160. package/dist/compiler/package-fingerprint.d.ts +7 -0
  161. package/dist/compiler/package-fingerprint.d.ts.map +1 -0
  162. package/dist/compiler/package-fingerprint.js +178 -0
  163. package/dist/compiler/package-fingerprint.js.map +1 -0
  164. package/dist/compiler/package-record-contracts.d.ts +5 -0
  165. package/dist/compiler/package-record-contracts.d.ts.map +1 -0
  166. package/dist/compiler/package-record-contracts.js +126 -0
  167. package/dist/compiler/package-record-contracts.js.map +1 -0
  168. package/dist/compiler/pipeline-companions.d.ts +18 -0
  169. package/dist/compiler/pipeline-companions.d.ts.map +1 -0
  170. package/dist/compiler/pipeline-companions.js +1042 -0
  171. package/dist/compiler/pipeline-companions.js.map +1 -0
  172. package/dist/compiler/pipelines/catalog.d.ts +15 -0
  173. package/dist/compiler/pipelines/catalog.d.ts.map +1 -0
  174. package/dist/compiler/pipelines/catalog.js +55 -0
  175. package/dist/compiler/pipelines/catalog.js.map +1 -0
  176. package/dist/compiler/pipelines/companions.d.ts +18 -0
  177. package/dist/compiler/pipelines/companions.d.ts.map +1 -0
  178. package/dist/compiler/pipelines/companions.js +1042 -0
  179. package/dist/compiler/pipelines/companions.js.map +1 -0
  180. package/dist/compiler/pipelines/resolution.d.ts +38 -0
  181. package/dist/compiler/pipelines/resolution.d.ts.map +1 -0
  182. package/dist/compiler/pipelines/resolution.js +571 -0
  183. package/dist/compiler/pipelines/resolution.js.map +1 -0
  184. package/dist/compiler/project-config.d.ts +28 -0
  185. package/dist/compiler/project-config.d.ts.map +1 -0
  186. package/dist/compiler/project-config.js +155 -0
  187. package/dist/compiler/project-config.js.map +1 -0
  188. package/dist/compiler/providers.d.ts +4 -0
  189. package/dist/compiler/providers.d.ts.map +1 -0
  190. package/dist/compiler/providers.js +101 -0
  191. package/dist/compiler/providers.js.map +1 -0
  192. package/dist/compiler/record-contracts.d.ts +6 -0
  193. package/dist/compiler/record-contracts.d.ts.map +1 -0
  194. package/dist/compiler/record-contracts.js +41 -0
  195. package/dist/compiler/record-contracts.js.map +1 -0
  196. package/dist/compiler/rules/control-flow.d.ts +10 -0
  197. package/dist/compiler/rules/control-flow.d.ts.map +1 -0
  198. package/dist/compiler/rules/control-flow.js +19 -0
  199. package/dist/compiler/rules/control-flow.js.map +1 -0
  200. package/dist/compiler/rules/diagnostic.d.ts +4 -0
  201. package/dist/compiler/rules/diagnostic.d.ts.map +1 -0
  202. package/dist/compiler/rules/diagnostic.js +2 -0
  203. package/dist/compiler/rules/diagnostic.js.map +1 -0
  204. package/dist/compiler/rules/module-scope-refs.d.ts +5 -0
  205. package/dist/compiler/rules/module-scope-refs.d.ts.map +1 -0
  206. package/dist/compiler/rules/module-scope-refs.js +47 -0
  207. package/dist/compiler/rules/module-scope-refs.js.map +1 -0
  208. package/dist/compiler/schemas/analysis.d.ts +13 -0
  209. package/dist/compiler/schemas/analysis.d.ts.map +1 -0
  210. package/dist/compiler/schemas/analysis.js +24 -0
  211. package/dist/compiler/schemas/analysis.js.map +1 -0
  212. package/dist/compiler/schemas/imported-record-functions.d.ts +4 -0
  213. package/dist/compiler/schemas/imported-record-functions.d.ts.map +1 -0
  214. package/dist/compiler/schemas/imported-record-functions.js +706 -0
  215. package/dist/compiler/schemas/imported-record-functions.js.map +1 -0
  216. package/dist/compiler/schemas/imported-schemas.d.ts +21 -0
  217. package/dist/compiler/schemas/imported-schemas.d.ts.map +1 -0
  218. package/dist/compiler/schemas/imported-schemas.js +461 -0
  219. package/dist/compiler/schemas/imported-schemas.js.map +1 -0
  220. package/dist/compiler/source-map.d.ts +6 -0
  221. package/dist/compiler/source-map.d.ts.map +1 -0
  222. package/dist/compiler/source-map.js +127 -0
  223. package/dist/compiler/source-map.js.map +1 -0
  224. package/dist/compiler/typescript-context.d.ts +33 -0
  225. package/dist/compiler/typescript-context.d.ts.map +1 -0
  226. package/dist/compiler/typescript-context.js +200 -0
  227. package/dist/compiler/typescript-context.js.map +1 -0
  228. package/dist/compiler.d.ts +77 -0
  229. package/dist/compiler.d.ts.map +1 -0
  230. package/dist/compiler.js +497 -0
  231. package/dist/compiler.js.map +1 -0
  232. package/dist/emitter/assemblyscript.d.ts +5 -0
  233. package/dist/emitter/assemblyscript.d.ts.map +1 -0
  234. package/dist/emitter/assemblyscript.js +979 -0
  235. package/dist/emitter/assemblyscript.js.map +1 -0
  236. package/dist/emitter/declarations.d.ts +46 -0
  237. package/dist/emitter/declarations.d.ts.map +1 -0
  238. package/dist/emitter/declarations.js +739 -0
  239. package/dist/emitter/declarations.js.map +1 -0
  240. package/dist/emitter/emitter.d.ts +165 -0
  241. package/dist/emitter/emitter.d.ts.map +1 -0
  242. package/dist/emitter/emitter.js +2448 -0
  243. package/dist/emitter/emitter.js.map +1 -0
  244. package/dist/emitter/imports.d.ts +6 -0
  245. package/dist/emitter/imports.d.ts.map +1 -0
  246. package/dist/emitter/imports.js +73 -0
  247. package/dist/emitter/imports.js.map +1 -0
  248. package/dist/emitter/indent.d.ts +3 -0
  249. package/dist/emitter/indent.d.ts.map +1 -0
  250. package/dist/emitter/indent.js +31 -0
  251. package/dist/emitter/indent.js.map +1 -0
  252. package/dist/emitter/jsx.d.ts +20 -0
  253. package/dist/emitter/jsx.d.ts.map +1 -0
  254. package/dist/emitter/jsx.js +82 -0
  255. package/dist/emitter/jsx.js.map +1 -0
  256. package/dist/emitter/local-bindings.d.ts +6 -0
  257. package/dist/emitter/local-bindings.d.ts.map +1 -0
  258. package/dist/emitter/local-bindings.js +32 -0
  259. package/dist/emitter/local-bindings.js.map +1 -0
  260. package/dist/emitter/match.d.ts +56 -0
  261. package/dist/emitter/match.d.ts.map +1 -0
  262. package/dist/emitter/match.js +1287 -0
  263. package/dist/emitter/match.js.map +1 -0
  264. package/dist/emitter/pipeline-catalog.d.ts +15 -0
  265. package/dist/emitter/pipeline-catalog.d.ts.map +1 -0
  266. package/dist/emitter/pipeline-catalog.js +55 -0
  267. package/dist/emitter/pipeline-catalog.js.map +1 -0
  268. package/dist/emitter/pipeline-resolution.d.ts +38 -0
  269. package/dist/emitter/pipeline-resolution.d.ts.map +1 -0
  270. package/dist/emitter/pipeline-resolution.js +571 -0
  271. package/dist/emitter/pipeline-resolution.js.map +1 -0
  272. package/dist/emitter/runtime-helpers.d.ts +10 -0
  273. package/dist/emitter/runtime-helpers.d.ts.map +1 -0
  274. package/dist/emitter/runtime-helpers.js +22 -0
  275. package/dist/emitter/runtime-helpers.js.map +1 -0
  276. package/dist/emitter/schemas.d.ts +36 -0
  277. package/dist/emitter/schemas.d.ts.map +1 -0
  278. package/dist/emitter/schemas.js +766 -0
  279. package/dist/emitter/schemas.js.map +1 -0
  280. package/dist/emitter/statements.d.ts +23 -0
  281. package/dist/emitter/statements.d.ts.map +1 -0
  282. package/dist/emitter/statements.js +216 -0
  283. package/dist/emitter/statements.js.map +1 -0
  284. package/dist/emitter/tagged-match.d.ts +23 -0
  285. package/dist/emitter/tagged-match.d.ts.map +1 -0
  286. package/dist/emitter/tagged-match.js +109 -0
  287. package/dist/emitter/tagged-match.js.map +1 -0
  288. package/dist/emitter/types.d.ts +22 -0
  289. package/dist/emitter/types.d.ts.map +1 -0
  290. package/dist/emitter/types.js +231 -0
  291. package/dist/emitter/types.js.map +1 -0
  292. package/dist/errors.d.ts +39 -0
  293. package/dist/errors.d.ts.map +1 -0
  294. package/dist/errors.js +98 -0
  295. package/dist/errors.js.map +1 -0
  296. package/dist/formatter/comments.d.ts +25 -0
  297. package/dist/formatter/comments.d.ts.map +1 -0
  298. package/dist/formatter/comments.js +283 -0
  299. package/dist/formatter/comments.js.map +1 -0
  300. package/dist/formatter/index.d.ts +71 -0
  301. package/dist/formatter/index.d.ts.map +1 -0
  302. package/dist/formatter/index.js +1113 -0
  303. package/dist/formatter/index.js.map +1 -0
  304. package/dist/formatter/operator-precedence.d.ts +3 -0
  305. package/dist/formatter/operator-precedence.d.ts.map +1 -0
  306. package/dist/formatter/operator-precedence.js +27 -0
  307. package/dist/formatter/operator-precedence.js.map +1 -0
  308. package/dist/formatter/prettier.d.ts +7 -0
  309. package/dist/formatter/prettier.d.ts.map +1 -0
  310. package/dist/formatter/prettier.js +51 -0
  311. package/dist/formatter/prettier.js.map +1 -0
  312. package/dist/index.d.ts +17 -0
  313. package/dist/index.d.ts.map +1 -0
  314. package/dist/index.js +17 -0
  315. package/dist/index.js.map +1 -0
  316. package/dist/interop/callback.d.ts +38 -0
  317. package/dist/interop/callback.d.ts.map +1 -0
  318. package/dist/interop/callback.js +130 -0
  319. package/dist/interop/callback.js.map +1 -0
  320. package/dist/interop/index.d.ts +6 -0
  321. package/dist/interop/index.d.ts.map +1 -0
  322. package/dist/interop/index.js +6 -0
  323. package/dist/interop/index.js.map +1 -0
  324. package/dist/interop/js.d.ts +16 -0
  325. package/dist/interop/js.d.ts.map +1 -0
  326. package/dist/interop/js.js +35 -0
  327. package/dist/interop/js.js.map +1 -0
  328. package/dist/interop/record.d.ts +9 -0
  329. package/dist/interop/record.d.ts.map +1 -0
  330. package/dist/interop/record.js +18 -0
  331. package/dist/interop/record.js.map +1 -0
  332. package/dist/interop/valibot.d.ts +9 -0
  333. package/dist/interop/valibot.d.ts.map +1 -0
  334. package/dist/interop/valibot.js +94 -0
  335. package/dist/interop/valibot.js.map +1 -0
  336. package/dist/interop/zod.d.ts +45 -0
  337. package/dist/interop/zod.d.ts.map +1 -0
  338. package/dist/interop/zod.js +143 -0
  339. package/dist/interop/zod.js.map +1 -0
  340. package/dist/lexer/lexer.d.ts +65 -0
  341. package/dist/lexer/lexer.d.ts.map +1 -0
  342. package/dist/lexer/lexer.js +1335 -0
  343. package/dist/lexer/lexer.js.map +1 -0
  344. package/dist/lexer/tokens.d.ts +96 -0
  345. package/dist/lexer/tokens.d.ts.map +1 -0
  346. package/dist/lexer/tokens.js +150 -0
  347. package/dist/lexer/tokens.js.map +1 -0
  348. package/dist/lsp/code-action-worker.d.ts +2 -0
  349. package/dist/lsp/code-action-worker.d.ts.map +1 -0
  350. package/dist/lsp/code-action-worker.js +17 -0
  351. package/dist/lsp/code-action-worker.js.map +1 -0
  352. package/dist/lsp/completion.d.ts +11 -0
  353. package/dist/lsp/completion.d.ts.map +1 -0
  354. package/dist/lsp/completion.js +260 -0
  355. package/dist/lsp/completion.js.map +1 -0
  356. package/dist/lsp/definition.d.ts +42 -0
  357. package/dist/lsp/definition.d.ts.map +1 -0
  358. package/dist/lsp/definition.js +1074 -0
  359. package/dist/lsp/definition.js.map +1 -0
  360. package/dist/lsp/diagnostics-worker.d.ts +2 -0
  361. package/dist/lsp/diagnostics-worker.d.ts.map +1 -0
  362. package/dist/lsp/diagnostics-worker.js +169 -0
  363. package/dist/lsp/diagnostics-worker.js.map +1 -0
  364. package/dist/lsp/docs.d.ts +37 -0
  365. package/dist/lsp/docs.d.ts.map +1 -0
  366. package/dist/lsp/docs.js +830 -0
  367. package/dist/lsp/docs.js.map +1 -0
  368. package/dist/lsp/error-channel.d.ts +3 -0
  369. package/dist/lsp/error-channel.d.ts.map +1 -0
  370. package/dist/lsp/error-channel.js +48 -0
  371. package/dist/lsp/error-channel.js.map +1 -0
  372. package/dist/lsp/hover.d.ts +5 -0
  373. package/dist/lsp/hover.d.ts.map +1 -0
  374. package/dist/lsp/hover.js +651 -0
  375. package/dist/lsp/hover.js.map +1 -0
  376. package/dist/lsp/imports.d.ts +5 -0
  377. package/dist/lsp/imports.d.ts.map +1 -0
  378. package/dist/lsp/imports.js +317 -0
  379. package/dist/lsp/imports.js.map +1 -0
  380. package/dist/lsp/index.d.ts +16 -0
  381. package/dist/lsp/index.d.ts.map +1 -0
  382. package/dist/lsp/index.js +17 -0
  383. package/dist/lsp/index.js.map +1 -0
  384. package/dist/lsp/inlay-hints.d.ts +3 -0
  385. package/dist/lsp/inlay-hints.d.ts.map +1 -0
  386. package/dist/lsp/inlay-hints.js +236 -0
  387. package/dist/lsp/inlay-hints.js.map +1 -0
  388. package/dist/lsp/interop-rename.d.ts +26 -0
  389. package/dist/lsp/interop-rename.d.ts.map +1 -0
  390. package/dist/lsp/interop-rename.js +346 -0
  391. package/dist/lsp/interop-rename.js.map +1 -0
  392. package/dist/lsp/match-arms.d.ts +3 -0
  393. package/dist/lsp/match-arms.d.ts.map +1 -0
  394. package/dist/lsp/match-arms.js +341 -0
  395. package/dist/lsp/match-arms.js.map +1 -0
  396. package/dist/lsp/navigation.d.ts +23 -0
  397. package/dist/lsp/navigation.d.ts.map +1 -0
  398. package/dist/lsp/navigation.js +430 -0
  399. package/dist/lsp/navigation.js.map +1 -0
  400. package/dist/lsp/parsed-documents.d.ts +25 -0
  401. package/dist/lsp/parsed-documents.d.ts.map +1 -0
  402. package/dist/lsp/parsed-documents.js +47 -0
  403. package/dist/lsp/parsed-documents.js.map +1 -0
  404. package/dist/lsp/rename-worker.d.ts +2 -0
  405. package/dist/lsp/rename-worker.d.ts.map +1 -0
  406. package/dist/lsp/rename-worker.js +27 -0
  407. package/dist/lsp/rename-worker.js.map +1 -0
  408. package/dist/lsp/server.d.ts +78 -0
  409. package/dist/lsp/server.d.ts.map +1 -0
  410. package/dist/lsp/server.js +1098 -0
  411. package/dist/lsp/server.js.map +1 -0
  412. package/dist/lsp/thunk-pipeline.d.ts +4 -0
  413. package/dist/lsp/thunk-pipeline.d.ts.map +1 -0
  414. package/dist/lsp/thunk-pipeline.js +95 -0
  415. package/dist/lsp/thunk-pipeline.js.map +1 -0
  416. package/dist/lsp/validation.d.ts +8 -0
  417. package/dist/lsp/validation.d.ts.map +1 -0
  418. package/dist/lsp/validation.js +124 -0
  419. package/dist/lsp/validation.js.map +1 -0
  420. package/dist/lsp/workspace.d.ts +8 -0
  421. package/dist/lsp/workspace.d.ts.map +1 -0
  422. package/dist/lsp/workspace.js +70 -0
  423. package/dist/lsp/workspace.js.map +1 -0
  424. package/dist/math.ts +1 -0
  425. package/dist/parser/declarations.d.ts +21 -0
  426. package/dist/parser/declarations.d.ts.map +1 -0
  427. package/dist/parser/declarations.js +626 -0
  428. package/dist/parser/declarations.js.map +1 -0
  429. package/dist/parser/errors.d.ts +9 -0
  430. package/dist/parser/errors.d.ts.map +1 -0
  431. package/dist/parser/errors.js +11 -0
  432. package/dist/parser/errors.js.map +1 -0
  433. package/dist/parser/index.d.ts +9 -0
  434. package/dist/parser/index.d.ts.map +1 -0
  435. package/dist/parser/index.js +9 -0
  436. package/dist/parser/index.js.map +1 -0
  437. package/dist/parser/jsx.d.ts +5 -0
  438. package/dist/parser/jsx.d.ts.map +1 -0
  439. package/dist/parser/jsx.js +188 -0
  440. package/dist/parser/jsx.js.map +1 -0
  441. package/dist/parser/operator-expressions.d.ts +16 -0
  442. package/dist/parser/operator-expressions.d.ts.map +1 -0
  443. package/dist/parser/operator-expressions.js +146 -0
  444. package/dist/parser/operator-expressions.js.map +1 -0
  445. package/dist/parser/parser.d.ts +104 -0
  446. package/dist/parser/parser.d.ts.map +1 -0
  447. package/dist/parser/parser.js +1216 -0
  448. package/dist/parser/parser.js.map +1 -0
  449. package/dist/parser/patterns.d.ts +9 -0
  450. package/dist/parser/patterns.d.ts.map +1 -0
  451. package/dist/parser/patterns.js +292 -0
  452. package/dist/parser/patterns.js.map +1 -0
  453. package/dist/parser/pipeline-expressions.d.ts +10 -0
  454. package/dist/parser/pipeline-expressions.d.ts.map +1 -0
  455. package/dist/parser/pipeline-expressions.js +57 -0
  456. package/dist/parser/pipeline-expressions.js.map +1 -0
  457. package/dist/parser/scope.d.ts +17 -0
  458. package/dist/parser/scope.d.ts.map +1 -0
  459. package/dist/parser/scope.js +56 -0
  460. package/dist/parser/scope.js.map +1 -0
  461. package/dist/parser/statements.d.ts +13 -0
  462. package/dist/parser/statements.d.ts.map +1 -0
  463. package/dist/parser/statements.js +737 -0
  464. package/dist/parser/statements.js.map +1 -0
  465. package/dist/parser/types.d.ts +13 -0
  466. package/dist/parser/types.d.ts.map +1 -0
  467. package/dist/parser/types.js +371 -0
  468. package/dist/parser/types.js.map +1 -0
  469. package/dist/plugins/bun-preload.d.ts +4 -0
  470. package/dist/plugins/bun-preload.d.ts.map +1 -0
  471. package/dist/plugins/bun-preload.js +18 -0
  472. package/dist/plugins/bun-preload.js.map +1 -0
  473. package/dist/plugins/bun.d.ts +115 -0
  474. package/dist/plugins/bun.d.ts.map +1 -0
  475. package/dist/plugins/bun.js +240 -0
  476. package/dist/plugins/bun.js.map +1 -0
  477. package/dist/plugins/esbuild.d.ts +45 -0
  478. package/dist/plugins/esbuild.d.ts.map +1 -0
  479. package/dist/plugins/esbuild.js +184 -0
  480. package/dist/plugins/esbuild.js.map +1 -0
  481. package/dist/plugins/type-view.d.ts +30 -0
  482. package/dist/plugins/type-view.d.ts.map +1 -0
  483. package/dist/plugins/type-view.js +245 -0
  484. package/dist/plugins/type-view.js.map +1 -0
  485. package/dist/plugins/vite.d.ts +56 -0
  486. package/dist/plugins/vite.d.ts.map +1 -0
  487. package/dist/plugins/vite.js +182 -0
  488. package/dist/plugins/vite.js.map +1 -0
  489. package/dist/service.ts +3 -0
  490. package/dist/service.ts.map +1 -0
  491. package/dist/testing/index.d.ts +24 -0
  492. package/dist/testing/index.d.ts.map +1 -0
  493. package/dist/testing/index.js +56 -0
  494. package/dist/testing/index.js.map +1 -0
  495. package/dist/tooling/doc.d.ts +82 -0
  496. package/dist/tooling/doc.d.ts.map +1 -0
  497. package/dist/tooling/doc.js +624 -0
  498. package/dist/tooling/doc.js.map +1 -0
  499. package/dist/tooling/idiomatic.d.ts +20 -0
  500. package/dist/tooling/idiomatic.d.ts.map +1 -0
  501. package/dist/tooling/idiomatic.js +154 -0
  502. package/dist/tooling/idiomatic.js.map +1 -0
  503. package/dist/tooling/migrate.d.ts +62 -0
  504. package/dist/tooling/migrate.d.ts.map +1 -0
  505. package/dist/tooling/migrate.js +608 -0
  506. package/dist/tooling/migrate.js.map +1 -0
  507. package/dist/tooling/pipeline-style.d.ts +12 -0
  508. package/dist/tooling/pipeline-style.d.ts.map +1 -0
  509. package/dist/tooling/pipeline-style.js +208 -0
  510. package/dist/tooling/pipeline-style.js.map +1 -0
  511. package/dist/version.d.ts +2 -0
  512. package/dist/version.d.ts.map +1 -0
  513. package/dist/version.js +25 -0
  514. package/dist/version.js.map +1 -0
  515. package/package.json +128 -4
  516. package/src/ast/types.ts +753 -0
  517. package/src/ast/walk.ts +35 -0
  518. package/src/cli/build-bun.ts +249 -0
  519. package/src/cli/build-watch.ts +299 -0
  520. package/src/cli/build.ts +450 -0
  521. package/src/cli/check.ts +342 -0
  522. package/src/cli/commands.ts +301 -0
  523. package/src/cli/doc.ts +81 -0
  524. package/src/cli/doctor.ts +173 -0
  525. package/src/cli/emit.ts +138 -0
  526. package/src/cli/explain.ts +127 -0
  527. package/src/cli/fmt.ts +170 -0
  528. package/src/cli/index.ts +227 -0
  529. package/src/cli/init.ts +491 -0
  530. package/src/cli/io.ts +150 -0
  531. package/src/cli/pipeline-style.ts +55 -0
  532. package/src/cli/repl.ts +443 -0
  533. package/src/cli/run.ts +238 -0
  534. package/src/cli/test.ts +148 -0
  535. package/src/cli/tsc.ts +207 -0
  536. package/src/cli/typecheck.ts +100 -0
  537. package/src/compiler/ast-inspection.ts +121 -0
  538. package/src/compiler/boolean-operators.ts +108 -0
  539. package/src/compiler/check.ts +2763 -0
  540. package/src/compiler/diagnostics.ts +179 -0
  541. package/src/compiler/effect-mutation-rule.ts +407 -0
  542. package/src/compiler/entry-rules.ts +116 -0
  543. package/src/compiler/incremental-build.ts +131 -0
  544. package/src/compiler/incremental-dependencies.ts +200 -0
  545. package/src/compiler/js-interop-nullability.ts +67 -0
  546. package/src/compiler/modules/output-collisions.ts +48 -0
  547. package/src/compiler/modules/output-plan.ts +46 -0
  548. package/src/compiler/modules/resolution.ts +56 -0
  549. package/src/compiler/numeric-comparisons.ts +213 -0
  550. package/src/compiler/optional-arguments.ts +335 -0
  551. package/src/compiler/package-fingerprint.ts +216 -0
  552. package/src/compiler/package-record-contracts.ts +156 -0
  553. package/src/compiler/pipelines/catalog.ts +1128 -0
  554. package/src/compiler/pipelines/companions.ts +1279 -0
  555. package/src/compiler/pipelines/resolution.ts +684 -0
  556. package/src/compiler/project-config.ts +221 -0
  557. package/src/compiler/record-contracts.ts +46 -0
  558. package/src/compiler/rules/control-flow.ts +57 -0
  559. package/src/compiler/rules/diagnostic.ts +11 -0
  560. package/src/compiler/rules/module-scope-refs.ts +63 -0
  561. package/src/compiler/schemas/analysis.ts +45 -0
  562. package/src/compiler/schemas/imported-record-functions.ts +984 -0
  563. package/src/compiler/schemas/imported-schemas.ts +761 -0
  564. package/src/compiler/source-map.ts +165 -0
  565. package/src/compiler/typescript-context.ts +250 -0
  566. package/src/compiler.ts +865 -0
  567. package/src/emitter/assemblyscript.ts +1220 -0
  568. package/src/emitter/declarations.ts +916 -0
  569. package/src/emitter/emitter.ts +3128 -0
  570. package/src/emitter/imports.ts +89 -0
  571. package/src/emitter/indent.ts +39 -0
  572. package/src/emitter/jsx.ts +122 -0
  573. package/src/emitter/local-bindings.ts +40 -0
  574. package/src/emitter/match.ts +1631 -0
  575. package/src/emitter/runtime-helpers.ts +31 -0
  576. package/src/emitter/schemas.ts +969 -0
  577. package/src/emitter/statements.ts +310 -0
  578. package/src/emitter/tagged-match.ts +171 -0
  579. package/src/emitter/types.ts +289 -0
  580. package/src/errors.ts +115 -0
  581. package/src/formatter/comments.ts +350 -0
  582. package/src/formatter/index.ts +1457 -0
  583. package/src/formatter/operator-precedence.ts +36 -0
  584. package/src/formatter/prettier.ts +61 -0
  585. package/src/index.ts +16 -0
  586. package/src/interop/callback.ts +188 -0
  587. package/src/interop/js.ts +66 -0
  588. package/src/interop/record.ts +36 -0
  589. package/src/interop/valibot.ts +141 -0
  590. package/src/interop/zod.ts +219 -0
  591. package/src/lexer/lexer.ts +1521 -0
  592. package/src/lexer/tokens.ts +174 -0
  593. package/src/lsp/code-action-worker.ts +31 -0
  594. package/src/lsp/completion.ts +343 -0
  595. package/src/lsp/definition.ts +1165 -0
  596. package/src/lsp/diagnostics-worker.ts +198 -0
  597. package/src/lsp/docs.ts +864 -0
  598. package/src/lsp/error-channel.ts +63 -0
  599. package/src/lsp/hover.ts +803 -0
  600. package/src/lsp/imports.ts +380 -0
  601. package/src/lsp/index.ts +55 -0
  602. package/src/lsp/inlay-hints.ts +308 -0
  603. package/src/lsp/interop-rename.ts +454 -0
  604. package/src/lsp/match-arms.ts +400 -0
  605. package/src/lsp/navigation.ts +553 -0
  606. package/src/lsp/parsed-documents.ts +64 -0
  607. package/src/lsp/rename-worker.ts +40 -0
  608. package/src/lsp/server.ts +1437 -0
  609. package/src/lsp/thunk-pipeline.ts +117 -0
  610. package/src/lsp/validation.ts +147 -0
  611. package/src/lsp/workspace.ts +74 -0
  612. package/src/parser/declarations.ts +808 -0
  613. package/src/parser/errors.ts +18 -0
  614. package/src/parser/jsx.ts +253 -0
  615. package/src/parser/operator-expressions.ts +170 -0
  616. package/src/parser/parser.ts +1565 -0
  617. package/src/parser/patterns.ts +342 -0
  618. package/src/parser/pipeline-expressions.ts +77 -0
  619. package/src/parser/scope.ts +69 -0
  620. package/src/parser/statements.ts +831 -0
  621. package/src/parser/types.ts +453 -0
  622. package/src/plugins/bun-preload.ts +25 -0
  623. package/src/plugins/bun.ts +448 -0
  624. package/src/plugins/esbuild.ts +308 -0
  625. package/src/plugins/type-view.ts +326 -0
  626. package/src/plugins/vite.ts +294 -0
  627. package/src/testing/index.ts +72 -0
  628. package/src/tooling/doc.ts +786 -0
  629. package/src/tooling/idiomatic.ts +202 -0
  630. package/src/tooling/pipeline-style.ts +248 -0
  631. package/src/version.ts +27 -0
@@ -0,0 +1,2448 @@
1
+ import { emitTaggedMatch } from "./tagged-match.js";
2
+ import { collectLocalBindings } from "./local-bindings.js";
3
+ import ts from "typescript";
4
+ import { indentContinuation } from "./indent.js";
5
+ import { isRecordContract, recordContractType, } from "../compiler/record-contracts.js";
6
+ import { FunScriptError } from "../errors.js";
7
+ import { collectBindingNames, emitBindingDeclaration, emitErrorDeclaration, emitServiceDeclaration, emitTopLevelDeclaration, emitUnpackedRecordPattern, extractRecordFields, isPrimitiveType, patternHasOptionalField, } from "./declarations.js";
8
+ import { emitJsxAttribute, emitJsxChild, emitJsxElement, emitJsxExpressionContainer, emitJsxSelfClosingElement, emitJsxTagName, emitJsxText, } from "./jsx.js";
9
+ import { MatchEmitter } from "./match.js";
10
+ import { COMPANION_IMPORT_SOURCE, PIPELINE_COMPANION_CATALOG, } from "../compiler/pipelines/catalog.js";
11
+ import { COMPARISON_METHOD_MAP, ES_TOOLKIT_METHODS, PipelineResolver, } from "../compiler/pipelines/resolution.js";
12
+ import { emitRuntimeHelpers } from "./runtime-helpers.js";
13
+ import { emitSchemaDeclaration, emitSchemaTypeField } from "./schemas.js";
14
+ import { emitArrowExpression, emitEffectBlockExpression, emitEffectCall, emitIndexTarget, emitMutativeRecipe, emitParBlockExpression, emitStatement, emitWhenStatement, } from "./statements.js";
15
+ import { EFFECT_BUILTIN_MODULES, emitPropertyKey, emitTypeNode, emitTypeParameters, } from "./types.js";
16
+ export { COMPARISON_METHOD_MAP, ES_TOOLKIT_DATA_LAST_CALLS, ES_TOOLKIT_MATH_COLLECTION, ES_TOOLKIT_MATH_DATA_LAST, ES_TOOLKIT_METHODS, ES_TOOLKIT_STRING_METHODS, ES_TOOLKIT_TIMING_DATA_LAST, PipelineResolutionError, } from "../compiler/pipelines/resolution.js";
17
+ export const EFFECT_MODULE_NAMES = new Set([
18
+ ...Object.keys(PIPELINE_COMPANION_CATALOG),
19
+ "Context",
20
+ "Data",
21
+ "Duration",
22
+ "Equal",
23
+ "Number",
24
+ "pipe",
25
+ ]);
26
+ const BANNED_INSTANCE_METHODS = new Map([
27
+ // Array methods
28
+ [
29
+ "map",
30
+ {
31
+ category: "array",
32
+ replacement: "Array.map",
33
+ pipeline: "|> Array.map(...)",
34
+ },
35
+ ],
36
+ [
37
+ "filter",
38
+ {
39
+ category: "array",
40
+ replacement: "Array.filter",
41
+ pipeline: "|> Array.filter(...)",
42
+ },
43
+ ],
44
+ [
45
+ "reduce",
46
+ {
47
+ category: "array",
48
+ replacement: "Array.reduce",
49
+ pipeline: "|> Array.reduce(...)",
50
+ },
51
+ ],
52
+ [
53
+ "reduceRight",
54
+ {
55
+ category: "array",
56
+ replacement: "Array.reduceRight",
57
+ pipeline: "|> Array.reduceRight(...)",
58
+ },
59
+ ],
60
+ [
61
+ "flatMap",
62
+ {
63
+ category: "array",
64
+ replacement: "Array.flatMap",
65
+ pipeline: "|> Array.flatMap(...)",
66
+ },
67
+ ],
68
+ [
69
+ "flat",
70
+ {
71
+ category: "array",
72
+ replacement: "Array.flatten",
73
+ pipeline: "|> Array.flatten",
74
+ },
75
+ ],
76
+ [
77
+ "find",
78
+ {
79
+ category: "array",
80
+ replacement: "Array.findFirst",
81
+ pipeline: "|> Array.findFirst(...)",
82
+ },
83
+ ],
84
+ [
85
+ "findIndex",
86
+ {
87
+ category: "array",
88
+ replacement: "Array.findFirstIndex",
89
+ pipeline: "|> Array.findFirstIndex(...)",
90
+ },
91
+ ],
92
+ [
93
+ "findLast",
94
+ {
95
+ category: "array",
96
+ replacement: "Array.findLast",
97
+ pipeline: "|> Array.findLast(...)",
98
+ },
99
+ ],
100
+ [
101
+ "findLastIndex",
102
+ {
103
+ category: "array",
104
+ replacement: "Array.findLastIndex",
105
+ pipeline: "|> Array.findLastIndex(...)",
106
+ },
107
+ ],
108
+ [
109
+ "some",
110
+ {
111
+ category: "array",
112
+ replacement: "Array.some",
113
+ pipeline: "|> Array.some(...)",
114
+ },
115
+ ],
116
+ [
117
+ "every",
118
+ {
119
+ category: "array",
120
+ replacement: "Array.every",
121
+ pipeline: "|> Array.every(...)",
122
+ },
123
+ ],
124
+ [
125
+ "sort",
126
+ {
127
+ category: "array",
128
+ replacement: "Array.sort",
129
+ pipeline: "|> Array.sort(...)",
130
+ },
131
+ ],
132
+ [
133
+ "reverse",
134
+ {
135
+ category: "array",
136
+ replacement: "Array.reverse",
137
+ pipeline: "|> Array.reverse",
138
+ },
139
+ ],
140
+ [
141
+ "push",
142
+ {
143
+ category: "array",
144
+ replacement: "Array.append",
145
+ pipeline: "|> Array.append(...)",
146
+ },
147
+ ],
148
+ [
149
+ "pop",
150
+ {
151
+ category: "array",
152
+ replacement: "Array.unappend",
153
+ pipeline: "|> Array.unappend",
154
+ },
155
+ ],
156
+ [
157
+ "shift",
158
+ {
159
+ category: "array",
160
+ replacement: "Array.unprepend",
161
+ pipeline: "|> Array.unprepend",
162
+ },
163
+ ],
164
+ [
165
+ "unshift",
166
+ {
167
+ category: "array",
168
+ replacement: "Array.prepend",
169
+ pipeline: "|> Array.prepend(...)",
170
+ },
171
+ ],
172
+ [
173
+ "splice",
174
+ {
175
+ category: "array",
176
+ replacement: "Array.remove / Array.modify",
177
+ pipeline: "Array.remove(...)",
178
+ },
179
+ ],
180
+ // String methods
181
+ [
182
+ "trim",
183
+ {
184
+ category: "string",
185
+ replacement: "String.trim",
186
+ pipeline: "|> String.trim",
187
+ },
188
+ ],
189
+ [
190
+ "trimStart",
191
+ {
192
+ category: "string",
193
+ replacement: "String.trimStart",
194
+ pipeline: "|> String.trimStart",
195
+ },
196
+ ],
197
+ [
198
+ "trimEnd",
199
+ {
200
+ category: "string",
201
+ replacement: "String.trimEnd",
202
+ pipeline: "|> String.trimEnd",
203
+ },
204
+ ],
205
+ [
206
+ "toLowerCase",
207
+ {
208
+ category: "string",
209
+ replacement: "String.toLowerCase",
210
+ pipeline: "|> String.toLowerCase",
211
+ },
212
+ ],
213
+ [
214
+ "toUpperCase",
215
+ {
216
+ category: "string",
217
+ replacement: "String.toUpperCase",
218
+ pipeline: "|> String.toUpperCase",
219
+ },
220
+ ],
221
+ [
222
+ "toLocaleLowerCase",
223
+ {
224
+ category: "string",
225
+ replacement: "String.toLocaleLowerCase",
226
+ pipeline: "|> String.toLocaleLowerCase",
227
+ },
228
+ ],
229
+ [
230
+ "toLocaleUpperCase",
231
+ {
232
+ category: "string",
233
+ replacement: "String.toLocaleUpperCase",
234
+ pipeline: "|> String.toLocaleUpperCase",
235
+ },
236
+ ],
237
+ [
238
+ "startsWith",
239
+ {
240
+ category: "string",
241
+ replacement: "String.startsWith",
242
+ pipeline: "|> String.startsWith(...)",
243
+ },
244
+ ],
245
+ [
246
+ "endsWith",
247
+ {
248
+ category: "string",
249
+ replacement: "String.endsWith",
250
+ pipeline: "|> String.endsWith(...)",
251
+ },
252
+ ],
253
+ [
254
+ "split",
255
+ {
256
+ category: "string",
257
+ replacement: "String.split",
258
+ pipeline: "|> String.split(...)",
259
+ },
260
+ ],
261
+ [
262
+ "replace",
263
+ {
264
+ category: "string",
265
+ replacement: "String.replace",
266
+ pipeline: "|> String.replace(...)",
267
+ },
268
+ ],
269
+ [
270
+ "replaceAll",
271
+ {
272
+ category: "string",
273
+ replacement: "String.replaceAll",
274
+ pipeline: "|> String.replaceAll(...)",
275
+ },
276
+ ],
277
+ [
278
+ "padStart",
279
+ {
280
+ category: "string",
281
+ replacement: "String.padStart",
282
+ pipeline: "|> String.padStart(...)",
283
+ },
284
+ ],
285
+ [
286
+ "padEnd",
287
+ {
288
+ category: "string",
289
+ replacement: "String.padEnd",
290
+ pipeline: "|> String.padEnd(...)",
291
+ },
292
+ ],
293
+ [
294
+ "repeat",
295
+ {
296
+ category: "string",
297
+ replacement: "String.repeat",
298
+ pipeline: "|> String.repeat(...)",
299
+ },
300
+ ],
301
+ // Collection mutation methods
302
+ [
303
+ "add",
304
+ {
305
+ category: "collection",
306
+ replacement: "HashSet.add",
307
+ pipeline: "|> HashSet.add(...)",
308
+ },
309
+ ],
310
+ [
311
+ "clear",
312
+ {
313
+ category: "collection",
314
+ replacement: "HashMap.empty() / HashSet.empty()",
315
+ pipeline: "HashMap.empty()",
316
+ },
317
+ ],
318
+ [
319
+ "delete",
320
+ {
321
+ category: "collection",
322
+ replacement: "HashMap.remove / Record.remove",
323
+ pipeline: "|> HashMap.remove(...)",
324
+ },
325
+ ],
326
+ [
327
+ "set",
328
+ {
329
+ category: "collection",
330
+ replacement: "HashMap.set / Record.set",
331
+ pipeline: "|> HashMap.set(...)",
332
+ },
333
+ ],
334
+ // Date mutation methods
335
+ [
336
+ "setFullYear",
337
+ { category: "date", replacement: "DateTime.*", pipeline: "|> DateTime.*" },
338
+ ],
339
+ [
340
+ "setMonth",
341
+ { category: "date", replacement: "DateTime.*", pipeline: "|> DateTime.*" },
342
+ ],
343
+ [
344
+ "setDate",
345
+ { category: "date", replacement: "DateTime.*", pipeline: "|> DateTime.*" },
346
+ ],
347
+ [
348
+ "setHours",
349
+ { category: "date", replacement: "DateTime.*", pipeline: "|> DateTime.*" },
350
+ ],
351
+ [
352
+ "setMinutes",
353
+ { category: "date", replacement: "DateTime.*", pipeline: "|> DateTime.*" },
354
+ ],
355
+ [
356
+ "setSeconds",
357
+ { category: "date", replacement: "DateTime.*", pipeline: "|> DateTime.*" },
358
+ ],
359
+ [
360
+ "setTime",
361
+ { category: "date", replacement: "DateTime.*", pipeline: "|> DateTime.*" },
362
+ ],
363
+ [
364
+ "setMilliseconds",
365
+ { category: "date", replacement: "DateTime.*", pipeline: "|> DateTime.*" },
366
+ ],
367
+ ]);
368
+ const BANNED_OBJECT_STATIC_METHODS = new Map([
369
+ ["keys", "Record.keys(...)"],
370
+ ["values", "Record.values(...)"],
371
+ ["entries", "Record.toEntries(...)"],
372
+ ["fromEntries", "Record.fromEntries(...)"],
373
+ ["assign", "Record.union(...) or object spread '{ ...a, ...b }'"],
374
+ [
375
+ "freeze",
376
+ "plain record literals '{ ... }' (FunkScript records are already immutable)",
377
+ ],
378
+ ["hasOwn", "Record.has(...)"],
379
+ ]);
380
+ function getRootCalleeName(node) {
381
+ if (node.kind === "Identifier" || node.kind === "UpperIdentifier") {
382
+ return node.name;
383
+ }
384
+ if (node.kind === "MemberExpression") {
385
+ return getRootCalleeName(node.object);
386
+ }
387
+ if (node.kind === "CallExpression") {
388
+ return getRootCalleeName(node.callee);
389
+ }
390
+ return null;
391
+ }
392
+ export function isEffectModule(moduleName) {
393
+ return EFFECT_MODULE_NAMES.has(moduleName);
394
+ }
395
+ // `Date` has both a call signature and a construct signature in TypeScript, so
396
+ // type-directed `constructorCalls` skips it; `Map`/`WeakMap` keep the 1-arg cast.
397
+ const AUTO_NEW_CONSTRUCTORS = new Set(["Date"]);
398
+ const NATIVE_CONSTRUCTOR_NAMES = new Set([
399
+ "Number",
400
+ "String",
401
+ "Boolean",
402
+ "Array",
403
+ ]);
404
+ export class Emitter {
405
+ program;
406
+ options;
407
+ effectImports = new Set();
408
+ parameterScopes = [];
409
+ variableTypeScopes = [];
410
+ localBindingScopes = [];
411
+ recordScopes = [];
412
+ userEffectBindings = new Set();
413
+ effectModuleBindings = new Set();
414
+ userEsToolkitBindings = new Set();
415
+ userImportBindings = new Set();
416
+ esToolkitImports = new Set();
417
+ needsTsPattern = false;
418
+ needsMutative = false;
419
+ needsReferenceEquality = false;
420
+ needsJsInterop = false;
421
+ needsDecodeUnknown = false;
422
+ needsFromNullishOrElse = false;
423
+ needsFromNullishOr = false;
424
+ needsOptionTry = false;
425
+ primitiveIdentifiers = new Set();
426
+ placeholderCounter = 0;
427
+ bindings = new Map();
428
+ emitCtx = {
429
+ inPipelineStage: false,
430
+ currentPlaceholderParam: null,
431
+ inTryContext: false,
432
+ pendingTryThunk: false,
433
+ pendingTryRecord: false,
434
+ };
435
+ withEmitContext(patch, fn) {
436
+ const prev = this.emitCtx;
437
+ this.emitCtx = { ...prev, ...patch };
438
+ try {
439
+ return fn();
440
+ }
441
+ finally {
442
+ this.emitCtx = prev;
443
+ }
444
+ }
445
+ activeDraftParams = new Set();
446
+ declaredTypeNames = new Set();
447
+ runtimeSchemaNames = new Set();
448
+ genericDataSchemas = new Map();
449
+ genericSchemaDeclarations = new Map();
450
+ get activeSchemaParameters() {
451
+ return this.emitCtx.activeSchemaParameters;
452
+ }
453
+ withSchemaParameters(names, fn) {
454
+ return this.withEmitContext({ activeSchemaParameters: names }, fn);
455
+ }
456
+ unsafeSchemaBinding;
457
+ recordContracts = new Map();
458
+ nullishSchemaFields = new Map();
459
+ typeSignatureSchemas = new Map();
460
+ needsCheckedRecordDecoder = false;
461
+ checkedCallbackKinds = new Set();
462
+ identityRecordSchemas = new Set();
463
+ checkedTaggedSchemas = new Map();
464
+ variantFields = new Map();
465
+ taggedUnionVariants = new Map();
466
+ taggedUnionParameters = new Map();
467
+ importedTaggedUnionNames = new Set();
468
+ importedTaggedFactories = new Map();
469
+ modularEffectImports;
470
+ preserveFunImports;
471
+ getRecordTypeNode(name) {
472
+ return this.recordContracts.get(name);
473
+ }
474
+ addEffectImport(name) {
475
+ this.effectImports.add(name);
476
+ }
477
+ constructor(program, contextProgram, options = {}) {
478
+ this.program = program;
479
+ this.options = options;
480
+ this.modularEffectImports = options.modularEffectImports ?? false;
481
+ this.preserveFunImports = options.preserveFunImports ?? false;
482
+ for (const [name, contract] of options.importedRecordContracts ?? [])
483
+ this.recordContracts.set(name, contract);
484
+ for (const [name, fields] of options.importedNullishSchemas ?? [])
485
+ this.nullishSchemaFields.set(name, new Map(fields));
486
+ for (const [name, variants] of options.importedTaggedUnionVariants ?? []) {
487
+ const returnedVariant = variants.returnedVariant;
488
+ if (returnedVariant) {
489
+ this.importedTaggedFactories.set(name, returnedVariant);
490
+ continue;
491
+ }
492
+ this.taggedUnionVariants.set(name, new Set(variants));
493
+ this.importedTaggedUnionNames.add(name);
494
+ const parameters = variants.typeParameters;
495
+ if (parameters)
496
+ this.taggedUnionParameters.set(name, parameters);
497
+ }
498
+ // Source-map emission renders declarations individually, but resolution
499
+ // still needs the bindings from the complete source program.
500
+ let unsafeSchemaBinding = false;
501
+ const allItems = (contextProgram ?? program)?.body ?? [];
502
+ for (const item of allItems) {
503
+ const decl = item.kind === "ExportDeclaration" ? item.declaration : item;
504
+ if (item.kind === "ImportDeclaration") {
505
+ for (const spec of item.specifiers) {
506
+ if (spec.local.name === "Schema" &&
507
+ (item.isTypeOnly ||
508
+ spec.isTypeOnly ||
509
+ item.source.raw !== '"effect"' ||
510
+ spec.imported.name !== "Schema"))
511
+ unsafeSchemaBinding = true;
512
+ }
513
+ if (item.namespaceBinding?.name === "Schema" &&
514
+ (item.isTypeOnly || item.source.raw !== '"effect/Schema"'))
515
+ unsafeSchemaBinding = true;
516
+ if (!item.isTypeOnly) {
517
+ for (const spec of item.specifiers) {
518
+ if (!spec.isTypeOnly)
519
+ this.userImportBindings.add(spec.local.name);
520
+ }
521
+ if (item.namespaceBinding)
522
+ this.userImportBindings.add(item.namespaceBinding.name);
523
+ }
524
+ }
525
+ if (item.kind === "ImportDeclaration" && item.source.raw === '"effect"') {
526
+ for (const spec of item.specifiers)
527
+ this.userEffectBindings.add(spec.local.name);
528
+ }
529
+ if (item.kind === "ImportDeclaration" &&
530
+ item.source.raw === '"es-toolkit"') {
531
+ for (const spec of item.specifiers)
532
+ this.userEsToolkitBindings.add(spec.local.name);
533
+ }
534
+ if (item.kind === "ImportDeclaration" &&
535
+ /^"effect(?:\/|")/.test(item.source.raw)) {
536
+ for (const spec of item.specifiers)
537
+ this.effectModuleBindings.add(spec.local.name);
538
+ if (item.namespaceBinding) {
539
+ this.effectModuleBindings.add(item.namespaceBinding.name);
540
+ if (item.source.raw === `"effect/${item.namespaceBinding.name}"`) {
541
+ this.userEffectBindings.add(item.namespaceBinding.name);
542
+ }
543
+ }
544
+ }
545
+ if (decl.kind === "SchemaDeclaration" ||
546
+ decl.kind === "ErrorDeclaration" ||
547
+ decl.kind === "ServiceDeclaration") {
548
+ this.declaredTypeNames.add(decl.id.name);
549
+ }
550
+ if (decl.kind === "BindingDeclaration" && "name" in decl.id)
551
+ this.bindings.set(decl.id.name, decl);
552
+ }
553
+ this.unsafeSchemaBinding = unsafeSchemaBinding;
554
+ const staticTypeNames = new Set();
555
+ for (const [name] of this.recordContracts)
556
+ staticTypeNames.add(name);
557
+ for (const item of allItems) {
558
+ const decl = item.kind === "ExportDeclaration" ? item.declaration : item;
559
+ if (decl.kind === "SchemaDeclaration" &&
560
+ decl.body.kind === "TypeSignatureSchema") {
561
+ staticTypeNames.add(decl.id.name);
562
+ if (!decl.typeParams?.length) {
563
+ this.typeSignatureSchemas.set(decl.id.name, decl.body.signature);
564
+ }
565
+ }
566
+ }
567
+ for (const item of allItems) {
568
+ const decl = item.kind === "ExportDeclaration" ? item.declaration : item;
569
+ if (decl.kind === "SchemaDeclaration" &&
570
+ decl.body.kind === "RecordSchema") {
571
+ const fields = new Map();
572
+ for (const field of decl.body.fields) {
573
+ const resolvedFieldType = this.unwrapTypeAlias(field.typeAnnotation);
574
+ if (resolvedFieldType?.kind === "TypeReferenceNode" &&
575
+ resolvedFieldType.name.name === "JSNullish") {
576
+ fields.set(field.name.name, resolvedFieldType);
577
+ }
578
+ }
579
+ if (fields.size)
580
+ this.nullishSchemaFields.set(decl.id.name, fields);
581
+ }
582
+ }
583
+ // Conservative whitelist: only local, non-transforming record codecs are used
584
+ // for generated Effect callback adapters. Optional/defaulted fields can change
585
+ // their encoded representation and are deliberately excluded.
586
+ const identityType = (type) => {
587
+ if (type.kind === "LiteralTypeNode")
588
+ return true;
589
+ if (type.kind === "UnionTypeNode")
590
+ return type.types.every(identityType);
591
+ if (type.kind === "ParenthesizedTypeNode")
592
+ return identityType(type.typeNode);
593
+ return (type.kind === "TypeReferenceNode" &&
594
+ !type.typeArgs?.length &&
595
+ ((["String", "Number", "Boolean"].includes(type.name.name) &&
596
+ !this.declaredTypeNames.has(type.name.name)) ||
597
+ this.identityRecordSchemas.has(type.name.name)));
598
+ };
599
+ let addedIdentity = true;
600
+ while (addedIdentity) {
601
+ addedIdentity = false;
602
+ for (const item of allItems) {
603
+ const decl = item.kind === "ExportDeclaration" ? item.declaration : item;
604
+ if (decl.kind !== "SchemaDeclaration" ||
605
+ decl.body.kind !== "RecordSchema" ||
606
+ decl.typeParams?.length ||
607
+ this.identityRecordSchemas.has(decl.id.name))
608
+ continue;
609
+ if (decl.body.fields.every((field) => !field.defaultValue && identityType(field.typeAnnotation))) {
610
+ this.identityRecordSchemas.add(decl.id.name);
611
+ addedIdentity = true;
612
+ }
613
+ }
614
+ }
615
+ for (const item of allItems) {
616
+ const decl = item.kind === "ExportDeclaration" ? item.declaration : item;
617
+ if (decl.kind === "SchemaDeclaration" &&
618
+ decl.body.kind === "TaggedUnionSchema") {
619
+ this.taggedUnionParameters.set(decl.id.name, decl.typeParams ?? []);
620
+ this.importedTaggedUnionNames.delete(decl.id.name);
621
+ this.taggedUnionVariants.set(decl.id.name, new Set(decl.body.variants.map((variant) => variant.name.name)));
622
+ for (const variant of decl.body.variants) {
623
+ this.variantFields.set(variant.name.name, variant.fields.map((f) => f.name.name));
624
+ }
625
+ }
626
+ }
627
+ // These codecs can be checked in place without transforming tagged payloads.
628
+ // Optional/defaulted, recursive, generic, and unverified imports stay excluded.
629
+ for (const item of allItems) {
630
+ const decl = item.kind === "ExportDeclaration" ? item.declaration : item;
631
+ if (decl.kind === "SchemaDeclaration" &&
632
+ decl.body.kind === "TaggedUnionSchema" &&
633
+ !decl.typeParams?.length &&
634
+ decl.body.variants.length > 0 &&
635
+ decl.body.variants.every((variant) => variant.fields.every((field) => field.name.name !== "_tag" &&
636
+ field.typeAnnotation.kind === "TypeReferenceNode" &&
637
+ !field.typeAnnotation.typeArgs?.length &&
638
+ ((["String", "Number", "Boolean"].includes(field.typeAnnotation.name.name) &&
639
+ !this.declaredTypeNames.has(field.typeAnnotation.name.name)) ||
640
+ this.identityRecordSchemas.has(field.typeAnnotation.name.name) ||
641
+ this.options.importedIdentitySchemas?.has(field.typeAnnotation.name.name) === true)))) {
642
+ this.checkedTaggedSchemas.set(decl.id.name, decl.body);
643
+ }
644
+ }
645
+ let changed = true;
646
+ while (changed) {
647
+ changed = false;
648
+ for (const item of allItems) {
649
+ const decl = item.kind === "ExportDeclaration" ? item.declaration : item;
650
+ if (decl.kind === "SchemaDeclaration" &&
651
+ decl.body.kind === "RecordSchema" &&
652
+ !staticTypeNames.has(decl.id.name)) {
653
+ const visibleStatics = new Set(staticTypeNames);
654
+ for (const param of decl.typeParams ?? [])
655
+ visibleStatics.delete(param.name.name);
656
+ if (isRecordContract(decl.body, visibleStatics)) {
657
+ staticTypeNames.add(decl.id.name);
658
+ changed = true;
659
+ }
660
+ }
661
+ }
662
+ }
663
+ for (const item of allItems) {
664
+ const decl = item.kind === "ExportDeclaration" ? item.declaration : item;
665
+ if (decl.kind === "SchemaDeclaration") {
666
+ if (decl.body.kind === "RecordSchema" &&
667
+ staticTypeNames.has(decl.id.name)) {
668
+ this.recordContracts.set(decl.id.name, recordContractType(decl.body));
669
+ }
670
+ else if ((decl.body.kind === "RecordSchema" &&
671
+ !staticTypeNames.has(decl.id.name)) ||
672
+ decl.body.kind === "StructuralUnionSchema" ||
673
+ decl.body.kind === "RefinementSchema" ||
674
+ decl.body.kind === "TsDerivedSchema" ||
675
+ decl.body.kind === "ImportedTsSchema") {
676
+ this.runtimeSchemaNames.add(decl.id.name);
677
+ }
678
+ }
679
+ }
680
+ for (const item of allItems) {
681
+ const decl = item.kind === "ExportDeclaration" ? item.declaration : item;
682
+ if (decl.kind === "SchemaDeclaration" &&
683
+ (decl.body.kind === "RecordSchema" ||
684
+ decl.body.kind === "StructuralUnionSchema") &&
685
+ decl.typeParams?.length &&
686
+ !this.recordContracts.has(decl.id.name)) {
687
+ this.genericDataSchemas.set(decl.id.name, decl.typeParams.length);
688
+ this.genericSchemaDeclarations.set(decl.id.name, decl);
689
+ }
690
+ }
691
+ }
692
+ emit() {
693
+ const bodyParts = this.program?.body.map((decl) => this.emitTopLevelDeclaration(decl)) ??
694
+ [];
695
+ // Generate header imports
696
+ let header = "";
697
+ const generatedEffectImports = Array.from(this.effectImports).filter((name) => {
698
+ const asMatch = /^(.+?)\s+as\s+(.+)$/.exec(name);
699
+ const localName = asMatch ? asMatch[2] : name;
700
+ const source = COMPANION_IMPORT_SOURCE[asMatch ? asMatch[1] : name];
701
+ if (source)
702
+ return !this.userImportBindings.has(localName);
703
+ return !this.userEffectBindings.has(localName);
704
+ });
705
+ // Generated imports stay in the header, preserving their module evaluation
706
+ // order. Compatible user bindings can share that existing import.
707
+ const mergeNamedImport = (source, names) => {
708
+ if (this.modularEffectImports)
709
+ return names;
710
+ const decl = this.program?.body.find((item) => item.kind === "ImportDeclaration" &&
711
+ (item.source.raw === JSON.stringify(source) ||
712
+ item.source.raw === `'${source}'`) &&
713
+ !item.isSideEffect &&
714
+ !item.isTypeOnly &&
715
+ !item.defaultBinding &&
716
+ !item.namespaceBinding &&
717
+ item.specifiers.length > 0);
718
+ if (!decl || decl.kind !== "ImportDeclaration")
719
+ return names;
720
+ const index = this.program.body.indexOf(decl);
721
+ bodyParts[index] = "";
722
+ const userNames = decl.specifiers.map((spec) => `${spec.isTypeOnly ? "type " : ""}${spec.imported.name}${spec.imported.name === spec.local.name ? "" : ` as ${spec.local.name}`}`);
723
+ return [...userNames, ...names];
724
+ };
725
+ if (generatedEffectImports.length > 0) {
726
+ if (this.modularEffectImports) {
727
+ for (const name of generatedEffectImports.sort()) {
728
+ const asMatch = /^(.+?)\s+as\s+(.+)$/.exec(name);
729
+ const moduleName = asMatch ? asMatch[1] : name;
730
+ const localName = asMatch ? asMatch[2] : name;
731
+ const source = COMPANION_IMPORT_SOURCE[moduleName];
732
+ if (moduleName === "pipe") {
733
+ const spec = localName === moduleName ? "pipe" : `pipe as ${localName}`;
734
+ header += `import { ${spec} } from "effect/Function";\n`;
735
+ }
736
+ else if (source) {
737
+ const spec = localName === moduleName
738
+ ? moduleName
739
+ : `${moduleName} as ${localName}`;
740
+ header += `import { ${spec} } from ${JSON.stringify(source)};\n`;
741
+ }
742
+ else {
743
+ header += `import * as ${localName} from "effect/${moduleName}";\n`;
744
+ }
745
+ }
746
+ }
747
+ else {
748
+ const bySource = new Map();
749
+ for (const name of generatedEffectImports.sort()) {
750
+ const asMatch = /^(.+?)\s+as\s+(.+)$/.exec(name);
751
+ const moduleName = asMatch ? asMatch[1] : name;
752
+ const source = COMPANION_IMPORT_SOURCE[moduleName] ?? "effect";
753
+ const list = bySource.get(source) ?? [];
754
+ list.push(name);
755
+ bySource.set(source, list);
756
+ }
757
+ for (const source of [...bySource.keys()].sort()) {
758
+ const names = bySource.get(source);
759
+ const combined = mergeNamedImport(source, names);
760
+ header += `import { ${combined.join(", ")} } from ${JSON.stringify(source)};\n`;
761
+ }
762
+ }
763
+ }
764
+ const generatedEsToolkitImports = Array.from(this.esToolkitImports)
765
+ .filter((name) => !this.userEsToolkitBindings.has(name))
766
+ .map((name) => (name === "slug" ? "kebabCase as slug" : name))
767
+ .sort((a, b) => a.localeCompare(b));
768
+ if (generatedEsToolkitImports.length > 0) {
769
+ const combined = mergeNamedImport("es-toolkit", generatedEsToolkitImports);
770
+ header += `import { ${combined.join(", ")} } from "es-toolkit";\n`;
771
+ }
772
+ if (this.needsCheckedRecordDecoder) {
773
+ const helpers = ["decodeCheckedRecord as $funscriptDecodeCheckedRecord"];
774
+ if (this.checkedCallbackKinds.has("sync"))
775
+ helpers.push("checkedSync as $funscriptCheckedSync");
776
+ if (this.checkedCallbackKinds.has("void"))
777
+ helpers.push("checkedSyncVoid as $funscriptCheckedSyncVoid");
778
+ if (this.checkedCallbackKinds.has("effect"))
779
+ helpers.push("checkedEffect as $funscriptCheckedEffect", "type CallbackBoundaryError as $funscriptCallbackBoundaryError");
780
+ header += `import { ${helpers.join(", ")} } from "funkscript/callback";\n`;
781
+ }
782
+ if (this.needsTsPattern) {
783
+ header += `import { match, P } from "ts-pattern";\n`;
784
+ }
785
+ if (this.needsMutative) {
786
+ header += `import { create } from "mutative";\n`;
787
+ }
788
+ if (this.needsJsInterop) {
789
+ header += `import { jsInterop as __funscriptJs } from "funkscript/js";\n`;
790
+ }
791
+ header += emitRuntimeHelpers({
792
+ referenceEquality: this.needsReferenceEquality,
793
+ decodeUnknown: this.needsDecodeUnknown,
794
+ fromNullishOrElse: this.needsFromNullishOrElse,
795
+ fromNullishOr: this.needsFromNullishOr,
796
+ optionTry: this.needsOptionTry,
797
+ });
798
+ if (header.length > 0) {
799
+ header += "\n";
800
+ }
801
+ return header + bodyParts.join("\n\n").trim() + "\n";
802
+ }
803
+ emitTopLevelDeclaration(decl, isExport = false) {
804
+ return emitTopLevelDeclaration(this, decl, isExport);
805
+ }
806
+ emitSchemaDeclaration(decl, isExport) {
807
+ return emitSchemaDeclaration(this, decl, isExport);
808
+ }
809
+ emitSchemaTypeField(typeNode) {
810
+ return emitSchemaTypeField(this, typeNode);
811
+ }
812
+ emitErrorDeclaration(decl, isExport) {
813
+ return emitErrorDeclaration(this, decl, isExport);
814
+ }
815
+ emitServiceDeclaration(decl, isExport) {
816
+ return emitServiceDeclaration(this, decl, isExport);
817
+ }
818
+ isPrimitiveType(type) {
819
+ return isPrimitiveType(type);
820
+ }
821
+ isPrimitive(expr) {
822
+ if (expr.kind === "NumberLiteral" ||
823
+ expr.kind === "StringLiteral" ||
824
+ expr.kind === "BooleanLiteral") {
825
+ return true;
826
+ }
827
+ if (expr.kind === "UnaryExpression") {
828
+ return true;
829
+ }
830
+ if (expr.kind === "BinaryExpression") {
831
+ return true;
832
+ }
833
+ if (expr.kind === "Identifier" &&
834
+ this.primitiveIdentifiers.has(expr.name)) {
835
+ return true;
836
+ }
837
+ return false;
838
+ }
839
+ isOptionalParameter(name) {
840
+ return ([...this.parameterScopes]
841
+ .reverse()
842
+ .find((scope) => scope.has(name))
843
+ ?.get(name) ?? false);
844
+ }
845
+ recordFields(name) {
846
+ for (let i = this.recordScopes.length - 1; i >= 0; i--) {
847
+ if (this.recordScopes[i].has(name))
848
+ return this.recordScopes[i].get(name);
849
+ }
850
+ return undefined;
851
+ }
852
+ recordField(expr) {
853
+ if (expr.kind === "IndexExpression" &&
854
+ expr.index.kind === "StringLiteral") {
855
+ const propName = expr.index.parts
856
+ .map((p) => ("value" in p ? String(p.value) : ""))
857
+ .join("");
858
+ const fields = expr.object.kind === "Identifier"
859
+ ? this.recordFields(expr.object.name)
860
+ : this.recordField(expr.object)?.fields;
861
+ return fields?.get(propName);
862
+ }
863
+ if (expr.kind !== "MemberExpression")
864
+ return undefined;
865
+ const fields = expr.object.kind === "Identifier"
866
+ ? this.recordFields(expr.object.name)
867
+ : this.recordField(expr.object)?.fields;
868
+ return fields?.get(expr.property.name);
869
+ }
870
+ getTypeNodeForIdentifier(name) {
871
+ for (let i = this.variableTypeScopes.length - 1; i >= 0; i--) {
872
+ if (this.variableTypeScopes[i].has(name)) {
873
+ return this.variableTypeScopes[i].get(name);
874
+ }
875
+ }
876
+ return this.bindings.get(name)?.typeAnnotation;
877
+ }
878
+ unwrapTypeAlias(type, visited = new Set()) {
879
+ let curr = type;
880
+ while (curr?.kind === "TypeReferenceNode" &&
881
+ !curr.typeArgs?.length &&
882
+ this.typeSignatureSchemas.has(curr.name.name) &&
883
+ !visited.has(curr.name.name)) {
884
+ visited.add(curr.name.name);
885
+ curr = this.typeSignatureSchemas.get(curr.name.name);
886
+ }
887
+ return curr;
888
+ }
889
+ getTypeNodeForExpression(expr) {
890
+ return this.unwrapTypeAlias(this.resolveExpressionTypeNode(expr, new Set()));
891
+ }
892
+ resolveExpressionTypeNode(expr, visited) {
893
+ if (expr.kind === "Identifier") {
894
+ for (let i = this.variableTypeScopes.length - 1; i >= 0; i--) {
895
+ if (this.variableTypeScopes[i].has(expr.name))
896
+ return this.variableTypeScopes[i].get(expr.name);
897
+ }
898
+ if (visited.has(expr.name))
899
+ return undefined;
900
+ const binding = this.bindings.get(expr.name);
901
+ if (!binding)
902
+ return undefined;
903
+ if (binding.typeAnnotation)
904
+ return binding.typeAnnotation;
905
+ visited.add(expr.name);
906
+ return this.resolveExpressionTypeNode(binding.init, visited);
907
+ }
908
+ if (expr.kind === "FunctionExpression" && expr.returnType) {
909
+ return {
910
+ kind: "FunctionTypeNode",
911
+ params: expr.params,
912
+ typeParams: expr.typeParams,
913
+ returnType: expr.returnType,
914
+ span: expr.span,
915
+ };
916
+ }
917
+ if (expr.kind === "CallExpression") {
918
+ const callee = this.resolveExpressionTypeNode(expr.callee, visited);
919
+ if (callee?.kind === "FunctionTypeNode")
920
+ return callee.returnType;
921
+ }
922
+ if (expr.kind === "MemberExpression") {
923
+ const objType = this.resolveExpressionTypeNode(expr.object, visited);
924
+ if (!objType)
925
+ return undefined;
926
+ let recordType = objType;
927
+ if (recordType.kind === "TypeReferenceNode") {
928
+ const nullishField = this.nullishSchemaFields
929
+ .get(recordType.name.name)
930
+ ?.get(expr.property.name);
931
+ if (nullishField)
932
+ return nullishField;
933
+ if (recordType.name.name === "Option" &&
934
+ recordType.typeArgs?.length === 1) {
935
+ recordType = recordType.typeArgs[0];
936
+ }
937
+ else {
938
+ recordType = this.recordContracts.get(recordType.name.name);
939
+ }
940
+ }
941
+ if (recordType?.kind === "RecordTypeNode") {
942
+ const field = recordType.fields.find((f) => f.name.name === expr.property.name);
943
+ return field?.typeAnnotation;
944
+ }
945
+ }
946
+ return undefined;
947
+ }
948
+ isTargetNativeCategory(expr, category, prop, visitedBindings = new Set()) {
949
+ if (category === "array" && expr.kind === "ArrayExpression")
950
+ return true;
951
+ if (category === "string" &&
952
+ (expr.kind === "StringLiteral" || expr.kind === "TemplateLiteral"))
953
+ return true;
954
+ if (expr.kind === "CallExpression") {
955
+ const callee = expr.callee;
956
+ if (callee.kind === "Identifier" || callee.kind === "UpperIdentifier") {
957
+ if (category === "array" && callee.name === "Array")
958
+ return true;
959
+ if (category === "collection" &&
960
+ (callee.name === "Map" ||
961
+ callee.name === "Set" ||
962
+ callee.name === "WeakMap" ||
963
+ callee.name === "WeakSet"))
964
+ return true;
965
+ if (category === "date" && callee.name === "Date")
966
+ return true;
967
+ }
968
+ }
969
+ const typeNode = this.getTypeNodeForExpression(expr);
970
+ if (typeNode) {
971
+ if (typeNode.kind === "ArrayTypeNode") {
972
+ return category === "array";
973
+ }
974
+ if (typeNode.kind === "TypeReferenceNode") {
975
+ const typeName = typeNode.name.name;
976
+ if (typeName === "Array" || typeName === "ReadonlyArray") {
977
+ return category === "array";
978
+ }
979
+ if (typeName === "String" || typeName === "string") {
980
+ return category === "string";
981
+ }
982
+ if (typeName === "Map" ||
983
+ typeName === "Set" ||
984
+ typeName === "WeakMap" ||
985
+ typeName === "WeakSet") {
986
+ return category === "collection";
987
+ }
988
+ if (typeName === "Date") {
989
+ return category === "date";
990
+ }
991
+ // Any other type reference (URLSearchParams, Headers, FormData, Request, Response, URL, Observable, QueryBuilder, Parser, Store, etc.)
992
+ // is NOT a native JavaScript type replaced by Effect.
993
+ return false;
994
+ }
995
+ if (typeNode.kind === "RecordTypeNode" ||
996
+ typeNode.kind === "FunctionTypeNode") {
997
+ return false;
998
+ }
999
+ }
1000
+ if (expr.kind === "Identifier") {
1001
+ const name = expr.name;
1002
+ // Check if initialized from a binding
1003
+ const binding = this.bindings.get(name);
1004
+ if (binding) {
1005
+ if (!visitedBindings.has(name)) {
1006
+ visitedBindings.add(name);
1007
+ if (this.isTargetNativeCategory(binding.init, category, prop, visitedBindings)) {
1008
+ return true;
1009
+ }
1010
+ }
1011
+ }
1012
+ }
1013
+ // TypeScript TypeChecker check (for unannotated identifiers, ts escape blocks, external imports)
1014
+ if (this.options.context) {
1015
+ const checker = this.options.context.getTypeChecker();
1016
+ const program = this.options.context.getProgram();
1017
+ if (checker && program && expr.kind === "Identifier") {
1018
+ const sourceFile = program.getSourceFile(this.options.context.getNormalizedFilename());
1019
+ if (sourceFile) {
1020
+ const tsType = this.findTsTypeForIdentifier(sourceFile, checker, expr.name);
1021
+ if (tsType) {
1022
+ const symName = tsType.symbol?.name ?? tsType.aliasSymbol?.name;
1023
+ if (category === "array") {
1024
+ return (checker.isArrayType(tsType) ||
1025
+ symName === "Array" ||
1026
+ symName === "ReadonlyArray");
1027
+ }
1028
+ if (category === "string") {
1029
+ return Boolean(tsType.flags & ts.TypeFlags.StringLike);
1030
+ }
1031
+ if (category === "collection") {
1032
+ return (symName === "Map" ||
1033
+ symName === "Set" ||
1034
+ symName === "WeakMap" ||
1035
+ symName === "WeakSet");
1036
+ }
1037
+ if (category === "date") {
1038
+ return symName === "Date";
1039
+ }
1040
+ return false;
1041
+ }
1042
+ }
1043
+ }
1044
+ }
1045
+ return false;
1046
+ }
1047
+ findTsTypeForIdentifier(sourceFile, checker, name) {
1048
+ let foundType;
1049
+ const visit = (node) => {
1050
+ if (ts.isIdentifier(node) && node.text === name) {
1051
+ foundType = checker.getTypeAtLocation(node);
1052
+ }
1053
+ if (!foundType) {
1054
+ ts.forEachChild(node, visit);
1055
+ }
1056
+ };
1057
+ visit(sourceFile);
1058
+ return foundType;
1059
+ }
1060
+ isHtmlPropsType(type) {
1061
+ if (!type)
1062
+ return false;
1063
+ if (type.kind === "TypeReferenceNode" && type.name.name === "HtmlProps")
1064
+ return true;
1065
+ if (type.kind === "IntersectionTypeNode") {
1066
+ return type.types.some((t) => this.isHtmlPropsType(t));
1067
+ }
1068
+ return false;
1069
+ }
1070
+ isOptionalValue(expr) {
1071
+ if (expr.kind === "Identifier")
1072
+ return this.isOptionalParameter(expr.name);
1073
+ if (expr.kind === "MemberExpression")
1074
+ return this.recordField(expr)?.optional ?? false;
1075
+ if (expr.kind === "IndexExpression")
1076
+ return true;
1077
+ return false;
1078
+ }
1079
+ validateRecordDefault(value, currentParamNames, subsequentParamNames) {
1080
+ const visit = (item, parent, key) => {
1081
+ if (!item || typeof item !== "object")
1082
+ return;
1083
+ if (Array.isArray(item)) {
1084
+ for (const child of item)
1085
+ visit(child, parent, key);
1086
+ return;
1087
+ }
1088
+ const node = item;
1089
+ if (node.kind === "Identifier" && typeof node.name === "string") {
1090
+ if ((parent?.kind === "MemberExpression" && key === "property") ||
1091
+ (parent?.kind === "FieldEntry" && key === "key"))
1092
+ return;
1093
+ if (currentParamNames.has(node.name)) {
1094
+ throw new FunScriptError(`Defaulted record field cannot reference its own record parameter '${node.name}'`, node.span);
1095
+ }
1096
+ if (subsequentParamNames.has(node.name)) {
1097
+ throw new FunScriptError(`Parameter '${node.name}' cannot be referenced in a default value before its declaration`, node.span);
1098
+ }
1099
+ }
1100
+ for (const [childKey, child] of Object.entries(node)) {
1101
+ if (childKey !== "span" &&
1102
+ childKey !== "typeAnnotation" &&
1103
+ childKey !== "returnType")
1104
+ visit(child, node, childKey);
1105
+ }
1106
+ };
1107
+ visit(value);
1108
+ }
1109
+ emitBindingDeclaration(decl, isExport = false) {
1110
+ return emitBindingDeclaration(this, decl, isExport);
1111
+ }
1112
+ emitBindingTarget(target) {
1113
+ if (target.kind === "Identifier" || target.kind === "UpperIdentifier") {
1114
+ return target.name;
1115
+ }
1116
+ if (target.kind === "VariablePattern") {
1117
+ return target.name.name;
1118
+ }
1119
+ if (target.kind === "WildcardPattern" || target.kind === "LiteralPattern") {
1120
+ return "";
1121
+ }
1122
+ if (target.kind === "RestPattern") {
1123
+ const arg = this.emitBindingTarget(target.argument);
1124
+ return arg ? `...${arg}` : "";
1125
+ }
1126
+ if (target.kind === "RecordPattern") {
1127
+ const fields = target.fields.map((f) => {
1128
+ if (f.isRest) {
1129
+ return `...${f.key.name}`;
1130
+ }
1131
+ if (!f.pattern ||
1132
+ (f.pattern.kind === "VariablePattern" &&
1133
+ f.pattern.name.name === f.key.name)) {
1134
+ return f.key.name;
1135
+ }
1136
+ return `${f.key.name}: ${this.emitBindingTarget(f.pattern)}`;
1137
+ });
1138
+ return `{ ${fields.join(", ")} }`;
1139
+ }
1140
+ if (target.kind === "ArrayPattern") {
1141
+ const elements = target.elements.map((el) => this.emitBindingTarget(el));
1142
+ while (elements.length > 0 && elements[elements.length - 1] === "") {
1143
+ elements.pop();
1144
+ }
1145
+ return `[${elements.join(", ")}]`;
1146
+ }
1147
+ return "_";
1148
+ }
1149
+ collectBindingNames(target) {
1150
+ return collectBindingNames(target);
1151
+ }
1152
+ // --- Expressions ---
1153
+ emitExpression(expr) {
1154
+ switch (expr.kind) {
1155
+ case "NumberLiteral":
1156
+ return expr.raw;
1157
+ case "StringLiteral":
1158
+ return this.emitStringLiteral(expr);
1159
+ case "TemplateLiteral":
1160
+ return this.emitTemplateLiteral(expr);
1161
+ case "TaggedTemplateExpression":
1162
+ return this.emitTaggedTemplateExpression(expr);
1163
+ case "BooleanLiteral":
1164
+ return expr.value ? "true" : "false";
1165
+ case "Identifier":
1166
+ case "UpperIdentifier":
1167
+ if (this.recordContracts.has(expr.name))
1168
+ throw new FunScriptError(`${expr.name} is a compile-time record contract, not a runtime schema. Validate data separately and use an explicit checked callback boundary for foreign functions.`, expr.span);
1169
+ if (expr.name === "Void")
1170
+ return "undefined";
1171
+ if (expr.name === "dbg" && !this.isUserBinding("dbg")) {
1172
+ return `((__v: any) => { console.log(__v); return __v; })`;
1173
+ }
1174
+ if (EFFECT_BUILTIN_MODULES.has(expr.name) &&
1175
+ !NATIVE_CONSTRUCTOR_NAMES.has(expr.name) &&
1176
+ !this.isUserBinding(expr.name)) {
1177
+ this.effectImports.add(expr.name);
1178
+ }
1179
+ const fields = this.recordFields(expr.name);
1180
+ if (fields) {
1181
+ const defaults = [...fields.entries()].filter(([_, info]) => info.defaultBinding);
1182
+ if (defaults.length > 0) {
1183
+ return `({ ...${expr.name}, ${defaults.map(([key, info]) => `${key}: ${info.defaultBinding}`).join(", ")} })`;
1184
+ }
1185
+ }
1186
+ return expr.name;
1187
+ case "Placeholder":
1188
+ return this.emitCtx.currentPlaceholderParam ?? "__placeholder";
1189
+ case "TypedHole":
1190
+ return `(() => { throw new Error("Typed hole reached: ${expr.label || "???"}"); })()`;
1191
+ case "PipelineExpression":
1192
+ return this.emitPipelineExpression(expr);
1193
+ case "BinaryExpression":
1194
+ return this.emitBinaryExpression(expr);
1195
+ case "UnaryExpression":
1196
+ return this.emitUnaryExpression(expr);
1197
+ case "CallExpression":
1198
+ return this.emitCallExpression(expr);
1199
+ case "MemberExpression": {
1200
+ const prop = expr.property.name;
1201
+ if (prop === "decodeJson" ||
1202
+ prop === "decodeJsonSync" ||
1203
+ prop === "encodeJson" ||
1204
+ prop === "encodeJsonSync") {
1205
+ this.effectImports.add("Schema");
1206
+ const schema = this.emitExpression(expr.object);
1207
+ let combinator = "Schema.decodeUnknownEffect";
1208
+ if (prop === "decodeJsonSync")
1209
+ combinator = "Schema.decodeUnknownSync";
1210
+ else if (prop === "encodeJson")
1211
+ combinator = "Schema.encodeEffect";
1212
+ else if (prop === "encodeJsonSync")
1213
+ combinator = "Schema.encodeSync";
1214
+ return `${combinator}(Schema.fromJsonString(${schema}))`;
1215
+ }
1216
+ const raw = `${this.emitExpression(expr.object)}.${this.emitMemberProperty(expr)}`;
1217
+ const field = this.recordField(expr);
1218
+ if (field?.defaultBinding)
1219
+ return field.defaultBinding;
1220
+ if (field?.optional) {
1221
+ this.effectImports.add("Option");
1222
+ return `Option.fromNullishOr(${raw})`;
1223
+ }
1224
+ return raw;
1225
+ }
1226
+ case "IndexExpression": {
1227
+ const raw = `${this.emitExpression(expr.object)}[${this.emitExpression(expr.index)}]`;
1228
+ const field = this.recordField(expr);
1229
+ if (field?.defaultBinding)
1230
+ return field.defaultBinding;
1231
+ if (field?.optional) {
1232
+ this.effectImports.add("Option");
1233
+ return `Option.fromNullishOr(${raw})`;
1234
+ }
1235
+ if (expr.index.kind === "StringLiteral") {
1236
+ return raw;
1237
+ }
1238
+ this.needsFromNullishOr = true;
1239
+ this.effectImports.add("Option");
1240
+ return `fromNullishOr(${raw})`;
1241
+ }
1242
+ case "RecordExpression":
1243
+ return this.emitRecordExpression(expr);
1244
+ case "ArrayExpression":
1245
+ return `[${expr.elements.map((e) => this.emitExpression(e)).join(", ")}]`;
1246
+ case "FunctionExpression":
1247
+ return this.emitFunctionExpression(expr);
1248
+ case "MutBlockExpression":
1249
+ this.needsMutative = true;
1250
+ return `create(${this.emitMutativeRecipe(expr)})`;
1251
+ case "MatchExpression":
1252
+ return this.emitMatchExpression(expr);
1253
+ case "EffectBlockExpression":
1254
+ return this.emitEffectBlockExpression(expr);
1255
+ case "ParBlockExpression":
1256
+ return this.emitParBlockExpression(expr);
1257
+ case "JSXElement":
1258
+ return this.emitJsxElement(expr);
1259
+ case "JSXSelfClosingElement":
1260
+ return this.emitJsxSelfClosingElement(expr);
1261
+ case "JsExpression":
1262
+ return this.emitJsExpression(expr);
1263
+ case "TsEscapeExpression":
1264
+ return expr.code;
1265
+ case "SpreadElement":
1266
+ return `...${this.emitExpression(expr.argument)}`;
1267
+ }
1268
+ }
1269
+ emitJsExpression(expr) {
1270
+ this.needsJsInterop = true;
1271
+ // compiler.ts replaces this provisional flag with the nullability inferred
1272
+ // from the native TypeScript return type.
1273
+ const inner = this.emitInTryContext(expr.expression);
1274
+ if (expr.expression.kind === "FunctionExpression" &&
1275
+ expr.expression.params.length === 0) {
1276
+ return `__funscriptJs(${inner}, false)`;
1277
+ }
1278
+ const wrapped = expr.expression.kind === "RecordExpression" ? `(${inner})` : inner;
1279
+ return `__funscriptJs(() => ${wrapped}, false)`;
1280
+ }
1281
+ emitMemberProperty(expr) {
1282
+ if (expr.object.kind === "UpperIdentifier" &&
1283
+ expr.object.name === "Effect") {
1284
+ const replacement = expr.property.name === "catchAll"
1285
+ ? "catch"
1286
+ : expr.property.name === "fork"
1287
+ ? "forkChild"
1288
+ : undefined;
1289
+ if (replacement) {
1290
+ throw new FunScriptError(`Effect.${expr.property.name} was removed; use Effect.${replacement} instead.`, expr.span);
1291
+ }
1292
+ }
1293
+ return expr.property.name;
1294
+ }
1295
+ emitMutativeRecipe(expr) {
1296
+ return emitMutativeRecipe(this, expr);
1297
+ }
1298
+ emitStringLiteral(lit) {
1299
+ if (lit.parts.length === 1 && lit.parts[0].kind === "StringRawPart") {
1300
+ return JSON.stringify(lit.parts[0].value);
1301
+ }
1302
+ const template = lit.parts
1303
+ .map((p) => {
1304
+ if (p.kind === "StringRawPart")
1305
+ return p.value.replace(/`/g, "\\`").replace(/\${/g, "\\${");
1306
+ return `\${${this.emitExpression(p.expression)}}`;
1307
+ })
1308
+ .join("");
1309
+ return `\`${template}\``;
1310
+ }
1311
+ emitTemplateLiteral(lit) {
1312
+ const template = lit.parts
1313
+ .map((p) => {
1314
+ if (p.kind === "StringRawPart")
1315
+ return p.value.replace(/`/g, "\\`").replace(/\${/g, "\\${");
1316
+ return `\${${this.emitExpression(p.expression)}}`;
1317
+ })
1318
+ .join("");
1319
+ return `\`${template}\``;
1320
+ }
1321
+ emitTaggedTemplateExpression(expr) {
1322
+ const tag = this.emitExpression(expr.tag);
1323
+ let typeArgs = "";
1324
+ if (expr.typeArguments && expr.typeArguments.length > 0) {
1325
+ typeArgs =
1326
+ "<" +
1327
+ expr.typeArguments.map((t) => this.emitTypeNode(t)).join(", ") +
1328
+ ">";
1329
+ }
1330
+ return `${tag}${typeArgs}${this.emitTemplateLiteral(expr.template)}`;
1331
+ }
1332
+ emitCallExpression(expr) {
1333
+ if (!this.isUserBinding("dbg") &&
1334
+ expr.callee.kind === "Identifier" &&
1335
+ expr.callee.name === "dbg") {
1336
+ if (expr.args.length === 1) {
1337
+ const val = this.emitExpression(expr.args[0]);
1338
+ return `((__v) => { console.log(__v); return __v; })(${val})`;
1339
+ }
1340
+ if (expr.args.length >= 2) {
1341
+ const label = this.emitExpression(expr.args[0]);
1342
+ const val = this.emitExpression(expr.args[1]);
1343
+ return `((__v) => { console.log(${label}, __v); return __v; })(${val})`;
1344
+ }
1345
+ return `((__v: any) => { console.log(__v); return __v; })`;
1346
+ }
1347
+ if (expr.callee.kind === "Identifier" &&
1348
+ !this.isUserBinding(expr.callee.name)) {
1349
+ const name = expr.callee.name;
1350
+ if (name === "decodeJson" ||
1351
+ name === "decodeJsonSync" ||
1352
+ name === "encodeJson" ||
1353
+ name === "encodeJsonSync") {
1354
+ this.effectImports.add("Schema");
1355
+ const schema = expr.args.length > 0
1356
+ ? this.emitExpression(expr.args[0])
1357
+ : "Schema.Unknown";
1358
+ let combinator = "Schema.decodeUnknownEffect";
1359
+ if (name === "decodeJsonSync")
1360
+ combinator = "Schema.decodeUnknownSync";
1361
+ else if (name === "encodeJson")
1362
+ combinator = "Schema.encodeEffect";
1363
+ else if (name === "encodeJsonSync")
1364
+ combinator = "Schema.encodeSync";
1365
+ const codec = `${combinator}(Schema.fromJsonString(${schema}))`;
1366
+ if (expr.args.length >= 2) {
1367
+ const target = this.emitExpression(expr.args[1]);
1368
+ return `${codec}(${target})`;
1369
+ }
1370
+ return codec;
1371
+ }
1372
+ }
1373
+ if (expr.callee.kind === "MemberExpression" &&
1374
+ (expr.callee.property.name === "decodeJson" ||
1375
+ expr.callee.property.name === "decodeJsonSync" ||
1376
+ expr.callee.property.name === "encodeJson" ||
1377
+ expr.callee.property.name === "encodeJsonSync")) {
1378
+ this.effectImports.add("Schema");
1379
+ const schema = this.emitExpression(expr.callee.object);
1380
+ const prop = expr.callee.property.name;
1381
+ let combinator = "Schema.decodeUnknownEffect";
1382
+ if (prop === "decodeJsonSync")
1383
+ combinator = "Schema.decodeUnknownSync";
1384
+ else if (prop === "encodeJson")
1385
+ combinator = "Schema.encodeEffect";
1386
+ else if (prop === "encodeJsonSync")
1387
+ combinator = "Schema.encodeSync";
1388
+ const codec = `${combinator}(Schema.fromJsonString(${schema}))`;
1389
+ if (expr.args.length >= 1) {
1390
+ const target = this.emitExpression(expr.args[0]);
1391
+ return `${codec}(${target})`;
1392
+ }
1393
+ return codec;
1394
+ }
1395
+ if (expr.callee.kind === "MemberExpression" &&
1396
+ (expr.callee.object.kind === "Identifier" ||
1397
+ expr.callee.object.kind === "UpperIdentifier") &&
1398
+ expr.callee.object.name === "Option" &&
1399
+ expr.callee.property.name === "fromNullishOrElse") {
1400
+ this.needsFromNullishOrElse = true;
1401
+ this.effectImports.add("Option");
1402
+ return `fromNullishOrElse(${expr.args.map((a) => this.emitExpression(a)).join(", ")})`;
1403
+ }
1404
+ if (expr.callee.kind === "MemberExpression" &&
1405
+ (expr.callee.object.kind === "Identifier" ||
1406
+ expr.callee.object.kind === "UpperIdentifier") &&
1407
+ expr.callee.object.name === "Option" &&
1408
+ expr.callee.property.name === "fromNullishOr") {
1409
+ this.needsFromNullishOr = true;
1410
+ this.effectImports.add("Option");
1411
+ return `fromNullishOr(${expr.args.map((a) => this.emitExpression(a)).join(", ")})`;
1412
+ }
1413
+ if (expr.callee.kind === "Identifier" &&
1414
+ expr.callee.name === "fromNullishOr" &&
1415
+ !this.isUserBinding("fromNullishOr")) {
1416
+ this.needsFromNullishOr = true;
1417
+ this.effectImports.add("Option");
1418
+ return `fromNullishOr(${expr.args.map((a) => this.emitExpression(a)).join(", ")})`;
1419
+ }
1420
+ if (expr.callee.kind === "Identifier" &&
1421
+ expr.callee.name === "fromNullishOrElse" &&
1422
+ !this.isUserBinding("fromNullishOrElse")) {
1423
+ this.needsFromNullishOrElse = true;
1424
+ this.effectImports.add("Option");
1425
+ return `fromNullishOrElse(${expr.args.map((a) => this.emitExpression(a)).join(", ")})`;
1426
+ }
1427
+ if (expr.callee.kind === "Identifier" &&
1428
+ (expr.callee.name === "parseInt" || expr.callee.name === "parseFloat")) {
1429
+ throw new FunScriptError(`'${expr.callee.name}()' is banned by the Effect style guide because it produces NaN on invalid input. Use 'Number.parse(s)' instead for total parsing returning Option<number>.`, expr.callee.span);
1430
+ }
1431
+ if ((expr.callee.kind === "UpperIdentifier" ||
1432
+ expr.callee.kind === "Identifier") &&
1433
+ expr.callee.name === "URL" &&
1434
+ !this.emitCtx.inTryContext) {
1435
+ throw new FunScriptError(`'URL(...)' is unsafe because URL constructors throw on malformed input. Guard it with 'js URL(...)', 'Result.try(() => URL(...))', or 'Option.try(() => URL(...))'.`, expr.callee.span);
1436
+ }
1437
+ if (expr.callee.kind === "MemberExpression" &&
1438
+ (expr.callee.object.kind === "Identifier" ||
1439
+ expr.callee.object.kind === "UpperIdentifier") &&
1440
+ expr.callee.object.name === "Option" &&
1441
+ expr.callee.property.name === "try") {
1442
+ this.needsOptionTry = true;
1443
+ this.effectImports.add("Option");
1444
+ const emittedArgs = expr.args.map((a) => this.emitTryArgument(a));
1445
+ return `optionTry(${emittedArgs.join(", ")})`;
1446
+ }
1447
+ if (expr.callee.kind === "MemberExpression" &&
1448
+ (expr.callee.object.kind === "Identifier" ||
1449
+ expr.callee.object.kind === "UpperIdentifier") &&
1450
+ expr.callee.object.name === "Result" &&
1451
+ expr.callee.property.name === "try") {
1452
+ this.effectImports.add("Result");
1453
+ const emittedArgs = expr.args.map((a) => this.emitTryArgument(a));
1454
+ return `Result.try(${emittedArgs.join(", ")})`;
1455
+ }
1456
+ if (expr.callee.kind === "MemberExpression") {
1457
+ const prop = expr.callee.property.name;
1458
+ const root = getRootCalleeName(expr.callee.object);
1459
+ const objName = expr.callee.object.kind === "Identifier" ||
1460
+ expr.callee.object.kind === "UpperIdentifier"
1461
+ ? expr.callee.object.name
1462
+ : null;
1463
+ if ((objName === "Number" || objName === "globalThis") &&
1464
+ (prop === "parseInt" || prop === "parseFloat")) {
1465
+ throw new FunScriptError(`'${objName}.${prop}()' is banned by the Effect style guide because it produces NaN on invalid input. Use 'Number.parse(s)' instead for total parsing returning Option<number>.`, expr.callee.property.span);
1466
+ }
1467
+ if ((objName === "JSON" || objName === "globalThis") &&
1468
+ prop === "parse" &&
1469
+ !this.emitCtx.inTryContext) {
1470
+ throw new FunScriptError(`'JSON.parse()' is unsafe because it throws on malformed input. Guard it with 'js JSON.parse(...)', 'Result.try(() => JSON.parse(...))', or use 'Schema.decodeUnknown'.`, expr.callee.property.span);
1471
+ }
1472
+ if ((objName === "Math" || objName === "globalThis") &&
1473
+ prop === "random") {
1474
+ throw new FunScriptError(`'Math.random()' is banned by the Effect style guide because it is unmanaged and non-deterministic. Use 'Random.next' or 'Random.nextIntBetween' instead.`, expr.callee.property.span);
1475
+ }
1476
+ if ((expr.callee.object.kind === "Identifier" ||
1477
+ expr.callee.object.kind === "UpperIdentifier") &&
1478
+ expr.callee.object.name === "Object" &&
1479
+ BANNED_OBJECT_STATIC_METHODS.has(prop)) {
1480
+ const replacement = BANNED_OBJECT_STATIC_METHODS.get(prop);
1481
+ throw new FunScriptError(`'Object.${prop}()' is banned by the Effect style guide. Use ${replacement} instead.`, expr.callee.property.span);
1482
+ }
1483
+ const isAllowed = root !== null &&
1484
+ (root[0] === root[0].toUpperCase() ||
1485
+ EFFECT_MODULE_NAMES.has(root) ||
1486
+ EFFECT_BUILTIN_MODULES.has(root));
1487
+ if (!isAllowed &&
1488
+ !this.activeDraftParams.has(root ?? "") &&
1489
+ BANNED_INSTANCE_METHODS.has(prop)) {
1490
+ const info = BANNED_INSTANCE_METHODS.get(prop);
1491
+ if (this.isTargetNativeCategory(expr.callee.object, info.category, prop)) {
1492
+ if (["push", "pop", "shift", "unshift", "splice"].includes(prop)) {
1493
+ throw new FunScriptError(`In-place mutation '.${prop}()' is quarantined in FunkScript. Use '${info.replacement}(...)' or pipeline '${info.pipeline}' instead, or isolate mutable edits inside 'mut (draft) => { ... }'.`, expr.callee.property.span);
1494
+ }
1495
+ else {
1496
+ throw new FunScriptError(`Native ${info.category} method '.${prop}()' is banned by the Effect style guide. Use '${info.replacement}(...)' or pipeline '${info.pipeline}' instead.`, expr.callee.property.span);
1497
+ }
1498
+ }
1499
+ }
1500
+ if ((expr.callee.object.kind === "Identifier" ||
1501
+ expr.callee.object.kind === "UpperIdentifier") &&
1502
+ EFFECT_BUILTIN_MODULES.has(expr.callee.object.name)) {
1503
+ this.effectImports.add(expr.callee.object.name);
1504
+ }
1505
+ }
1506
+ if ((expr.callee.kind === "UpperIdentifier" ||
1507
+ expr.callee.kind === "Identifier") &&
1508
+ (expr.callee.name === "Map" || expr.callee.name === "WeakMap") &&
1509
+ expr.args.length === 1 &&
1510
+ !this.bindings.has(expr.callee.name) &&
1511
+ !this.declaredTypeNames.has(expr.callee.name)) {
1512
+ return `new ${expr.callee.name}(${this.emitExpression(expr.args[0])} as any)`;
1513
+ }
1514
+ if (this.options.constructorCalls?.has(expr.callee.span.end.offset)) {
1515
+ return `new ${this.emitExpression(expr.callee)}(${expr.args.map((a) => this.emitExpression(a)).join(", ")})`;
1516
+ }
1517
+ if ((expr.callee.kind === "UpperIdentifier" ||
1518
+ expr.callee.kind === "Identifier") &&
1519
+ AUTO_NEW_CONSTRUCTORS.has(expr.callee.name) &&
1520
+ !this.bindings.has(expr.callee.name) &&
1521
+ !this.declaredTypeNames.has(expr.callee.name)) {
1522
+ return `new ${expr.callee.name}(${expr.args.map((a) => this.emitExpression(a)).join(", ")})`;
1523
+ }
1524
+ if (expr.callee.kind === "MemberExpression" &&
1525
+ AUTO_NEW_CONSTRUCTORS.has(expr.callee.property.name) &&
1526
+ expr.callee.object.kind === "Identifier" &&
1527
+ (expr.callee.object.name === "globalThis" ||
1528
+ expr.callee.object.name === "window")) {
1529
+ return `new ${this.emitExpression(expr.callee)}(${expr.args.map((a) => this.emitExpression(a)).join(", ")})`;
1530
+ }
1531
+ if ((expr.callee.kind === "UpperIdentifier" ||
1532
+ expr.callee.kind === "Identifier") &&
1533
+ expr.callee.name === "Brand") {
1534
+ this.effectImports.add("Schema");
1535
+ return `Schema.brand(${expr.args.map((a) => this.emitExpression(a)).join(", ")})`;
1536
+ }
1537
+ const isPipelineStageCall = this.emitCtx.inPipelineStage;
1538
+ return this.withEmitContext({ inPipelineStage: false }, () => {
1539
+ if (this.options.markPipelineSources &&
1540
+ !isPipelineStageCall &&
1541
+ expr.callee.kind === "Identifier" &&
1542
+ expr.args.length >= 1) {
1543
+ const fnName = expr.callee.name;
1544
+ if (fnName in COMPARISON_METHOD_MAP ||
1545
+ (!this.bindings.has(fnName) && !this.userEffectBindings.has(fnName))) {
1546
+ const firstArg = this.emitExpression(expr.args[0]);
1547
+ const restArgs = expr.args
1548
+ .slice(1)
1549
+ .map((a) => this.emitExpression(a));
1550
+ const markedFirstArg = `__funscriptDirectCall(${expr.span.start.offset}, ${firstArg})`;
1551
+ return `${fnName}(${[markedFirstArg, ...restArgs].join(", ")})`;
1552
+ }
1553
+ }
1554
+ if (this.options.directCallResolutions?.has(expr.span.start.offset)) {
1555
+ const res = this.options.directCallResolutions.get(expr.span.start.offset);
1556
+ if (isEffectModule(res.module)) {
1557
+ this.effectImports.add(res.module);
1558
+ }
1559
+ const callee = `${res.module}.${res.method ?? expr.callee.name}`;
1560
+ return `${callee}(${expr.args.map((a) => this.emitExpression(a)).join(", ")})`;
1561
+ }
1562
+ if (expr.callee.kind === "Identifier" &&
1563
+ !this.bindings.has(expr.callee.name) &&
1564
+ ES_TOOLKIT_METHODS.has(expr.callee.name)) {
1565
+ this.esToolkitImports.add(expr.callee.name);
1566
+ }
1567
+ const emittedCallee = this.emitExpression(expr.callee);
1568
+ const calleeCode = this.options.markCallCallees && !isPipelineStageCall
1569
+ ? `__funscriptCallCallee(${expr.callee.span.end.offset}, ${emittedCallee})`
1570
+ : emittedCallee;
1571
+ return `${calleeCode}(${expr.args
1572
+ .map((a) => {
1573
+ const emitted = this.emitExpression(a);
1574
+ if (this.options.forwardNullArguments?.has(a.span.start.offset)) {
1575
+ this.effectImports.add("Option");
1576
+ return `Option.getOrNull(${emitted})`;
1577
+ }
1578
+ if (this.options.forwardOptionalArguments?.has(a.span.start.offset)) {
1579
+ this.effectImports.add("Option");
1580
+ return `Option.getOrUndefined(${emitted})`;
1581
+ }
1582
+ return this.options.markCallArguments
1583
+ ? `__funscriptCallArgument(${a.span.start.offset}, ${emitted})`
1584
+ : emitted;
1585
+ })
1586
+ .join(", ")})`;
1587
+ });
1588
+ }
1589
+ emitPipelineExpression(expr) {
1590
+ this.effectImports.add("pipe");
1591
+ const resolver = new PipelineResolver({
1592
+ bindings: this.bindings,
1593
+ pipelineCompanions: this.options.pipelineCompanions,
1594
+ allowAmbiguousPipeline: this.options.allowAmbiguousPipeline,
1595
+ isUserBinding: (name) => this.isUserBinding(name),
1596
+ effectImports: this.effectImports,
1597
+ esToolkitImports: this.esToolkitImports,
1598
+ requireDecodeUnknown: () => {
1599
+ this.needsDecodeUnknown = true;
1600
+ },
1601
+ });
1602
+ // Flatten left-nested pipelines: a |> b |> c
1603
+ const stages = [];
1604
+ let curr = expr;
1605
+ let deferredSource = false;
1606
+ while (curr.kind === "PipelineExpression") {
1607
+ stages.unshift(curr.right);
1608
+ if (curr.deferred) {
1609
+ deferredSource = true;
1610
+ curr = curr.left;
1611
+ break;
1612
+ }
1613
+ curr = curr.left;
1614
+ }
1615
+ stages.unshift(curr);
1616
+ let preferredCompanion = resolver.inferPipelineCompanion(stages[0]);
1617
+ const emittedStages = stages.map((s, idx) => {
1618
+ if (idx === 0) {
1619
+ return this.withEmitContext({ inPipelineStage: false }, () => {
1620
+ const value = this.emitExpression(s);
1621
+ const emitted = deferredSource ? `() => (${value})` : value;
1622
+ return this.options.markPipelineSources
1623
+ ? `__funscriptPipelineSource(${s.span.start.offset}, ${emitted})`
1624
+ : emitted;
1625
+ });
1626
+ }
1627
+ return this.withEmitContext({ inPipelineStage: true }, () => {
1628
+ if (idx === 1 &&
1629
+ deferredSource &&
1630
+ s.kind === "Identifier" &&
1631
+ [
1632
+ "sync",
1633
+ "suspend",
1634
+ "promise",
1635
+ "try",
1636
+ "tryPromise",
1637
+ "failSync",
1638
+ ].includes(s.name) &&
1639
+ !this.isUserBinding(s.name)) {
1640
+ this.effectImports.add("Effect");
1641
+ return s.name === "try" || s.name === "tryPromise"
1642
+ ? `(__thunk) => Effect.${s.name}(__thunk)`
1643
+ : `Effect.${s.name}`;
1644
+ }
1645
+ if (idx === 1 &&
1646
+ deferredSource &&
1647
+ s.kind === "MemberExpression" &&
1648
+ s.object.kind === "UpperIdentifier" &&
1649
+ s.object.name === "Effect" &&
1650
+ (s.property.name === "try" || s.property.name === "tryPromise")) {
1651
+ this.effectImports.add("Effect");
1652
+ return `(__thunk) => Effect.${s.property.name}(__thunk)`;
1653
+ }
1654
+ if (s.kind === "MatchExpression" && s.isCatch) {
1655
+ return this.emitMatchExpression(s);
1656
+ }
1657
+ if (s.kind === "MutBlockExpression") {
1658
+ this.needsMutative = true;
1659
+ return `(__mutInput) => create(__mutInput, ${this.emitMutativeRecipe(s)})`;
1660
+ }
1661
+ if (!this.isUserBinding("fromNullishOr")) {
1662
+ if (s.kind === "Identifier" && s.name === "fromNullishOr") {
1663
+ this.needsFromNullishOr = true;
1664
+ this.effectImports.add("Option");
1665
+ return `fromNullishOr`;
1666
+ }
1667
+ }
1668
+ if (!this.isUserBinding("fromNullishOrElse")) {
1669
+ if (s.kind === "CallExpression" &&
1670
+ s.callee.kind === "Identifier" &&
1671
+ s.callee.name === "fromNullishOrElse") {
1672
+ this.needsFromNullishOrElse = true;
1673
+ this.effectImports.add("Option");
1674
+ return `fromNullishOrElse(${s.args.map((a) => this.emitExpression(a)).join(", ")})`;
1675
+ }
1676
+ }
1677
+ if (!this.isUserBinding("dbg")) {
1678
+ if (s.kind === "Identifier" && s.name === "dbg") {
1679
+ return `((__v) => { console.log(__v); return __v; })`;
1680
+ }
1681
+ if (s.kind === "CallExpression" &&
1682
+ s.callee.kind === "Identifier" &&
1683
+ s.callee.name === "dbg") {
1684
+ const labelArg = s.args.length > 0 ? this.emitExpression(s.args[0]) : undefined;
1685
+ const logCall = labelArg
1686
+ ? `console.log(${labelArg}, __v)`
1687
+ : `console.log(__v)`;
1688
+ return `((__v) => { ${logCall}; return __v; })`;
1689
+ }
1690
+ }
1691
+ // Check if stage was resolved by type-directed resolution
1692
+ if (this.options.stageResolutions?.has(s.span.start.offset)) {
1693
+ const res = this.options.stageResolutions.get(s.span.start.offset);
1694
+ if (isEffectModule(res.module)) {
1695
+ this.effectImports.add(res.module);
1696
+ }
1697
+ if (res.module === "Effect" &&
1698
+ (res.method === "retry" ||
1699
+ (s.kind === "CallExpression" &&
1700
+ s.callee.name === "retry"))) {
1701
+ const resolved = resolver.resolvePipelineStage(s, "Effect");
1702
+ return this.emitExpression(resolved);
1703
+ }
1704
+ if (s.kind === "Identifier" || s.kind === "UpperIdentifier") {
1705
+ return `${res.module}.${res.method ?? s.name}`;
1706
+ }
1707
+ if (s.kind === "CallExpression") {
1708
+ const callee = s.callee;
1709
+ if (res.module === "Schema" &&
1710
+ (res.method === "decode" ||
1711
+ (!res.method && callee.name === "decode"))) {
1712
+ this.needsDecodeUnknown = true;
1713
+ }
1714
+ const method = res.module === "Schema" &&
1715
+ (res.method === "decode" ||
1716
+ (!res.method && callee.name === "decode"))
1717
+ ? "decodeUnknown"
1718
+ : (res.method ?? callee.name);
1719
+ const calleeName = `${res.module}.${method}`;
1720
+ if (resolver.hasPlaceholder(s)) {
1721
+ const placeholderParam = this.emitCtx.currentPlaceholderParam
1722
+ ? `__p${++this.placeholderCounter}`
1723
+ : "__p";
1724
+ return this.withEmitContext({ currentPlaceholderParam: placeholderParam }, () => {
1725
+ const args = s.args
1726
+ .map((a) => this.emitExpression(a))
1727
+ .join(", ");
1728
+ return `(${placeholderParam}) => ${calleeName}(${args})`;
1729
+ });
1730
+ }
1731
+ const args = s.args.map((a) => this.emitExpression(a)).join(", ");
1732
+ return `${calleeName}(${args})`;
1733
+ }
1734
+ }
1735
+ // Auto-namespace resolution for pipeline stage callee
1736
+ resolver.assertPipelineStageIsNotAmbiguous(s, preferredCompanion);
1737
+ const resolvedStage = resolver.resolvePipelineStage(s, preferredCompanion);
1738
+ // `js`, `runPromise`, and `runSync` run an Effect and leave the Effect pipeline domain.
1739
+ const isEffectRunner = (s.kind === "Identifier" &&
1740
+ (s.name === "js" ||
1741
+ s.name === "runPromise" ||
1742
+ s.name === "runSync")) ||
1743
+ (s.kind === "CallExpression" &&
1744
+ s.callee.kind === "Identifier" &&
1745
+ (s.callee.name === "runPromise" || s.callee.name === "runSync") &&
1746
+ s.args.length === 0);
1747
+ if (isEffectRunner)
1748
+ preferredCompanion = undefined;
1749
+ // Check if stage has placeholder '_'
1750
+ if (resolver.hasPlaceholder(resolvedStage)) {
1751
+ const placeholderParam = this.emitCtx.currentPlaceholderParam
1752
+ ? `__p${++this.placeholderCounter}`
1753
+ : "__p";
1754
+ return this.withEmitContext({ currentPlaceholderParam: placeholderParam }, () => {
1755
+ const body = this.emitExpression(resolvedStage);
1756
+ const formattedBody = resolvedStage.kind === "RecordExpression" ? `(${body})` : body;
1757
+ return `(${placeholderParam}) => ${formattedBody}`;
1758
+ });
1759
+ }
1760
+ if (idx === 1 && s.kind === "MatchExpression" && !s.isCatch) {
1761
+ return this.emitMatchExpression(s, this.getTypeNodeForExpression(stages[0]), stages[0]);
1762
+ }
1763
+ return this.emitExpression(resolvedStage);
1764
+ });
1765
+ });
1766
+ const checkedStages = this.options.markPipelineSources
1767
+ ? emittedStages.map((stage, index) => index === 0
1768
+ ? stage
1769
+ : `(__funscriptPipelineValue) => (${stage})(__funscriptPipelineStageInput(${stages[index].span.start.offset}, __funscriptPipelineValue))`)
1770
+ : emittedStages;
1771
+ return `pipe(\n ${checkedStages.join(",\n ")}\n)`;
1772
+ }
1773
+ isUserBinding(name) {
1774
+ return (this.bindings.has(name) ||
1775
+ this.userImportBindings.has(name) ||
1776
+ this.userEffectBindings.has(name) ||
1777
+ this.userEsToolkitBindings.has(name) ||
1778
+ this.declaredTypeNames.has(name) ||
1779
+ this.parameterScopes.some((scope) => scope.has(name)));
1780
+ }
1781
+ emitBinaryExpression(expr) {
1782
+ const emitOperand = (operand) => {
1783
+ const emitted = this.emitExpression(operand);
1784
+ return operand.kind === "FunctionExpression" ? `(${emitted})` : emitted;
1785
+ };
1786
+ let left = emitOperand(expr.left);
1787
+ const right = emitOperand(expr.right);
1788
+ // A left-nested addition already has JavaScript's default grouping. Keep
1789
+ // right-nested additions parenthesized: strings and floating point values
1790
+ // make reassociation observable.
1791
+ if (expr.operator === "+" &&
1792
+ expr.left.kind === "BinaryExpression" &&
1793
+ expr.left.operator === "+" &&
1794
+ left.startsWith("(") &&
1795
+ left.endsWith(")")) {
1796
+ left = left.slice(1, -1);
1797
+ }
1798
+ const markBoolean = (operand, emitted) => this.options.markBooleanOperands
1799
+ ? `__funscriptBooleanOperand(${operand.span.start.offset}, ${JSON.stringify(expr.operator)}, ${emitted})`
1800
+ : emitted;
1801
+ switch (expr.operator) {
1802
+ case "and":
1803
+ return `(${markBoolean(expr.left, left)} && ${markBoolean(expr.right, right)})`;
1804
+ case "or":
1805
+ return `(${markBoolean(expr.left, left)} || ${markBoolean(expr.right, right)})`;
1806
+ case "@=":
1807
+ if (this.isPrimitive(expr.left) || this.isPrimitive(expr.right)) {
1808
+ throw new Error(`Reference identity operator '@=' cannot be used with primitive values; use '#=' or '#!' for value equality`);
1809
+ }
1810
+ this.needsReferenceEquality = true;
1811
+ return `referenceEquals(${left}, ${right})`;
1812
+ case "@!":
1813
+ if (this.isPrimitive(expr.left) || this.isPrimitive(expr.right)) {
1814
+ throw new Error(`Reference identity operator '@!' cannot be used with primitive values; use '#=' or '#!' for value equality`);
1815
+ }
1816
+ this.needsReferenceEquality = true;
1817
+ return `(!referenceEquals(${left}, ${right}))`;
1818
+ case "#=":
1819
+ if (this.isPrimitive(expr.left) || this.isPrimitive(expr.right)) {
1820
+ return `(${left} === ${right})`;
1821
+ }
1822
+ this.effectImports.add("Equal");
1823
+ return `Equal.equals(${left}, ${right})`;
1824
+ case "#!":
1825
+ if (this.isPrimitive(expr.left) || this.isPrimitive(expr.right)) {
1826
+ return `(${left} !== ${right})`;
1827
+ }
1828
+ this.effectImports.add("Equal");
1829
+ return `(!Equal.equals(${left}, ${right}))`;
1830
+ case "<":
1831
+ case "<=":
1832
+ case ">":
1833
+ case ">=": {
1834
+ if (!this.options.markNumericComparisonOperands) {
1835
+ return `(${left} ${expr.operator} ${right})`;
1836
+ }
1837
+ const mark = (operand, offset) => `__funscriptNumericOperand(${offset}, ${JSON.stringify(expr.operator)}, ${operand})`;
1838
+ return `(${mark(left, expr.left.span.start.offset)} ${expr.operator} ${mark(right, expr.right.span.start.offset)})`;
1839
+ }
1840
+ default:
1841
+ return `(${left} ${expr.operator} ${right})`;
1842
+ }
1843
+ }
1844
+ emitUnaryExpression(expr) {
1845
+ const arg = this.emitExpression(expr.argument);
1846
+ if (expr.operator === "not")
1847
+ return `(!${arg})`;
1848
+ return `(-${arg})`;
1849
+ }
1850
+ emitInTryContext(arg) {
1851
+ if (arg.kind === "FunctionExpression") {
1852
+ return this.withEmitContext({ pendingTryThunk: true }, () => this.emitExpression(arg));
1853
+ }
1854
+ return this.withEmitContext({ inTryContext: true }, () => this.emitExpression(arg));
1855
+ }
1856
+ emitTryArgument(arg) {
1857
+ if (arg.kind === "RecordExpression") {
1858
+ return this.withEmitContext({ pendingTryRecord: true }, () => this.emitExpression(arg));
1859
+ }
1860
+ return this.emitInTryContext(arg);
1861
+ }
1862
+ emitRecordExpression(expr) {
1863
+ const isTryRecord = this.emitCtx.pendingTryRecord;
1864
+ return this.withEmitContext({ pendingTryRecord: false }, () => {
1865
+ const hasDotPaths = expr.entries.some((e) => e.kind === "DotPathEntry");
1866
+ if (hasDotPaths) {
1867
+ // Lower to Mutative create
1868
+ this.needsMutative = true;
1869
+ const baseSpread = expr.entries.find((e) => e.kind === "SpreadEntry");
1870
+ const base = baseSpread && "argument" in baseSpread
1871
+ ? this.emitExpression(baseSpread.argument)
1872
+ : "{}";
1873
+ const mutations = expr.entries
1874
+ .filter((e) => e.kind !== "SpreadEntry")
1875
+ .map((e) => {
1876
+ if (e.kind === "DotPathEntry") {
1877
+ return ` draft.${e.path.map((p) => p.name).join(".")} = ${this.emitExpression(e.value)};`;
1878
+ }
1879
+ if (e.kind === "FieldEntry") {
1880
+ const keyAccess = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e.key.name)
1881
+ ? `.${e.key.name}`
1882
+ : `[${JSON.stringify(e.key.name)}]`;
1883
+ return ` draft${keyAccess} = ${this.emitExpression(e.value)};`;
1884
+ }
1885
+ return ` draft.${e.key.name} = ${e.key.name};`;
1886
+ })
1887
+ .join("\n");
1888
+ return `create(${base}, (draft) => {\n${mutations}\n})`;
1889
+ }
1890
+ const DISCRIMINANT_RECORD_KEYS = new Set([
1891
+ "_tag",
1892
+ "type",
1893
+ "kind",
1894
+ "status",
1895
+ "code",
1896
+ "tag",
1897
+ "ok",
1898
+ "state",
1899
+ ]);
1900
+ const entries = expr.entries
1901
+ .map((e) => {
1902
+ if (e.kind === "SpreadEntry")
1903
+ return `...${this.emitExpression(e.argument)}`;
1904
+ if (e.kind === "FieldEntry" || e.kind === "ShorthandEntry") {
1905
+ const keyName = e.key.name;
1906
+ const valueExpr = e.kind === "FieldEntry" ? e.value : e.key;
1907
+ let val;
1908
+ if (isTryRecord && keyName === "try") {
1909
+ val = this.emitInTryContext(valueExpr);
1910
+ }
1911
+ else {
1912
+ val = this.emitExpression(valueExpr);
1913
+ }
1914
+ if (this.options.forwardNullProperties?.has(valueExpr.span.start.offset)) {
1915
+ this.effectImports.add("Option");
1916
+ return `[${JSON.stringify(keyName)}]: Option.getOrNull(${val})`;
1917
+ }
1918
+ if (this.options.forwardOptionalProperties?.has(valueExpr.span.start.offset)) {
1919
+ this.effectImports.add("Option");
1920
+ return `...((__value: import("effect").Option.Option<any>) => Option.isSome(__value) ? { [${JSON.stringify(keyName)}]: __value.value } : {})(${val})`;
1921
+ }
1922
+ if (this.options.markCallArguments)
1923
+ val = `__funscriptCallArgument(${valueExpr.span.start.offset}, ${val})`;
1924
+ if (valueExpr.kind === "BooleanLiteral") {
1925
+ val = `${val} as const`;
1926
+ }
1927
+ else if ((valueExpr.kind === "StringLiteral" ||
1928
+ valueExpr.kind === "NumberLiteral") &&
1929
+ DISCRIMINANT_RECORD_KEYS.has(keyName)) {
1930
+ val = `${val} as const`;
1931
+ }
1932
+ if (e.kind === "ShorthandEntry" &&
1933
+ !this.options.markCallArguments) {
1934
+ return keyName;
1935
+ }
1936
+ return `${emitPropertyKey(keyName)}: ${val}`;
1937
+ }
1938
+ return "";
1939
+ })
1940
+ .join(", ");
1941
+ return `{ ${entries} }`;
1942
+ });
1943
+ }
1944
+ emitNamedEffectFunction(expr, name) {
1945
+ return this.emitFunctionExpression(expr, name);
1946
+ }
1947
+ emitFunctionExpression(expr, traceName) {
1948
+ const isTryThunk = this.emitCtx.pendingTryThunk;
1949
+ const prevPrimitiveIdentifiers = new Set(this.primitiveIdentifiers);
1950
+ try {
1951
+ return this.withEmitContext({
1952
+ pendingTryThunk: false,
1953
+ inTryContext: isTryThunk,
1954
+ inPipelineStage: false,
1955
+ currentPlaceholderParam: null,
1956
+ }, () => {
1957
+ for (const p of expr.params) {
1958
+ const isPrim = this.isPrimitiveType(p.typeAnnotation);
1959
+ for (const n of this.collectBindingNames(p.name)) {
1960
+ if (isPrim) {
1961
+ this.primitiveIdentifiers.add(n);
1962
+ }
1963
+ else {
1964
+ this.primitiveIdentifiers.delete(n);
1965
+ }
1966
+ }
1967
+ }
1968
+ const params = expr.params
1969
+ .map((p, index) => {
1970
+ const rest = p.isRest ? "..." : "";
1971
+ let name = this.emitBindingTarget(p.name);
1972
+ if (p.name.kind === "RecordPattern") {
1973
+ let recType = p.typeAnnotation;
1974
+ if (recType?.kind === "TypeReferenceNode") {
1975
+ recType = this.getRecordTypeNode(recType.name.name);
1976
+ }
1977
+ const recFields = recType?.kind === "RecordTypeNode"
1978
+ ? extractRecordFields(recType, (name) => this.getRecordTypeNode(name))
1979
+ : undefined;
1980
+ if (patternHasOptionalField(p.name, recFields)) {
1981
+ name = `$funscriptParam${index}`;
1982
+ }
1983
+ }
1984
+ let typeAnn = "";
1985
+ if (p.typeAnnotation) {
1986
+ const base = this.emitTypeNode(p.typeAnnotation);
1987
+ typeAnn = `: ${base}`;
1988
+ }
1989
+ const defaultValue = p.defaultValue
1990
+ ? ` = ${this.emitExpression(p.defaultValue)}`
1991
+ : "";
1992
+ return `${rest}${name}${typeAnn}${defaultValue}`;
1993
+ })
1994
+ .join(", ");
1995
+ const typeParams = this.emitTypeParameters(expr.typeParams, true);
1996
+ const retType = expr.returnType
1997
+ ? `: ${this.emitTypeNode(expr.returnType)}`
1998
+ : "";
1999
+ const records = new Map();
2000
+ const recordDefaults = [];
2001
+ expr.params.forEach((param, paramIndex) => {
2002
+ if (param.name.kind === "RecordPattern") {
2003
+ let recType = param.typeAnnotation;
2004
+ if (recType?.kind === "TypeReferenceNode") {
2005
+ recType = this.getRecordTypeNode(recType.name.name);
2006
+ }
2007
+ const recFields = recType?.kind === "RecordTypeNode"
2008
+ ? extractRecordFields(recType, (name) => this.getRecordTypeNode(name))
2009
+ : undefined;
2010
+ if (patternHasOptionalField(param.name, recFields)) {
2011
+ recordDefaults.push(...emitUnpackedRecordPattern({
2012
+ pat: param.name,
2013
+ basePath: `$funscriptParam${paramIndex}`,
2014
+ fieldsMap: recFields,
2015
+ emitBindingTarget: (target) => this.emitBindingTarget(target),
2016
+ addEffectImport: (name) => this.effectImports.add(name),
2017
+ indent: " ",
2018
+ onRecordBinding: (varName, fields) => {
2019
+ records.set(varName, fields);
2020
+ },
2021
+ }));
2022
+ }
2023
+ return;
2024
+ }
2025
+ if (param.name.kind !== "Identifier")
2026
+ return;
2027
+ const paramName = param.name.name;
2028
+ const declared = param.typeAnnotation;
2029
+ if (this.isHtmlPropsType(declared)) {
2030
+ records.set(paramName, undefined);
2031
+ return;
2032
+ }
2033
+ const recordType = declared?.kind === "TypeReferenceNode"
2034
+ ? this.getRecordTypeNode(declared.name.name)
2035
+ : declared;
2036
+ if (recordType?.kind !== "RecordTypeNode") {
2037
+ records.set(paramName, undefined);
2038
+ return;
2039
+ }
2040
+ const fields = recordType.fields;
2041
+ const nestedFields = (type) => {
2042
+ if (type.kind !== "RecordTypeNode") {
2043
+ return undefined;
2044
+ }
2045
+ const result = new Map();
2046
+ for (const field of type.fields) {
2047
+ const children = nestedFields(field.typeAnnotation);
2048
+ result.set(field.name.name, {
2049
+ optional: Boolean(field.optional),
2050
+ fields: children,
2051
+ });
2052
+ }
2053
+ return [...result.values()].some((field) => field.optional || field.fields)
2054
+ ? result
2055
+ : undefined;
2056
+ };
2057
+ if (!fields.some((field) => field.optional ||
2058
+ field.defaultValue ||
2059
+ nestedFields(field.typeAnnotation))) {
2060
+ records.set(paramName, undefined);
2061
+ return;
2062
+ }
2063
+ const mapped = new Map();
2064
+ fields.forEach((field, fieldIndex) => {
2065
+ const binding = field.defaultValue
2066
+ ? `$funscriptField${paramIndex}_${fieldIndex}`
2067
+ : undefined;
2068
+ if (field.defaultValue) {
2069
+ const currentParamNames = new Set(this.collectBindingNames(expr.params[paramIndex].name));
2070
+ const subsequentParamNames = new Set(expr.params
2071
+ .slice(paramIndex + 1)
2072
+ .flatMap((p) => this.collectBindingNames(p.name)));
2073
+ this.validateRecordDefault(field.defaultValue, currentParamNames, subsequentParamNames);
2074
+ const raw = `$funscriptFieldRaw${paramIndex}_${fieldIndex}`;
2075
+ recordDefaults.push(` const ${raw} = ${paramName}.${field.name.name};`);
2076
+ recordDefaults.push(` const ${binding} = ${raw} === undefined ? ${this.emitExpression(field.defaultValue)} : ${raw};`);
2077
+ }
2078
+ const children = nestedFields(field.typeAnnotation);
2079
+ mapped.set(field.name.name, {
2080
+ optional: Boolean(field.optional),
2081
+ defaultBinding: binding,
2082
+ fields: children,
2083
+ });
2084
+ });
2085
+ records.set(paramName, mapped);
2086
+ });
2087
+ if (expr.body.kind === "BlockStatement") {
2088
+ for (const stmt of expr.body.statements) {
2089
+ if (stmt.kind !== "BindingDeclaration" ||
2090
+ stmt.isMut ||
2091
+ stmt.isJs ||
2092
+ !("name" in stmt.id) ||
2093
+ records.has(stmt.id.name))
2094
+ continue;
2095
+ if (stmt.init.kind === "Identifier") {
2096
+ const fields = records.get(stmt.init.name);
2097
+ if (!fields ||
2098
+ [...fields.values()].some((field) => field.defaultBinding))
2099
+ continue;
2100
+ records.set(stmt.id.name, fields);
2101
+ }
2102
+ else if (stmt.init.kind === "RecordExpression") {
2103
+ const fields = new Map();
2104
+ let hasTracked = false;
2105
+ for (const prop of stmt.init.entries) {
2106
+ if (prop.kind === "SpreadEntry") {
2107
+ if (prop.argument.kind === "Identifier") {
2108
+ const spreadFields = records.get(prop.argument.name);
2109
+ if (spreadFields) {
2110
+ for (const [key, info] of spreadFields) {
2111
+ if (info.optional)
2112
+ hasTracked = true;
2113
+ fields.set(key, {
2114
+ optional: info.optional,
2115
+ defaultBinding: undefined,
2116
+ fields: info.fields,
2117
+ });
2118
+ }
2119
+ }
2120
+ }
2121
+ }
2122
+ else if (prop.kind === "FieldEntry" ||
2123
+ prop.kind === "ShorthandEntry") {
2124
+ const keyName = prop.key.name;
2125
+ if (keyName) {
2126
+ fields.set(keyName, {
2127
+ optional: false,
2128
+ defaultBinding: undefined,
2129
+ fields: undefined,
2130
+ });
2131
+ }
2132
+ }
2133
+ }
2134
+ if (hasTracked) {
2135
+ records.set(stmt.id.name, fields);
2136
+ }
2137
+ }
2138
+ }
2139
+ }
2140
+ const paramScopeEntries = [];
2141
+ const varTypeEntries = [];
2142
+ for (const p of expr.params) {
2143
+ if (p.name.kind === "RecordPattern") {
2144
+ let recType = p.typeAnnotation;
2145
+ if (recType?.kind === "TypeReferenceNode") {
2146
+ recType = this.getRecordTypeNode(recType.name.name);
2147
+ }
2148
+ const recFields = recType?.kind === "RecordTypeNode"
2149
+ ? extractRecordFields(recType, (name) => this.getRecordTypeNode(name))
2150
+ : undefined;
2151
+ if (patternHasOptionalField(p.name, recFields)) {
2152
+ const collectParamsFromPattern = (pat, fieldsMap, typeNode, parentIsOpt = false) => {
2153
+ for (const f of pat.fields) {
2154
+ if (f.isRest) {
2155
+ paramScopeEntries.push([f.key.name, parentIsOpt]);
2156
+ varTypeEntries.push([f.key.name, undefined]);
2157
+ continue;
2158
+ }
2159
+ const info = fieldsMap?.get(f.key.name);
2160
+ const isOpt = parentIsOpt || info?.optional === true;
2161
+ const matchingFieldType = typeNode?.kind === "RecordTypeNode"
2162
+ ? typeNode.fields.find((tf) => tf.name.name === f.key.name)?.typeAnnotation
2163
+ : undefined;
2164
+ if (f.pattern?.kind === "RecordPattern") {
2165
+ let subType = matchingFieldType;
2166
+ if (subType?.kind === "TypeReferenceNode") {
2167
+ subType = this.getRecordTypeNode(subType.name.name);
2168
+ }
2169
+ collectParamsFromPattern(f.pattern, info?.fields, subType, isOpt);
2170
+ }
2171
+ else if (f.pattern?.kind === "ArrayPattern") {
2172
+ const elemType = matchingFieldType?.kind === "ArrayTypeNode"
2173
+ ? matchingFieldType.elementType
2174
+ : undefined;
2175
+ for (const el of f.pattern.elements) {
2176
+ for (const n of this.collectBindingNames(el)) {
2177
+ paramScopeEntries.push([n, isOpt]);
2178
+ varTypeEntries.push([n, elemType]);
2179
+ }
2180
+ }
2181
+ }
2182
+ else {
2183
+ const varName = f.pattern?.kind === "VariablePattern"
2184
+ ? f.pattern.name.name
2185
+ : f.key.name;
2186
+ paramScopeEntries.push([varName, isOpt]);
2187
+ varTypeEntries.push([varName, matchingFieldType]);
2188
+ }
2189
+ }
2190
+ };
2191
+ collectParamsFromPattern(p.name, recFields, recType);
2192
+ continue;
2193
+ }
2194
+ }
2195
+ for (const n of this.collectBindingNames(p.name)) {
2196
+ paramScopeEntries.push([n, false]);
2197
+ varTypeEntries.push([n, p.typeAnnotation]);
2198
+ }
2199
+ }
2200
+ this.parameterScopes.push(new Map(paramScopeEntries));
2201
+ this.variableTypeScopes.push(new Map(varTypeEntries));
2202
+ this.recordScopes.push(records);
2203
+ this.localBindingScopes.push(collectLocalBindings(expr.body.kind === "BlockStatement" ? expr.body.statements : []));
2204
+ try {
2205
+ if (traceName &&
2206
+ (expr.params.some((p) => p.defaultValue) ||
2207
+ recordDefaults.length > 0)) {
2208
+ const body = this.emitFunctionBody(expr.body);
2209
+ const defaults = recordDefaults.length
2210
+ ? `${recordDefaults.join("\n")}\n`
2211
+ : "";
2212
+ return `${typeParams}(${params})${retType} => {\n${defaults} return Effect.fn(${JSON.stringify(traceName)})(() => {\n ${indentContinuation(body, 2)}\n })();\n}`;
2213
+ }
2214
+ let result;
2215
+ if (expr.body.kind === "BlockStatement" || recordDefaults.length) {
2216
+ const body = this.emitFunctionBody(expr.body);
2217
+ result = `${typeParams}(${params})${retType} => {\n${[...recordDefaults, body].filter(Boolean).join("\n")}\n}`;
2218
+ }
2219
+ else {
2220
+ result = `${typeParams}(${params})${retType} => ${this.emitArrowExpression(expr.body)}`;
2221
+ }
2222
+ return traceName
2223
+ ? `Effect.fn(${JSON.stringify(traceName)})(${result})`
2224
+ : result;
2225
+ }
2226
+ finally {
2227
+ this.localBindingScopes.pop();
2228
+ this.recordScopes.pop();
2229
+ this.parameterScopes.pop();
2230
+ this.variableTypeScopes.pop();
2231
+ }
2232
+ });
2233
+ }
2234
+ finally {
2235
+ this.primitiveIdentifiers = prevPrimitiveIdentifiers;
2236
+ }
2237
+ }
2238
+ emitFunctionBody(body) {
2239
+ if (body.kind === "BlockStatement") {
2240
+ const stmts = body.statements
2241
+ .map((s) => " " + this.emitStatement(s))
2242
+ .join("\n");
2243
+ const isUnit = body.finalExpression &&
2244
+ (body.finalExpression.kind === "Identifier" ||
2245
+ body.finalExpression.kind === "UpperIdentifier") &&
2246
+ body.finalExpression.name === "Void";
2247
+ const ret = isUnit
2248
+ ? " return;"
2249
+ : body.finalExpression
2250
+ ? ` return ${this.indentReturnedExpression(body.finalExpression)};`
2251
+ : "";
2252
+ if (stmts && ret)
2253
+ return `${stmts}\n${ret}`;
2254
+ if (stmts)
2255
+ return stmts;
2256
+ if (ret)
2257
+ return ret;
2258
+ return "";
2259
+ }
2260
+ const isUnit = (body.kind === "Identifier" || body.kind === "UpperIdentifier") &&
2261
+ body.name === "Void";
2262
+ if (isUnit)
2263
+ return " return;";
2264
+ return ` return ${this.indentReturnedExpression(body)};`;
2265
+ }
2266
+ indentReturnedExpression(expr) {
2267
+ const emitted = this.emitExpression(expr);
2268
+ return expr.kind === "PipelineExpression" || expr.kind === "MatchExpression"
2269
+ ? indentContinuation(emitted, 2)
2270
+ : emitted;
2271
+ }
2272
+ emitArrowExpression(expr) {
2273
+ return emitArrowExpression(this, expr);
2274
+ }
2275
+ emitIndexTarget(expr) {
2276
+ return emitIndexTarget(this, expr);
2277
+ }
2278
+ emitStatement(stmt) {
2279
+ return emitStatement(this, stmt);
2280
+ }
2281
+ emitWhenStatement(stmt, insideEffect = false) {
2282
+ return emitWhenStatement(this, stmt, insideEffect);
2283
+ }
2284
+ emitMatchExpression(expr, pipelineScrutineeType, pipelineSource) {
2285
+ return new MatchEmitter({
2286
+ emitExpression: (expression) => this.emitExpression(expression),
2287
+ emitFunctionBody: (body) => this.emitFunctionBody(body),
2288
+ emitArrowExpression: (expression) => this.emitArrowExpression(expression),
2289
+ emitBindingTarget: (target) => this.emitBindingTarget(target),
2290
+ emitStringLiteral: (literal) => this.emitStringLiteral(literal),
2291
+ recordField: (expression) => this.recordField(expression),
2292
+ recordFields: (name) => this.recordFields(name),
2293
+ getRecordTypeNode: (name) => this.getRecordTypeNode(name),
2294
+ getVariantFields: (name) => this.variantFields.get(name),
2295
+ isTaggedUnionVariant: (type, variant) => this.taggedUnionVariants.get(type)?.has(variant) ?? false,
2296
+ recordContracts: this.recordContracts,
2297
+ isOptionalParameter: (name) => this.isOptionalParameter(name),
2298
+ isOptionalValue: (expression) => this.isOptionalValue(expression),
2299
+ addEffectImport: (name) => this.addEffectImport(name),
2300
+ getTypeNodeForExpression: (expression) => this.getTypeNodeForExpression(expression),
2301
+ emitTaggedMatch: (expression, arms, inputType, source) => emitTaggedMatch({
2302
+ taggedUnionVariants: this.taggedUnionVariants,
2303
+ taggedUnionParameters: this.taggedUnionParameters,
2304
+ localBindingScopes: this.localBindingScopes,
2305
+ importedTaggedUnionNames: this.importedTaggedUnionNames,
2306
+ getTypeNodeForExpression: (value) => this.getTypeNodeForExpression(value),
2307
+ parameterScopes: this.parameterScopes,
2308
+ bindings: this.bindings,
2309
+ importedTaggedFactories: this.importedTaggedFactories,
2310
+ collectBindingNames: (target) => this.collectBindingNames(target),
2311
+ emitExpression: (value) => this.emitExpression(value),
2312
+ emitTypeParameters: (params, arrow) => this.emitTypeParameters(params, arrow),
2313
+ }, expression, arms, inputType, source),
2314
+ requireTsPattern: () => {
2315
+ this.needsTsPattern = true;
2316
+ },
2317
+ enterOptionalPayload: (name, fields, _arm, payloadType) => {
2318
+ this.recordScopes.push(new Map([[name, fields]]));
2319
+ this.parameterScopes.push(new Map([[name, false]]));
2320
+ this.variableTypeScopes.push(new Map([[name, payloadType]]));
2321
+ },
2322
+ leaveOptionalPayload: () => {
2323
+ this.variableTypeScopes.pop();
2324
+ this.parameterScopes.pop();
2325
+ this.recordScopes.pop();
2326
+ },
2327
+ enterOptionalRecordPattern: (pattern, fields, _arm, payloadType) => {
2328
+ const recordScope = new Map();
2329
+ const paramScope = new Map();
2330
+ const varTypeScope = new Map();
2331
+ let typeFields;
2332
+ if (payloadType?.kind === "RecordTypeNode") {
2333
+ typeFields = payloadType.fields;
2334
+ }
2335
+ else if (payloadType?.kind === "TypeReferenceNode") {
2336
+ const contract = this.getRecordTypeNode(payloadType.name.name) ??
2337
+ this.recordContracts.get(payloadType.name.name);
2338
+ if (contract?.kind === "RecordTypeNode") {
2339
+ typeFields = contract.fields;
2340
+ }
2341
+ }
2342
+ const registerRecordPatternFields = (pat, fieldsMap, recordTypeFields) => {
2343
+ for (const f of pat.fields) {
2344
+ if (f.isRest) {
2345
+ paramScope.set(f.key.name, false);
2346
+ continue;
2347
+ }
2348
+ if (f.pattern?.kind === "WildcardPattern")
2349
+ continue;
2350
+ const info = fieldsMap?.get(f.key.name);
2351
+ const isOpt = info?.optional === true;
2352
+ const fieldTypeNode = recordTypeFields?.find((tf) => tf.name.name === f.key.name)?.typeAnnotation;
2353
+ if (f.pattern?.kind === "RecordPattern") {
2354
+ let subTypeFields;
2355
+ if (fieldTypeNode?.kind === "RecordTypeNode") {
2356
+ subTypeFields = fieldTypeNode.fields;
2357
+ }
2358
+ else if (fieldTypeNode?.kind === "TypeReferenceNode") {
2359
+ const contract = this.getRecordTypeNode(fieldTypeNode.name.name) ??
2360
+ this.recordContracts.get(fieldTypeNode.name.name);
2361
+ if (contract?.kind === "RecordTypeNode") {
2362
+ subTypeFields = contract.fields;
2363
+ }
2364
+ }
2365
+ registerRecordPatternFields(f.pattern, info?.fields, subTypeFields);
2366
+ }
2367
+ else {
2368
+ const varName = f.pattern?.kind === "VariablePattern"
2369
+ ? f.pattern.name.name
2370
+ : f.key.name;
2371
+ paramScope.set(varName, isOpt);
2372
+ if (info?.fields) {
2373
+ recordScope.set(varName, info.fields);
2374
+ }
2375
+ if (fieldTypeNode) {
2376
+ if (isOpt) {
2377
+ varTypeScope.set(varName, {
2378
+ kind: "TypeReferenceNode",
2379
+ name: { kind: "Identifier", name: "Option", span: f.span },
2380
+ typeArgs: [fieldTypeNode],
2381
+ span: f.span,
2382
+ });
2383
+ }
2384
+ else {
2385
+ varTypeScope.set(varName, fieldTypeNode);
2386
+ }
2387
+ }
2388
+ }
2389
+ }
2390
+ };
2391
+ registerRecordPatternFields(pattern, fields, typeFields);
2392
+ this.recordScopes.push(recordScope);
2393
+ this.parameterScopes.push(paramScope);
2394
+ this.variableTypeScopes.push(varTypeScope);
2395
+ },
2396
+ leaveOptionalRecordPattern: () => {
2397
+ this.variableTypeScopes.pop();
2398
+ this.parameterScopes.pop();
2399
+ this.recordScopes.pop();
2400
+ },
2401
+ }).emitMatchExpression(expr, pipelineScrutineeType, pipelineSource);
2402
+ }
2403
+ emitEffectBlockExpression(expr) {
2404
+ this.localBindingScopes.push(collectLocalBindings(expr.body));
2405
+ try {
2406
+ return emitEffectBlockExpression(this, expr);
2407
+ }
2408
+ finally {
2409
+ this.localBindingScopes.pop();
2410
+ }
2411
+ }
2412
+ emitParBlockExpression(expr) {
2413
+ return emitParBlockExpression(this, expr);
2414
+ }
2415
+ emitEffectCall(effectExpr) {
2416
+ return emitEffectCall(this, effectExpr);
2417
+ }
2418
+ // --- Types ---
2419
+ emitTypeParameters(typeParams, forArrowExpression = false) {
2420
+ return emitTypeParameters(this, typeParams, forArrowExpression);
2421
+ }
2422
+ emitTypeNode(node) {
2423
+ return emitTypeNode(this, node);
2424
+ }
2425
+ // --- JSX ---
2426
+ emitJsxElement(el) {
2427
+ return emitJsxElement(this, el);
2428
+ }
2429
+ emitJsxSelfClosingElement(el) {
2430
+ return emitJsxSelfClosingElement(this, el);
2431
+ }
2432
+ emitJsxTagName(name) {
2433
+ return emitJsxTagName(name);
2434
+ }
2435
+ emitJsxAttribute(attr) {
2436
+ return emitJsxAttribute(this, attr);
2437
+ }
2438
+ emitJsxExpressionContainer(container) {
2439
+ return emitJsxExpressionContainer(this, container);
2440
+ }
2441
+ emitJsxText(text) {
2442
+ return emitJsxText(text);
2443
+ }
2444
+ emitJsxChild(child) {
2445
+ return emitJsxChild(this, child);
2446
+ }
2447
+ }
2448
+ //# sourceMappingURL=emitter.js.map