@synergenius/flow-weaver 0.33.2 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (922) hide show
  1. package/LICENSE +201 -226
  2. package/NOTICE +13 -0
  3. package/README.md +152 -245
  4. package/dist/agent/agent-loop.d.ts +4 -2
  5. package/dist/agent/cli-session.d.ts +3 -3
  6. package/dist/agent/cli-session.js +511 -438
  7. package/dist/agent/cli-spawn-config.d.ts +4 -4
  8. package/dist/agent/gate.d.ts +164 -0
  9. package/dist/agent/index.d.ts +4 -4
  10. package/dist/agent/index.js +174 -28
  11. package/dist/agent/mcp-bridge.d.ts +1 -1
  12. package/dist/agent/mcp-bridge.js +114 -128
  13. package/dist/agent/mcp-tool-server.d.ts +2 -2
  14. package/dist/agent/mcp-tool-server.js +147 -189
  15. package/dist/agent/profiles.d.ts +69 -0
  16. package/dist/agent/providers/anthropic.d.ts +2 -4
  17. package/dist/agent/providers/claude-cli.d.ts +4 -5
  18. package/dist/agent/providers/openai-compat.d.ts +8 -1
  19. package/dist/agent/streaming.d.ts +2 -2
  20. package/dist/agent/types.d.ts +16 -10
  21. package/dist/api/builder.d.ts +3 -3
  22. package/dist/api/compile.d.ts +9 -4
  23. package/dist/api/durable-validation.d.ts +15 -0
  24. package/dist/api/generate-in-place.d.ts +21 -19
  25. package/dist/api/generate.d.ts +21 -16
  26. package/dist/api/generated-module/local-node-functions.d.ts +24 -0
  27. package/dist/api/generated-module/module-format.d.ts +23 -0
  28. package/dist/api/generated-module/module-writer.d.ts +34 -0
  29. package/dist/api/generated-module/node-type-imports.d.ts +39 -0
  30. package/dist/api/generated-module/preamble.d.ts +16 -0
  31. package/dist/api/generated-module/workflow-functions.d.ts +29 -0
  32. package/dist/api/graph-identity.d.ts +39 -0
  33. package/dist/api/helpers.d.ts +4 -60
  34. package/dist/api/in-place/built-in-nodes.d.ts +18 -0
  35. package/dist/api/in-place/function-body.d.ts +21 -0
  36. package/dist/api/in-place/fw-imports.d.ts +30 -0
  37. package/dist/api/in-place/macro-coverage.d.ts +14 -0
  38. package/dist/api/in-place/node-type-functions.d.ts +18 -0
  39. package/dist/api/in-place/node-type-jsdoc.d.ts +20 -0
  40. package/dist/api/in-place/orphaned-node-types.d.ts +16 -0
  41. package/dist/api/in-place/runtime-section.d.ts +16 -0
  42. package/dist/api/in-place/signature.d.ts +47 -0
  43. package/dist/api/in-place/source-file.d.ts +19 -0
  44. package/dist/api/in-place/workflow-jsdoc.d.ts +19 -0
  45. package/dist/api/index.d.ts +18 -21
  46. package/dist/api/index.js +259 -53
  47. package/dist/api/inline-engine.generated.d.ts +3 -0
  48. package/dist/api/inline-runtime.d.ts +10 -2
  49. package/dist/api/manipulation/connections.d.ts +1 -1
  50. package/dist/api/manipulation/index.d.ts +8 -8
  51. package/dist/api/manipulation/node-types.d.ts +1 -1
  52. package/dist/api/manipulation/nodes.d.ts +3 -13
  53. package/dist/api/manipulation/ports.d.ts +1 -1
  54. package/dist/api/manipulation/scopes.d.ts +1 -1
  55. package/dist/api/manipulation/workflow.d.ts +1 -1
  56. package/dist/api/modify-operation.d.ts +0 -2
  57. package/dist/api/parse.d.ts +22 -1
  58. package/dist/api/port-references.d.ts +66 -0
  59. package/dist/api/query.d.ts +18 -2
  60. package/dist/api/templates.d.ts +1 -1
  61. package/dist/api/transform.d.ts +1 -1
  62. package/dist/api/validate.d.ts +1 -1
  63. package/dist/api/validation-registry.d.ts +2 -2
  64. package/dist/artifacts/brief.d.ts +43 -0
  65. package/dist/artifacts/index.d.ts +31 -0
  66. package/dist/artifacts/pdf.d.ts +19 -0
  67. package/dist/ast/builder.d.ts +3 -3
  68. package/dist/ast/index.d.ts +4 -4
  69. package/dist/ast/index.js +60 -5
  70. package/dist/ast/serialization-node.d.ts +1 -1
  71. package/dist/ast/serialization.d.ts +1 -1
  72. package/dist/ast/types.d.ts +82 -291
  73. package/dist/ast/workflow-utils.d.ts +4 -4
  74. package/dist/built-in-nodes/coercion-types.d.ts +1 -1
  75. package/dist/built-in-nodes/delay.d.ts +3 -1
  76. package/dist/built-in-nodes/generated-registry.d.ts +1 -1
  77. package/dist/built-in-nodes/index.d.ts +6 -5
  78. package/dist/built-in-nodes/index.js +79 -5
  79. package/dist/built-in-nodes/invoke-workflow.d.ts +2 -1
  80. package/dist/built-in-nodes/mock-types.d.ts +45 -14
  81. package/dist/built-in-nodes/sleep.d.ts +12 -0
  82. package/dist/built-in-nodes/wait-for-agent.d.ts +2 -1
  83. package/dist/built-in-nodes/wait-for-event.d.ts +2 -1
  84. package/dist/chevrotain-parser/coerce-parser.d.ts +1 -1
  85. package/dist/chevrotain-parser/connect-parser.d.ts +1 -1
  86. package/dist/chevrotain-parser/grammar-diagrams.d.ts +1 -1
  87. package/dist/chevrotain-parser/index.d.ts +20 -23
  88. package/dist/chevrotain-parser/node-parser.d.ts +7 -8
  89. package/dist/chevrotain-parser/parse-line.d.ts +54 -0
  90. package/dist/chevrotain-parser/tokens.d.ts +0 -17
  91. package/dist/chevrotain-parser/trigger-cancel-parser.d.ts +6 -1
  92. package/dist/chunks/chunk-4EUSHAY6.js +298 -0
  93. package/dist/chunks/chunk-4KDUEOFD.js +197 -0
  94. package/dist/chunks/chunk-5Y3AIUWY.js +911 -0
  95. package/dist/chunks/chunk-6KMVP6AU.js +20 -0
  96. package/dist/chunks/chunk-6PNJORFL.js +128 -0
  97. package/dist/chunks/chunk-7AAQNGRH.js +2001 -0
  98. package/dist/chunks/chunk-7YYKTPJ5.js +22705 -0
  99. package/dist/chunks/chunk-A5MBOFVY.js +33 -0
  100. package/dist/chunks/chunk-AXNQRVJB.js +18 -0
  101. package/dist/chunks/chunk-B6HQ6YS5.js +572 -0
  102. package/dist/chunks/chunk-CY3RNVML.js +296 -0
  103. package/dist/chunks/chunk-CYHYDLV4.js +653 -0
  104. package/dist/chunks/chunk-CZBCCK4Y.js +82 -0
  105. package/dist/chunks/chunk-DCMGQP5V.js +505 -0
  106. package/dist/chunks/chunk-DIAA66GL.js +72 -0
  107. package/dist/chunks/chunk-DUO6H5PR.js +20 -0
  108. package/dist/chunks/chunk-E5WN7IGO.js +125 -0
  109. package/dist/chunks/chunk-EFGFXXQF.js +184 -0
  110. package/dist/chunks/chunk-F3RTZV2A.js +2811 -0
  111. package/dist/chunks/chunk-FMTLP5ZX.js +1397 -0
  112. package/dist/chunks/chunk-HKZLQJDV.js +79 -0
  113. package/dist/chunks/chunk-INDEVYEC.js +146 -0
  114. package/dist/chunks/chunk-JQTF4R5L.js +390 -0
  115. package/dist/chunks/chunk-KMCAYNUM.js +331 -0
  116. package/dist/chunks/chunk-KMWCCOUJ.js +1444 -0
  117. package/dist/chunks/chunk-KU3CLJI2.js +338 -0
  118. package/dist/chunks/chunk-NDSTGMKR.js +3300 -0
  119. package/dist/chunks/chunk-NQNLUAPO.js +505 -0
  120. package/dist/chunks/chunk-O2U2LO57.js +466 -0
  121. package/dist/chunks/chunk-OOQG7UPP.js +457 -0
  122. package/dist/chunks/chunk-OZQAW5ZG.js +112 -0
  123. package/dist/chunks/chunk-P2CVDGHR.js +487 -0
  124. package/dist/chunks/chunk-P44RIZ7C.js +592 -0
  125. package/dist/chunks/chunk-PEZCT37T.js +1475 -0
  126. package/dist/chunks/chunk-PKWSAW6O.js +152 -0
  127. package/dist/chunks/chunk-Q6MDDZMT.js +4373 -0
  128. package/dist/chunks/chunk-QDE4Z7KW.js +6 -0
  129. package/dist/chunks/chunk-QJDAVSNY.js +8 -0
  130. package/dist/chunks/chunk-QYPORSLO.js +7552 -0
  131. package/dist/chunks/chunk-R4QGNK34.js +183 -0
  132. package/dist/chunks/chunk-REEYC73I.js +3002 -0
  133. package/dist/chunks/chunk-SEWDMQ6Q.js +46 -0
  134. package/dist/chunks/chunk-TAIUWKZB.js +3057 -0
  135. package/dist/chunks/chunk-TN4YZ3O7.js +196 -0
  136. package/dist/chunks/chunk-TRMFB43C.js +143 -0
  137. package/dist/chunks/chunk-VO4QXG2X.js +1016 -0
  138. package/dist/chunks/chunk-VP2P3BPA.js +1002 -0
  139. package/dist/chunks/chunk-VQ7H33J4.js +2176 -0
  140. package/dist/chunks/chunk-VWA7MCV2.js +105 -0
  141. package/dist/chunks/chunk-XAV22WD7.js +253 -0
  142. package/dist/chunks/chunk-YSPBPZDV.js +148 -0
  143. package/dist/chunks/chunk-ZKEGXO73.js +282 -0
  144. package/dist/chunks/chunk-ZMGN6F3S.js +4256 -0
  145. package/dist/chunks/grammar-diagrams-AI7VDXOM.js +14 -0
  146. package/dist/chunks/index.min-ECJD6GZC.js +37 -0
  147. package/dist/chunks/manifest-EPTR5MYH.js +21 -0
  148. package/dist/chunks/openapi-document-6TCGVDUW.js +69 -0
  149. package/dist/chunks/registry-K2U5KUTY.js +23 -0
  150. package/dist/chunks/serialization-node-UGY6CFH6.js +38 -0
  151. package/dist/chunks/validate-GEKSZPIN.js +24 -0
  152. package/dist/chunks/validation-registry-IQZX3UE3.js +7 -0
  153. package/dist/chunks/validator-VXFHLPDW.js +26 -0
  154. package/dist/chunks/workflow-executor-KBGFKHNR.js +36 -0
  155. package/dist/cli/commands/agents.d.ts +16 -0
  156. package/dist/cli/commands/artifact.d.ts +10 -0
  157. package/dist/cli/commands/compile.d.ts +0 -30
  158. package/dist/cli/commands/console.d.ts +32 -0
  159. package/dist/cli/commands/context.d.ts +0 -3
  160. package/dist/cli/commands/describe.js +386 -352
  161. package/dist/cli/commands/dev.d.ts +9 -4
  162. package/dist/cli/commands/diagram.d.ts +3 -5
  163. package/dist/cli/commands/doctor.d.ts +27 -4
  164. package/dist/cli/commands/doctor.js +3307 -633
  165. package/dist/cli/commands/export.d.ts +6 -4
  166. package/dist/cli/commands/grammar.d.ts +0 -3
  167. package/dist/cli/commands/implement.d.ts +1 -1
  168. package/dist/cli/commands/init/agent-handoff.d.ts +28 -0
  169. package/dist/cli/commands/init/config.d.ts +3 -0
  170. package/dist/cli/commands/init/files.d.ts +12 -0
  171. package/dist/cli/commands/init/naming.d.ts +13 -0
  172. package/dist/cli/commands/init/output.d.ts +12 -0
  173. package/dist/cli/commands/init/setup.d.ts +21 -0
  174. package/dist/cli/commands/init/types.d.ts +53 -0
  175. package/dist/cli/commands/init-personas.d.ts +9 -1
  176. package/dist/cli/commands/init.d.ts +24 -88
  177. package/dist/cli/commands/market.d.ts +1 -1
  178. package/dist/cli/commands/mcp-setup.d.ts +1 -4
  179. package/dist/cli/commands/modify.d.ts +0 -5
  180. package/dist/cli/commands/openapi.d.ts +9 -11
  181. package/dist/cli/commands/run.d.ts +0 -4
  182. package/dist/cli/commands/serve.d.ts +24 -26
  183. package/dist/cli/commands/status.d.ts +1 -1
  184. package/dist/cli/exports.d.ts +3 -4
  185. package/dist/cli/exports.js +124 -23
  186. package/dist/cli/flow-weaver-agents-H653446S.mjs +81 -0
  187. package/dist/cli/flow-weaver-artifact-WBFYTW76.mjs +58 -0
  188. package/dist/cli/flow-weaver-chunk-265CEK74.mjs +2 -0
  189. package/dist/cli/flow-weaver-chunk-2C7PZCV5.mjs +186 -0
  190. package/dist/cli/flow-weaver-chunk-3BSYCWPL.mjs +3109 -0
  191. package/dist/cli/flow-weaver-chunk-3MKUQP3D.mjs +547 -0
  192. package/dist/cli/flow-weaver-chunk-3ZLMPQTH.mjs +27 -0
  193. package/dist/cli/flow-weaver-chunk-4DVY73ML.mjs +280 -0
  194. package/dist/cli/flow-weaver-chunk-54M4KNEL.mjs +200 -0
  195. package/dist/cli/flow-weaver-chunk-55QMUZIA.mjs +256 -0
  196. package/dist/cli/flow-weaver-chunk-6ZUJ7LMX.mjs +2003 -0
  197. package/dist/cli/flow-weaver-chunk-7ET6N32V.mjs +419 -0
  198. package/dist/cli/flow-weaver-chunk-7G63RR4K.mjs +8880 -0
  199. package/dist/cli/flow-weaver-chunk-A6M5K3W7.mjs +4418 -0
  200. package/dist/cli/flow-weaver-chunk-AA3NATMX.mjs +154 -0
  201. package/dist/cli/flow-weaver-chunk-APX6MQ5A.mjs +5652 -0
  202. package/dist/cli/flow-weaver-chunk-BHCC5FE5.mjs +17 -0
  203. package/dist/cli/flow-weaver-chunk-DM4BBRRU.mjs +35 -0
  204. package/dist/cli/flow-weaver-chunk-DRN7KPWY.mjs +168 -0
  205. package/dist/cli/flow-weaver-chunk-EKWF27G6.mjs +23 -0
  206. package/dist/cli/flow-weaver-chunk-EM5HWQ4R.mjs +338 -0
  207. package/dist/cli/flow-weaver-chunk-FPPPU2DG.mjs +226 -0
  208. package/dist/cli/flow-weaver-chunk-GAQXZHNO.mjs +3005 -0
  209. package/dist/cli/flow-weaver-chunk-GBUNNP33.mjs +1329 -0
  210. package/dist/cli/flow-weaver-chunk-HMAKDE55.mjs +636 -0
  211. package/dist/cli/flow-weaver-chunk-HQ3ZAN44.mjs +367 -0
  212. package/dist/cli/flow-weaver-chunk-I4APCXYN.mjs +21442 -0
  213. package/dist/cli/flow-weaver-chunk-IJJ4JXTL.mjs +2297 -0
  214. package/dist/cli/flow-weaver-chunk-J7EPZW2I.mjs +33 -0
  215. package/dist/cli/flow-weaver-chunk-KOEMJHLG.mjs +83 -0
  216. package/dist/cli/flow-weaver-chunk-M6CBWQKJ.mjs +271 -0
  217. package/dist/cli/flow-weaver-chunk-MHJ4N652.mjs +1580 -0
  218. package/dist/cli/flow-weaver-chunk-MKAFQWLP.mjs +202 -0
  219. package/dist/cli/flow-weaver-chunk-MMV2XGD3.mjs +3291 -0
  220. package/dist/cli/flow-weaver-chunk-MSI2UJES.mjs +125 -0
  221. package/dist/cli/flow-weaver-chunk-N767YRAI.mjs +48 -0
  222. package/dist/cli/flow-weaver-chunk-NQKKWDGF.mjs +56 -0
  223. package/dist/cli/flow-weaver-chunk-NYZDQYFU.mjs +45 -0
  224. package/dist/cli/flow-weaver-chunk-OMVWSNHJ.mjs +14 -0
  225. package/dist/cli/flow-weaver-chunk-PUWZ47H5.mjs +2188 -0
  226. package/dist/cli/flow-weaver-chunk-QOPRVDES.mjs +46 -0
  227. package/dist/cli/flow-weaver-chunk-RIWE7YTR.mjs +216 -0
  228. package/dist/cli/flow-weaver-chunk-S63Q3JIU.mjs +789 -0
  229. package/dist/cli/flow-weaver-chunk-T7X5A23H.mjs +558 -0
  230. package/dist/cli/flow-weaver-chunk-TLV3VZUN.mjs +2 -0
  231. package/dist/cli/flow-weaver-chunk-TS5P3PIN.mjs +194 -0
  232. package/dist/cli/flow-weaver-chunk-U3EO3X4B.mjs +649 -0
  233. package/dist/cli/flow-weaver-chunk-UNFS3NQP.mjs +34 -0
  234. package/dist/cli/flow-weaver-chunk-V6DHWFQG.mjs +2811 -0
  235. package/dist/cli/flow-weaver-chunk-VXWNLYQU.mjs +9 -0
  236. package/dist/cli/flow-weaver-chunk-W3YNK26P.mjs +149 -0
  237. package/dist/cli/flow-weaver-chunk-XG2WKXYZ.mjs +324 -0
  238. package/dist/cli/flow-weaver-chunk-YLSRZWFK.mjs +2219 -0
  239. package/dist/cli/flow-weaver-chunk-YVPURWS6.mjs +40 -0
  240. package/dist/cli/flow-weaver-chunk-Z44JK332.mjs +582 -0
  241. package/dist/cli/flow-weaver-chunk-Z5ZJPNSY.mjs +517 -0
  242. package/dist/cli/flow-weaver-chunk-ZQALO25T.mjs +594 -0
  243. package/dist/cli/flow-weaver-compile-A2CABDSB.mjs +37 -0
  244. package/dist/cli/flow-weaver-console-6EBHDBTN.mjs +71 -0
  245. package/dist/cli/flow-weaver-context-ECLYANFF.mjs +17 -0
  246. package/dist/cli/flow-weaver-context-ZRUMW2KE.mjs +69 -0
  247. package/dist/cli/flow-weaver-create-WIP4EFNP.mjs +124 -0
  248. package/dist/cli/flow-weaver-deployment-WJJRK7NO.mjs +14 -0
  249. package/dist/cli/flow-weaver-describe-XDIFF5LI.mjs +41 -0
  250. package/dist/cli/flow-weaver-dev-LG2NSQAU.mjs +196 -0
  251. package/dist/cli/flow-weaver-diagram-3EVQARQE.mjs +52 -0
  252. package/dist/cli/flow-weaver-diagram-7LR7O4M2.mjs +44 -0
  253. package/dist/cli/flow-weaver-diff-USF7DJLU.mjs +85 -0
  254. package/dist/cli/flow-weaver-docs-QU2ZOXKH.mjs +96 -0
  255. package/dist/cli/flow-weaver-doctor-K447YWHR.mjs +43 -0
  256. package/dist/cli/flow-weaver-export-LAS6N56Y.mjs +140 -0
  257. package/dist/cli/flow-weaver-grammar-RIRUS3Q6.mjs +49 -0
  258. package/dist/cli/flow-weaver-grammar-diagrams-WXRTW5SK.mjs +15 -0
  259. package/dist/cli/flow-weaver-implement-5JG6BCFZ.mjs +114 -0
  260. package/dist/cli/flow-weaver-index.min-OR5SIHXD.mjs +39 -0
  261. package/dist/cli/flow-weaver-init-34YZNPQX.mjs +972 -0
  262. package/dist/cli/flow-weaver-init-personas-NOGZTQQ2.mjs +48 -0
  263. package/dist/cli/flow-weaver-manifest-4JNUSEB3.mjs +18 -0
  264. package/dist/cli/flow-weaver-market-WA4CKHKV.mjs +444 -0
  265. package/dist/cli/flow-weaver-mcp-setup-O26MGXSD.mjs +22 -0
  266. package/dist/cli/flow-weaver-migrate-VFVEUTPH.mjs +119 -0
  267. package/dist/cli/flow-weaver-modify-VM3JP5K6.mjs +97 -0
  268. package/dist/cli/flow-weaver-openapi-IRBWI3HM.mjs +71 -0
  269. package/dist/cli/flow-weaver-openapi-document-7N6YMPG3.mjs +30 -0
  270. package/dist/cli/flow-weaver-pack-commands-OS2QRXAK.mjs +146 -0
  271. package/dist/cli/flow-weaver-registry-5MLFRPPT.mjs +25 -0
  272. package/dist/cli/flow-weaver-run-DSTLSTHR.mjs +555 -0
  273. package/dist/cli/flow-weaver-serialization-node-LE6PCG4M.mjs +50 -0
  274. package/dist/cli/flow-weaver-serve-NVLCLSOW.mjs +192 -0
  275. package/dist/cli/flow-weaver-server-7IERLVXE.mjs +2925 -0
  276. package/dist/cli/flow-weaver-server-KWF4PXYC.mjs +19112 -0
  277. package/dist/cli/flow-weaver-status-75W2S3YB.mjs +138 -0
  278. package/dist/cli/flow-weaver-strip-AZPXUYVA.mjs +79 -0
  279. package/dist/cli/flow-weaver-templates-DSNMB6K7.mjs +72 -0
  280. package/dist/cli/flow-weaver-validate-A4UWDQN6.mjs +19 -0
  281. package/dist/cli/flow-weaver-validate-GRBZ5W4C.mjs +296 -0
  282. package/dist/cli/flow-weaver-validation-registry-BINGUNXX.mjs +9 -0
  283. package/dist/cli/flow-weaver-validator-TY56CI42.mjs +21 -0
  284. package/dist/cli/flow-weaver-watch-OPPERXL6.mjs +114 -0
  285. package/dist/cli/flow-weaver-workflow-executor-6AHYPXAN.mjs +26 -0
  286. package/dist/cli/flow-weaver.mjs +3557 -89384
  287. package/dist/cli/index.d.ts +5 -2
  288. package/dist/cli/pack-commands-needed.d.ts +12 -0
  289. package/dist/cli/program.d.ts +14 -0
  290. package/dist/cli/templates/ai/mock-provider.d.ts +1 -1
  291. package/dist/cli/templates/index.d.ts +1 -8
  292. package/dist/cli/templates/nodes/agent-router.d.ts +1 -1
  293. package/dist/cli/templates/nodes/aggregator.d.ts +1 -1
  294. package/dist/cli/templates/nodes/conversation-memory.d.ts +1 -1
  295. package/dist/cli/templates/nodes/http.d.ts +1 -1
  296. package/dist/cli/templates/nodes/human-approval.d.ts +1 -1
  297. package/dist/cli/templates/nodes/json-extractor.d.ts +1 -1
  298. package/dist/cli/templates/nodes/llm-call.d.ts +1 -1
  299. package/dist/cli/templates/nodes/prompt-template.d.ts +1 -1
  300. package/dist/cli/templates/nodes/rag-retriever.d.ts +1 -1
  301. package/dist/cli/templates/nodes/tool-executor.d.ts +1 -1
  302. package/dist/cli/templates/nodes/transformer.d.ts +1 -1
  303. package/dist/cli/templates/nodes/validator.d.ts +1 -1
  304. package/dist/cli/templates/shared/approval-types.d.ts +1 -1
  305. package/dist/cli/templates/shared/case.d.ts +14 -0
  306. package/dist/cli/templates/shared/llm-types.d.ts +4 -4
  307. package/dist/cli/templates/workflows/aggregator.d.ts +1 -1
  308. package/dist/cli/templates/workflows/ai-agent.d.ts +1 -1
  309. package/dist/cli/templates/workflows/ai-chat.d.ts +1 -1
  310. package/dist/cli/templates/workflows/ai-rag.d.ts +1 -1
  311. package/dist/cli/templates/workflows/ai-react.d.ts +1 -1
  312. package/dist/cli/templates/workflows/approval.d.ts +10 -0
  313. package/dist/cli/templates/workflows/conditional.d.ts +2 -2
  314. package/dist/cli/templates/workflows/error-handler.d.ts +2 -2
  315. package/dist/cli/templates/workflows/foreach.d.ts +1 -1
  316. package/dist/cli/templates/workflows/sequential.d.ts +1 -1
  317. package/dist/cli/templates/workflows/webhook.d.ts +1 -1
  318. package/dist/cli/utils/interactive.d.ts +6 -0
  319. package/dist/cli/utils/json-option.d.ts +8 -0
  320. package/dist/cli/utils/logger.d.ts +2 -0
  321. package/dist/compiler/durable-source-proof.d.ts +23 -0
  322. package/dist/compiler/executable-artifact.d.ts +29 -0
  323. package/dist/compiler/index.d.ts +4 -0
  324. package/dist/compiler/index.js +36 -0
  325. package/dist/console/app.js +106 -0
  326. package/dist/console/assets/synergenius.svg +18 -0
  327. package/dist/console/author.d.ts +32 -0
  328. package/dist/console/cli-catalog.d.ts +21 -0
  329. package/dist/console/cli-run.d.ts +35 -0
  330. package/dist/console/cli-run.js +46 -0
  331. package/dist/console/debug.d.ts +67 -0
  332. package/dist/console/diff-view.d.ts +96 -0
  333. package/dist/console/export.d.ts +36 -0
  334. package/dist/console/git.d.ts +27 -0
  335. package/dist/console/index.d.ts +4 -0
  336. package/dist/console/index.html +16 -0
  337. package/dist/console/index.js +203 -0
  338. package/dist/console/packs.d.ts +100 -0
  339. package/dist/console/request-guard.d.ts +10 -0
  340. package/dist/console/respond.d.ts +16 -0
  341. package/dist/console/router.d.ts +64 -0
  342. package/dist/console/routes-agents.d.ts +14 -0
  343. package/dist/console/routes-project.d.ts +3 -0
  344. package/dist/console/routes-runs.d.ts +3 -0
  345. package/dist/console/routes-services.d.ts +7 -0
  346. package/dist/console/routes-tools.d.ts +3 -0
  347. package/dist/console/runs.d.ts +69 -0
  348. package/dist/console/scan.d.ts +49 -0
  349. package/dist/console/schema.d.ts +74 -0
  350. package/dist/console/server.d.ts +34 -0
  351. package/dist/console/server.js +43264 -0
  352. package/dist/console/services.d.ts +119 -0
  353. package/dist/console/source.d.ts +23 -0
  354. package/dist/console/status.d.ts +68 -0
  355. package/dist/console/styles.css +1023 -0
  356. package/dist/console/terminals.d.ts +22 -0
  357. package/dist/console/workflow-view.d.ts +153 -0
  358. package/dist/constants.d.ts +5 -1
  359. package/dist/constants.js +56 -167
  360. package/dist/context/index.d.ts +10 -0
  361. package/dist/context/index.js +14 -191
  362. package/dist/coordinator/agent-gate.d.ts +107 -0
  363. package/dist/coordinator/bundle-digest.d.ts +20 -0
  364. package/dist/coordinator/clock-tick.d.ts +4 -0
  365. package/dist/coordinator/effect-receipts.d.ts +10 -0
  366. package/dist/coordinator/errors.d.ts +31 -0
  367. package/dist/coordinator/file-store.d.ts +3 -0
  368. package/dist/coordinator/gate-labeling.d.ts +33 -0
  369. package/dist/coordinator/gate-resolution.d.ts +28 -0
  370. package/dist/coordinator/index.d.ts +12 -0
  371. package/dist/coordinator/index.js +107 -0
  372. package/dist/coordinator/memory-store.d.ts +3 -0
  373. package/dist/coordinator/params.d.ts +18 -0
  374. package/dist/coordinator/run-annotations.d.ts +6 -0
  375. package/dist/coordinator/run-context.d.ts +11 -0
  376. package/dist/coordinator/run-ending.d.ts +5 -0
  377. package/dist/coordinator/run-outcome.d.ts +31 -0
  378. package/dist/coordinator/run-resume.d.ts +6 -0
  379. package/dist/coordinator/run-start.d.ts +4 -0
  380. package/dist/coordinator/run-store.d.ts +275 -0
  381. package/dist/coordinator/run-trace.d.ts +41 -0
  382. package/dist/coordinator/run-views.d.ts +12 -0
  383. package/dist/coordinator/runs-dir.d.ts +26 -0
  384. package/dist/coordinator/store.d.ts +67 -0
  385. package/dist/coordinator/time.d.ts +39 -0
  386. package/dist/coordinator/workflow-selection.d.ts +6 -0
  387. package/dist/deployment/index.d.ts +11 -16
  388. package/dist/deployment/index.js +541 -50
  389. package/dist/deployment/targets/base.d.ts +11 -13
  390. package/dist/deployment/targets/openapi-parts.d.ts +92 -0
  391. package/dist/diagram/arms.d.ts +70 -0
  392. package/dist/diagram/ascii-renderer.d.ts +1 -1
  393. package/dist/diagram/geometry.d.ts +20 -32
  394. package/dist/diagram/graph/bounds.d.ts +30 -0
  395. package/dist/diagram/graph/metrics.d.ts +21 -0
  396. package/dist/diagram/graph/nodes.d.ts +33 -0
  397. package/dist/diagram/graph/placement.d.ts +22 -0
  398. package/dist/diagram/graph/ports.d.ts +23 -0
  399. package/dist/diagram/graph/routing.d.ts +40 -0
  400. package/dist/diagram/graph/scopes.d.ts +30 -0
  401. package/dist/diagram/index.d.ts +15 -23
  402. package/dist/diagram/index.js +632 -111
  403. package/dist/diagram/labels.d.ts +12 -0
  404. package/dist/diagram/lanes.d.ts +93 -0
  405. package/dist/diagram/layout.d.ts +1 -1
  406. package/dist/diagram/material-symbols.d.ts +7 -0
  407. package/dist/diagram/orthogonal-router.d.ts +2 -3
  408. package/dist/diagram/process-view.d.ts +79 -0
  409. package/dist/diagram/spine.d.ts +25 -0
  410. package/dist/diagram/theme.d.ts +1 -5
  411. package/dist/diagram/types.d.ts +6 -20
  412. package/dist/diff/index.js +53 -9
  413. package/dist/diff/types.d.ts +1 -5
  414. package/dist/doc-metadata/extractors/annotations.d.ts +0 -4
  415. package/dist/doc-metadata/extractors/cli-commands.d.ts +2 -1
  416. package/dist/doc-metadata/extractors/core-metadata.d.ts +19 -4
  417. package/dist/doc-metadata/extractors/error-codes.d.ts +1 -1
  418. package/dist/doc-metadata/extractors/mcp-tools.d.ts +7 -3
  419. package/dist/doc-metadata/index.d.ts +1 -2
  420. package/dist/doc-metadata/index.js +2368 -9
  421. package/dist/doc-metadata/types.d.ts +7 -24
  422. package/dist/docs/guide.d.ts +33 -0
  423. package/dist/docs/index.d.ts +7 -4
  424. package/dist/docs/index.js +298 -298
  425. package/dist/docs/pack-topics.d.ts +18 -0
  426. package/dist/editor-completions/annotationValues.d.ts +1 -1
  427. package/dist/editor-completions/contextParser.d.ts +3 -2
  428. package/dist/editor-completions/dataTypes.d.ts +1 -1
  429. package/dist/editor-completions/goToDefinition.d.ts +1 -1
  430. package/dist/editor-completions/index.d.ts +8 -8
  431. package/dist/editor-completions/index.js +1244 -175
  432. package/dist/editor-completions/jsDocAnnotations.d.ts +1 -1
  433. package/dist/editor-completions/modifierCompletions.d.ts +1 -1
  434. package/dist/export/index.d.ts +7 -1
  435. package/dist/generated-branding.js +8 -21
  436. package/dist/generated-version.d.ts +1 -1
  437. package/dist/generated-version.js +7 -3
  438. package/dist/generator/annotation-generator.d.ts +84 -0
  439. package/dist/generator/async-detection.d.ts +1 -1
  440. package/dist/{body-generator.d.ts → generator/body-generator.d.ts} +7 -3
  441. package/dist/generator/code-utils.d.ts +15 -60
  442. package/dist/generator/connection-reads.d.ts +94 -0
  443. package/dist/generator/control-flow-plan.d.ts +74 -0
  444. package/dist/generator/control-flow.d.ts +1 -1
  445. package/dist/generator/exit-assembly.d.ts +11 -0
  446. package/dist/generator/index.d.ts +4 -5
  447. package/dist/generator/index.js +34 -11
  448. package/dist/generator/input-port-values.d.ts +22 -0
  449. package/dist/generator/{scope-function-generator.d.ts → node-arguments.d.ts} +76 -1
  450. package/dist/generator/node-invocation.d.ts +74 -0
  451. package/dist/{node-types-generator.d.ts → generator/node-types-generator.d.ts} +3 -2
  452. package/dist/generator/scope-closure.d.ts +23 -0
  453. package/dist/generator/scoped-child.d.ts +49 -0
  454. package/dist/{sugar-optimizer.d.ts → generator/sugar-optimizer.d.ts} +1 -1
  455. package/dist/generator/unified.d.ts +14 -2
  456. package/dist/generator/workflow-generator.d.ts +37 -0
  457. package/dist/index.d.ts +29 -26
  458. package/dist/index.js +1322 -92
  459. package/dist/jsdoc-port-sync/apply-diff.d.ts +15 -0
  460. package/dist/jsdoc-port-sync/callback-signature.d.ts +17 -0
  461. package/dist/jsdoc-port-sync/diff.d.ts +5 -7
  462. package/dist/jsdoc-port-sync/incomplete-lines.d.ts +41 -0
  463. package/dist/jsdoc-port-sync/index.d.ts +11 -11
  464. package/dist/jsdoc-port-sync/index.js +88 -45
  465. package/dist/jsdoc-port-sync/jsdoc-to-signature.d.ts +66 -0
  466. package/dist/jsdoc-port-sync/port-parser.d.ts +6 -24
  467. package/dist/jsdoc-port-sync/port-tag-placement.d.ts +55 -0
  468. package/dist/jsdoc-port-sync/scoped-ports.d.ts +21 -0
  469. package/dist/jsdoc-port-sync/signature-parser.d.ts +8 -1
  470. package/dist/jsdoc-port-sync/signature-to-jsdoc.d.ts +77 -0
  471. package/dist/jsdoc-port-sync/sync.d.ts +4 -1
  472. package/dist/marketplace/index.d.ts +5 -3
  473. package/dist/marketplace/index.js +62 -10
  474. package/dist/marketplace/install.d.ts +24 -0
  475. package/dist/marketplace/manifest.d.ts +1 -1
  476. package/dist/marketplace/npmrc.d.ts +24 -0
  477. package/dist/marketplace/registry.d.ts +46 -11
  478. package/dist/marketplace/types.d.ts +41 -24
  479. package/dist/marketplace/validator.d.ts +1 -1
  480. package/dist/mcp/debug-session.d.ts +2 -4
  481. package/dist/mcp/dist-imports.d.ts +12 -0
  482. package/dist/mcp/response-utils.d.ts +11 -9
  483. package/dist/mcp/server.d.ts +0 -1
  484. package/dist/mcp/tools-context.d.ts +11 -0
  485. package/dist/mcp/tools-diagram.d.ts +1 -2
  486. package/dist/mcp/tools-export.d.ts +2 -2
  487. package/dist/mcp/tools-marketplace.d.ts +1 -1
  488. package/dist/mcp/tools-run.d.ts +17 -0
  489. package/dist/mcp/tools-workflow.d.ts +3 -0
  490. package/dist/mcp/types.d.ts +4 -14
  491. package/dist/mcp/workflow-executor.d.ts +57 -19
  492. package/dist/npm-packages.d.ts +1 -1
  493. package/dist/npm-packages.js +10 -473
  494. package/dist/parser/annotation-parser.d.ts +88 -0
  495. package/dist/parser/annotation-suggestion.d.ts +23 -0
  496. package/dist/parser/durable-effect-contract.d.ts +10 -0
  497. package/dist/parser/expression-references.d.ts +101 -0
  498. package/dist/parser/external-node-types.d.ts +69 -0
  499. package/dist/{function-like.d.ts → parser/function-like.d.ts} +10 -3
  500. package/dist/parser/generated-sections.d.ts +25 -0
  501. package/dist/parser/import-resolution.d.ts +67 -0
  502. package/dist/parser/import-stub.d.ts +29 -0
  503. package/dist/parser/jsdoc/config-types.d.ts +209 -0
  504. package/dist/parser/jsdoc/graph-tags.d.ts +54 -0
  505. package/dist/parser/jsdoc/node-type-block.d.ts +23 -0
  506. package/dist/parser/jsdoc/parse-line-once.d.ts +11 -0
  507. package/dist/parser/jsdoc/port-tags.d.ts +42 -0
  508. package/dist/parser/jsdoc/runtime-tags.d.ts +65 -0
  509. package/dist/parser/jsdoc/signature-types.d.ts +52 -0
  510. package/dist/parser/jsdoc/workflow-block.d.ts +22 -0
  511. package/dist/parser/jsdoc-parser.d.ts +23 -0
  512. package/dist/parser/macro-expansion.d.ts +80 -0
  513. package/dist/parser/module-resolution.d.ts +38 -0
  514. package/dist/parser/node-inference.d.ts +39 -0
  515. package/dist/parser/npm-node-types.d.ts +24 -0
  516. package/dist/parser/pack-handlers.d.ts +12 -0
  517. package/dist/parser/path-data-resolution.d.ts +75 -0
  518. package/dist/parser/port-inference.d.ts +15 -0
  519. package/dist/{resolve-package-types.d.ts → parser/resolve-package-types.d.ts} +4 -0
  520. package/dist/parser/serialize-deploy-annotations.d.ts +19 -0
  521. package/dist/parser/tag-registry.d.ts +22 -0
  522. package/dist/parser/workflow-extraction.d.ts +39 -0
  523. package/dist/runtime/ExecutionContext.d.ts +87 -99
  524. package/dist/runtime/continuation-core.d.ts +147 -0
  525. package/dist/runtime/continuation.d.ts +48 -0
  526. package/dist/runtime/debug-controller.d.ts +7 -22
  527. package/dist/runtime/durable-execution.d.ts +176 -0
  528. package/dist/runtime/events.d.ts +16 -1
  529. package/dist/runtime/executable-module-contract.d.ts +16 -0
  530. package/dist/runtime/index.d.ts +13 -10
  531. package/dist/runtime/index.js +947 -9
  532. package/dist/runtime/strict-json.d.ts +15 -0
  533. package/dist/server/access.d.ts +12 -0
  534. package/dist/server/api.d.ts +126 -0
  535. package/dist/server/callback-delivery.d.ts +62 -0
  536. package/dist/server/callback-url.d.ts +44 -0
  537. package/dist/server/context.d.ts +35 -0
  538. package/dist/server/http-error.d.ts +10 -0
  539. package/dist/server/index.d.ts +7 -1
  540. package/dist/server/index.js +125 -6
  541. package/dist/server/openapi-document.d.ts +33 -0
  542. package/dist/server/openapi.d.ts +32 -0
  543. package/dist/server/respond.d.ts +35 -0
  544. package/dist/server/route-params.d.ts +17 -0
  545. package/dist/server/route-plan.d.ts +41 -0
  546. package/dist/server/routes-catalog.d.ts +5 -0
  547. package/dist/server/routes-declared.d.ts +12 -0
  548. package/dist/server/routes-runs.d.ts +8 -0
  549. package/dist/server/run-driver.d.ts +58 -0
  550. package/dist/server/run-view.d.ts +26 -0
  551. package/dist/server/transport.d.ts +35 -0
  552. package/dist/server/types.d.ts +143 -52
  553. package/dist/server/webhook-server.d.ts +12 -38
  554. package/dist/server/workflow-registry.d.ts +7 -4
  555. package/dist/service-registry.d.ts +49 -0
  556. package/dist/service-registry.js +123 -0
  557. package/dist/testing/assertions.d.ts +2 -2
  558. package/dist/testing/index.d.ts +14 -13
  559. package/dist/testing/index.js +582 -24
  560. package/dist/testing/mock-approval.d.ts +3 -5
  561. package/dist/testing/mock-llm.d.ts +2 -3
  562. package/dist/testing/recorder.d.ts +5 -6
  563. package/dist/testing/replayer.d.ts +6 -7
  564. package/dist/testing/run-store-check.d.ts +3 -0
  565. package/dist/testing/token-tracker.d.ts +2 -2
  566. package/dist/{type-mappings.d.ts → types/type-mappings.d.ts} +13 -1
  567. package/dist/utils/error-utils.d.ts +4 -2
  568. package/dist/utils/port-ordering.d.ts +2 -2
  569. package/dist/utils/port-tag-utils.d.ts +1 -1
  570. package/dist/validation/agent-detection.d.ts +17 -5
  571. package/dist/validation/agent-rules.d.ts +6 -7
  572. package/dist/validation/core-rules.d.ts +49 -0
  573. package/dist/validation/design-rules.d.ts +9 -3
  574. package/dist/validation/rule-registry.d.ts +3 -3
  575. package/dist/validation/rules/connections.d.ts +27 -0
  576. package/dist/validation/rules/context.d.ts +11 -0
  577. package/dist/validation/rules/cycles.d.ts +17 -0
  578. package/dist/validation/rules/data-flow.d.ts +19 -0
  579. package/dist/validation/rules/scope-topology.d.ts +35 -0
  580. package/dist/validation/rules/type-compatibility.d.ts +30 -0
  581. package/dist/validation/type-checker.d.ts +39 -0
  582. package/dist/validation/validator-helpers.d.ts +31 -0
  583. package/dist/validation/validator.d.ts +30 -0
  584. package/docs/reference/advanced-annotations.md +277 -60
  585. package/docs/reference/built-in-nodes.md +164 -94
  586. package/docs/reference/cancellation.md +44 -0
  587. package/docs/reference/cli-reference.md +252 -234
  588. package/docs/reference/compilation.md +36 -109
  589. package/docs/reference/concepts.md +80 -63
  590. package/docs/reference/console.md +169 -0
  591. package/docs/reference/debugging.md +26 -57
  592. package/docs/reference/deployment.md +217 -143
  593. package/docs/reference/durable-gates.md +445 -0
  594. package/docs/reference/error-codes.md +90 -43
  595. package/docs/reference/export-interface.md +91 -26
  596. package/docs/reference/iterative-development.md +50 -28
  597. package/docs/reference/jsdoc-grammar.md +66 -311
  598. package/docs/reference/library.md +250 -0
  599. package/docs/reference/marketplace.md +301 -152
  600. package/docs/reference/mcp-tools.md +102 -0
  601. package/docs/reference/node-conversion.md +84 -59
  602. package/docs/reference/orientation.md +68 -0
  603. package/docs/reference/scaffold.md +5 -4
  604. package/docs/reference/tutorial.md +106 -166
  605. package/docs/reference/visual-reference.md +1 -1
  606. package/package.json +85 -50
  607. package/dist/agent/agent-loop.js +0 -156
  608. package/dist/agent/cli-spawn-config.js +0 -65
  609. package/dist/agent/device-connection.d.ts +0 -79
  610. package/dist/agent/device-connection.js +0 -184
  611. package/dist/agent/env-allowlist.js +0 -60
  612. package/dist/agent/providers/anthropic.js +0 -198
  613. package/dist/agent/providers/claude-cli.js +0 -161
  614. package/dist/agent/providers/openai-compat.js +0 -205
  615. package/dist/agent/providers/platform.d.ts +0 -23
  616. package/dist/agent/providers/platform.js +0 -132
  617. package/dist/agent/streaming.js +0 -186
  618. package/dist/agent/types.js +0 -20
  619. package/dist/annotation-generator.d.ts +0 -50
  620. package/dist/annotation-generator.js +0 -743
  621. package/dist/api/builder.js +0 -345
  622. package/dist/api/command-runner.js +0 -787
  623. package/dist/api/compile.js +0 -148
  624. package/dist/api/extract-types.js +0 -57
  625. package/dist/api/generate-in-place.js +0 -1477
  626. package/dist/api/generate.js +0 -514
  627. package/dist/api/helpers.js +0 -285
  628. package/dist/api/inline-runtime.js +0 -526
  629. package/dist/api/manipulation/connections.js +0 -151
  630. package/dist/api/manipulation/index.js +0 -41
  631. package/dist/api/manipulation/node-types.js +0 -200
  632. package/dist/api/manipulation/nodes.js +0 -355
  633. package/dist/api/manipulation/ports.js +0 -228
  634. package/dist/api/manipulation/scopes.js +0 -156
  635. package/dist/api/manipulation/workflow.js +0 -116
  636. package/dist/api/modify-operation.js +0 -177
  637. package/dist/api/parse.js +0 -115
  638. package/dist/api/patterns.d.ts +0 -112
  639. package/dist/api/patterns.js +0 -303
  640. package/dist/api/query.js +0 -840
  641. package/dist/api/templates.js +0 -117
  642. package/dist/api/transform.js +0 -40
  643. package/dist/api/validate.js +0 -64
  644. package/dist/api/validation-registry.js +0 -10
  645. package/dist/api/workflow-file-operations.js +0 -180
  646. package/dist/ast/builder.js +0 -395
  647. package/dist/ast/serialization-node.js +0 -30
  648. package/dist/ast/serialization.js +0 -134
  649. package/dist/ast/types.js +0 -2
  650. package/dist/ast/workflow-utils.js +0 -114
  651. package/dist/body-generator.js +0 -35
  652. package/dist/built-in-nodes/coercion-types.js +0 -61
  653. package/dist/built-in-nodes/delay.js +0 -29
  654. package/dist/built-in-nodes/generated-registry.js +0 -299
  655. package/dist/built-in-nodes/invoke-workflow.js +0 -36
  656. package/dist/built-in-nodes/mock-types.js +0 -42
  657. package/dist/built-in-nodes/wait-for-agent.js +0 -31
  658. package/dist/built-in-nodes/wait-for-event.js +0 -25
  659. package/dist/chevrotain-parser/coerce-parser.js +0 -103
  660. package/dist/chevrotain-parser/connect-parser.js +0 -136
  661. package/dist/chevrotain-parser/fan-parser.js +0 -149
  662. package/dist/chevrotain-parser/grammar-diagrams.js +0 -273
  663. package/dist/chevrotain-parser/index.js +0 -31
  664. package/dist/chevrotain-parser/map-parser.js +0 -130
  665. package/dist/chevrotain-parser/node-parser.js +0 -558
  666. package/dist/chevrotain-parser/path-parser.js +0 -140
  667. package/dist/chevrotain-parser/port-parser.js +0 -519
  668. package/dist/chevrotain-parser/position-parser.d.ts +0 -20
  669. package/dist/chevrotain-parser/position-parser.js +0 -83
  670. package/dist/chevrotain-parser/scope-parser.js +0 -104
  671. package/dist/chevrotain-parser/tokens.js +0 -429
  672. package/dist/chevrotain-parser/trigger-cancel-parser.js +0 -291
  673. package/dist/cli/commands/account.d.ts +0 -4
  674. package/dist/cli/commands/account.js +0 -50
  675. package/dist/cli/commands/ai-credentials.d.ts +0 -12
  676. package/dist/cli/commands/ai-credentials.js +0 -95
  677. package/dist/cli/commands/apikey.d.ts +0 -4
  678. package/dist/cli/commands/apikey.js +0 -64
  679. package/dist/cli/commands/auth.d.ts +0 -9
  680. package/dist/cli/commands/auth.js +0 -255
  681. package/dist/cli/commands/compile.js +0 -331
  682. package/dist/cli/commands/connect.d.ts +0 -4
  683. package/dist/cli/commands/connect.js +0 -163
  684. package/dist/cli/commands/context.js +0 -51
  685. package/dist/cli/commands/create.js +0 -139
  686. package/dist/cli/commands/deploy.d.ts +0 -6
  687. package/dist/cli/commands/deploy.js +0 -74
  688. package/dist/cli/commands/dev.js +0 -227
  689. package/dist/cli/commands/diagram.js +0 -39
  690. package/dist/cli/commands/diff.js +0 -57
  691. package/dist/cli/commands/docs.js +0 -74
  692. package/dist/cli/commands/export.js +0 -153
  693. package/dist/cli/commands/grammar.js +0 -40
  694. package/dist/cli/commands/implement.js +0 -91
  695. package/dist/cli/commands/init-personas.js +0 -541
  696. package/dist/cli/commands/init.js +0 -797
  697. package/dist/cli/commands/market.js +0 -440
  698. package/dist/cli/commands/mcp-setup.js +0 -433
  699. package/dist/cli/commands/migrate.js +0 -91
  700. package/dist/cli/commands/modify.js +0 -58
  701. package/dist/cli/commands/openapi.js +0 -71
  702. package/dist/cli/commands/org.d.ts +0 -8
  703. package/dist/cli/commands/org.js +0 -136
  704. package/dist/cli/commands/pattern.d.ts +0 -34
  705. package/dist/cli/commands/pattern.js +0 -186
  706. package/dist/cli/commands/plugin.d.ts +0 -16
  707. package/dist/cli/commands/plugin.js +0 -176
  708. package/dist/cli/commands/run.js +0 -742
  709. package/dist/cli/commands/serve.js +0 -93
  710. package/dist/cli/commands/status.js +0 -123
  711. package/dist/cli/commands/strip.js +0 -61
  712. package/dist/cli/commands/templates.js +0 -58
  713. package/dist/cli/commands/validate.js +0 -267
  714. package/dist/cli/commands/watch.js +0 -71
  715. package/dist/cli/config/credentials.d.ts +0 -15
  716. package/dist/cli/config/credentials.js +0 -43
  717. package/dist/cli/config/platform-client.d.ts +0 -123
  718. package/dist/cli/config/platform-client.js +0 -248
  719. package/dist/cli/env-setup.js +0 -12
  720. package/dist/cli/index.js +0 -850
  721. package/dist/cli/pack-commands.js +0 -122
  722. package/dist/cli/postinstall.d.ts +0 -16
  723. package/dist/cli/postinstall.js +0 -119
  724. package/dist/cli/templates/ai/mock-provider.js +0 -64
  725. package/dist/cli/templates/ai/types.js +0 -5
  726. package/dist/cli/templates/approvals/index.d.ts +0 -15
  727. package/dist/cli/templates/approvals/index.js +0 -241
  728. package/dist/cli/templates/index.js +0 -123
  729. package/dist/cli/templates/nodes/agent-router.js +0 -114
  730. package/dist/cli/templates/nodes/aggregator.js +0 -63
  731. package/dist/cli/templates/nodes/conversation-memory.js +0 -85
  732. package/dist/cli/templates/nodes/http.js +0 -80
  733. package/dist/cli/templates/nodes/human-approval.js +0 -109
  734. package/dist/cli/templates/nodes/json-extractor.js +0 -119
  735. package/dist/cli/templates/nodes/llm-call.js +0 -106
  736. package/dist/cli/templates/nodes/prompt-template.js +0 -52
  737. package/dist/cli/templates/nodes/rag-retriever.js +0 -128
  738. package/dist/cli/templates/nodes/tool-executor.js +0 -108
  739. package/dist/cli/templates/nodes/transformer.js +0 -68
  740. package/dist/cli/templates/nodes/validator.js +0 -62
  741. package/dist/cli/templates/pack-loader.js +0 -58
  742. package/dist/cli/templates/providers/index.js +0 -239
  743. package/dist/cli/templates/shared/approval-types.js +0 -31
  744. package/dist/cli/templates/shared/llm-types.js +0 -109
  745. package/dist/cli/templates/workflows/aggregator.js +0 -101
  746. package/dist/cli/templates/workflows/ai-agent.js +0 -326
  747. package/dist/cli/templates/workflows/ai-chat.js +0 -167
  748. package/dist/cli/templates/workflows/ai-rag.js +0 -184
  749. package/dist/cli/templates/workflows/ai-react.js +0 -293
  750. package/dist/cli/templates/workflows/conditional.js +0 -139
  751. package/dist/cli/templates/workflows/error-handler.js +0 -145
  752. package/dist/cli/templates/workflows/foreach.js +0 -140
  753. package/dist/cli/templates/workflows/sequential.js +0 -200
  754. package/dist/cli/templates/workflows/webhook.js +0 -158
  755. package/dist/cli/utils/cli-helpers.d.ts +0 -44
  756. package/dist/cli/utils/cli-helpers.js +0 -99
  757. package/dist/cli/utils/logger.js +0 -126
  758. package/dist/cli/utils/parse-int-strict.js +0 -17
  759. package/dist/cli/utils/safe-write.js +0 -54
  760. package/dist/deployment/config/defaults.d.ts +0 -29
  761. package/dist/deployment/config/defaults.js +0 -98
  762. package/dist/deployment/config/loader.d.ts +0 -24
  763. package/dist/deployment/config/loader.js +0 -237
  764. package/dist/deployment/config/types.d.ts +0 -117
  765. package/dist/deployment/config/types.js +0 -5
  766. package/dist/deployment/core/adapters.d.ts +0 -66
  767. package/dist/deployment/core/adapters.js +0 -156
  768. package/dist/deployment/core/executor.d.ts +0 -62
  769. package/dist/deployment/core/executor.js +0 -197
  770. package/dist/deployment/core/formatters.d.ts +0 -42
  771. package/dist/deployment/core/formatters.js +0 -146
  772. package/dist/deployment/openapi/generator.d.ts +0 -146
  773. package/dist/deployment/openapi/generator.js +0 -347
  774. package/dist/deployment/openapi/schema-converter.d.ts +0 -49
  775. package/dist/deployment/openapi/schema-converter.js +0 -192
  776. package/dist/deployment/targets/base.js +0 -855
  777. package/dist/deployment/types.d.ts +0 -140
  778. package/dist/deployment/types.js +0 -8
  779. package/dist/diagram/ascii-renderer.js +0 -528
  780. package/dist/diagram/geometry.js +0 -1226
  781. package/dist/diagram/html-viewer.d.ts +0 -21
  782. package/dist/diagram/html-viewer.js +0 -1745
  783. package/dist/diagram/layout.js +0 -143
  784. package/dist/diagram/orthogonal-router.js +0 -458
  785. package/dist/diagram/renderer.d.ts +0 -3
  786. package/dist/diagram/renderer.js +0 -280
  787. package/dist/diagram/theme.js +0 -282
  788. package/dist/diagram/types.js +0 -2
  789. package/dist/diff/WorkflowDiffer.js +0 -429
  790. package/dist/diff/formatDiff.js +0 -239
  791. package/dist/diff/impact.js +0 -119
  792. package/dist/diff/types.js +0 -35
  793. package/dist/doc-metadata/extractors/annotations.js +0 -638
  794. package/dist/doc-metadata/extractors/cli-commands.js +0 -326
  795. package/dist/doc-metadata/extractors/core-metadata.js +0 -61
  796. package/dist/doc-metadata/extractors/error-codes.js +0 -372
  797. package/dist/doc-metadata/extractors/grammar-rules.js +0 -51
  798. package/dist/doc-metadata/extractors/mcp-tools.js +0 -705
  799. package/dist/doc-metadata/extractors/plugin-api.d.ts +0 -19
  800. package/dist/doc-metadata/extractors/plugin-api.js +0 -279
  801. package/dist/doc-metadata/types.js +0 -5
  802. package/dist/editor-completions/annotationValues.js +0 -146
  803. package/dist/editor-completions/contextParser.js +0 -410
  804. package/dist/editor-completions/dataTypes.js +0 -95
  805. package/dist/editor-completions/goToDefinition.js +0 -112
  806. package/dist/editor-completions/jsDocAnnotations.js +0 -359
  807. package/dist/editor-completions/modifierCompletions.js +0 -197
  808. package/dist/editor-completions/types.js +0 -8
  809. package/dist/export/index.js +0 -212
  810. package/dist/extensions/index.d.ts +0 -16
  811. package/dist/extensions/index.js +0 -17
  812. package/dist/friendly-errors.js +0 -761
  813. package/dist/function-like.js +0 -84
  814. package/dist/generator/async-detection.js +0 -56
  815. package/dist/generator/code-utils.js +0 -551
  816. package/dist/generator/compile-target-registry.d.ts +0 -20
  817. package/dist/generator/compile-target-registry.js +0 -20
  818. package/dist/generator/control-flow.js +0 -358
  819. package/dist/generator/dev-mode-registry.d.ts +0 -27
  820. package/dist/generator/dev-mode-registry.js +0 -20
  821. package/dist/generator/scope-function-generator.js +0 -397
  822. package/dist/generator/unified.js +0 -1831
  823. package/dist/generator.d.ts +0 -54
  824. package/dist/generator.js +0 -101
  825. package/dist/jsdoc-parser.d.ts +0 -377
  826. package/dist/jsdoc-parser.js +0 -1189
  827. package/dist/jsdoc-port-sync/constants.js +0 -103
  828. package/dist/jsdoc-port-sync/diff.js +0 -319
  829. package/dist/jsdoc-port-sync/port-parser.js +0 -579
  830. package/dist/jsdoc-port-sync/rename.js +0 -256
  831. package/dist/jsdoc-port-sync/signature-parser.js +0 -559
  832. package/dist/jsdoc-port-sync/sync.js +0 -653
  833. package/dist/marketplace/manifest.js +0 -194
  834. package/dist/marketplace/registry.js +0 -198
  835. package/dist/marketplace/types.js +0 -9
  836. package/dist/marketplace/validator.js +0 -150
  837. package/dist/mcp/agent-channel.d.ts +0 -35
  838. package/dist/mcp/agent-channel.js +0 -61
  839. package/dist/mcp/auto-registration.d.ts +0 -3
  840. package/dist/mcp/auto-registration.js +0 -62
  841. package/dist/mcp/debug-session.js +0 -25
  842. package/dist/mcp/index.d.ts +0 -11
  843. package/dist/mcp/index.js +0 -10
  844. package/dist/mcp/pack-tools.js +0 -59
  845. package/dist/mcp/prompts.js +0 -68
  846. package/dist/mcp/response-utils.js +0 -97
  847. package/dist/mcp/run-registry.d.ts +0 -29
  848. package/dist/mcp/run-registry.js +0 -24
  849. package/dist/mcp/server.js +0 -63
  850. package/dist/mcp/tools-context.js +0 -51
  851. package/dist/mcp/tools-debug.js +0 -451
  852. package/dist/mcp/tools-diagram.js +0 -97
  853. package/dist/mcp/tools-docs.js +0 -62
  854. package/dist/mcp/tools-export.js +0 -222
  855. package/dist/mcp/tools-marketplace.js +0 -132
  856. package/dist/mcp/tools-model.d.ts +0 -3
  857. package/dist/mcp/tools-model.js +0 -279
  858. package/dist/mcp/tools-pattern.d.ts +0 -3
  859. package/dist/mcp/tools-pattern.js +0 -604
  860. package/dist/mcp/tools-query.js +0 -377
  861. package/dist/mcp/tools-resources.js +0 -41
  862. package/dist/mcp/tools-template.js +0 -119
  863. package/dist/mcp/tools-workflow-run.d.ts +0 -40
  864. package/dist/mcp/tools-workflow-run.js +0 -150
  865. package/dist/mcp/types.js +0 -2
  866. package/dist/mcp/workflow-executor.js +0 -242
  867. package/dist/migration/registry.js +0 -29
  868. package/dist/node-types-generator.js +0 -139
  869. package/dist/parser/tag-registry.js +0 -57
  870. package/dist/parser.d.ts +0 -232
  871. package/dist/parser.js +0 -2500
  872. package/dist/plugin/PluginPanel.d.ts +0 -12
  873. package/dist/plugin/PluginPanel.js +0 -5
  874. package/dist/plugin/index.d.ts +0 -13
  875. package/dist/plugin/index.js +0 -14
  876. package/dist/plugin/types.d.ts +0 -75
  877. package/dist/plugin/types.js +0 -8
  878. package/dist/resolve-package-types.js +0 -123
  879. package/dist/runtime/CancellationError.js +0 -20
  880. package/dist/runtime/ExecutionContext.js +0 -280
  881. package/dist/runtime/builtin-functions.js +0 -549
  882. package/dist/runtime/checkpoint.d.ts +0 -84
  883. package/dist/runtime/checkpoint.js +0 -225
  884. package/dist/runtime/debug-controller.js +0 -247
  885. package/dist/runtime/events.js +0 -2
  886. package/dist/runtime/function-registry.js +0 -66
  887. package/dist/runtime/parameter-resolver.js +0 -113
  888. package/dist/server/types.js +0 -5
  889. package/dist/server/webhook-server.js +0 -269
  890. package/dist/server/workflow-registry.js +0 -202
  891. package/dist/shared-project.js +0 -28
  892. package/dist/sugar-optimizer.js +0 -498
  893. package/dist/testing/assertions.js +0 -127
  894. package/dist/testing/mock-approval.js +0 -98
  895. package/dist/testing/mock-llm.js +0 -119
  896. package/dist/testing/recorder.js +0 -70
  897. package/dist/testing/replayer.js +0 -143
  898. package/dist/testing/token-tracker.js +0 -94
  899. package/dist/type-checker.d.ts +0 -42
  900. package/dist/type-checker.js +0 -190
  901. package/dist/type-mappings.js +0 -131
  902. package/dist/types/branded-ports.d.ts +0 -151
  903. package/dist/types/branded-ports.js +0 -121
  904. package/dist/types/index.d.ts +0 -5
  905. package/dist/types/index.js +0 -5
  906. package/dist/types.d.ts +0 -139
  907. package/dist/types.js +0 -15
  908. package/dist/utils/error-utils.js +0 -27
  909. package/dist/utils/lru-cache.js +0 -40
  910. package/dist/utils/port-ordering.js +0 -81
  911. package/dist/utils/port-tag-utils.js +0 -41
  912. package/dist/utils/string-distance.js +0 -56
  913. package/dist/validation/agent-detection.js +0 -115
  914. package/dist/validation/agent-rules.js +0 -262
  915. package/dist/validation/design-rules.js +0 -377
  916. package/dist/validation/rule-registry.js +0 -37
  917. package/dist/validator.d.ts +0 -113
  918. package/dist/validator.js +0 -1631
  919. package/docs/reference/patterns.md +0 -159
  920. package/scripts/postinstall.cjs +0 -86
  921. /package/dist/{shared-project.d.ts → parser/shared-project.d.ts} +0 -0
  922. /package/dist/{friendly-errors.d.ts → validation/friendly-errors.d.ts} +0 -0
@@ -0,0 +1,4373 @@
1
+ import {
2
+ getErrorMessage
3
+ } from "./chunk-DUO6H5PR.js";
4
+
5
+ // node_modules/js-yaml/dist/js-yaml.mjs
6
+ var NOT_RESOLVED = /* @__PURE__ */ Symbol("NOT_RESOLVED");
7
+ function defineScalarTag(tagName, options) {
8
+ return {
9
+ tagName,
10
+ nodeKind: "scalar",
11
+ implicit: options.implicit ?? false,
12
+ matchByTagPrefix: options.matchByTagPrefix ?? false,
13
+ implicitFirstChars: options.implicitFirstChars ?? null,
14
+ resolve: options.resolve,
15
+ identify: options.identify,
16
+ represent: options.represent ?? ((data) => String(data)),
17
+ representTagName: options.representTagName ?? (() => tagName)
18
+ };
19
+ }
20
+ function defineSequenceTag(tagName, options) {
21
+ const carrierIsResult = options.finalize === void 0;
22
+ return {
23
+ tagName,
24
+ nodeKind: "sequence",
25
+ implicit: false,
26
+ matchByTagPrefix: options.matchByTagPrefix ?? false,
27
+ create: options.create,
28
+ addItem: options.addItem,
29
+ finalize: options.finalize ?? ((carrier) => carrier),
30
+ carrierIsResult,
31
+ identify: options.identify,
32
+ represent: options.represent ?? ((data) => data),
33
+ representTagName: options.representTagName ?? (() => tagName)
34
+ };
35
+ }
36
+ function defineMappingTag(tagName, options) {
37
+ const carrierIsResult = options.finalize === void 0;
38
+ return {
39
+ tagName,
40
+ nodeKind: "mapping",
41
+ implicit: false,
42
+ matchByTagPrefix: options.matchByTagPrefix ?? false,
43
+ create: options.create,
44
+ addPair: options.addPair,
45
+ has: options.has,
46
+ keys: options.keys,
47
+ get: options.get,
48
+ finalize: options.finalize ?? ((carrier) => carrier),
49
+ carrierIsResult,
50
+ identify: options.identify,
51
+ represent: options.represent ?? ((data) => data),
52
+ representTagName: options.representTagName ?? (() => tagName)
53
+ };
54
+ }
55
+ var strTag = defineScalarTag("tag:yaml.org,2002:str", {
56
+ resolve: (source) => source,
57
+ identify: (data) => typeof data === "string"
58
+ });
59
+ var NULL_VALUES$1 = [
60
+ "",
61
+ "~",
62
+ "null",
63
+ "Null",
64
+ "NULL"
65
+ ];
66
+ var nullCoreTag = defineScalarTag("tag:yaml.org,2002:null", {
67
+ implicit: true,
68
+ implicitFirstChars: [
69
+ "",
70
+ "~",
71
+ "n",
72
+ "N"
73
+ ],
74
+ resolve: (source) => {
75
+ if (NULL_VALUES$1.indexOf(source) !== -1) return null;
76
+ return NOT_RESOLVED;
77
+ },
78
+ identify: (object) => object === null,
79
+ represent: () => "null"
80
+ });
81
+ var nullJsonTag = defineScalarTag("tag:yaml.org,2002:null", {
82
+ implicit: true,
83
+ implicitFirstChars: ["n"],
84
+ resolve: (source, isExplicit) => {
85
+ if (source === "null" || isExplicit && source === "") return null;
86
+ return NOT_RESOLVED;
87
+ },
88
+ identify: (object) => object === null,
89
+ represent: () => "null"
90
+ });
91
+ var NULL_VALUES = [
92
+ "",
93
+ "~",
94
+ "null",
95
+ "Null",
96
+ "NULL"
97
+ ];
98
+ var nullYaml11Tag = defineScalarTag("tag:yaml.org,2002:null", {
99
+ implicit: true,
100
+ implicitFirstChars: [
101
+ "",
102
+ "~",
103
+ "n",
104
+ "N"
105
+ ],
106
+ resolve: (source) => {
107
+ if (NULL_VALUES.indexOf(source) !== -1) return null;
108
+ return NOT_RESOLVED;
109
+ },
110
+ identify: (object) => object === null,
111
+ represent: () => "null"
112
+ });
113
+ var TRUE_VALUES$2 = [
114
+ "true",
115
+ "True",
116
+ "TRUE"
117
+ ];
118
+ var FALSE_VALUES$2 = [
119
+ "false",
120
+ "False",
121
+ "FALSE"
122
+ ];
123
+ var boolCoreTag = defineScalarTag("tag:yaml.org,2002:bool", {
124
+ implicit: true,
125
+ implicitFirstChars: [
126
+ "t",
127
+ "T",
128
+ "f",
129
+ "F"
130
+ ],
131
+ resolve: (source) => {
132
+ if (TRUE_VALUES$2.indexOf(source) !== -1) return true;
133
+ if (FALSE_VALUES$2.indexOf(source) !== -1) return false;
134
+ return NOT_RESOLVED;
135
+ },
136
+ identify: (object) => Object.prototype.toString.call(object) === "[object Boolean]",
137
+ represent: (object) => object ? "true" : "false"
138
+ });
139
+ var TRUE_VALUES$1 = ["true"];
140
+ var FALSE_VALUES$1 = ["false"];
141
+ var boolJsonTag = defineScalarTag("tag:yaml.org,2002:bool", {
142
+ implicit: true,
143
+ implicitFirstChars: ["t", "f"],
144
+ resolve: (source) => {
145
+ if (TRUE_VALUES$1.indexOf(source) !== -1) return true;
146
+ if (FALSE_VALUES$1.indexOf(source) !== -1) return false;
147
+ return NOT_RESOLVED;
148
+ },
149
+ identify: (object) => Object.prototype.toString.call(object) === "[object Boolean]",
150
+ represent: (object) => object ? "true" : "false"
151
+ });
152
+ var TRUE_VALUES = [
153
+ "true",
154
+ "True",
155
+ "TRUE",
156
+ "y",
157
+ "Y",
158
+ "yes",
159
+ "Yes",
160
+ "YES",
161
+ "on",
162
+ "On",
163
+ "ON"
164
+ ];
165
+ var FALSE_VALUES = [
166
+ "false",
167
+ "False",
168
+ "FALSE",
169
+ "n",
170
+ "N",
171
+ "no",
172
+ "No",
173
+ "NO",
174
+ "off",
175
+ "Off",
176
+ "OFF"
177
+ ];
178
+ var boolYaml11Tag = defineScalarTag("tag:yaml.org,2002:bool", {
179
+ implicit: true,
180
+ implicitFirstChars: [
181
+ "y",
182
+ "Y",
183
+ "n",
184
+ "N",
185
+ "t",
186
+ "T",
187
+ "f",
188
+ "F",
189
+ "o",
190
+ "O"
191
+ ],
192
+ resolve: (source) => {
193
+ if (TRUE_VALUES.indexOf(source) !== -1) return true;
194
+ if (FALSE_VALUES.indexOf(source) !== -1) return false;
195
+ return NOT_RESOLVED;
196
+ },
197
+ identify: (object) => Object.prototype.toString.call(object) === "[object Boolean]",
198
+ represent: (object) => object ? "true" : "false"
199
+ });
200
+ var YAML_INTEGER_IMPLICIT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:0o[0-7]+|0x[0-9a-fA-F]+|[-+]?[0-9]+)$");
201
+ var YAML_INTEGER_EXPLICIT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");
202
+ function parseYamlInteger$2(source) {
203
+ let value = source;
204
+ let sign = 1;
205
+ if (value[0] === "-" || value[0] === "+") {
206
+ if (value[0] === "-") sign = -1;
207
+ value = value.slice(1);
208
+ }
209
+ if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2);
210
+ if (value.startsWith("0o")) return sign * parseInt(value.slice(2), 8);
211
+ if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16);
212
+ return sign * parseInt(value, 10);
213
+ }
214
+ function resolveYamlInteger$2(source, isExplicit) {
215
+ if (isExplicit) {
216
+ if (!YAML_INTEGER_EXPLICIT_PATTERN$1.test(source)) return NOT_RESOLVED;
217
+ } else if (!YAML_INTEGER_IMPLICIT_PATTERN$1.test(source)) return NOT_RESOLVED;
218
+ const result = parseYamlInteger$2(source);
219
+ return Number.isFinite(result) ? result : NOT_RESOLVED;
220
+ }
221
+ var intCoreTag = defineScalarTag("tag:yaml.org,2002:int", {
222
+ implicit: true,
223
+ implicitFirstChars: [
224
+ "-",
225
+ "+",
226
+ ..."0123456789"
227
+ ],
228
+ resolve: resolveYamlInteger$2,
229
+ identify: (object) => Number.isInteger(object) && !Object.is(object, -0) && object.toString(10).indexOf("e") < 0,
230
+ represent: (object) => object.toString(10)
231
+ });
232
+ var YAML_INTEGER_IMPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^-?(?:0|[1-9][0-9]*)$");
233
+ var YAML_INTEGER_EXPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1]+|[-+]?0o[0-7]+|[-+]?0x[0-9a-fA-F]+|[-+]?[0-9]+)$");
234
+ function parseYamlInteger$1(source) {
235
+ let value = source;
236
+ let sign = 1;
237
+ if (value[0] === "-" || value[0] === "+") {
238
+ if (value[0] === "-") sign = -1;
239
+ value = value.slice(1);
240
+ }
241
+ if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2);
242
+ if (value.startsWith("0o")) return sign * parseInt(value.slice(2), 8);
243
+ if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16);
244
+ return sign * parseInt(value, 10);
245
+ }
246
+ function resolveYamlInteger$1(source, isExplicit) {
247
+ if (isExplicit) {
248
+ if (!YAML_INTEGER_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED;
249
+ } else if (!YAML_INTEGER_IMPLICIT_PATTERN.test(source)) return NOT_RESOLVED;
250
+ const result = parseYamlInteger$1(source);
251
+ return Number.isFinite(result) ? result : NOT_RESOLVED;
252
+ }
253
+ var intJsonTag = defineScalarTag("tag:yaml.org,2002:int", {
254
+ implicit: true,
255
+ implicitFirstChars: ["-", ..."0123456789"],
256
+ resolve: resolveYamlInteger$1,
257
+ identify: (object) => Number.isInteger(object) && !Object.is(object, -0) && object.toString(10).indexOf("e") < 0,
258
+ represent: (object) => object.toString(10)
259
+ });
260
+ var YAML_INTEGER_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?0b[0-1_]+|[-+]?0[0-7_]+|[-+]?0x[0-9a-fA-F_]+|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+|[-+]?(?:0|[1-9][0-9_]*))$");
261
+ function parseYamlInteger(source) {
262
+ let value = source.replace(/_/g, "");
263
+ let sign = 1;
264
+ if (value[0] === "-" || value[0] === "+") {
265
+ if (value[0] === "-") sign = -1;
266
+ value = value.slice(1);
267
+ }
268
+ if (value.startsWith("0b")) return sign * parseInt(value.slice(2), 2);
269
+ if (value.startsWith("0x")) return sign * parseInt(value.slice(2), 16);
270
+ if (value.includes(":")) {
271
+ let result = 0;
272
+ for (const part of value.split(":")) result = result * 60 + Number(part);
273
+ return sign * result;
274
+ }
275
+ if (value !== "0" && value[0] === "0") return sign * parseInt(value, 8);
276
+ return sign * parseInt(value, 10);
277
+ }
278
+ function resolveYamlInteger(source) {
279
+ if (!YAML_INTEGER_PATTERN.test(source)) return NOT_RESOLVED;
280
+ const result = parseYamlInteger(source);
281
+ return Number.isFinite(result) ? result : NOT_RESOLVED;
282
+ }
283
+ var intYaml11Tag = defineScalarTag("tag:yaml.org,2002:int", {
284
+ implicit: true,
285
+ implicitFirstChars: [
286
+ "-",
287
+ "+",
288
+ ..."0123456789"
289
+ ],
290
+ resolve: resolveYamlInteger,
291
+ identify: (object) => Number.isInteger(object) && !Object.is(object, -0) && object.toString(10).indexOf("e") < 0,
292
+ represent: (object) => object.toString(10)
293
+ });
294
+ var YAML_FLOAT_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
295
+ var YAML_FLOAT_SPECIAL_PATTERN$1 = /* @__PURE__ */ new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
296
+ function resolveYamlFloat$2(source) {
297
+ if (!YAML_FLOAT_PATTERN$1.test(source)) return NOT_RESOLVED;
298
+ let value = source.toLowerCase();
299
+ const sign = value[0] === "-" ? -1 : 1;
300
+ if ("+-".includes(value[0])) value = value.slice(1);
301
+ if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
302
+ if (value === ".nan") return NaN;
303
+ const result = sign * parseFloat(value);
304
+ if (Number.isFinite(result) || YAML_FLOAT_SPECIAL_PATTERN$1.test(source)) return result;
305
+ return NOT_RESOLVED;
306
+ }
307
+ function representYamlFloat$2(object) {
308
+ if (isNaN(object)) return ".nan";
309
+ if (object === Number.POSITIVE_INFINITY) return ".inf";
310
+ if (object === Number.NEGATIVE_INFINITY) return "-.inf";
311
+ if (Object.is(object, -0)) return "-0.0";
312
+ const result = object.toString(10);
313
+ return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result;
314
+ }
315
+ var floatCoreTag = defineScalarTag("tag:yaml.org,2002:float", {
316
+ implicit: true,
317
+ implicitFirstChars: [
318
+ "-",
319
+ "+",
320
+ ".",
321
+ ..."0123456789"
322
+ ],
323
+ resolve: resolveYamlFloat$2,
324
+ identify: (object) => typeof object === "number" && (!Number.isInteger(object) || Object.is(object, -0) || object.toString(10).indexOf("e") >= 0),
325
+ represent: representYamlFloat$2
326
+ });
327
+ var YAML_FLOAT_IMPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$");
328
+ var YAML_FLOAT_EXPLICIT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?[0-9]+(?:\\.[0-9]*)?(?:[eE][-+]?[0-9]+)?|[-+]?\\.[0-9]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
329
+ function resolveYamlFloat$1(source, isExplicit) {
330
+ if (isExplicit) {
331
+ if (!YAML_FLOAT_EXPLICIT_PATTERN.test(source)) return NOT_RESOLVED;
332
+ let value = source.toLowerCase();
333
+ const sign = value[0] === "-" ? -1 : 1;
334
+ if ("+-".includes(value[0])) value = value.slice(1);
335
+ if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
336
+ if (value === ".nan") return NaN;
337
+ const result2 = sign * parseFloat(value);
338
+ return Number.isFinite(result2) ? result2 : NOT_RESOLVED;
339
+ }
340
+ if (!YAML_FLOAT_IMPLICIT_PATTERN.test(source)) return NOT_RESOLVED;
341
+ const result = Number(source);
342
+ if (Number.isFinite(result)) return result;
343
+ return NOT_RESOLVED;
344
+ }
345
+ function representYamlFloat$1(object) {
346
+ if (isNaN(object)) return ".nan";
347
+ if (object === Number.POSITIVE_INFINITY) return ".inf";
348
+ if (object === Number.NEGATIVE_INFINITY) return "-.inf";
349
+ if (Object.is(object, -0)) return "-0.0";
350
+ const result = object.toString(10);
351
+ return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result;
352
+ }
353
+ var floatJsonTag = defineScalarTag("tag:yaml.org,2002:float", {
354
+ implicit: true,
355
+ implicitFirstChars: ["-", ..."0123456789"],
356
+ resolve: resolveYamlFloat$1,
357
+ identify: (object) => typeof object === "number" && (!Number.isInteger(object) || Object.is(object, -0) || object.toString(10).indexOf("e") >= 0),
358
+ represent: representYamlFloat$1
359
+ });
360
+ var YAML_FLOAT_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?(?:(?:[0-9][0-9_]*)?\\.[0-9_]*)(?:[eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
361
+ var YAML_FLOAT_SPECIAL_PATTERN = /* @__PURE__ */ new RegExp("^(?:[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");
362
+ function resolveYamlFloat(source) {
363
+ if (!YAML_FLOAT_PATTERN.test(source)) return NOT_RESOLVED;
364
+ let value = source.toLowerCase().replace(/_/g, "");
365
+ const sign = value[0] === "-" ? -1 : 1;
366
+ if ("+-".includes(value[0])) value = value.slice(1);
367
+ if (value === ".inf") return sign === 1 ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;
368
+ if (value === ".nan") return NaN;
369
+ let result = 0;
370
+ if (value.includes(":")) {
371
+ for (const part of value.split(":")) result = result * 60 + Number(part);
372
+ result *= sign;
373
+ } else result = sign * parseFloat(value);
374
+ if (Number.isFinite(result) || YAML_FLOAT_SPECIAL_PATTERN.test(source)) return result;
375
+ return NOT_RESOLVED;
376
+ }
377
+ function representYamlFloat(object) {
378
+ if (isNaN(object)) return ".nan";
379
+ if (object === Number.POSITIVE_INFINITY) return ".inf";
380
+ if (object === Number.NEGATIVE_INFINITY) return "-.inf";
381
+ if (Object.is(object, -0)) return "-0.0";
382
+ const result = object.toString(10);
383
+ return /^[-+]?[0-9]+e/.test(result) ? result.replace("e", ".e") : result;
384
+ }
385
+ var floatYaml11Tag = defineScalarTag("tag:yaml.org,2002:float", {
386
+ implicit: true,
387
+ implicitFirstChars: [
388
+ "-",
389
+ "+",
390
+ ".",
391
+ ..."0123456789"
392
+ ],
393
+ resolve: resolveYamlFloat,
394
+ identify: (object) => typeof object === "number" && (!Number.isInteger(object) || Object.is(object, -0) || object.toString(10).indexOf("e") >= 0),
395
+ represent: representYamlFloat
396
+ });
397
+ var mergeTag = defineScalarTag("tag:yaml.org,2002:merge", {
398
+ implicit: true,
399
+ implicitFirstChars: ["<"],
400
+ resolve: (source, isExplicit) => {
401
+ if (source === "<<" || isExplicit && source === "") return "<<";
402
+ return NOT_RESOLVED;
403
+ },
404
+ identify: () => false
405
+ });
406
+ var BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/;
407
+ function resolveYamlBinary(source) {
408
+ const input = source.replace(/\s/g, "");
409
+ if (input.length % 4 !== 0 || !BASE64_PATTERN.test(input)) return NOT_RESOLVED;
410
+ const binary = atob(input);
411
+ const result = new Uint8Array(binary.length);
412
+ for (let index = 0; index < binary.length; index++) result[index] = binary.charCodeAt(index);
413
+ return result;
414
+ }
415
+ function representYamlBinary(object) {
416
+ let binary = "";
417
+ for (let index = 0; index < object.length; index++) binary += String.fromCharCode(object[index]);
418
+ return btoa(binary);
419
+ }
420
+ var binaryTag = defineScalarTag("tag:yaml.org,2002:binary", {
421
+ resolve: resolveYamlBinary,
422
+ identify: (object) => Object.prototype.toString.call(object) === "[object Uint8Array]",
423
+ represent: representYamlBinary
424
+ });
425
+ var YAML_DATE_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$");
426
+ var YAML_TIMESTAMP_REGEXP = /* @__PURE__ */ new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");
427
+ function makeUtcDate(year, month, day, hour = 0, minute = 0, second = 0, fraction = 0) {
428
+ const date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));
429
+ date.setUTCFullYear(year, month, day);
430
+ return date;
431
+ }
432
+ function resolveYamlTimestamp(source) {
433
+ let match = YAML_DATE_REGEXP.exec(source);
434
+ if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(source);
435
+ if (match === null) return NOT_RESOLVED;
436
+ const year = +match[1];
437
+ const month = +match[2] - 1;
438
+ const day = +match[3];
439
+ if (!match[4]) {
440
+ const date2 = makeUtcDate(year, month, day);
441
+ if (date2.getUTCFullYear() !== year || date2.getUTCMonth() !== month || date2.getUTCDate() !== day) return NOT_RESOLVED;
442
+ return date2;
443
+ }
444
+ const hour = +match[4];
445
+ const minute = +match[5];
446
+ const second = +match[6];
447
+ let fraction = 0;
448
+ if (hour > 23 || minute > 59 || second > 59) return NOT_RESOLVED;
449
+ if (match[7]) {
450
+ let value = match[7].slice(0, 3);
451
+ while (value.length < 3) value += "0";
452
+ fraction = +value;
453
+ }
454
+ const date = makeUtcDate(year, month, day, hour, minute, second, fraction);
455
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month || date.getUTCDate() !== day) return NOT_RESOLVED;
456
+ if (match[9]) {
457
+ const offsetHour = +match[10];
458
+ const offsetMinute = +(match[11] || 0);
459
+ if (offsetHour > 23 || offsetMinute > 59) return NOT_RESOLVED;
460
+ const offset = (offsetHour * 60 + offsetMinute) * 6e4;
461
+ date.setTime(date.getTime() - (match[9] === "-" ? -offset : offset));
462
+ }
463
+ return date;
464
+ }
465
+ var timestampTag = defineScalarTag("tag:yaml.org,2002:timestamp", {
466
+ implicit: true,
467
+ implicitFirstChars: [..."0123456789"],
468
+ resolve: resolveYamlTimestamp,
469
+ identify: (object) => object instanceof Date,
470
+ represent: (object) => object.toISOString()
471
+ });
472
+ var seqTag = defineSequenceTag("tag:yaml.org,2002:seq", {
473
+ create: () => [],
474
+ addItem: (container, item) => {
475
+ container.push(item);
476
+ },
477
+ identify: Array.isArray
478
+ });
479
+ function isPlainObject(data) {
480
+ if (data === null || typeof data !== "object" || Array.isArray(data)) return false;
481
+ const prototype = Object.getPrototypeOf(data);
482
+ return prototype === null || prototype === Object.prototype;
483
+ }
484
+ function pick(object, keys) {
485
+ const result = {};
486
+ for (const key of keys) if (object[key] !== void 0) result[key] = object[key];
487
+ return result;
488
+ }
489
+ var omapTag = defineSequenceTag("tag:yaml.org,2002:omap", {
490
+ create: () => ({
491
+ list: [],
492
+ seen: /* @__PURE__ */ new Set()
493
+ }),
494
+ addItem: (carrier, item) => {
495
+ let key;
496
+ if (item instanceof Map) {
497
+ if (item.size !== 1) return "cannot resolve an ordered map item";
498
+ key = item.keys().next().value;
499
+ } else if (isPlainObject(item)) {
500
+ const itemKeys = Object.keys(item);
501
+ if (itemKeys.length !== 1) return "cannot resolve an ordered map item";
502
+ key = itemKeys[0];
503
+ } else return "cannot resolve an ordered map item";
504
+ if (carrier.seen.has(key)) return "duplicate key in ordered map";
505
+ carrier.seen.add(key);
506
+ carrier.list.push(item);
507
+ return "";
508
+ },
509
+ finalize: (carrier) => carrier.list,
510
+ identify: () => false
511
+ });
512
+ var pairsTag = defineSequenceTag("tag:yaml.org,2002:pairs", {
513
+ create: () => [],
514
+ addItem: (container, item) => {
515
+ if (item instanceof Map) {
516
+ if (item.size !== 1) return "cannot resolve a pairs item";
517
+ container.push(item.entries().next().value);
518
+ return "";
519
+ }
520
+ if (Object.prototype.toString.call(item) !== "[object Object]") return "cannot resolve a pairs item";
521
+ const object = item;
522
+ const keys = Object.keys(object);
523
+ if (keys.length !== 1) return "cannot resolve a pairs item";
524
+ container.push([keys[0], object[keys[0]]]);
525
+ return "";
526
+ },
527
+ identify: () => false
528
+ });
529
+ var mapTag = defineMappingTag("tag:yaml.org,2002:map", {
530
+ create: () => ({}),
531
+ identify: isPlainObject,
532
+ represent: (o) => {
533
+ const map = /* @__PURE__ */ new Map();
534
+ for (const key of Object.keys(o)) map.set(key, o[key]);
535
+ return map;
536
+ },
537
+ addPair: (container, key, value) => {
538
+ if (key !== null && typeof key === "object") return "object-based map does not support complex keys";
539
+ const normalizedKey = String(key);
540
+ if (normalizedKey === "__proto__") Object.defineProperty(container, normalizedKey, {
541
+ value,
542
+ enumerable: true,
543
+ configurable: true,
544
+ writable: true
545
+ });
546
+ else container[normalizedKey] = value;
547
+ return "";
548
+ },
549
+ has: (container, key) => {
550
+ if (key !== null && typeof key === "object") return false;
551
+ return Object.prototype.hasOwnProperty.call(container, String(key));
552
+ },
553
+ keys: (container) => Object.keys(container),
554
+ get: (container, key) => {
555
+ const normalizedKey = String(key);
556
+ if (!Object.prototype.hasOwnProperty.call(container, normalizedKey)) return null;
557
+ return container[normalizedKey];
558
+ }
559
+ });
560
+ var setTag = defineMappingTag("tag:yaml.org,2002:set", {
561
+ create: () => /* @__PURE__ */ new Set(),
562
+ identify: (data) => data instanceof Set,
563
+ represent: (data) => {
564
+ const map = /* @__PURE__ */ new Map();
565
+ for (const key of data) map.set(key, null);
566
+ return map;
567
+ },
568
+ addPair: (container, key, value) => {
569
+ if (value !== null) return "cannot resolve a set item";
570
+ container.add(key);
571
+ return "";
572
+ },
573
+ has: (container, key) => container.has(key),
574
+ keys: (container) => container.keys(),
575
+ get: () => null
576
+ });
577
+ function createTagDefinitionMap() {
578
+ return {
579
+ scalar: /* @__PURE__ */ Object.create(null),
580
+ sequence: /* @__PURE__ */ Object.create(null),
581
+ mapping: /* @__PURE__ */ Object.create(null)
582
+ };
583
+ }
584
+ function createTagDefinitionListMap() {
585
+ return {
586
+ scalar: [],
587
+ sequence: [],
588
+ mapping: []
589
+ };
590
+ }
591
+ function compileTags(tags) {
592
+ const result = [];
593
+ for (const tag of tags) {
594
+ let index = result.length;
595
+ for (let previousIndex = 0; previousIndex < result.length; previousIndex++) {
596
+ const previous = result[previousIndex];
597
+ if (previous.nodeKind === tag.nodeKind && previous.tagName === tag.tagName && previous.matchByTagPrefix === tag.matchByTagPrefix) {
598
+ index = previousIndex;
599
+ break;
600
+ }
601
+ }
602
+ result[index] = tag;
603
+ }
604
+ return result;
605
+ }
606
+ var Schema = class Schema2 {
607
+ tags;
608
+ /** @internal */
609
+ implicitScalarTags;
610
+ /**
611
+ * Dispatch implicit scalar resolvers by `source.charAt(0)`. Each bucket holds
612
+ * the resolvers that may match that key, in schema order; a key absent from
613
+ * the map uses
614
+ * {@link Schema.implicitScalarAnyFirstChar}
615
+ * (resolvers that declared no first-char constraint, so they apply to any
616
+ * first character).
617
+ */
618
+ implicitScalarByFirstChar;
619
+ implicitScalarAnyFirstChar;
620
+ /**
621
+ * The default scalar tag (`!!str`), resolved once so the composer's fallback
622
+ * for unresolved plain scalars avoids a keyed lookup per scalar.
623
+ *
624
+ * @internal
625
+ */
626
+ defaultScalarTag;
627
+ /**
628
+ * The default container tags (`!!seq` / `!!map`), used by the dumper: when a
629
+ * value is identified by its default tag, the tag is implicit and not
630
+ * printed. Undefined if the schema does not define them (then such values
631
+ * can't be dumped).
632
+ *
633
+ * @internal
634
+ */
635
+ defaultSequenceTag;
636
+ /** @internal */
637
+ defaultMappingTag;
638
+ exact;
639
+ prefix;
640
+ constructor(tags) {
641
+ const compiledTags = compileTags(tags);
642
+ const implicitScalarTags = [];
643
+ const exact = createTagDefinitionMap();
644
+ const prefix = createTagDefinitionListMap();
645
+ for (const tag of compiledTags) {
646
+ if (tag.nodeKind === "scalar" && tag.implicit) {
647
+ if (tag.matchByTagPrefix) throw new Error("Implicit scalar tags cannot match by tag prefix");
648
+ implicitScalarTags.push(tag);
649
+ }
650
+ switch (tag.nodeKind) {
651
+ case "scalar":
652
+ if (tag.matchByTagPrefix) prefix.scalar.push(tag);
653
+ else exact.scalar[tag.tagName] = tag;
654
+ break;
655
+ case "sequence":
656
+ if (tag.matchByTagPrefix) prefix.sequence.push(tag);
657
+ else exact.sequence[tag.tagName] = tag;
658
+ break;
659
+ case "mapping":
660
+ if (tag.matchByTagPrefix) prefix.mapping.push(tag);
661
+ else exact.mapping[tag.tagName] = tag;
662
+ break;
663
+ }
664
+ }
665
+ const implicitScalarAnyFirstChar = implicitScalarTags.filter((tag) => tag.implicitFirstChars === null);
666
+ const keys = /* @__PURE__ */ new Set();
667
+ for (const tag of implicitScalarTags) if (tag.implicitFirstChars !== null) for (const key of tag.implicitFirstChars) keys.add(key);
668
+ const implicitScalarByFirstChar = /* @__PURE__ */ new Map();
669
+ for (const key of keys) implicitScalarByFirstChar.set(key, implicitScalarTags.filter((tag) => tag.implicitFirstChars === null || tag.implicitFirstChars.indexOf(key) !== -1));
670
+ const defaultScalarTag = exact.scalar["tag:yaml.org,2002:str"];
671
+ if (!defaultScalarTag) throw new Error("schema does not define the default scalar tag (tag:yaml.org,2002:str)");
672
+ this.tags = compiledTags;
673
+ this.implicitScalarTags = implicitScalarTags;
674
+ this.implicitScalarByFirstChar = implicitScalarByFirstChar;
675
+ this.implicitScalarAnyFirstChar = implicitScalarAnyFirstChar;
676
+ this.defaultScalarTag = defaultScalarTag;
677
+ this.defaultSequenceTag = exact.sequence["tag:yaml.org,2002:seq"];
678
+ this.defaultMappingTag = exact.mapping["tag:yaml.org,2002:map"];
679
+ this.exact = exact;
680
+ this.prefix = prefix;
681
+ }
682
+ /** @internal */
683
+ lookupScalarTag(tagName) {
684
+ const exactTag = this.exact.scalar[tagName];
685
+ if (exactTag) return exactTag;
686
+ for (const tag of this.prefix.scalar) if (tagName.startsWith(tag.tagName)) return tag;
687
+ }
688
+ /** @internal */
689
+ lookupSequenceTag(tagName) {
690
+ const exactTag = this.exact.sequence[tagName];
691
+ if (exactTag) return exactTag;
692
+ for (const tag of this.prefix.sequence) if (tagName.startsWith(tag.tagName)) return tag;
693
+ }
694
+ /** @internal */
695
+ lookupMappingTag(tagName) {
696
+ const exactTag = this.exact.mapping[tagName];
697
+ if (exactTag) return exactTag;
698
+ for (const tag of this.prefix.mapping) if (tagName.startsWith(tag.tagName)) return tag;
699
+ }
700
+ /** @internal */
701
+ resolveImplicitScalarTag(source) {
702
+ const candidates = this.implicitScalarByFirstChar.get(source.charAt(0)) ?? this.implicitScalarAnyFirstChar;
703
+ for (const tag2 of candidates) {
704
+ const value = tag2.resolve(source, false, tag2.tagName);
705
+ if (value !== NOT_RESOLVED) return {
706
+ value,
707
+ tag: tag2
708
+ };
709
+ }
710
+ const tag = this.defaultScalarTag;
711
+ return {
712
+ value: tag.resolve(source, false, tag.tagName),
713
+ tag
714
+ };
715
+ }
716
+ /**
717
+ * Creates a new schema with the specified tags added. If a tag already
718
+ * exists, it is replaced by the specified tag.
719
+ *
720
+ * @example
721
+ *
722
+ * ```javascript
723
+ * import { CORE_SCHEMA, mergeTag, realMapTag } from 'js-yaml'
724
+ *
725
+ * const schema = CORE_SCHEMA.withTags(mergeTag, realMapTag)
726
+ * ```
727
+ */
728
+ withTags(...tags) {
729
+ let flatTags = [];
730
+ for (const tag of tags) flatTags = flatTags.concat(tag);
731
+ return new Schema2([...this.tags, ...flatTags]);
732
+ }
733
+ };
734
+ var FAILSAFE_SCHEMA = new Schema([
735
+ strTag,
736
+ seqTag,
737
+ mapTag
738
+ ]);
739
+ var JSON_SCHEMA = new Schema([
740
+ ...FAILSAFE_SCHEMA.tags,
741
+ nullJsonTag,
742
+ boolJsonTag,
743
+ intJsonTag,
744
+ floatJsonTag
745
+ ]);
746
+ var CORE_SCHEMA = new Schema([
747
+ ...FAILSAFE_SCHEMA.tags,
748
+ nullCoreTag,
749
+ boolCoreTag,
750
+ intCoreTag,
751
+ floatCoreTag
752
+ ]);
753
+ var YAML11_SCHEMA = new Schema([
754
+ ...FAILSAFE_SCHEMA.tags,
755
+ nullYaml11Tag,
756
+ boolYaml11Tag,
757
+ intYaml11Tag,
758
+ floatYaml11Tag,
759
+ timestampTag,
760
+ mergeTag,
761
+ binaryTag,
762
+ omapTag,
763
+ pairsTag,
764
+ setTag
765
+ ]);
766
+ var DUMP_SCHEMA = YAML11_SCHEMA.withTags({
767
+ ...intYaml11Tag,
768
+ resolve: (source, isExplicit, tagName) => {
769
+ const result = intYaml11Tag.resolve(source, isExplicit, tagName);
770
+ return result === NOT_RESOLVED ? intCoreTag.resolve(source, isExplicit, tagName) : result;
771
+ }
772
+ }, {
773
+ ...floatYaml11Tag,
774
+ resolve: (source, isExplicit, tagName) => {
775
+ const result = floatYaml11Tag.resolve(source, isExplicit, tagName);
776
+ return result === NOT_RESOLVED ? floatCoreTag.resolve(source, isExplicit, tagName) : result;
777
+ }
778
+ });
779
+ var realMapTag = defineMappingTag("tag:yaml.org,2002:map", {
780
+ create: () => /* @__PURE__ */ new Map(),
781
+ addPair: (container, key, value) => {
782
+ container.set(key, value);
783
+ return "";
784
+ },
785
+ has: (container, key) => container.has(key),
786
+ keys: (container) => container.keys(),
787
+ get: (container, key) => container.get(key),
788
+ identify: (data) => data instanceof Map || isPlainObject(data),
789
+ represent: (data) => {
790
+ if (data instanceof Map) return data;
791
+ const map = /* @__PURE__ */ new Map();
792
+ const obj = data;
793
+ for (const key of Object.keys(obj)) map.set(key, obj[key]);
794
+ return map;
795
+ }
796
+ });
797
+ function normalizeKey(key) {
798
+ if (Array.isArray(key)) {
799
+ const array = Array.prototype.slice.call(key);
800
+ for (let index = 0; index < array.length; index++) {
801
+ if (Array.isArray(array[index])) return null;
802
+ if (typeof array[index] === "object" && Object.prototype.toString.call(array[index]) === "[object Object]") array[index] = "[object Object]";
803
+ }
804
+ return String(array);
805
+ }
806
+ if (typeof key === "object" && Object.prototype.toString.call(key) === "[object Object]") return "[object Object]";
807
+ return String(key);
808
+ }
809
+ var legacyMapTag = defineMappingTag("tag:yaml.org,2002:map", {
810
+ create: () => ({}),
811
+ identify: isPlainObject,
812
+ represent: (o) => {
813
+ const map = /* @__PURE__ */ new Map();
814
+ for (const key of Object.keys(o)) map.set(key, o[key]);
815
+ return map;
816
+ },
817
+ addPair: (container, key, value) => {
818
+ const normalizedKey = normalizeKey(key);
819
+ if (normalizedKey === null) return "nested arrays are not supported inside keys";
820
+ if (normalizedKey === "__proto__") Object.defineProperty(container, normalizedKey, {
821
+ value,
822
+ enumerable: true,
823
+ configurable: true,
824
+ writable: true
825
+ });
826
+ else container[normalizedKey] = value;
827
+ return "";
828
+ },
829
+ has: (container, key) => {
830
+ const normalizedKey = normalizeKey(key);
831
+ return normalizedKey !== null && Object.prototype.hasOwnProperty.call(container, normalizedKey);
832
+ },
833
+ keys: (container) => Object.keys(container),
834
+ get: (container, key) => {
835
+ const normalizedKey = String(key);
836
+ if (!Object.prototype.hasOwnProperty.call(container, normalizedKey)) return null;
837
+ return container[normalizedKey];
838
+ }
839
+ });
840
+ var DEFAULT_SNIPPET_OPTIONS = {
841
+ maxLength: 79,
842
+ indent: 1,
843
+ linesBefore: 3,
844
+ linesAfter: 2
845
+ };
846
+ function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
847
+ let head = "";
848
+ let tail = "";
849
+ const maxHalfLength = Math.floor(maxLineLength / 2) - 1;
850
+ if (position - lineStart > maxHalfLength) {
851
+ head = " ... ";
852
+ lineStart = position - maxHalfLength + head.length;
853
+ }
854
+ if (lineEnd - position > maxHalfLength) {
855
+ tail = " ...";
856
+ lineEnd = position + maxHalfLength - tail.length;
857
+ }
858
+ return {
859
+ str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, "\u2192") + tail,
860
+ pos: position - lineStart + head.length
861
+ };
862
+ }
863
+ function padStart(string, max) {
864
+ return " ".repeat(Math.max(max - string.length, 0)) + string;
865
+ }
866
+ function makeSnippet(mark, options) {
867
+ if (!mark.buffer) return null;
868
+ const opts = {
869
+ ...DEFAULT_SNIPPET_OPTIONS,
870
+ ...options
871
+ };
872
+ const re = /\r?\n|\r|\0/g;
873
+ const lineStarts = [0];
874
+ const lineEnds = [];
875
+ let match;
876
+ let foundLineNo = -1;
877
+ while (match = re.exec(mark.buffer)) {
878
+ lineEnds.push(match.index);
879
+ lineStarts.push(match.index + match[0].length);
880
+ if (mark.position <= match.index && foundLineNo < 0) foundLineNo = lineStarts.length - 2;
881
+ }
882
+ if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;
883
+ let result = "";
884
+ const lineNoLength = Math.min(mark.line + opts.linesAfter, lineEnds.length).toString().length;
885
+ const maxLineLength = opts.maxLength - (opts.indent + lineNoLength + 3);
886
+ for (let i = 1; i <= opts.linesBefore; i++) {
887
+ if (foundLineNo - i < 0) break;
888
+ const line2 = getLine(mark.buffer, lineStarts[foundLineNo - i], lineEnds[foundLineNo - i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), maxLineLength);
889
+ result = `${" ".repeat(opts.indent)}${padStart((mark.line - i + 1).toString(), lineNoLength)} | ${line2.str}
890
+ ${result}`;
891
+ }
892
+ const line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
893
+ result += `${" ".repeat(opts.indent)}${padStart((mark.line + 1).toString(), lineNoLength)} | ${line.str}
894
+ `;
895
+ result += `${"-".repeat(opts.indent + lineNoLength + 3 + line.pos)}^
896
+ `;
897
+ for (let i = 1; i <= opts.linesAfter; i++) {
898
+ if (foundLineNo + i >= lineEnds.length) break;
899
+ const line2 = getLine(mark.buffer, lineStarts[foundLineNo + i], lineEnds[foundLineNo + i], mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), maxLineLength);
900
+ result += `${" ".repeat(opts.indent)}${padStart((mark.line + i + 1).toString(), lineNoLength)} | ${line2.str}
901
+ `;
902
+ }
903
+ return result.replace(/\n$/, "");
904
+ }
905
+ function formatError(exception, compact) {
906
+ let where = "";
907
+ if (!exception.mark) return exception.reason;
908
+ if (exception.mark.name) where += `in "${exception.mark.name}" `;
909
+ where += `(${exception.mark.line + 1}:${exception.mark.column + 1})`;
910
+ if (!compact && exception.mark.snippet) where += `
911
+
912
+ ${exception.mark.snippet}`;
913
+ return `${exception.reason} ${where}`;
914
+ }
915
+ var YAMLException = class YAMLException2 extends Error {
916
+ reason;
917
+ mark;
918
+ /**
919
+ * Optional `mark` contains source snippet data. Usually, use
920
+ * {@link YAMLException.throwAt} instead of passing it directly.
921
+ */
922
+ constructor(reason, mark) {
923
+ super();
924
+ this.name = "YAMLException";
925
+ this.reason = reason;
926
+ this.mark = mark;
927
+ this.message = formatError(this, false);
928
+ if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
929
+ }
930
+ /**
931
+ * Returns the formatted error, omitting the source snippet in compact mode.
932
+ */
933
+ toString(compact) {
934
+ return `${this.name}: ${formatError(this, compact)}`;
935
+ }
936
+ /**
937
+ * Builds a YAMLException with a source snippet and throws it. `source` is
938
+ * the raw input text; `position` is an offset into it.
939
+ */
940
+ static throwAt(source, position, message, filename = "") {
941
+ let line = 0;
942
+ let lineStart = 0;
943
+ for (let index = 0; index < position; index++) {
944
+ const ch = source.charCodeAt(index);
945
+ if (ch === 10) {
946
+ line++;
947
+ lineStart = index + 1;
948
+ } else if (ch === 13) {
949
+ line++;
950
+ if (source.charCodeAt(index + 1) === 10) index++;
951
+ lineStart = index + 1;
952
+ }
953
+ }
954
+ const mark = {
955
+ name: filename,
956
+ buffer: source,
957
+ position,
958
+ line,
959
+ column: position - lineStart
960
+ };
961
+ mark.snippet = makeSnippet(mark);
962
+ throw new YAMLException2(message, mark);
963
+ }
964
+ };
965
+ var EVENT_ID = {
966
+ DOCUMENT: 1,
967
+ SEQUENCE: 2,
968
+ MAPPING: 3,
969
+ SCALAR: 4,
970
+ ALIAS: 5,
971
+ POP: 6
972
+ };
973
+ var SCALAR_STYLE = {
974
+ PLAIN: 1,
975
+ SINGLE_QUOTED: 2,
976
+ DOUBLE_QUOTED: 3,
977
+ LITERAL_BLOCK: 4,
978
+ FOLDED_BLOCK: 5
979
+ };
980
+ var COLLECTION_STYLE = {
981
+ BLOCK: 1,
982
+ FLOW: 2
983
+ };
984
+ var CHOMPING_MODE = {
985
+ CLIP: 1,
986
+ STRIP: 2,
987
+ KEEP: 3
988
+ };
989
+ var NO_RANGE$3 = -1;
990
+ function simpleEscapeSequence(c) {
991
+ switch (c) {
992
+ case 48:
993
+ return "\0";
994
+ case 97:
995
+ return "\x07";
996
+ case 98:
997
+ return "\b";
998
+ case 116:
999
+ return " ";
1000
+ case 9:
1001
+ return " ";
1002
+ case 110:
1003
+ return "\n";
1004
+ case 118:
1005
+ return "\v";
1006
+ case 102:
1007
+ return "\f";
1008
+ case 114:
1009
+ return "\r";
1010
+ case 101:
1011
+ return "\x1B";
1012
+ case 32:
1013
+ return " ";
1014
+ case 34:
1015
+ return '"';
1016
+ case 47:
1017
+ return "/";
1018
+ case 92:
1019
+ return "\\";
1020
+ case 78:
1021
+ return "\x85";
1022
+ case 95:
1023
+ return "\xA0";
1024
+ case 76:
1025
+ return "\u2028";
1026
+ case 80:
1027
+ return "\u2029";
1028
+ default:
1029
+ return "";
1030
+ }
1031
+ }
1032
+ var simpleEscapeCheck = new Array(256);
1033
+ var simpleEscapeMap = new Array(256);
1034
+ for (let i = 0; i < 256; i++) {
1035
+ simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
1036
+ simpleEscapeMap[i] = simpleEscapeSequence(i);
1037
+ }
1038
+ function charFromCodepoint(c) {
1039
+ if (c <= 65535) return String.fromCharCode(c);
1040
+ return String.fromCharCode((c - 65536 >> 10) + 55296, (c - 65536 & 1023) + 56320);
1041
+ }
1042
+ function fromHexCode$1(c) {
1043
+ if (c >= 48 && c <= 57) return c - 48;
1044
+ return (c | 32) - 97 + 10;
1045
+ }
1046
+ function escapedHexLen$1(c) {
1047
+ if (c === 120) return 2;
1048
+ if (c === 117) return 4;
1049
+ return 8;
1050
+ }
1051
+ function skipFoldedBreaks(input, position, end) {
1052
+ let breaks = 0;
1053
+ while (position < end) {
1054
+ const ch = input.charCodeAt(position);
1055
+ if (ch === 10) {
1056
+ breaks++;
1057
+ position++;
1058
+ } else if (ch === 13) {
1059
+ breaks++;
1060
+ position++;
1061
+ if (input.charCodeAt(position) === 10) position++;
1062
+ } else if (ch === 32 || ch === 9) position++;
1063
+ else break;
1064
+ }
1065
+ return {
1066
+ position,
1067
+ breaks
1068
+ };
1069
+ }
1070
+ function foldedBreaks(count) {
1071
+ if (count === 1) return " ";
1072
+ return "\n".repeat(count - 1);
1073
+ }
1074
+ function getPlainValue(input, start, end) {
1075
+ let result = "";
1076
+ let position = start;
1077
+ let captureStart = start;
1078
+ let captureEnd = start;
1079
+ while (position < end) {
1080
+ const ch = input.charCodeAt(position);
1081
+ if (ch === 10 || ch === 13) {
1082
+ result += input.slice(captureStart, captureEnd);
1083
+ const fold = skipFoldedBreaks(input, position, end);
1084
+ result += foldedBreaks(fold.breaks);
1085
+ position = captureStart = captureEnd = fold.position;
1086
+ } else {
1087
+ position++;
1088
+ if (ch !== 32 && ch !== 9) captureEnd = position;
1089
+ }
1090
+ }
1091
+ return result + input.slice(captureStart, captureEnd);
1092
+ }
1093
+ function getSingleQuotedValue(input, start, end) {
1094
+ let result = "";
1095
+ let position = start;
1096
+ let captureStart = start;
1097
+ let captureEnd = start;
1098
+ while (position < end) {
1099
+ const ch = input.charCodeAt(position);
1100
+ if (ch === 39) {
1101
+ result += input.slice(captureStart, position) + "'";
1102
+ position += 2;
1103
+ captureStart = captureEnd = position;
1104
+ } else if (ch === 10 || ch === 13) {
1105
+ result += input.slice(captureStart, captureEnd);
1106
+ const fold = skipFoldedBreaks(input, position, end);
1107
+ result += foldedBreaks(fold.breaks);
1108
+ position = captureStart = captureEnd = fold.position;
1109
+ } else {
1110
+ position++;
1111
+ if (ch !== 32 && ch !== 9) captureEnd = position;
1112
+ }
1113
+ }
1114
+ return result + input.slice(captureStart, end);
1115
+ }
1116
+ function getDoubleQuotedValue(input, start, end) {
1117
+ let result = "";
1118
+ let position = start;
1119
+ let captureStart = start;
1120
+ let captureEnd = start;
1121
+ while (position < end) {
1122
+ const ch = input.charCodeAt(position);
1123
+ if (ch === 92) {
1124
+ result += input.slice(captureStart, position);
1125
+ position++;
1126
+ const escaped = input.charCodeAt(position);
1127
+ if (escaped === 10 || escaped === 13) position = skipFoldedBreaks(input, position, end).position;
1128
+ else if (escaped < 256 && simpleEscapeCheck[escaped]) {
1129
+ result += simpleEscapeMap[escaped];
1130
+ position++;
1131
+ } else {
1132
+ let hexLength = escapedHexLen$1(escaped);
1133
+ let hexResult = 0;
1134
+ for (; hexLength > 0; hexLength--) {
1135
+ position++;
1136
+ const digit = fromHexCode$1(input.charCodeAt(position));
1137
+ hexResult = (hexResult << 4) + digit;
1138
+ }
1139
+ result += charFromCodepoint(hexResult);
1140
+ position++;
1141
+ }
1142
+ captureStart = captureEnd = position;
1143
+ } else if (ch === 10 || ch === 13) {
1144
+ result += input.slice(captureStart, captureEnd);
1145
+ const fold = skipFoldedBreaks(input, position, end);
1146
+ result += foldedBreaks(fold.breaks);
1147
+ position = captureStart = captureEnd = fold.position;
1148
+ } else {
1149
+ position++;
1150
+ if (ch !== 32 && ch !== 9) captureEnd = position;
1151
+ }
1152
+ }
1153
+ return result + input.slice(captureStart, end);
1154
+ }
1155
+ function getBlockValue(input, start, end, indent, chomping, folded) {
1156
+ const textIndent = indent < 0 ? 0 : indent;
1157
+ const region = input.slice(start, end).replace(/\r\n?/g, "\n");
1158
+ const lines = region === "" ? [] : (region.endsWith("\n") ? region.slice(0, -1) : region).split("\n");
1159
+ let result = "";
1160
+ let didReadContent = false;
1161
+ let emptyLines = 0;
1162
+ let atMoreIndented = false;
1163
+ for (const line of lines) {
1164
+ let column = 0;
1165
+ while (column < textIndent && line.charCodeAt(column) === 32) column++;
1166
+ if (indent < 0 || column >= line.length) {
1167
+ emptyLines++;
1168
+ continue;
1169
+ }
1170
+ const content = line.slice(textIndent);
1171
+ const first = content.charCodeAt(0);
1172
+ if (folded) if (first === 32 || first === 9) {
1173
+ atMoreIndented = true;
1174
+ result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
1175
+ } else if (atMoreIndented) {
1176
+ atMoreIndented = false;
1177
+ result += "\n".repeat(emptyLines + 1);
1178
+ } else if (emptyLines === 0) {
1179
+ if (didReadContent) result += " ";
1180
+ } else result += "\n".repeat(emptyLines);
1181
+ else result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
1182
+ result += content;
1183
+ didReadContent = true;
1184
+ emptyLines = 0;
1185
+ }
1186
+ if (chomping === CHOMPING_MODE.KEEP) result += "\n".repeat(didReadContent ? 1 + emptyLines : emptyLines);
1187
+ else if (chomping !== CHOMPING_MODE.STRIP) {
1188
+ if (didReadContent) result += "\n";
1189
+ }
1190
+ return result;
1191
+ }
1192
+ function getScalarValue(input, scalar) {
1193
+ if (scalar.valueStart === NO_RANGE$3) return "";
1194
+ const { valueStart, valueEnd } = scalar;
1195
+ if (scalar.fast) return input.slice(valueStart, valueEnd);
1196
+ switch (scalar.style) {
1197
+ case SCALAR_STYLE.SINGLE_QUOTED:
1198
+ return getSingleQuotedValue(input, valueStart, valueEnd);
1199
+ case SCALAR_STYLE.DOUBLE_QUOTED:
1200
+ return getDoubleQuotedValue(input, valueStart, valueEnd);
1201
+ case SCALAR_STYLE.LITERAL_BLOCK:
1202
+ return getBlockValue(input, valueStart, valueEnd, scalar.indent, scalar.chomping, false);
1203
+ case SCALAR_STYLE.FOLDED_BLOCK:
1204
+ return getBlockValue(input, valueStart, valueEnd, scalar.indent, scalar.chomping, true);
1205
+ default:
1206
+ return getPlainValue(input, valueStart, valueEnd);
1207
+ }
1208
+ }
1209
+ var DEFAULT_TAG_HANDLERS = Object.assign(/* @__PURE__ */ Object.create(null), {
1210
+ "!": "!",
1211
+ "!!": "tag:yaml.org,2002:"
1212
+ });
1213
+ function tagPercentEncode(source) {
1214
+ return encodeURI(source).replace(/!/g, "%21");
1215
+ }
1216
+ function tagNameFull(rawTag, tagHandlers) {
1217
+ if (rawTag.startsWith("!<") && rawTag.endsWith(">")) return decodeURIComponent(rawTag.slice(2, -1));
1218
+ const handleEnd = rawTag.indexOf("!", 1);
1219
+ const handle = handleEnd === -1 ? "!" : rawTag.slice(0, handleEnd + 1);
1220
+ const prefix = tagHandlers?.[handle] ?? DEFAULT_TAG_HANDLERS[handle] ?? handle;
1221
+ return decodeURIComponent(prefix) + decodeURIComponent(rawTag.slice(handle.length));
1222
+ }
1223
+ function tagNameShort(fullTag) {
1224
+ let tag = fullTag;
1225
+ if (tag.charCodeAt(0) === 33) {
1226
+ tag = tag.slice(1);
1227
+ return `!${tagPercentEncode(tag)}`;
1228
+ }
1229
+ if (tag.slice(0, 18) === "tag:yaml.org,2002:") return `!!${tagPercentEncode(tag.slice(18))}`;
1230
+ return `!<${tagPercentEncode(tag)}>`;
1231
+ }
1232
+ var NO_RANGE$2 = -1;
1233
+ var MERGE_TAG_NAME = "tag:yaml.org,2002:merge";
1234
+ var DEFAULT_CONSTRUCTOR_OPTIONS = {
1235
+ filename: "",
1236
+ schema: CORE_SCHEMA,
1237
+ json: false,
1238
+ maxTotalMergeKeys: 1e4,
1239
+ maxAliases: -1
1240
+ };
1241
+ function eventPosition$1(event) {
1242
+ if ("tagStart" in event && event.tagStart !== NO_RANGE$2) return event.tagStart;
1243
+ if ("anchorStart" in event && event.anchorStart !== NO_RANGE$2) return event.anchorStart;
1244
+ if ("valueStart" in event && event.valueStart !== NO_RANGE$2) return event.valueStart;
1245
+ if ("start" in event) return event.start;
1246
+ return 0;
1247
+ }
1248
+ function throwError$1(state, message) {
1249
+ YAMLException.throwAt(state.source, state.position, message, state.filename);
1250
+ }
1251
+ function finalizeCollection(state, position, tag, carrier) {
1252
+ try {
1253
+ return tag.finalize(carrier);
1254
+ } catch (error) {
1255
+ if (error instanceof YAMLException) throw error;
1256
+ YAMLException.throwAt(state.source, position, error instanceof Error ? error.message : String(error), state.filename);
1257
+ }
1258
+ }
1259
+ function constructScalar(state, event) {
1260
+ const source = getScalarValue(state.source, event);
1261
+ const rawTag = event.tagStart === NO_RANGE$2 ? "" : state.source.slice(event.tagStart, event.tagEnd);
1262
+ const strTag2 = state.schema.defaultScalarTag;
1263
+ if (rawTag !== "") {
1264
+ if (rawTag === "!") return {
1265
+ value: source,
1266
+ tag: strTag2
1267
+ };
1268
+ const tagName = tagNameFull(rawTag, state.tagHandlers);
1269
+ const scalarTag = state.schema.lookupScalarTag(tagName);
1270
+ if (scalarTag) {
1271
+ const result = scalarTag.resolve(source, true, tagName);
1272
+ if (result === NOT_RESOLVED) throwError$1(state, `cannot resolve a node with !<${tagName}> explicit tag`);
1273
+ return {
1274
+ value: result,
1275
+ tag: scalarTag
1276
+ };
1277
+ }
1278
+ const collectionTagDef = state.schema.lookupMappingTag(tagName) ?? state.schema.lookupSequenceTag(tagName);
1279
+ if (collectionTagDef) {
1280
+ if (source !== "") throwError$1(state, `cannot resolve a node with !<${tagName}> explicit tag`);
1281
+ const carrier = collectionTagDef.create(tagName);
1282
+ return {
1283
+ value: collectionTagDef.carrierIsResult ? carrier : finalizeCollection(state, state.position, collectionTagDef, carrier),
1284
+ tag: collectionTagDef
1285
+ };
1286
+ }
1287
+ throwError$1(state, `unknown scalar tag !<${tagName}>`);
1288
+ }
1289
+ if (event.style === SCALAR_STYLE.PLAIN) return state.schema.resolveImplicitScalarTag(source);
1290
+ return {
1291
+ value: strTag2.resolve(source, false, strTag2.tagName),
1292
+ tag: strTag2
1293
+ };
1294
+ }
1295
+ function collectionTagName(state, event, defaultTagName) {
1296
+ const rawTag = event.tagStart === NO_RANGE$2 ? "" : state.source.slice(event.tagStart, event.tagEnd);
1297
+ return rawTag === "" || rawTag === "!" ? defaultTagName : tagNameFull(rawTag, state.tagHandlers);
1298
+ }
1299
+ function isMappingTag(tag) {
1300
+ return tag.nodeKind === "mapping";
1301
+ }
1302
+ function chargeMergeWork(state) {
1303
+ state.totalMergeKeys++;
1304
+ if (state.maxTotalMergeKeys !== -1 && state.totalMergeKeys > state.maxTotalMergeKeys) throwError$1(state, `merge keys exceeded maxTotalMergeKeys (${state.maxTotalMergeKeys})`);
1305
+ }
1306
+ function mergeKeys(state, frame, source, sourceTag) {
1307
+ chargeMergeWork(state);
1308
+ for (const sourceKey of sourceTag.keys(source)) {
1309
+ chargeMergeWork(state);
1310
+ if (frame.tag.has(frame.value, sourceKey)) continue;
1311
+ const err = frame.tag.addPair(frame.value, sourceKey, sourceTag.get(source, sourceKey));
1312
+ if (err) throwError$1(state, err);
1313
+ frame.overridable ??= /* @__PURE__ */ new Set();
1314
+ frame.overridable.add(sourceKey);
1315
+ }
1316
+ }
1317
+ function mergeSource(state, frame, source, sourceTag) {
1318
+ state.position = frame.keyPosition;
1319
+ if (isMappingTag(sourceTag)) mergeKeys(state, frame, source, sourceTag);
1320
+ else if (sourceTag.nodeKind === "sequence" && Array.isArray(source)) {
1321
+ if (source.length > 100) throwError$1(state, "abnormal merge sequence size");
1322
+ for (const element of source) {
1323
+ const elementTag = state.nodeTags.get(element);
1324
+ if (!elementTag) throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1325
+ mergeKeys(state, frame, element, elementTag);
1326
+ }
1327
+ } else throwError$1(state, "cannot merge mappings; the provided source object is unacceptable");
1328
+ }
1329
+ function addMappingValue(state, frame, key, value, tag) {
1330
+ state.position = frame.keyPosition;
1331
+ if (frame.keyIsMerge) {
1332
+ mergeSource(state, frame, value, tag);
1333
+ return;
1334
+ }
1335
+ if (!state.json && frame.tag.has(frame.value, key) && !frame.overridable?.has(key)) throwError$1(state, "duplicated mapping key");
1336
+ const err = frame.tag.addPair(frame.value, key, value);
1337
+ if (err) throwError$1(state, err);
1338
+ frame.overridable?.delete(key);
1339
+ }
1340
+ function addValue(state, value, tag) {
1341
+ const frame = state.frames[state.frames.length - 1];
1342
+ if (frame.kind === "document") {
1343
+ frame.value = value;
1344
+ frame.hasValue = true;
1345
+ } else if (frame.kind === "sequence") {
1346
+ if (isMappingTag(tag)) state.nodeTags.set(value, tag);
1347
+ const err = frame.tag.addItem(frame.value, value, frame.index++);
1348
+ if (err) throwError$1(state, err);
1349
+ } else if (frame.hasKey) {
1350
+ const key = frame.key;
1351
+ frame.key = void 0;
1352
+ frame.hasKey = false;
1353
+ addMappingValue(state, frame, key, value, tag);
1354
+ } else {
1355
+ frame.key = value;
1356
+ frame.keyPosition = state.position;
1357
+ frame.hasKey = true;
1358
+ frame.keyIsMerge = tag.tagName === MERGE_TAG_NAME;
1359
+ }
1360
+ }
1361
+ function storeAnchor(state, event, value, tag, isValueFinal) {
1362
+ if (event.anchorStart !== NO_RANGE$2) {
1363
+ const anchor = {
1364
+ value,
1365
+ tag,
1366
+ isValueFinal
1367
+ };
1368
+ state.anchors.set(state.source.slice(event.anchorStart, event.anchorEnd), anchor);
1369
+ return anchor;
1370
+ }
1371
+ return null;
1372
+ }
1373
+ function constructFromEvents(events, options) {
1374
+ const state = {
1375
+ ...DEFAULT_CONSTRUCTOR_OPTIONS,
1376
+ ...options,
1377
+ events,
1378
+ documents: [],
1379
+ eventIndex: 0,
1380
+ position: 0,
1381
+ frames: [],
1382
+ anchors: /* @__PURE__ */ new Map(),
1383
+ nodeTags: /* @__PURE__ */ new Map(),
1384
+ tagHandlers: /* @__PURE__ */ Object.create(null),
1385
+ totalMergeKeys: 0,
1386
+ aliasCount: 0
1387
+ };
1388
+ while (state.eventIndex < state.events.length) {
1389
+ const event = state.events[state.eventIndex++];
1390
+ state.position = eventPosition$1(event);
1391
+ switch (event.type) {
1392
+ case EVENT_ID.DOCUMENT:
1393
+ state.anchors = /* @__PURE__ */ new Map();
1394
+ state.nodeTags = /* @__PURE__ */ new Map();
1395
+ state.aliasCount = 0;
1396
+ state.tagHandlers = /* @__PURE__ */ Object.create(null);
1397
+ for (const directive of event.directives) if (directive.kind === "tag") state.tagHandlers[directive.handle] = directive.prefix;
1398
+ state.frames.push({
1399
+ kind: "document",
1400
+ position: state.position,
1401
+ value: void 0,
1402
+ hasValue: false
1403
+ });
1404
+ break;
1405
+ case EVENT_ID.SCALAR: {
1406
+ const { value, tag } = constructScalar(state, event);
1407
+ storeAnchor(state, event, value, tag, true);
1408
+ addValue(state, value, tag);
1409
+ break;
1410
+ }
1411
+ case EVENT_ID.SEQUENCE: {
1412
+ const tagName = collectionTagName(state, event, "tag:yaml.org,2002:seq");
1413
+ const tag = state.schema.lookupSequenceTag(tagName);
1414
+ if (!tag) throwError$1(state, `unknown sequence tag !<${tagName}>`);
1415
+ const value = tag.create(tagName);
1416
+ const anchor = storeAnchor(state, event, value, tag, tag.carrierIsResult);
1417
+ state.frames.push({
1418
+ kind: "sequence",
1419
+ position: state.position,
1420
+ value,
1421
+ tag,
1422
+ anchor,
1423
+ index: 0
1424
+ });
1425
+ break;
1426
+ }
1427
+ case EVENT_ID.MAPPING: {
1428
+ const tagName = collectionTagName(state, event, "tag:yaml.org,2002:map");
1429
+ const tag = state.schema.lookupMappingTag(tagName);
1430
+ if (!tag) throwError$1(state, `unknown mapping tag !<${tagName}>`);
1431
+ const value = tag.create(tagName);
1432
+ const anchor = storeAnchor(state, event, value, tag, tag.carrierIsResult);
1433
+ state.frames.push({
1434
+ kind: "mapping",
1435
+ position: state.position,
1436
+ value,
1437
+ tag,
1438
+ anchor,
1439
+ key: void 0,
1440
+ keyPosition: state.position,
1441
+ hasKey: false,
1442
+ keyIsMerge: false,
1443
+ overridable: null
1444
+ });
1445
+ break;
1446
+ }
1447
+ case EVENT_ID.ALIAS: {
1448
+ if (state.maxAliases !== -1 && ++state.aliasCount > state.maxAliases) throwError$1(state, `aliases exceeded maxAliases (${state.maxAliases})`);
1449
+ const name = state.source.slice(event.anchorStart, event.anchorEnd);
1450
+ const anchor = state.anchors.get(name);
1451
+ if (!anchor) throwError$1(state, `unidentified alias "${name}"`);
1452
+ if (!anchor.isValueFinal) throwError$1(state, `recursive alias "${name}" is not supported for tag ${anchor.tag.tagName} because it uses finalize()`);
1453
+ addValue(state, anchor.value, anchor.tag);
1454
+ break;
1455
+ }
1456
+ case EVENT_ID.POP: {
1457
+ const frame = state.frames.pop();
1458
+ if (frame.kind === "mapping" && frame.hasKey) {
1459
+ state.position = frame.keyPosition;
1460
+ throwError$1(state, "incomplete mapping pair in event stream");
1461
+ }
1462
+ if (frame.kind === "document") state.documents.push(frame.value);
1463
+ else {
1464
+ const value = frame.tag.carrierIsResult ? frame.value : finalizeCollection(state, frame.position, frame.tag, frame.value);
1465
+ if (frame.anchor) {
1466
+ frame.anchor.value = value;
1467
+ frame.anchor.isValueFinal = true;
1468
+ }
1469
+ addValue(state, value, frame.tag);
1470
+ }
1471
+ break;
1472
+ }
1473
+ }
1474
+ }
1475
+ return state.documents;
1476
+ }
1477
+ var NO_RANGE$1 = -1;
1478
+ var HAS_OWN = Object.prototype.hasOwnProperty;
1479
+ var CONTEXT_FLOW_IN = 1;
1480
+ var CONTEXT_FLOW_OUT = 2;
1481
+ var CONTEXT_BLOCK_IN = 3;
1482
+ var CONTEXT_BLOCK_OUT = 4;
1483
+ var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
1484
+ var PATTERN_FLOW_INDICATORS = /[,\[\]{}]/;
1485
+ var PATTERN_TAG_HANDLE = /^(?:!|!!|![0-9A-Za-z-]+!)$/;
1486
+ var NS_URI_CHAR = String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$,_.!~*'()\[\]])`;
1487
+ var NS_TAG_CHAR = String.raw`(?:%[0-9A-Fa-f]{2}|[0-9A-Za-z\-#;/?:@&=+$.~*'()_])`;
1488
+ var PATTERN_TAG_URI = new RegExp(`^(?:${NS_URI_CHAR})*$`);
1489
+ var PATTERN_TAG_SUFFIX = new RegExp(`^(?:${NS_TAG_CHAR})+$`);
1490
+ var PATTERN_TAG_PREFIX = new RegExp(`^(?:!(?:${NS_URI_CHAR})*|${NS_TAG_CHAR}(?:${NS_URI_CHAR})*)$`);
1491
+ var DEFAULT_PARSER_OPTIONS = {
1492
+ filename: "",
1493
+ maxDepth: 100
1494
+ };
1495
+ function addDocumentEvent(state, explicitStart, explicitEnd) {
1496
+ state.events.push({
1497
+ type: EVENT_ID.DOCUMENT,
1498
+ explicitStart,
1499
+ explicitEnd,
1500
+ directives: state.directives
1501
+ });
1502
+ }
1503
+ function addSequenceEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) {
1504
+ state.events.push({
1505
+ type: EVENT_ID.SEQUENCE,
1506
+ start,
1507
+ anchorStart,
1508
+ anchorEnd,
1509
+ tagStart,
1510
+ tagEnd,
1511
+ style
1512
+ });
1513
+ }
1514
+ function addMappingEvent(state, start, anchorStart, anchorEnd, tagStart, tagEnd, style) {
1515
+ state.events.push({
1516
+ type: EVENT_ID.MAPPING,
1517
+ start,
1518
+ anchorStart,
1519
+ anchorEnd,
1520
+ tagStart,
1521
+ tagEnd,
1522
+ style
1523
+ });
1524
+ }
1525
+ function insertFlowPairMappingEvent(state, snapshot) {
1526
+ state.events.splice(snapshot.eventsLength, 0, {
1527
+ type: EVENT_ID.MAPPING,
1528
+ start: snapshot.position,
1529
+ anchorStart: NO_RANGE$1,
1530
+ anchorEnd: NO_RANGE$1,
1531
+ tagStart: NO_RANGE$1,
1532
+ tagEnd: NO_RANGE$1,
1533
+ style: COLLECTION_STYLE.FLOW
1534
+ });
1535
+ }
1536
+ function addScalarEvent(state, valueStart, valueEnd, anchorStart, anchorEnd, tagStart, tagEnd, style, chomping = CHOMPING_MODE.CLIP, indent = -1, fast = false) {
1537
+ state.events.push({
1538
+ type: EVENT_ID.SCALAR,
1539
+ valueStart,
1540
+ valueEnd,
1541
+ anchorStart,
1542
+ anchorEnd,
1543
+ tagStart,
1544
+ tagEnd,
1545
+ style,
1546
+ chomping,
1547
+ indent,
1548
+ fast
1549
+ });
1550
+ }
1551
+ function addAliasEvent(state, anchorStart, anchorEnd) {
1552
+ state.events.push({
1553
+ type: EVENT_ID.ALIAS,
1554
+ anchorStart,
1555
+ anchorEnd
1556
+ });
1557
+ }
1558
+ function addPopEvent(state) {
1559
+ state.events.push({ type: EVENT_ID.POP });
1560
+ }
1561
+ function addEmptyScalarEvent(state) {
1562
+ addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, NO_RANGE$1, SCALAR_STYLE.PLAIN);
1563
+ }
1564
+ function emptyProperties() {
1565
+ return {
1566
+ anchorStart: NO_RANGE$1,
1567
+ anchorEnd: NO_RANGE$1,
1568
+ tagStart: NO_RANGE$1,
1569
+ tagEnd: NO_RANGE$1
1570
+ };
1571
+ }
1572
+ function snapshotState(state) {
1573
+ return {
1574
+ position: state.position,
1575
+ line: state.line,
1576
+ lineStart: state.lineStart,
1577
+ lineIndent: state.lineIndent,
1578
+ firstTabInLine: state.firstTabInLine,
1579
+ eventsLength: state.events.length
1580
+ };
1581
+ }
1582
+ function restoreState(state, snapshot) {
1583
+ state.position = snapshot.position;
1584
+ state.line = snapshot.line;
1585
+ state.lineStart = snapshot.lineStart;
1586
+ state.lineIndent = snapshot.lineIndent;
1587
+ state.firstTabInLine = snapshot.firstTabInLine;
1588
+ state.events.length = snapshot.eventsLength;
1589
+ }
1590
+ function throwError(state, message) {
1591
+ YAMLException.throwAt(state.input.slice(0, state.length), state.position, message, state.filename);
1592
+ }
1593
+ function isEol(c) {
1594
+ return c === 10 || c === 13;
1595
+ }
1596
+ function isWhiteSpace(c) {
1597
+ return c === 9 || c === 32;
1598
+ }
1599
+ function isWsOrEol(c) {
1600
+ return isWhiteSpace(c) || isEol(c);
1601
+ }
1602
+ function isWsOrEolOrEnd(c) {
1603
+ return c === 0 || isWsOrEol(c);
1604
+ }
1605
+ function isFlowIndicator(c) {
1606
+ return c === 44 || c === 91 || c === 93 || c === 123 || c === 125;
1607
+ }
1608
+ function fromDecimalCode(c) {
1609
+ return c >= 48 && c <= 57 ? c - 48 : -1;
1610
+ }
1611
+ function fromHexCode(c) {
1612
+ if (c >= 48 && c <= 57) return c - 48;
1613
+ const lc = c | 32;
1614
+ if (lc >= 97 && lc <= 102) return lc - 97 + 10;
1615
+ return -1;
1616
+ }
1617
+ function escapedHexLen(c) {
1618
+ if (c === 120) return 2;
1619
+ if (c === 117) return 4;
1620
+ if (c === 85) return 8;
1621
+ return 0;
1622
+ }
1623
+ function isSimpleEscape(c) {
1624
+ return c === 48 || c === 97 || c === 98 || c === 116 || c === 9 || c === 110 || c === 118 || c === 102 || c === 114 || c === 101 || c === 32 || c === 34 || c === 47 || c === 92 || c === 78 || c === 95 || c === 76 || c === 80;
1625
+ }
1626
+ function consumeLineBreak(state) {
1627
+ if (state.input.charCodeAt(state.position) === 10) state.position++;
1628
+ else {
1629
+ state.position++;
1630
+ if (state.input.charCodeAt(state.position) === 10) state.position++;
1631
+ }
1632
+ state.line++;
1633
+ state.lineStart = state.position;
1634
+ state.lineIndent = 0;
1635
+ state.firstTabInLine = -1;
1636
+ }
1637
+ function skipSeparationSpace(state, allowComments) {
1638
+ let lineBreaks = 0;
1639
+ let ch = state.input.charCodeAt(state.position);
1640
+ let hasSeparation = state.position === state.lineStart || isWsOrEol(state.input.charCodeAt(state.position - 1));
1641
+ while (ch !== 0) {
1642
+ while (isWhiteSpace(ch)) {
1643
+ hasSeparation = true;
1644
+ if (ch === 9 && state.firstTabInLine === -1) state.firstTabInLine = state.position;
1645
+ ch = state.input.charCodeAt(++state.position);
1646
+ }
1647
+ if (allowComments && hasSeparation && ch === 35) do
1648
+ ch = state.input.charCodeAt(++state.position);
1649
+ while (!isEol(ch) && ch !== 0);
1650
+ if (!isEol(ch)) break;
1651
+ consumeLineBreak(state);
1652
+ lineBreaks++;
1653
+ hasSeparation = true;
1654
+ ch = state.input.charCodeAt(state.position);
1655
+ while (ch === 32) {
1656
+ state.lineIndent++;
1657
+ ch = state.input.charCodeAt(++state.position);
1658
+ }
1659
+ }
1660
+ return lineBreaks;
1661
+ }
1662
+ function testDocumentSeparator(state, position = state.position) {
1663
+ const ch = state.input.charCodeAt(position);
1664
+ if ((ch === 45 || ch === 46) && ch === state.input.charCodeAt(position + 1) && ch === state.input.charCodeAt(position + 2)) {
1665
+ const following = state.input.charCodeAt(position + 3);
1666
+ return following === 0 || isWsOrEol(following);
1667
+ }
1668
+ return false;
1669
+ }
1670
+ function skipByteOrderMark(state) {
1671
+ if (state.position === state.lineStart && state.input.charCodeAt(state.position) === 65279) {
1672
+ state.position++;
1673
+ state.lineStart = state.position;
1674
+ }
1675
+ }
1676
+ function testDocumentBoundary(state) {
1677
+ if (state.position !== state.lineStart) return false;
1678
+ if (testDocumentSeparator(state)) return true;
1679
+ if (state.input.charCodeAt(state.position) !== 65279) return false;
1680
+ const snapshot = snapshotState(state);
1681
+ skipByteOrderMark(state);
1682
+ skipSeparationSpace(state, true);
1683
+ const ch = state.input.charCodeAt(state.position);
1684
+ const result = state.position === state.lineStart && (ch === 37 || ch === 45 && testDocumentSeparator(state));
1685
+ restoreState(state, snapshot);
1686
+ return result;
1687
+ }
1688
+ function skipUntilLineEnd(state) {
1689
+ let ch = state.input.charCodeAt(state.position);
1690
+ while (ch !== 0 && !isEol(ch)) ch = state.input.charCodeAt(++state.position);
1691
+ }
1692
+ function checkPrintable(state, start, end) {
1693
+ if (PATTERN_NON_PRINTABLE.test(state.input.slice(start, end))) throwError(state, "the stream contains non-printable characters");
1694
+ }
1695
+ function readTagProperty(state, props, inFlow) {
1696
+ if (state.input.charCodeAt(state.position) !== 33) return false;
1697
+ if (props.tagStart !== NO_RANGE$1) throwError(state, "duplication of a tag property");
1698
+ const start = state.position;
1699
+ let isVerbatim = false;
1700
+ let isNamed = false;
1701
+ let tagHandle = "!";
1702
+ let ch = state.input.charCodeAt(++state.position);
1703
+ if (ch === 60) {
1704
+ isVerbatim = true;
1705
+ ch = state.input.charCodeAt(++state.position);
1706
+ } else if (ch === 33) {
1707
+ isNamed = true;
1708
+ tagHandle = "!!";
1709
+ ch = state.input.charCodeAt(++state.position);
1710
+ }
1711
+ let suffixStart = state.position;
1712
+ let tagName;
1713
+ if (isVerbatim) {
1714
+ while (ch !== 0 && ch !== 62) ch = state.input.charCodeAt(++state.position);
1715
+ if (ch !== 62) throwError(state, "unexpected end of the stream within a verbatim tag");
1716
+ tagName = state.input.slice(suffixStart, state.position);
1717
+ state.position++;
1718
+ } else {
1719
+ while (ch !== 0 && !isWsOrEol(ch) && !(inFlow && isFlowIndicator(ch))) {
1720
+ if (ch === 33) if (!isNamed) {
1721
+ tagHandle = state.input.slice(suffixStart - 1, state.position + 1);
1722
+ if (!PATTERN_TAG_HANDLE.test(tagHandle)) throwError(state, "named tag handle cannot contain such characters");
1723
+ isNamed = true;
1724
+ suffixStart = state.position + 1;
1725
+ } else throwError(state, "tag suffix cannot contain exclamation marks");
1726
+ ch = state.input.charCodeAt(++state.position);
1727
+ }
1728
+ tagName = state.input.slice(suffixStart, state.position);
1729
+ if (PATTERN_FLOW_INDICATORS.test(tagName)) throwError(state, "tag suffix cannot contain flow indicator characters");
1730
+ }
1731
+ if (tagName && !(isVerbatim ? PATTERN_TAG_URI.test(tagName) : PATTERN_TAG_SUFFIX.test(tagName))) throwError(state, `tag name cannot contain such characters: ${tagName}`);
1732
+ if (!isVerbatim && tagHandle !== "!" && tagHandle !== "!!" && !HAS_OWN.call(state.tagHandlers, tagHandle)) throwError(state, `undeclared tag handle "${tagHandle}"`);
1733
+ props.tagStart = start;
1734
+ props.tagEnd = state.position;
1735
+ return true;
1736
+ }
1737
+ function readAnchorProperty(state, props) {
1738
+ if (state.input.charCodeAt(state.position) !== 38) return false;
1739
+ if (props.anchorStart !== NO_RANGE$1) throwError(state, "duplication of an anchor property");
1740
+ state.position++;
1741
+ const start = state.position;
1742
+ while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++;
1743
+ if (state.position === start) throwError(state, "name of an anchor node must contain at least one character");
1744
+ props.anchorStart = start;
1745
+ props.anchorEnd = state.position;
1746
+ return true;
1747
+ }
1748
+ function readAlias(state, props) {
1749
+ if (state.input.charCodeAt(state.position) !== 42) return false;
1750
+ if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) throwError(state, "alias node should not have any properties");
1751
+ state.position++;
1752
+ const start = state.position;
1753
+ while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position)) && !isFlowIndicator(state.input.charCodeAt(state.position))) state.position++;
1754
+ if (state.position === start) throwError(state, "name of an alias node must contain at least one character");
1755
+ addAliasEvent(state, start, state.position);
1756
+ return true;
1757
+ }
1758
+ function readFlowScalarBreak(state, nodeIndent) {
1759
+ skipSeparationSpace(state, false);
1760
+ if (state.lineIndent < nodeIndent) throwError(state, "deficient indentation");
1761
+ }
1762
+ function readSingleQuotedScalar(state, nodeIndent, props) {
1763
+ if (state.input.charCodeAt(state.position) !== 39) return false;
1764
+ state.position++;
1765
+ const start = state.position;
1766
+ let simple = true;
1767
+ while (state.input.charCodeAt(state.position) !== 0) {
1768
+ const ch = state.input.charCodeAt(state.position);
1769
+ if (ch === 39) {
1770
+ if (state.input.charCodeAt(state.position + 1) === 39) {
1771
+ simple = false;
1772
+ state.position += 2;
1773
+ continue;
1774
+ }
1775
+ const end = state.position;
1776
+ state.position++;
1777
+ addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.SINGLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple);
1778
+ return true;
1779
+ }
1780
+ if (isEol(ch)) {
1781
+ simple = false;
1782
+ readFlowScalarBreak(state, nodeIndent);
1783
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a single quoted scalar");
1784
+ else if (ch !== 9 && ch < 32) throwError(state, "expected valid JSON character");
1785
+ else state.position++;
1786
+ }
1787
+ throwError(state, "unexpected end of the stream within a single quoted scalar");
1788
+ }
1789
+ function readDoubleQuotedScalar(state, nodeIndent, props) {
1790
+ if (state.input.charCodeAt(state.position) !== 34) return false;
1791
+ state.position++;
1792
+ const start = state.position;
1793
+ let simple = true;
1794
+ while (state.input.charCodeAt(state.position) !== 0) {
1795
+ const ch = state.input.charCodeAt(state.position);
1796
+ if (ch === 34) {
1797
+ const end = state.position;
1798
+ state.position++;
1799
+ addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.DOUBLE_QUOTED, CHOMPING_MODE.CLIP, -1, simple);
1800
+ return true;
1801
+ }
1802
+ if (ch === 92) {
1803
+ simple = false;
1804
+ const escaped = state.input.charCodeAt(++state.position);
1805
+ if (isEol(escaped)) readFlowScalarBreak(state, nodeIndent);
1806
+ else if (isSimpleEscape(escaped)) state.position++;
1807
+ else {
1808
+ let hexLength = escapedHexLen(escaped);
1809
+ if (hexLength === 0) throwError(state, "unknown escape sequence");
1810
+ while (hexLength-- > 0) {
1811
+ state.position++;
1812
+ if (fromHexCode(state.input.charCodeAt(state.position)) < 0) throwError(state, "expected hexadecimal character");
1813
+ }
1814
+ state.position++;
1815
+ }
1816
+ } else if (isEol(ch)) {
1817
+ simple = false;
1818
+ readFlowScalarBreak(state, nodeIndent);
1819
+ } else if (state.position === state.lineStart && testDocumentSeparator(state)) throwError(state, "unexpected end of the document within a double quoted scalar");
1820
+ else if (ch !== 9 && ch < 32) throwError(state, "expected valid JSON character");
1821
+ else state.position++;
1822
+ }
1823
+ throwError(state, "unexpected end of the stream within a double quoted scalar");
1824
+ }
1825
+ function readBlockScalar(state, parentIndent, props) {
1826
+ const ch = state.input.charCodeAt(state.position);
1827
+ let chomping = CHOMPING_MODE.CLIP;
1828
+ let indent = -1;
1829
+ let detectedIndent = false;
1830
+ if (ch !== 124 && ch !== 62) return false;
1831
+ const style = ch === 124 ? SCALAR_STYLE.LITERAL_BLOCK : SCALAR_STYLE.FOLDED_BLOCK;
1832
+ state.position++;
1833
+ while (state.input.charCodeAt(state.position) !== 0) {
1834
+ const current = state.input.charCodeAt(state.position);
1835
+ const digit = fromDecimalCode(current);
1836
+ if (current === 43 || current === 45) {
1837
+ if (chomping !== CHOMPING_MODE.CLIP) throwError(state, "repeat of a chomping mode identifier");
1838
+ chomping = current === 43 ? CHOMPING_MODE.KEEP : CHOMPING_MODE.STRIP;
1839
+ state.position++;
1840
+ } else if (digit >= 0) {
1841
+ if (digit === 0) throwError(state, "bad explicit indentation width of a block scalar; it cannot be less than one");
1842
+ if (detectedIndent) throwError(state, "repeat of an indentation width identifier");
1843
+ indent = parentIndent + digit - 1;
1844
+ detectedIndent = true;
1845
+ state.position++;
1846
+ } else break;
1847
+ }
1848
+ let hadWhitespace = false;
1849
+ while (isWhiteSpace(state.input.charCodeAt(state.position))) {
1850
+ hadWhitespace = true;
1851
+ state.position++;
1852
+ }
1853
+ if (hadWhitespace && state.input.charCodeAt(state.position) === 35) skipUntilLineEnd(state);
1854
+ if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state);
1855
+ else if (state.input.charCodeAt(state.position) !== 0) throwError(state, "a line break is expected");
1856
+ let contentIndent = detectedIndent ? indent : -1;
1857
+ let maxLeadingIndent = 0;
1858
+ const valueStart = state.position;
1859
+ let valueEnd = state.position;
1860
+ while (state.input.charCodeAt(state.position) !== 0) {
1861
+ const linePosition = state.position;
1862
+ let column = 0;
1863
+ while (state.input.charCodeAt(linePosition + column) === 32) column++;
1864
+ const first = state.input.charCodeAt(linePosition + column);
1865
+ if (first === 0) {
1866
+ if (contentIndent >= 0) {
1867
+ if (column > contentIndent) valueEnd = linePosition + column;
1868
+ } else if (column > 0) valueEnd = linePosition + column;
1869
+ break;
1870
+ }
1871
+ if (testDocumentBoundary(state)) break;
1872
+ if (!detectedIndent && contentIndent === -1 && isEol(first)) maxLeadingIndent = Math.max(maxLeadingIndent, column);
1873
+ if (!detectedIndent && contentIndent === -1 && !isEol(first)) {
1874
+ if (first === 9 && column < parentIndent) {
1875
+ state.position = linePosition + column;
1876
+ throwError(state, "tab characters must not be used in indentation");
1877
+ }
1878
+ if (column < maxLeadingIndent) {
1879
+ state.position = linePosition + column;
1880
+ throwError(state, "bad indentation of a mapping entry");
1881
+ }
1882
+ }
1883
+ if (contentIndent === -1 && first !== 0 && !isEol(first) && column < parentIndent) {
1884
+ state.lineIndent = column;
1885
+ state.position = linePosition + column;
1886
+ break;
1887
+ }
1888
+ if (!detectedIndent && first !== 0 && !isEol(first) && contentIndent === -1) contentIndent = column;
1889
+ const requiredIndent = contentIndent === -1 ? parentIndent + 1 : contentIndent;
1890
+ if (first !== 0 && !isEol(first) && column < requiredIndent) {
1891
+ state.lineIndent = column;
1892
+ state.position = linePosition + column;
1893
+ break;
1894
+ }
1895
+ skipUntilLineEnd(state);
1896
+ valueEnd = state.position;
1897
+ if (isEol(state.input.charCodeAt(state.position))) {
1898
+ consumeLineBreak(state);
1899
+ valueEnd = state.position;
1900
+ }
1901
+ }
1902
+ checkPrintable(state, valueStart, valueEnd);
1903
+ addScalarEvent(state, valueStart, valueEnd, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, style, chomping, contentIndent);
1904
+ return true;
1905
+ }
1906
+ function canStartPlainScalar(state, nodeContext) {
1907
+ const ch = state.input.charCodeAt(state.position);
1908
+ const inFlow = nodeContext === CONTEXT_FLOW_IN;
1909
+ if (ch === 0 || isWsOrEol(ch) || ch === 35 || ch === 38 || ch === 42 || ch === 33 || ch === 124 || ch === 62 || ch === 39 || ch === 34 || ch === 37 || ch === 64 || ch === 96 || inFlow && isFlowIndicator(ch)) return false;
1910
+ if (ch === 63 || ch === 45) {
1911
+ const following = state.input.charCodeAt(state.position + 1);
1912
+ if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) return false;
1913
+ }
1914
+ return true;
1915
+ }
1916
+ function readPlainScalar(state, nodeIndent, nodeContext, props) {
1917
+ if (!canStartPlainScalar(state, nodeContext)) return false;
1918
+ const start = state.position;
1919
+ let end = state.position;
1920
+ let ch = state.input.charCodeAt(state.position);
1921
+ const inFlow = nodeContext === CONTEXT_FLOW_IN;
1922
+ let multiline = false;
1923
+ while (ch !== 0) {
1924
+ if (testDocumentBoundary(state)) break;
1925
+ if (ch === 58) {
1926
+ const following = state.input.charCodeAt(state.position + 1);
1927
+ if (isWsOrEolOrEnd(following) || inFlow && isFlowIndicator(following)) break;
1928
+ } else if (ch === 35) {
1929
+ if (isWsOrEol(state.input.charCodeAt(state.position - 1))) break;
1930
+ } else if (inFlow && isFlowIndicator(ch)) break;
1931
+ else if (isEol(ch)) {
1932
+ const savedPosition = state.position;
1933
+ const savedLine = state.line;
1934
+ const savedLineStart = state.lineStart;
1935
+ const savedLineIndent = state.lineIndent;
1936
+ skipSeparationSpace(state, false);
1937
+ if (state.lineIndent >= nodeIndent) {
1938
+ multiline = true;
1939
+ ch = state.input.charCodeAt(state.position);
1940
+ continue;
1941
+ }
1942
+ state.position = savedPosition;
1943
+ state.line = savedLine;
1944
+ state.lineStart = savedLineStart;
1945
+ state.lineIndent = savedLineIndent;
1946
+ break;
1947
+ }
1948
+ if (!isWhiteSpace(ch)) end = state.position + 1;
1949
+ ch = state.input.charCodeAt(++state.position);
1950
+ }
1951
+ if (end === start) return false;
1952
+ checkPrintable(state, start, end);
1953
+ addScalarEvent(state, start, end, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.PLAIN, CHOMPING_MODE.CLIP, -1, !multiline);
1954
+ return true;
1955
+ }
1956
+ function skipFlowSeparationSpace(state, nodeIndent) {
1957
+ const startLine = state.line;
1958
+ skipSeparationSpace(state, true);
1959
+ if (state.line > startLine && state.lineIndent < nodeIndent || state.firstTabInLine !== -1 && state.lineIndent < nodeIndent) throwError(state, "deficient indentation");
1960
+ }
1961
+ function readFlowCollection(state, nodeIndent, props) {
1962
+ const ch = state.input.charCodeAt(state.position);
1963
+ const isMapping = ch === 123;
1964
+ const start = state.position;
1965
+ let readNext = true;
1966
+ if (ch !== 91 && ch !== 123) return false;
1967
+ const terminator = isMapping ? 125 : 93;
1968
+ if (isMapping) addMappingEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW);
1969
+ else addSequenceEvent(state, start, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.FLOW);
1970
+ state.position++;
1971
+ while (state.input.charCodeAt(state.position) !== 0) {
1972
+ skipFlowSeparationSpace(state, nodeIndent);
1973
+ let ch2 = state.input.charCodeAt(state.position);
1974
+ if (ch2 === terminator) {
1975
+ state.position++;
1976
+ addPopEvent(state);
1977
+ return true;
1978
+ } else if (!readNext) throwError(state, "missed comma between flow collection entries");
1979
+ else if (ch2 === 44) throwError(state, "expected the node content, but found ','");
1980
+ let isPair = false;
1981
+ let isExplicitPair = false;
1982
+ if (ch2 === 63 && isWsOrEol(state.input.charCodeAt(state.position + 1))) {
1983
+ isPair = isExplicitPair = true;
1984
+ state.position += 1;
1985
+ skipFlowSeparationSpace(state, nodeIndent);
1986
+ }
1987
+ const entryLine = state.line;
1988
+ const entryStart = snapshotState(state);
1989
+ const keyWasRead = parseNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
1990
+ skipFlowSeparationSpace(state, nodeIndent);
1991
+ ch2 = state.input.charCodeAt(state.position);
1992
+ if ((isMapping || isExplicitPair || state.line === entryLine) && ch2 === 58) {
1993
+ isPair = true;
1994
+ state.position++;
1995
+ skipFlowSeparationSpace(state, nodeIndent);
1996
+ if (!isMapping) {
1997
+ insertFlowPairMappingEvent(state, entryStart);
1998
+ if (!keyWasRead) addEmptyScalarEvent(state);
1999
+ } else if (!keyWasRead) addEmptyScalarEvent(state);
2000
+ if (!parseNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true)) addEmptyScalarEvent(state);
2001
+ skipFlowSeparationSpace(state, nodeIndent);
2002
+ if (!isMapping) addPopEvent(state);
2003
+ } else if (isMapping && isPair) {
2004
+ if (!keyWasRead) addEmptyScalarEvent(state);
2005
+ addEmptyScalarEvent(state);
2006
+ } else if (isMapping) addEmptyScalarEvent(state);
2007
+ else if (isPair) {
2008
+ insertFlowPairMappingEvent(state, entryStart);
2009
+ if (!keyWasRead) addEmptyScalarEvent(state);
2010
+ addEmptyScalarEvent(state);
2011
+ addPopEvent(state);
2012
+ }
2013
+ ch2 = state.input.charCodeAt(state.position);
2014
+ if (ch2 === 44) {
2015
+ readNext = true;
2016
+ state.position++;
2017
+ } else readNext = false;
2018
+ }
2019
+ throwError(state, "unexpected end of the stream within a flow collection");
2020
+ }
2021
+ function readBlockSequence(state, nodeIndent, props) {
2022
+ if (state.firstTabInLine !== -1 || state.input.charCodeAt(state.position) !== 45 || !isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) return false;
2023
+ addSequenceEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2024
+ while (state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) {
2025
+ if (state.firstTabInLine !== -1) {
2026
+ state.position = state.firstTabInLine;
2027
+ throwError(state, "tab characters must not be used in indentation");
2028
+ }
2029
+ const entryLine = state.line;
2030
+ state.position++;
2031
+ const hadBreak = skipSeparationSpace(state, true) > 0;
2032
+ if (state.firstTabInLine !== -1 && state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) throwError(state, "bad indentation of a sequence entry");
2033
+ if (hadBreak && state.lineIndent <= nodeIndent) addEmptyScalarEvent(state);
2034
+ else parseNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
2035
+ skipSeparationSpace(state, true);
2036
+ if (state.lineIndent < nodeIndent || state.position >= state.length) break;
2037
+ if (state.lineIndent > nodeIndent) throwError(state, "bad indentation of a sequence entry");
2038
+ if (state.line === entryLine && state.input.charCodeAt(state.position) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 1))) throwError(state, "bad indentation of a sequence entry");
2039
+ }
2040
+ addPopEvent(state);
2041
+ return true;
2042
+ }
2043
+ function readBlockMapping(state, nodeIndent, flowIndent, props) {
2044
+ let atExplicitKey = false;
2045
+ let detected = false;
2046
+ let mappingOpened = false;
2047
+ let pendingExplicitKey = false;
2048
+ if (state.firstTabInLine !== -1) return false;
2049
+ let ch = state.input.charCodeAt(state.position);
2050
+ while (ch !== 0) {
2051
+ if (!atExplicitKey && state.firstTabInLine !== -1) {
2052
+ state.position = state.firstTabInLine;
2053
+ throwError(state, "tab characters must not be used in indentation");
2054
+ }
2055
+ const following = state.input.charCodeAt(state.position + 1);
2056
+ const entryLine = state.line;
2057
+ if ((ch === 63 || ch === 58) && isWsOrEolOrEnd(following)) {
2058
+ if (!mappingOpened) {
2059
+ addMappingEvent(state, state.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2060
+ mappingOpened = true;
2061
+ }
2062
+ if (ch === 63) {
2063
+ if (atExplicitKey) addEmptyScalarEvent(state);
2064
+ detected = true;
2065
+ atExplicitKey = true;
2066
+ } else if (atExplicitKey) atExplicitKey = false;
2067
+ else {
2068
+ addEmptyScalarEvent(state);
2069
+ detected = true;
2070
+ atExplicitKey = false;
2071
+ }
2072
+ state.position += 1;
2073
+ pendingExplicitKey = true;
2074
+ } else {
2075
+ if (atExplicitKey) {
2076
+ addEmptyScalarEvent(state);
2077
+ atExplicitKey = false;
2078
+ }
2079
+ const beforeKey = snapshotState(state);
2080
+ if (!parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) break;
2081
+ if (state.line === entryLine) {
2082
+ ch = state.input.charCodeAt(state.position);
2083
+ while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position);
2084
+ if (ch === 58) {
2085
+ ch = state.input.charCodeAt(++state.position);
2086
+ if (!isWsOrEolOrEnd(ch)) throwError(state, "a whitespace character is expected after the key-value separator within a block mapping");
2087
+ if (!mappingOpened) {
2088
+ restoreState(state, beforeKey);
2089
+ addMappingEvent(state, beforeKey.position, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, COLLECTION_STYLE.BLOCK);
2090
+ mappingOpened = true;
2091
+ parseNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true);
2092
+ ch = state.input.charCodeAt(state.position);
2093
+ while (isWhiteSpace(ch)) ch = state.input.charCodeAt(++state.position);
2094
+ state.position++;
2095
+ }
2096
+ detected = true;
2097
+ atExplicitKey = false;
2098
+ pendingExplicitKey = false;
2099
+ } else if (detected) throwError(state, "expected ':' after a mapping key");
2100
+ else {
2101
+ if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) {
2102
+ restoreState(state, beforeKey);
2103
+ return false;
2104
+ }
2105
+ return true;
2106
+ }
2107
+ } else if (detected) throwError(state, "can not read a block mapping entry; a multiline key may not be an implicit key");
2108
+ else {
2109
+ if (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1) {
2110
+ restoreState(state, beforeKey);
2111
+ return false;
2112
+ }
2113
+ return true;
2114
+ }
2115
+ }
2116
+ if (parseNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, pendingExplicitKey)) pendingExplicitKey = false;
2117
+ if (!atExplicitKey) {
2118
+ if (pendingExplicitKey) {
2119
+ addEmptyScalarEvent(state);
2120
+ pendingExplicitKey = false;
2121
+ }
2122
+ }
2123
+ skipSeparationSpace(state, true);
2124
+ ch = state.input.charCodeAt(state.position);
2125
+ if ((state.line === entryLine || state.lineIndent > nodeIndent) && ch !== 0) throwError(state, "bad indentation of a mapping entry");
2126
+ else if (state.lineIndent < nodeIndent) break;
2127
+ }
2128
+ if (!detected) return false;
2129
+ if (atExplicitKey) addEmptyScalarEvent(state);
2130
+ if (mappingOpened) addPopEvent(state);
2131
+ return true;
2132
+ }
2133
+ function parseNode(state, parentIndent, nodeContext, allowToSeek, allowCompact, allowPropertyMapping = true) {
2134
+ if (state.depth >= state.maxDepth) throwError(state, `nesting exceeded maxDepth (${state.maxDepth})`);
2135
+ state.depth++;
2136
+ let indentStatus = 1;
2137
+ let atNewLine = false;
2138
+ let hasContent = false;
2139
+ let propertyStart = null;
2140
+ const props = emptyProperties();
2141
+ let allowBlockScalars = nodeContext === CONTEXT_BLOCK_OUT || nodeContext === CONTEXT_BLOCK_IN;
2142
+ let allowBlockCollections = allowBlockScalars;
2143
+ const allowBlockStyles = allowBlockScalars;
2144
+ if (allowToSeek && skipSeparationSpace(state, true)) {
2145
+ atNewLine = true;
2146
+ if (state.lineIndent > parentIndent) indentStatus = 1;
2147
+ else if (state.lineIndent === parentIndent) indentStatus = 0;
2148
+ else indentStatus = -1;
2149
+ }
2150
+ if (indentStatus === 1) while (true) {
2151
+ const ch = state.input.charCodeAt(state.position);
2152
+ const propertyState = snapshotState(state);
2153
+ if (atNewLine && indentStatus !== 1 && (ch === 33 || ch === 38)) break;
2154
+ if (atNewLine && allowBlockStyles && (props.tagStart !== NO_RANGE$1 || props.anchorStart !== NO_RANGE$1) && (ch === 33 || ch === 38)) {
2155
+ const fallbackState = snapshotState(state);
2156
+ const flowIndent = parentIndent + 1;
2157
+ if (readBlockMapping(state, state.position - state.lineStart, flowIndent, props) && state.events[fallbackState.eventsLength]?.type === EVENT_ID.MAPPING) {
2158
+ state.depth--;
2159
+ return true;
2160
+ }
2161
+ restoreState(state, fallbackState);
2162
+ }
2163
+ if (atNewLine && (ch === 33 && props.tagStart !== NO_RANGE$1 || ch === 38 && props.anchorStart !== NO_RANGE$1)) break;
2164
+ if (!readTagProperty(state, props, nodeContext === CONTEXT_FLOW_IN) && !readAnchorProperty(state, props)) break;
2165
+ if (propertyStart === null) propertyStart = propertyState;
2166
+ if (skipSeparationSpace(state, true)) {
2167
+ atNewLine = true;
2168
+ allowBlockCollections = allowBlockStyles;
2169
+ if (state.lineIndent > parentIndent) indentStatus = 1;
2170
+ else if (state.lineIndent === parentIndent) indentStatus = 0;
2171
+ else indentStatus = -1;
2172
+ } else allowBlockCollections = false;
2173
+ }
2174
+ if (allowBlockCollections) allowBlockCollections = atNewLine || allowCompact;
2175
+ if (indentStatus === 1 || nodeContext === CONTEXT_BLOCK_OUT) {
2176
+ const flowIndent = nodeContext === CONTEXT_FLOW_IN || nodeContext === CONTEXT_FLOW_OUT ? parentIndent : parentIndent + 1;
2177
+ const blockIndent = state.position - state.lineStart;
2178
+ if (indentStatus === 1) if (allowBlockCollections && (readBlockSequence(state, blockIndent, props) || readBlockMapping(state, blockIndent, flowIndent, props)) || readFlowCollection(state, flowIndent, props)) hasContent = true;
2179
+ else {
2180
+ const ch = state.input.charCodeAt(state.position);
2181
+ if (propertyStart !== null && allowPropertyMapping && allowBlockStyles && !allowBlockCollections && ch !== 124 && ch !== 62) {
2182
+ const fallbackState = snapshotState(state);
2183
+ const propertyIndent = propertyStart.position - propertyStart.lineStart;
2184
+ restoreState(state, propertyStart);
2185
+ if (readBlockMapping(state, propertyIndent, flowIndent, emptyProperties()) && state.events[fallbackState.eventsLength]?.type === EVENT_ID.MAPPING) hasContent = true;
2186
+ else restoreState(state, fallbackState);
2187
+ }
2188
+ if (!hasContent && (allowBlockScalars && readBlockScalar(state, flowIndent, props) || readSingleQuotedScalar(state, flowIndent, props) || readDoubleQuotedScalar(state, flowIndent, props) || readAlias(state, props) || readPlainScalar(state, flowIndent, nodeContext, props))) hasContent = true;
2189
+ }
2190
+ else if (indentStatus === 0) hasContent = allowBlockCollections && readBlockSequence(state, blockIndent, props);
2191
+ }
2192
+ allowBlockScalars = allowBlockScalars && !hasContent;
2193
+ if (!hasContent && (props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1 || allowBlockScalars)) {
2194
+ addScalarEvent(state, NO_RANGE$1, NO_RANGE$1, props.anchorStart, props.anchorEnd, props.tagStart, props.tagEnd, SCALAR_STYLE.PLAIN);
2195
+ hasContent = true;
2196
+ }
2197
+ state.depth--;
2198
+ return hasContent || props.anchorStart !== NO_RANGE$1 || props.tagStart !== NO_RANGE$1;
2199
+ }
2200
+ function readDirective(state) {
2201
+ if (state.lineIndent > 0 || state.input.charCodeAt(state.position) !== 37) return false;
2202
+ state.position++;
2203
+ const nameStart = state.position;
2204
+ while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++;
2205
+ const name = state.input.slice(nameStart, state.position);
2206
+ const args = [];
2207
+ if (name.length === 0) throwError(state, "directive name must not be less than one character in length");
2208
+ while (state.input.charCodeAt(state.position) !== 0 && !isEol(state.input.charCodeAt(state.position))) {
2209
+ while (isWhiteSpace(state.input.charCodeAt(state.position))) state.position++;
2210
+ if (state.input.charCodeAt(state.position) === 35 || isEol(state.input.charCodeAt(state.position)) || state.input.charCodeAt(state.position) === 0) break;
2211
+ const start = state.position;
2212
+ while (state.input.charCodeAt(state.position) !== 0 && !isWsOrEol(state.input.charCodeAt(state.position))) state.position++;
2213
+ args.push(state.input.slice(start, state.position));
2214
+ }
2215
+ if (isEol(state.input.charCodeAt(state.position))) consumeLineBreak(state);
2216
+ if (name === "YAML") {
2217
+ if (state.directives.some((directive) => directive.kind === "yaml")) throwError(state, "duplication of %YAML directive");
2218
+ if (args.length !== 1) throwError(state, "YAML directive accepts exactly one argument");
2219
+ const match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);
2220
+ if (match === null) throwError(state, "ill-formed argument of the YAML directive");
2221
+ if (parseInt(match[1], 10) !== 1) throwError(state, "unacceptable YAML version of the document");
2222
+ state.directives.push({
2223
+ kind: "yaml",
2224
+ version: args[0]
2225
+ });
2226
+ } else if (name === "TAG") {
2227
+ if (args.length !== 2) throwError(state, "TAG directive accepts exactly two arguments");
2228
+ const [handle, prefix] = args;
2229
+ if (!PATTERN_TAG_HANDLE.test(handle)) throwError(state, "ill-formed tag handle (first argument) of the TAG directive");
2230
+ if (HAS_OWN.call(state.tagHandlers, handle)) throwError(state, `there is a previously declared suffix for "${handle}" tag handle`);
2231
+ if (!PATTERN_TAG_PREFIX.test(prefix)) throwError(state, "ill-formed tag prefix (second argument) of the TAG directive");
2232
+ state.tagHandlers[handle] = prefix;
2233
+ state.directives.push({
2234
+ kind: "tag",
2235
+ handle,
2236
+ prefix
2237
+ });
2238
+ }
2239
+ return true;
2240
+ }
2241
+ function readDocument(state) {
2242
+ state.directives = [];
2243
+ state.tagHandlers = /* @__PURE__ */ Object.create(null);
2244
+ let hasDirectives = false;
2245
+ skipSeparationSpace(state, true);
2246
+ while (readDirective(state)) {
2247
+ hasDirectives = true;
2248
+ skipSeparationSpace(state, true);
2249
+ }
2250
+ let explicitStart = false;
2251
+ let explicitEnd = false;
2252
+ let allowCompact = true;
2253
+ if (state.lineIndent === 0 && state.input.charCodeAt(state.position) === 45 && state.input.charCodeAt(state.position + 1) === 45 && state.input.charCodeAt(state.position + 2) === 45 && isWsOrEolOrEnd(state.input.charCodeAt(state.position + 3))) {
2254
+ explicitStart = true;
2255
+ const markerLine = state.line;
2256
+ state.position += 3;
2257
+ skipSeparationSpace(state, true);
2258
+ allowCompact = state.line > markerLine;
2259
+ } else if (hasDirectives) throwError(state, "directives end mark is expected");
2260
+ const documentEventIndex = state.events.length;
2261
+ if (!explicitStart && state.position === state.lineStart && state.input.charCodeAt(state.position) === 46 && testDocumentSeparator(state)) {
2262
+ state.position += 3;
2263
+ skipSeparationSpace(state, true);
2264
+ return;
2265
+ }
2266
+ addDocumentEvent(state, explicitStart, false);
2267
+ if (!parseNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, allowCompact, allowCompact)) addEmptyScalarEvent(state);
2268
+ skipSeparationSpace(state, true);
2269
+ if (state.position === state.lineStart && testDocumentSeparator(state)) {
2270
+ explicitEnd = state.input.charCodeAt(state.position) === 46;
2271
+ if (explicitEnd) {
2272
+ const markerLine = state.line;
2273
+ state.position += 3;
2274
+ skipSeparationSpace(state, true);
2275
+ if (state.line === markerLine && state.position < state.length) throwError(state, "end of the stream or a document separator is expected");
2276
+ }
2277
+ }
2278
+ const documentEvent = state.events[documentEventIndex];
2279
+ if (documentEvent?.type === EVENT_ID.DOCUMENT) documentEvent.explicitEnd = explicitEnd;
2280
+ addPopEvent(state);
2281
+ if (!explicitEnd && state.position < state.length && !testDocumentBoundary(state)) throwError(state, "end of the stream or a document separator is expected");
2282
+ }
2283
+ function parseEvents(input, options) {
2284
+ const length = input.length;
2285
+ const state = {
2286
+ ...DEFAULT_PARSER_OPTIONS,
2287
+ ...options,
2288
+ input: `${input}\0`,
2289
+ length,
2290
+ position: 0,
2291
+ line: 0,
2292
+ lineStart: 0,
2293
+ lineIndent: 0,
2294
+ firstTabInLine: -1,
2295
+ depth: 0,
2296
+ directives: [],
2297
+ tagHandlers: /* @__PURE__ */ Object.create(null),
2298
+ events: []
2299
+ };
2300
+ const nullpos = input.indexOf("\0");
2301
+ if (nullpos !== -1) YAMLException.throwAt(input, nullpos, "null byte is not allowed in input", state.filename);
2302
+ while (state.position < state.length) {
2303
+ skipByteOrderMark(state);
2304
+ skipSeparationSpace(state, true);
2305
+ if (state.position >= state.length) break;
2306
+ const documentStart = state.position;
2307
+ readDocument(state);
2308
+ if (state.position === documentStart)
2309
+ throwError(state, "can not read a document");
2310
+ }
2311
+ return state.events;
2312
+ }
2313
+ var DEFAULT_LOAD_OPTIONS = {
2314
+ ...DEFAULT_PARSER_OPTIONS,
2315
+ ...DEFAULT_CONSTRUCTOR_OPTIONS
2316
+ };
2317
+ function loadDocuments(input, options = {}) {
2318
+ const opts = {
2319
+ ...DEFAULT_LOAD_OPTIONS,
2320
+ ...options
2321
+ };
2322
+ const source = String(input);
2323
+ const PARSER_OPT_KEYS = Object.keys(DEFAULT_PARSER_OPTIONS);
2324
+ const CONSTRUCTOR_OPT_KEYS = Object.keys(DEFAULT_CONSTRUCTOR_OPTIONS);
2325
+ return constructFromEvents(parseEvents(source, pick(opts, PARSER_OPT_KEYS)), {
2326
+ ...pick(opts, CONSTRUCTOR_OPT_KEYS),
2327
+ source
2328
+ });
2329
+ }
2330
+ function load(input, options) {
2331
+ const documents = loadDocuments(input, options);
2332
+ if (documents.length === 0) throw new YAMLException("expected a document, but the input is empty");
2333
+ if (documents.length === 1) return documents[0];
2334
+ throw new YAMLException("expected a single document in the stream, but found more");
2335
+ }
2336
+ var INVALID = /* @__PURE__ */ Symbol("INVALID");
2337
+ function buildRepresentTypes(schema) {
2338
+ const defaultTags = new Set([
2339
+ schema.defaultScalarTag,
2340
+ schema.defaultSequenceTag,
2341
+ schema.defaultMappingTag
2342
+ ].filter((t) => t !== void 0));
2343
+ const implicitScalars = schema.implicitScalarTags;
2344
+ const explicitTags = schema.tags.filter((t) => !(t.nodeKind === "scalar" && t.implicit) && !defaultTags.has(t));
2345
+ const defaultTagsLast = schema.tags.filter((t) => defaultTags.has(t));
2346
+ return [
2347
+ ...implicitScalars.map((tag) => ({
2348
+ tag,
2349
+ implicitTag: true
2350
+ })),
2351
+ ...explicitTags.map((tag) => ({
2352
+ tag,
2353
+ implicitTag: false
2354
+ })),
2355
+ ...defaultTagsLast.map((tag) => ({
2356
+ tag,
2357
+ implicitTag: true
2358
+ }))
2359
+ ];
2360
+ }
2361
+ function matchTag(state, object) {
2362
+ for (let index = 0, length = state.representTypes.length; index < length; index += 1) {
2363
+ const { tag, implicitTag } = state.representTypes[index];
2364
+ if (tag.identify(object)) {
2365
+ let tagName;
2366
+ if (tag.matchByTagPrefix) tagName = tag.representTagName(object);
2367
+ else tagName = tag.tagName;
2368
+ return {
2369
+ tag,
2370
+ tagName,
2371
+ implicitTag
2372
+ };
2373
+ }
2374
+ }
2375
+ return null;
2376
+ }
2377
+ function build(state, object) {
2378
+ if (!state.noRefs && object !== null && typeof object === "object") {
2379
+ const existing = state.refs.get(object);
2380
+ if (existing) {
2381
+ if (existing.anchor === void 0) existing.anchor = `ref_${state.refCounter++}`;
2382
+ return {
2383
+ kind: "alias",
2384
+ anchor: existing.anchor
2385
+ };
2386
+ }
2387
+ }
2388
+ const matched = matchTag(state, object);
2389
+ if (!matched) {
2390
+ if (object === void 0) return INVALID;
2391
+ if (state.skipInvalid) return INVALID;
2392
+ throw new YAMLException(`unacceptable kind of an object to dump ${Object.prototype.toString.call(object)}`);
2393
+ }
2394
+ const { tag, tagName, implicitTag } = matched;
2395
+ const nodeTagName = implicitTag ? tagName : tagNameShort(tagName);
2396
+ if (tag.nodeKind === "scalar") return {
2397
+ kind: "scalar",
2398
+ tag: nodeTagName,
2399
+ tagged: !implicitTag,
2400
+ style: SCALAR_STYLE.PLAIN,
2401
+ value: tag.represent(object)
2402
+ };
2403
+ if (tag.nodeKind === "sequence") {
2404
+ const container = tag.represent(object);
2405
+ const node2 = {
2406
+ kind: "sequence",
2407
+ tag: nodeTagName,
2408
+ tagged: !implicitTag,
2409
+ style: COLLECTION_STYLE.BLOCK,
2410
+ items: []
2411
+ };
2412
+ if (!state.noRefs) state.refs.set(object, node2);
2413
+ for (let index = 0, length = container.length; index < length; index += 1) {
2414
+ let item = build(state, container[index]);
2415
+ if (item === INVALID && container[index] === void 0) item = build(state, null);
2416
+ if (item === INVALID) continue;
2417
+ node2.items.push(item);
2418
+ }
2419
+ return node2;
2420
+ }
2421
+ const map = tag.represent(object);
2422
+ const node = {
2423
+ kind: "mapping",
2424
+ tag: nodeTagName,
2425
+ tagged: !implicitTag,
2426
+ style: COLLECTION_STYLE.BLOCK,
2427
+ items: []
2428
+ };
2429
+ if (!state.noRefs) state.refs.set(object, node);
2430
+ for (const [objectKey, objectValue] of map) {
2431
+ const key = build(state, objectKey);
2432
+ if (key === INVALID) continue;
2433
+ const value = build(state, objectValue);
2434
+ if (value === INVALID) continue;
2435
+ node.items.push({
2436
+ key,
2437
+ value
2438
+ });
2439
+ }
2440
+ return node;
2441
+ }
2442
+ function jsToAst(input, schema, options = {}) {
2443
+ const root = build({
2444
+ representTypes: buildRepresentTypes(schema),
2445
+ noRefs: options.noRefs ?? false,
2446
+ skipInvalid: options.skipInvalid ?? false,
2447
+ refs: /* @__PURE__ */ new Map(),
2448
+ refCounter: 0
2449
+ }, input);
2450
+ return [{
2451
+ contents: root === INVALID ? null : root,
2452
+ directives: []
2453
+ }];
2454
+ }
2455
+ var VISIT_BREAK = /* @__PURE__ */ Symbol("visit:break");
2456
+ var VISIT_SKIP = /* @__PURE__ */ Symbol("visit:skip");
2457
+ function visitNode(node, visitor, ctx) {
2458
+ const control = visitor(node, ctx);
2459
+ if (control === VISIT_BREAK) return true;
2460
+ if (control === VISIT_SKIP) return false;
2461
+ const depth = ctx.depth + 1;
2462
+ switch (node.kind) {
2463
+ case "sequence":
2464
+ for (const item of node.items) if (visitNode(item, visitor, {
2465
+ depth,
2466
+ parent: node,
2467
+ isKey: false
2468
+ })) return true;
2469
+ break;
2470
+ case "mapping":
2471
+ for (const { key, value } of node.items) {
2472
+ if (visitNode(key, visitor, {
2473
+ depth,
2474
+ parent: node,
2475
+ isKey: true
2476
+ })) return true;
2477
+ if (visitNode(value, visitor, {
2478
+ depth,
2479
+ parent: node,
2480
+ isKey: false
2481
+ })) return true;
2482
+ }
2483
+ break;
2484
+ }
2485
+ return false;
2486
+ }
2487
+ function visit(documents, visitor) {
2488
+ for (const doc of documents) if (doc.contents && visitNode(doc.contents, visitor, {
2489
+ depth: 0,
2490
+ parent: null,
2491
+ isKey: false
2492
+ })) return;
2493
+ }
2494
+ function hasBit(mask, bit) {
2495
+ return (mask & 1 << bit) !== 0;
2496
+ }
2497
+ var DEFAULT_SCALAR_STYLE_RULES = {
2498
+ applyQuoteFlowKeysOption,
2499
+ doubleQuoteForInvisibles,
2500
+ doubleQuoteWhitespaceOnly,
2501
+ applyForceQuotesOption,
2502
+ tryLongOrMultilineAsBlock,
2503
+ quoteInvalidPlain,
2504
+ fallbackToDoubleQuoted
2505
+ };
2506
+ function _preferredQuotedStyle(layout) {
2507
+ if (layout.presenterOptions.quoteStyle === "single" && hasBit(layout.allowedStylesMask, SCALAR_STYLE.SINGLE_QUOTED)) return SCALAR_STYLE.SINGLE_QUOTED;
2508
+ return SCALAR_STYLE.DOUBLE_QUOTED;
2509
+ }
2510
+ function applyQuoteFlowKeysOption(layout) {
2511
+ if (!layout.presenterOptions.quoteFlowKeys) return;
2512
+ if (!layout.isKey || !layout.flowOnly || layout.style !== SCALAR_STYLE.PLAIN) return;
2513
+ layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2514
+ }
2515
+ function doubleQuoteForInvisibles(layout) {
2516
+ if (layout.style === SCALAR_STYLE.PLAIN && /[\t\x7F-\xA0\u2028\u2029\uFEFF\uFFFE\uFFFF]/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2517
+ }
2518
+ function doubleQuoteWhitespaceOnly(layout) {
2519
+ if (layout.style === SCALAR_STYLE.PLAIN && /^\s+$/.test(layout.node.value)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2520
+ }
2521
+ function applyForceQuotesOption(layout) {
2522
+ if (!layout.presenterOptions.forceQuotes) return;
2523
+ if (layout.isKey || layout.style !== SCALAR_STYLE.PLAIN) return;
2524
+ if (layout.node.tag !== layout.presenterOptions.schema.defaultScalarTag.tagName) return;
2525
+ layout.style = layout.node.value.includes("\n") ? SCALAR_STYLE.DOUBLE_QUOTED : _preferredQuotedStyle(layout);
2526
+ }
2527
+ function tryLongOrMultilineAsBlock(layout) {
2528
+ if (layout.style !== SCALAR_STYLE.PLAIN || layout.isKey) return;
2529
+ const value = layout.node.value;
2530
+ const multiline = value.indexOf("\n") !== -1;
2531
+ if (!hasBit(layout.allowedStylesMask, SCALAR_STYLE.LITERAL_BLOCK)) {
2532
+ if (multiline) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2533
+ return;
2534
+ }
2535
+ const w = layout.presenterOptions.lineWidth;
2536
+ if (w === -1) {
2537
+ if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
2538
+ return;
2539
+ }
2540
+ const availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
2541
+ let position = 0;
2542
+ let shouldFold = false;
2543
+ while (position <= value.length) {
2544
+ let lineEnd = value.length;
2545
+ const nextLineBreak = value.indexOf("\n", position);
2546
+ if (nextLineBreak !== -1) lineEnd = nextLineBreak;
2547
+ const line = value.slice(position, lineEnd);
2548
+ if (line.length > availableWidth && line[0] !== " " && / [^ \t]/.test(line)) shouldFold = true;
2549
+ if (nextLineBreak === -1) break;
2550
+ position = nextLineBreak + 1;
2551
+ }
2552
+ if (shouldFold) layout.style = SCALAR_STYLE.FOLDED_BLOCK;
2553
+ else if (multiline) layout.style = SCALAR_STYLE.LITERAL_BLOCK;
2554
+ }
2555
+ function quoteInvalidPlain(layout) {
2556
+ if (layout.style === SCALAR_STYLE.PLAIN && !hasBit(layout.allowedStylesMask, SCALAR_STYLE.PLAIN)) layout.style = _preferredQuotedStyle(layout);
2557
+ }
2558
+ function fallbackToDoubleQuoted(layout) {
2559
+ if (!hasBit(layout.allowedStylesMask, layout.style)) layout.style = SCALAR_STYLE.DOUBLE_QUOTED;
2560
+ }
2561
+ function setBit(mask, bit) {
2562
+ return mask | 1 << bit;
2563
+ }
2564
+ var SRC_C_PRINTABLE = "[\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\u{10000}-\\u{10FFFF}]";
2565
+ var SRC_B_CHAR = "[\\n\\r]";
2566
+ var SRC_C_BYTE_ORDER_MARK = "\\uFEFF";
2567
+ var SRC_S_WHITE = "[ \\t]";
2568
+ var SRC_NB_CHAR = `(?:(?!(?:${SRC_B_CHAR}|${SRC_C_BYTE_ORDER_MARK}))${SRC_C_PRINTABLE})`;
2569
+ var SRC_NS_CHAR = `(?:(?!${SRC_S_WHITE})${SRC_NB_CHAR})`;
2570
+ var SRC_NB_JSON = "[\\x09\\x20-\\uD7FF\\uE000-\\uFFFF\\u{10000}-\\u{10FFFF}]";
2571
+ var SRC_C_INDICATOR = "[-?:,\\[\\]{}#&*!|>'\"%@`]";
2572
+ var SRC_C_FLOW_INDICATOR = "[,\\[\\]{}]";
2573
+ var SRC_NS_PLAIN_SAFE_FLOW_OUT = SRC_NS_CHAR;
2574
+ var SRC_NS_PLAIN_SAFE_FLOW_IN = `(?:(?!${SRC_C_FLOW_INDICATOR})${SRC_NS_CHAR})`;
2575
+ var SRC_NS_PLAIN_FIRST_FLOW_OUT = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))`;
2576
+ var SRC_NS_PLAIN_FIRST_FLOW_IN = `(?:(?:(?!${SRC_C_INDICATOR})${SRC_NS_CHAR})|[?:-](?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))`;
2577
+ var SRC_NS_PLAIN_CHAR_FLOW_OUT = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_OUT})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_OUT}))#*`;
2578
+ var SRC_NS_PLAIN_CHAR_FLOW_IN = `(?:(?:(?![:#])${SRC_NS_PLAIN_SAFE_FLOW_IN})|:(?=${SRC_NS_PLAIN_SAFE_FLOW_IN}))#*`;
2579
+ var SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_OUT})*`;
2580
+ var SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN = `(?:${SRC_S_WHITE}*${SRC_NS_PLAIN_CHAR_FLOW_IN})*`;
2581
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_OUT = `${SRC_NS_PLAIN_FIRST_FLOW_OUT}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
2582
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_IN = `${SRC_NS_PLAIN_FIRST_FLOW_IN}#*${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
2583
+ var SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_OUT;
2584
+ var SRC_NS_PLAIN_ONE_LINE_FLOW_KEY = SRC_NS_PLAIN_ONE_LINE_FLOW_IN;
2585
+ var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_OUT}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_OUT}`;
2586
+ var SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN = `\\n+${SRC_NS_PLAIN_CHAR_FLOW_IN}${SRC_NB_NS_PLAIN_IN_LINE_FLOW_IN}`;
2587
+ var SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT = `${SRC_NS_PLAIN_ONE_LINE_FLOW_OUT}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_OUT})*`;
2588
+ var SRC_NS_PLAIN_MULTI_LINE_FLOW_IN = `${SRC_NS_PLAIN_ONE_LINE_FLOW_IN}(?:${SRC_S_NS_PLAIN_NEXT_LINE_FLOW_IN})*`;
2589
+ var NS_PLAIN_FLOW_OUT = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_OUT})$`, "u");
2590
+ var NS_PLAIN_FLOW_IN = new RegExp(`^(?:${SRC_NS_PLAIN_MULTI_LINE_FLOW_IN})$`, "u");
2591
+ var NS_PLAIN_BLOCK_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_BLOCK_KEY})$`, "u");
2592
+ var NS_PLAIN_FLOW_KEY = new RegExp(`^(?:${SRC_NS_PLAIN_ONE_LINE_FLOW_KEY})$`, "u");
2593
+ var NB_SINGLE_ONE_LINE = new RegExp(`^(?:${SRC_NB_JSON})*$`, "u");
2594
+ var NB_SINGLE_MULTI_LINE = new RegExp(`^(?:${SRC_NB_JSON}|\\n)*$`, "u");
2595
+ var BLOCK_SCALAR_CONTENT = new RegExp(`^(?:${SRC_NB_CHAR}|\\n)*$`, "u");
2596
+ var C_FORBIDDEN_FIRST_LINE = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/;
2597
+ var C_FORBIDDEN_CONTENT = /^(?:---|\.\.\.)(?=$|[ \t\n\r])/m;
2598
+ function canUsePlain(layout) {
2599
+ const str = layout.node.value;
2600
+ if (str !== "") {
2601
+ if (!(layout.isKey ? layout.flowOnly ? NS_PLAIN_FLOW_KEY : NS_PLAIN_BLOCK_KEY : layout.flowOnly ? NS_PLAIN_FLOW_IN : NS_PLAIN_FLOW_OUT).test(str)) return false;
2602
+ if (layout.shiftOfFirstLine === 0 && C_FORBIDDEN_FIRST_LINE.test(str)) return false;
2603
+ if (layout.shiftOfContent === 0) {
2604
+ const firstLineBreak = str.indexOf("\n");
2605
+ if (firstLineBreak !== -1) {
2606
+ const content = str.slice(firstLineBreak + 1);
2607
+ if (C_FORBIDDEN_CONTENT.test(content)) return false;
2608
+ }
2609
+ }
2610
+ }
2611
+ const resolvedTag = layout.presenterOptions.schema.resolveImplicitScalarTag(str).tag.tagName;
2612
+ if (!layout.node.tagged && resolvedTag !== layout.node.tag) return false;
2613
+ if (!layout.node.tagged && str === "=" && resolvedTag === layout.presenterOptions.schema.defaultScalarTag.tagName) return false;
2614
+ return true;
2615
+ }
2616
+ function canUseSingleQuoted(layout) {
2617
+ const str = layout.node.value;
2618
+ if (!(layout.isKey ? NB_SINGLE_ONE_LINE : NB_SINGLE_MULTI_LINE).test(str)) return false;
2619
+ if (/[ \t]\n|\n[ \t]/.test(str)) return false;
2620
+ if (!layout.isKey && layout.shiftOfContent === 0) {
2621
+ const firstLineBreak = str.indexOf("\n");
2622
+ if (firstLineBreak !== -1 && C_FORBIDDEN_CONTENT.test(str.slice(firstLineBreak + 1))) return false;
2623
+ }
2624
+ return true;
2625
+ }
2626
+ function canUseBlock(layout) {
2627
+ if (layout.flowOnly || !BLOCK_SCALAR_CONTENT.test(layout.node.value)) return false;
2628
+ const contentIndent = layout.shiftOfContent - layout.shiftOfParent;
2629
+ if (contentIndent < 1) return false;
2630
+ if (contentIndent > 9 && /^\n* /.test(layout.node.value)) return false;
2631
+ if (layout.shiftOfContent === 0 && C_FORBIDDEN_CONTENT.test(layout.node.value)) return false;
2632
+ return true;
2633
+ }
2634
+ function detectAllowedStyles(layout) {
2635
+ let mask = setBit(0, SCALAR_STYLE.DOUBLE_QUOTED);
2636
+ if (canUsePlain(layout)) mask = setBit(mask, SCALAR_STYLE.PLAIN);
2637
+ if (canUseSingleQuoted(layout)) mask = setBit(mask, SCALAR_STYLE.SINGLE_QUOTED);
2638
+ if (canUseBlock(layout)) mask = setBit(setBit(mask, SCALAR_STYLE.LITERAL_BLOCK), SCALAR_STYLE.FOLDED_BLOCK);
2639
+ layout.allowedStylesMask = mask;
2640
+ }
2641
+ function renderScalar(layout) {
2642
+ switch (layout.style) {
2643
+ case SCALAR_STYLE.PLAIN:
2644
+ return renderPlain(layout);
2645
+ case SCALAR_STYLE.SINGLE_QUOTED:
2646
+ return renderSingleQuoted(layout);
2647
+ case SCALAR_STYLE.LITERAL_BLOCK:
2648
+ return renderLiteralBlock(layout);
2649
+ case SCALAR_STYLE.FOLDED_BLOCK:
2650
+ return renderFoldedBlock(layout);
2651
+ case SCALAR_STYLE.DOUBLE_QUOTED:
2652
+ return renderDoubleQuoted(layout);
2653
+ }
2654
+ }
2655
+ function renderPlain(layout) {
2656
+ return encodeFlowBreaks(layout.node.value, layout.shiftOfContent);
2657
+ }
2658
+ function renderSingleQuoted(layout) {
2659
+ return `'${encodeFlowBreaks(layout.node.value, layout.shiftOfContent).replace(/'/g, "''")}'`;
2660
+ }
2661
+ function renderLiteralBlock(layout) {
2662
+ const value = layout.node.value;
2663
+ return "|" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(value, layout.shiftOfContent));
2664
+ }
2665
+ function renderFoldedBlock(layout) {
2666
+ const value = layout.node.value;
2667
+ const w = layout.presenterOptions.lineWidth;
2668
+ let availableWidth = Infinity;
2669
+ if (w !== -1) availableWidth = Math.max(Math.min(w, 40), w - layout.shiftOfContent);
2670
+ return ">" + blockHeader(value, layout.shiftOfParent, layout.shiftOfContent) + dropEndingNewline(indentString(foldBlockScalar(value, availableWidth), layout.shiftOfContent));
2671
+ }
2672
+ function renderDoubleQuoted(layout) {
2673
+ return `"${escapeString(layout.node.value)}"`;
2674
+ }
2675
+ function encodeFlowBreaks(string, shiftOfContent) {
2676
+ let nextLF = string.indexOf("\n");
2677
+ if (nextLF === -1) return string;
2678
+ const pad = " ".repeat(shiftOfContent);
2679
+ let result = string.slice(0, nextLF);
2680
+ const lineRe = /(\n+)([^\n]*)/g;
2681
+ lineRe.lastIndex = nextLF;
2682
+ let match;
2683
+ while (match = lineRe.exec(string)) {
2684
+ const breaks = match[1].length;
2685
+ const line = match[2];
2686
+ result += "\n".repeat(breaks + 1) + pad + line;
2687
+ }
2688
+ return result;
2689
+ }
2690
+ function indentString(string, spaces) {
2691
+ const indent = " ".repeat(spaces);
2692
+ let position = 0;
2693
+ let result = "";
2694
+ const length = string.length;
2695
+ while (position < length) {
2696
+ let line;
2697
+ const next = string.indexOf("\n", position);
2698
+ if (next === -1) {
2699
+ line = string.slice(position);
2700
+ position = length;
2701
+ } else {
2702
+ line = string.slice(position, next + 1);
2703
+ position = next + 1;
2704
+ }
2705
+ if (line.length && line !== "\n") result += indent;
2706
+ result += line;
2707
+ }
2708
+ return result;
2709
+ }
2710
+ function needIndentIndicator(string) {
2711
+ return /^\n* /.test(string);
2712
+ }
2713
+ function blockHeader(string, shiftOfParent, shiftOfContent) {
2714
+ const indentIndicator = needIndentIndicator(string) ? String(shiftOfContent - shiftOfParent) : "";
2715
+ const clip = string[string.length - 1] === "\n";
2716
+ return `${indentIndicator}${clip && (string[string.length - 2] === "\n" || string === "\n") ? "+" : clip ? "" : "-"}
2717
+ `;
2718
+ }
2719
+ function dropEndingNewline(string) {
2720
+ return string[string.length - 1] === "\n" ? string.slice(0, -1) : string;
2721
+ }
2722
+ function isMoreIndented(char) {
2723
+ return char === " " || char === " ";
2724
+ }
2725
+ function foldLine(line, width) {
2726
+ if (line === "" || isMoreIndented(line[0])) return line;
2727
+ const breakRe = / [^ \t]/g;
2728
+ let match;
2729
+ let start = 0;
2730
+ let end;
2731
+ let curr = 0;
2732
+ let next = 0;
2733
+ let result = "";
2734
+ while (match = breakRe.exec(line)) {
2735
+ next = match.index;
2736
+ if (next - start > width) {
2737
+ end = curr > start ? curr : next;
2738
+ result += `
2739
+ ${line.slice(start, end)}`;
2740
+ start = end + 1;
2741
+ }
2742
+ curr = next;
2743
+ }
2744
+ result += "\n";
2745
+ if (line.length - start > width && curr > start) result += `${line.slice(start, curr)}
2746
+ ${line.slice(curr + 1)}`;
2747
+ else result += line.slice(start);
2748
+ return result.slice(1);
2749
+ }
2750
+ function foldBlockScalar(string, width) {
2751
+ const lineRe = /(\n+)([^\n]*)/g;
2752
+ let nextLF = string.indexOf("\n");
2753
+ if (nextLF === -1) nextLF = string.length;
2754
+ lineRe.lastIndex = nextLF;
2755
+ let result = foldLine(string.slice(0, nextLF), width);
2756
+ let prevMoreIndented = string[0] === "\n" || isMoreIndented(string[0]);
2757
+ let moreIndented;
2758
+ let match;
2759
+ while (match = lineRe.exec(string)) {
2760
+ const prefix = match[1];
2761
+ const line = match[2];
2762
+ moreIndented = line !== "" && isMoreIndented(line[0]);
2763
+ result += prefix + (!prevMoreIndented && !moreIndented && line !== "" ? "\n" : "") + foldLine(line, width);
2764
+ prevMoreIndented = moreIndented;
2765
+ }
2766
+ return result;
2767
+ }
2768
+ var CHARACTERS_TO_ESCAPE = /["\\\x00-\x1F\x7F-\xA0\u2028\u2029\uD800-\uDFFF\uFEFF\uFFFE\uFFFF]/gu;
2769
+ function escapeCharacter(character) {
2770
+ switch (character) {
2771
+ case "\0":
2772
+ return "\\0";
2773
+ case "\x07":
2774
+ return "\\a";
2775
+ case "\b":
2776
+ return "\\b";
2777
+ case " ":
2778
+ return "\\t";
2779
+ case "\n":
2780
+ return "\\n";
2781
+ case "\v":
2782
+ return "\\v";
2783
+ case "\f":
2784
+ return "\\f";
2785
+ case "\r":
2786
+ return "\\r";
2787
+ case "\x1B":
2788
+ return "\\e";
2789
+ case '"':
2790
+ return '\\"';
2791
+ case "\\":
2792
+ return "\\\\";
2793
+ case "\x85":
2794
+ return "\\N";
2795
+ case "\xA0":
2796
+ return "\\_";
2797
+ case "\u2028":
2798
+ return "\\L";
2799
+ case "\u2029":
2800
+ return "\\P";
2801
+ }
2802
+ const code = character.charCodeAt(0);
2803
+ const hex = code.toString(16).toUpperCase();
2804
+ if (code <= 255) return `\\x${"0".repeat(2 - hex.length)}${hex}`;
2805
+ return `\\u${"0".repeat(4 - hex.length)}${hex}`;
2806
+ }
2807
+ function escapeString(string) {
2808
+ return string.replace(CHARACTERS_TO_ESCAPE, escapeCharacter);
2809
+ }
2810
+ var CHAR_LINE_FEED = 10;
2811
+ var DEFAULT_PRESENTER_OPTIONS = {
2812
+ indent: 2,
2813
+ seqNoIndent: false,
2814
+ seqInlineFirst: true,
2815
+ lineWidth: 80,
2816
+ flowBracketPadding: false,
2817
+ flowSkipCommaSpace: false,
2818
+ flowSkipColonSpace: false,
2819
+ quoteFlowKeys: false,
2820
+ quoteStyle: "single",
2821
+ forceQuotes: false,
2822
+ scalarStyleRules: Object.keys(DEFAULT_SCALAR_STYLE_RULES).map((name) => Reflect.get(DEFAULT_SCALAR_STYLE_RULES, name)),
2823
+ tagBeforeAnchor: false
2824
+ };
2825
+ function nodeTagShort(node) {
2826
+ return node.tagged ? node.tag : tagNameShort(node.tag);
2827
+ }
2828
+ function createPresenterState(options) {
2829
+ const opts = {
2830
+ ...DEFAULT_PRESENTER_OPTIONS,
2831
+ ...options
2832
+ };
2833
+ if (opts.flowSkipColonSpace) opts.quoteFlowKeys = true;
2834
+ return {
2835
+ ...opts,
2836
+ defaultScalarTagName: opts.schema.defaultScalarTag.tagName,
2837
+ openEnded: false
2838
+ };
2839
+ }
2840
+ function generateNextLine(state, level) {
2841
+ return `
2842
+ ${" ".repeat(state.indent * level)}`;
2843
+ }
2844
+ function scalarLayout(state, node, parent, level, isKey, flowOnly) {
2845
+ return {
2846
+ node,
2847
+ parent,
2848
+ level,
2849
+ isKey,
2850
+ flowOnly,
2851
+ shiftOfParent: level === 0 ? -1 : state.indent * (level - 1),
2852
+ shiftOfContent: state.indent * Math.max(1, level),
2853
+ shiftOfFirstLine: level === 0 ? 0 : state.indent * level,
2854
+ presenterOptions: state,
2855
+ allowedStylesMask: 0,
2856
+ style: node.style
2857
+ };
2858
+ }
2859
+ function writeFlowSequence(state, level, node) {
2860
+ let result = "";
2861
+ for (let index = 0, length = node.items.length; index < length; index += 1) {
2862
+ const item = writeNode(state, level, node.items[index], node, {}).text;
2863
+ if (index > 0) result += `,${!state.flowSkipCommaSpace ? " " : ""}`;
2864
+ result += item;
2865
+ }
2866
+ const pad = state.flowBracketPadding && node.items.length > 0 ? " " : "";
2867
+ return `[${pad}${result}${pad}]`;
2868
+ }
2869
+ function writeBlockSequence(state, level, node, compact) {
2870
+ let result = "";
2871
+ for (let index = 0, length = node.items.length; index < length; index += 1) {
2872
+ const item = writeNode(state, level + 1, node.items[index], node, {
2873
+ block: true,
2874
+ compact: state.seqInlineFirst,
2875
+ isblockseq: true
2876
+ }).text;
2877
+ if (!compact || result !== "") result += generateNextLine(state, level);
2878
+ if (item === "" || CHAR_LINE_FEED === item.charCodeAt(0)) result += "-";
2879
+ else result += "- ";
2880
+ result += item;
2881
+ }
2882
+ return result;
2883
+ }
2884
+ function writeFlowMapping(state, level, node) {
2885
+ let result = "";
2886
+ for (const { key, value } of node.items) {
2887
+ let pairBuffer = "";
2888
+ if (result !== "") pairBuffer += `,${!state.flowSkipCommaSpace ? " " : ""}`;
2889
+ const keyRender = writeNode(state, level, key, node, { iskey: true });
2890
+ const keyText = keyRender.text;
2891
+ const valueText = writeNode(state, level, value, node, {}).text;
2892
+ const sep = state.flowSkipColonSpace || valueText === "" ? "" : " ";
2893
+ const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0);
2894
+ const keyColonSep = key.kind === "alias" || keyIsBareProps ? " " : "";
2895
+ pairBuffer += `${keyText}${keyColonSep}:${sep}${valueText}`;
2896
+ result += pairBuffer;
2897
+ }
2898
+ const pad = state.flowBracketPadding && result !== "" ? " " : "";
2899
+ return `{${pad}${result}${pad}}`;
2900
+ }
2901
+ function writeBlockMapping(state, level, node, compact) {
2902
+ let result = "";
2903
+ for (let index = 0, length = node.items.length; index < length; index += 1) {
2904
+ let pairBuffer = "";
2905
+ if (!compact || result !== "") pairBuffer += generateNextLine(state, level);
2906
+ const { key, value } = node.items[index];
2907
+ const keyIsBlock = (key.kind === "mapping" || key.kind === "sequence") && key.style === COLLECTION_STYLE.BLOCK && key.items.length !== 0 || key.kind === "scalar" && (key.style === SCALAR_STYLE.LITERAL_BLOCK || key.style === SCALAR_STYLE.FOLDED_BLOCK);
2908
+ const keyRender = keyIsBlock ? writeNode(state, level + 1, key, node, {
2909
+ block: true,
2910
+ compact: true,
2911
+ isblockseq: !cannotBeCompact(state, key, level + 1)
2912
+ }) : writeNode(state, level + 1, key, node, {
2913
+ block: true,
2914
+ compact: true,
2915
+ iskey: true
2916
+ });
2917
+ const keyText = keyRender.text;
2918
+ const keyHasLineBreak = key.kind === "scalar" && key.value.indexOf("\n") !== -1;
2919
+ const keyIsTooLong = keyText.length > 1024 && /^[\s\S]{1025}/u.test(keyText);
2920
+ const explicitPair = keyIsBlock || keyHasLineBreak || keyIsTooLong;
2921
+ if (explicitPair) if (keyText && CHAR_LINE_FEED === keyText.charCodeAt(0)) pairBuffer += "?";
2922
+ else pairBuffer += "? ";
2923
+ pairBuffer += keyText;
2924
+ if (explicitPair) pairBuffer += generateNextLine(state, level);
2925
+ const valueText = writeNode(state, level + 1, value, node, {
2926
+ block: true,
2927
+ compact: explicitPair,
2928
+ isblockseq: explicitPair && !cannotBeCompact(state, value, level + 1)
2929
+ }).text;
2930
+ const keyIsBareProps = key.kind === "scalar" && keyRender.noBody && (key.tagged || key.anchor !== void 0);
2931
+ const keyColonSep = !explicitPair && (key.kind === "alias" || keyIsBareProps) ? " " : "";
2932
+ if (valueText === "" || CHAR_LINE_FEED === valueText.charCodeAt(0)) pairBuffer += `${keyColonSep}:`;
2933
+ else pairBuffer += `${keyColonSep}: `;
2934
+ pairBuffer += valueText;
2935
+ result += pairBuffer;
2936
+ }
2937
+ return result;
2938
+ }
2939
+ function cannotBeCompact(state, node, level) {
2940
+ if (node.kind === "alias") return true;
2941
+ return node.tagged || node.anchor !== void 0 || state.indent < 2 && level > 0;
2942
+ }
2943
+ function writeNode(state, level, node, parent, ctx) {
2944
+ if (node.kind === "alias") {
2945
+ state.openEnded = false;
2946
+ return {
2947
+ text: `*${node.anchor}`,
2948
+ noBody: false
2949
+ };
2950
+ }
2951
+ const { block = false, iskey = false, isblockseq = false } = ctx;
2952
+ let compact = ctx.compact ?? false;
2953
+ const hasAnchor = node.anchor !== void 0;
2954
+ if (cannotBeCompact(state, node, level)) compact = false;
2955
+ let body;
2956
+ let shouldPrintTag = node.tagged;
2957
+ const useBlockCollection = block && (node.kind === "mapping" || node.kind === "sequence") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0;
2958
+ if (node.kind === "mapping") if (useBlockCollection) body = writeBlockMapping(state, level, node, compact);
2959
+ else body = writeFlowMapping(state, level, node);
2960
+ else if (node.kind === "sequence") if (useBlockCollection) if (state.seqNoIndent && !isblockseq && level > 0) body = writeBlockSequence(state, level - 1, node, compact);
2961
+ else body = writeBlockSequence(state, level, node, compact);
2962
+ else body = writeFlowSequence(state, level, node);
2963
+ else {
2964
+ const layout = scalarLayout(state, node, parent, level, iskey, !block);
2965
+ detectAllowedStyles(layout);
2966
+ for (const rule of state.scalarStyleRules) rule(layout);
2967
+ body = renderScalar(layout);
2968
+ state.openEnded = (layout.style === SCALAR_STYLE.LITERAL_BLOCK || layout.style === SCALAR_STYLE.FOLDED_BLOCK) && (node.value === "\n" || node.value.endsWith("\n\n"));
2969
+ shouldPrintTag = node.tagged || body === "" && layout.flowOnly && parent?.kind === "sequence" && !hasAnchor || layout.style !== SCALAR_STYLE.PLAIN && node.tag !== state.defaultScalarTagName;
2970
+ }
2971
+ if ((node.kind === "mapping" || node.kind === "sequence") && !useBlockCollection) state.openEnded = false;
2972
+ if (useBlockCollection && compact && level > 0 && state.indent > 2) body = `${" ".repeat(state.indent - 2)}${body}`;
2973
+ const noBody = body === "";
2974
+ let text = body;
2975
+ if (shouldPrintTag || hasAnchor) {
2976
+ const props = [];
2977
+ const tag = shouldPrintTag ? nodeTagShort(node) : null;
2978
+ const anchor = hasAnchor ? `&${node.anchor}` : null;
2979
+ if (state.tagBeforeAnchor) {
2980
+ if (tag !== null) props.push(tag);
2981
+ if (anchor !== null) props.push(anchor);
2982
+ } else {
2983
+ if (anchor !== null) props.push(anchor);
2984
+ if (tag !== null) props.push(tag);
2985
+ }
2986
+ const sep = body === "" || body.charCodeAt(0) === CHAR_LINE_FEED ? "" : " ";
2987
+ text = `${props.join(" ")}${sep}${body}`;
2988
+ }
2989
+ return {
2990
+ text,
2991
+ noBody
2992
+ };
2993
+ }
2994
+ function rootStartsOwnLine(node) {
2995
+ return (node.kind === "sequence" || node.kind === "mapping") && node.style === COLLECTION_STYLE.BLOCK && node.items.length !== 0 && !node.tagged && node.anchor === void 0;
2996
+ }
2997
+ function writeDocumentDirectives(doc) {
2998
+ let result = "";
2999
+ for (const directive of doc.directives) {
3000
+ if (directive.kind === "yaml") {
3001
+ result += `%YAML ${directive.version}
3002
+ `;
3003
+ continue;
3004
+ }
3005
+ const { handle, prefix } = directive;
3006
+ result += `%TAG ${handle} ${prefix}
3007
+ `;
3008
+ }
3009
+ return result;
3010
+ }
3011
+ function present(documents, options) {
3012
+ const state = createPresenterState(options);
3013
+ let result = "";
3014
+ let previousEnded = false;
3015
+ for (let index = 0; index < documents.length; index += 1) {
3016
+ const doc = documents[index];
3017
+ state.openEnded = false;
3018
+ const directives = writeDocumentDirectives(doc);
3019
+ const hasDirectives = directives !== "";
3020
+ const marker = doc.explicitStart || hasDirectives || index > 0 && !previousEnded;
3021
+ result += directives;
3022
+ if (doc.contents === null) {
3023
+ if (marker) result += "---\n";
3024
+ } else if (marker) {
3025
+ const body = writeNode(state, 0, doc.contents, null, {
3026
+ block: true,
3027
+ compact: true
3028
+ }).text;
3029
+ const sep = body === "" ? "" : hasDirectives || rootStartsOwnLine(doc.contents) ? "\n" : " ";
3030
+ result += `---${sep}${body}
3031
+ `;
3032
+ } else result += writeNode(state, 0, doc.contents, null, {
3033
+ block: true,
3034
+ compact: true
3035
+ }).text + "\n";
3036
+ previousEnded = doc.explicitEnd || state.openEnded;
3037
+ if (previousEnded) result += "...\n";
3038
+ }
3039
+ return result;
3040
+ }
3041
+ var DEFAULT_DUMP_OPTIONS = {
3042
+ ...DEFAULT_PRESENTER_OPTIONS,
3043
+ schema: DUMP_SCHEMA,
3044
+ skipInvalid: false,
3045
+ noRefs: false,
3046
+ flowLevel: -1,
3047
+ sortKeys: false,
3048
+ transform: () => {
3049
+ }
3050
+ };
3051
+ function defaultCompareFn(a, b) {
3052
+ const x = String(a);
3053
+ const y = String(b);
3054
+ if (x < y) return -1;
3055
+ if (x > y) return 1;
3056
+ return 0;
3057
+ }
3058
+ function dump(input, options = {}) {
3059
+ const opts = {
3060
+ ...DEFAULT_DUMP_OPTIONS,
3061
+ ...options
3062
+ };
3063
+ const documents = jsToAst(input, opts.schema, {
3064
+ noRefs: opts.noRefs,
3065
+ skipInvalid: opts.skipInvalid
3066
+ });
3067
+ if (opts.flowLevel >= 0) visit(documents, (node, ctx) => {
3068
+ if (ctx.depth < opts.flowLevel) return;
3069
+ if (node.kind === "sequence" || node.kind === "mapping") node.style = COLLECTION_STYLE.FLOW;
3070
+ return VISIT_SKIP;
3071
+ });
3072
+ if (opts.sortKeys) {
3073
+ const compareFn = opts.sortKeys === true ? defaultCompareFn : opts.sortKeys;
3074
+ visit(documents, (node) => {
3075
+ if (node.kind !== "mapping") return;
3076
+ node.items.sort((a, b) => compareFn(a.key.kind === "scalar" ? a.key.value : "", b.key.kind === "scalar" ? b.key.value : ""));
3077
+ });
3078
+ }
3079
+ opts.transform(documents);
3080
+ return present(documents, {
3081
+ ...pick(opts, Object.keys(DEFAULT_PRESENTER_OPTIONS)),
3082
+ schema: opts.schema
3083
+ });
3084
+ }
3085
+ var EVENT_DOCUMENT = EVENT_ID.DOCUMENT;
3086
+ var EVENT_SEQUENCE = EVENT_ID.SEQUENCE;
3087
+ var EVENT_MAPPING = EVENT_ID.MAPPING;
3088
+ var EVENT_SCALAR = EVENT_ID.SCALAR;
3089
+ var EVENT_ALIAS = EVENT_ID.ALIAS;
3090
+ var EVENT_POP = EVENT_ID.POP;
3091
+ var SCALAR_STYLE_PLAIN = SCALAR_STYLE.PLAIN;
3092
+ var SCALAR_STYLE_SINGLE_QUOTED = SCALAR_STYLE.SINGLE_QUOTED;
3093
+ var SCALAR_STYLE_DOUBLE_QUOTED = SCALAR_STYLE.DOUBLE_QUOTED;
3094
+ var SCALAR_STYLE_LITERAL_BLOCK = SCALAR_STYLE.LITERAL_BLOCK;
3095
+ var SCALAR_STYLE_FOLDED_BLOCK = SCALAR_STYLE.FOLDED_BLOCK;
3096
+ var COLLECTION_STYLE_BLOCK = COLLECTION_STYLE.BLOCK;
3097
+ var COLLECTION_STYLE_FLOW = COLLECTION_STYLE.FLOW;
3098
+ var CHOMPING_CLIP = CHOMPING_MODE.CLIP;
3099
+ var CHOMPING_STRIP = CHOMPING_MODE.STRIP;
3100
+ var CHOMPING_KEEP = CHOMPING_MODE.KEEP;
3101
+
3102
+ // src/agent/profiles.ts
3103
+ import * as fs from "node:fs";
3104
+ import * as path from "node:path";
3105
+ var PROVIDERS = /* @__PURE__ */ new Set(["anthropic", "openai", "claude-cli"]);
3106
+ var DEFAULT_MODEL = {
3107
+ anthropic: "claude-sonnet-5",
3108
+ openai: "gpt-4o",
3109
+ "claude-cli": ""
3110
+ };
3111
+ var DEFAULT_KEY_ENV = {
3112
+ anthropic: "ANTHROPIC_API_KEY",
3113
+ openai: "OPENAI_API_KEY",
3114
+ "claude-cli": void 0
3115
+ };
3116
+ var DEFAULT_MAX_ITERATIONS = 8;
3117
+ var STARTER_AGENTS_YAML = `# Agent profiles: what answers a waitForAgent gate when nobody is watching.
3118
+ # Keys are read from the environment variable named here, never stored.
3119
+ default: assistant
3120
+ agents:
3121
+ assistant:
3122
+ provider: anthropic # anthropic | openai | claude-cli
3123
+ model: claude-sonnet-5
3124
+ apiKeyEnv: ANTHROPIC_API_KEY
3125
+ system: |
3126
+ You are a careful assistant answering one step of a workflow.
3127
+ Do exactly the task described and return only what is asked for.
3128
+ maxIterations: 8
3129
+ gates: {} # agentId or workflow/node -> profile name
3130
+ `;
3131
+ function agentsFile(projectDir) {
3132
+ return path.join(projectDir, ".flowweaver", "agents.yaml");
3133
+ }
3134
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3135
+ function loadAgentProfiles(projectDir) {
3136
+ const file = agentsFile(projectDir);
3137
+ const out = { file, exists: false, agents: {}, gates: {}, errors: [] };
3138
+ if (!fs.existsSync(file)) return out;
3139
+ out.exists = true;
3140
+ let doc;
3141
+ try {
3142
+ doc = load(fs.readFileSync(file, "utf8"));
3143
+ } catch (e) {
3144
+ out.errors.push(`could not parse: ${getErrorMessage(e)}`);
3145
+ return out;
3146
+ }
3147
+ if (doc == null) return out;
3148
+ if (!isRecord(doc)) {
3149
+ out.errors.push("the file must be a mapping");
3150
+ return out;
3151
+ }
3152
+ const agents = doc.agents;
3153
+ if (agents !== void 0) {
3154
+ if (!isRecord(agents)) out.errors.push("`agents` must be a mapping of name \u2192 profile");
3155
+ else {
3156
+ for (const [name, raw] of Object.entries(agents)) {
3157
+ if (!isRecord(raw)) {
3158
+ out.errors.push(`agents.${name} must be a mapping`);
3159
+ continue;
3160
+ }
3161
+ const provider = raw.provider;
3162
+ if (typeof provider !== "string" || !PROVIDERS.has(provider)) {
3163
+ out.errors.push(`agents.${name}.provider must be one of anthropic, openai, claude-cli`);
3164
+ continue;
3165
+ }
3166
+ const str = (k) => typeof raw[k] === "string" && raw[k].trim() ? raw[k] : void 0;
3167
+ const num = (k) => typeof raw[k] === "number" && Number.isFinite(raw[k]) ? raw[k] : void 0;
3168
+ out.agents[name] = {
3169
+ name,
3170
+ provider,
3171
+ model: str("model"),
3172
+ apiKeyEnv: str("apiKeyEnv"),
3173
+ baseUrl: str("baseUrl"),
3174
+ system: str("system"),
3175
+ maxIterations: num("maxIterations"),
3176
+ maxTokens: num("maxTokens"),
3177
+ bin: str("bin"),
3178
+ description: str("description")
3179
+ };
3180
+ }
3181
+ }
3182
+ }
3183
+ if (doc.default !== void 0) {
3184
+ if (typeof doc.default !== "string") out.errors.push("`default` must be a profile name");
3185
+ else if (!out.agents[doc.default]) out.errors.push(`default names an unknown profile: ${doc.default}`);
3186
+ else out.default = doc.default;
3187
+ }
3188
+ const gates = doc.gates;
3189
+ if (gates !== void 0) {
3190
+ if (!isRecord(gates)) out.errors.push("`gates` must be a mapping of agentId or workflow/node \u2192 profile name");
3191
+ else {
3192
+ for (const [key, target] of Object.entries(gates)) {
3193
+ if (typeof target !== "string") {
3194
+ out.errors.push(`gates.${key} must be a profile name`);
3195
+ continue;
3196
+ }
3197
+ if (!out.agents[target]) {
3198
+ out.errors.push(`gates.${key} names an unknown profile: ${target}`);
3199
+ continue;
3200
+ }
3201
+ out.gates[key] = target;
3202
+ }
3203
+ }
3204
+ }
3205
+ return out;
3206
+ }
3207
+ function profileForGate(profiles, gate) {
3208
+ const byStep = profiles.gates[`${gate.workflow}/${gate.node}`];
3209
+ if (byStep) return profiles.agents[byStep];
3210
+ if (typeof gate.agentId === "string" && gate.agentId && profiles.gates[gate.agentId]) return profiles.agents[profiles.gates[gate.agentId]];
3211
+ if (profiles.default) return profiles.agents[profiles.default];
3212
+ return void 0;
3213
+ }
3214
+ function keyEnvOf(profile) {
3215
+ if (profile.provider === "claude-cli") return void 0;
3216
+ return profile.apiKeyEnv ?? DEFAULT_KEY_ENV[profile.provider];
3217
+ }
3218
+ function binaryFound(bin, env) {
3219
+ if (bin.includes("/") || bin.includes("\\")) return fs.existsSync(bin);
3220
+ const dirs = (env.PATH ?? "").split(path.delimiter).filter(Boolean);
3221
+ const exts = process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""];
3222
+ return dirs.some((d) => exts.some((x) => fs.existsSync(path.join(d, bin + x))));
3223
+ }
3224
+ var SUGGESTED_MODELS = {
3225
+ anthropic: ["claude-sonnet-5", "claude-opus-5", "claude-haiku-4-5-20251001"],
3226
+ openai: ["gpt-4o", "gpt-4.1", "gpt-4o-mini", "llama3", "qwen2.5"],
3227
+ "claude-cli": ["", "sonnet", "opus", "haiku"]
3228
+ };
3229
+ var NAME = /^[a-z][a-z0-9_-]{0,40}$/i;
3230
+ function validateProfile(p) {
3231
+ const errors = [];
3232
+ if (!p.name || !NAME.test(p.name)) errors.push("the name is letters, digits, - and _, starting with a letter");
3233
+ if (!p.provider || !PROVIDERS.has(p.provider)) errors.push("pick a provider: anthropic, openai or claude-cli");
3234
+ if (p.provider === "openai" && p.baseUrl && !/^https?:\/\//.test(p.baseUrl)) errors.push("the base URL starts with http:// or https://");
3235
+ if (p.apiKeyEnv && !/^[A-Z_][A-Z0-9_]*$/.test(p.apiKeyEnv)) errors.push("the key variable is an environment variable name, like MY_API_KEY");
3236
+ if (p.maxIterations !== void 0 && (!Number.isInteger(p.maxIterations) || p.maxIterations < 1 || p.maxIterations > 50)) errors.push("turns is a whole number from 1 to 50");
3237
+ return errors;
3238
+ }
3239
+ function saveAgentProfiles(projectDir, profiles) {
3240
+ const agents = {};
3241
+ for (const [name, p] of Object.entries(profiles.agents)) {
3242
+ const out = { provider: p.provider };
3243
+ for (const k of ["model", "apiKeyEnv", "baseUrl", "bin", "description", "system", "maxIterations", "maxTokens"]) {
3244
+ const v = p[k];
3245
+ if (v !== void 0 && v !== "" && v !== null) out[k] = v;
3246
+ }
3247
+ agents[name] = out;
3248
+ }
3249
+ const doc = {};
3250
+ if (profiles.default && profiles.agents[profiles.default]) doc.default = profiles.default;
3251
+ doc.agents = agents;
3252
+ if (Object.keys(profiles.gates).length) doc.gates = profiles.gates;
3253
+ const header = "# Agent profiles: what answers a waitForAgent gate when nobody is watching.\n# Keys are read from the environment variable named here, never stored.\n# Edited by fw console. See the Agents page.\n";
3254
+ const text = header + dump(doc, { lineWidth: 100, noRefs: true, quoteStyle: "double" });
3255
+ const file = agentsFile(projectDir);
3256
+ fs.mkdirSync(path.dirname(file), { recursive: true });
3257
+ const tmp = `${file}.tmp-${process.pid}`;
3258
+ fs.writeFileSync(tmp, text);
3259
+ fs.renameSync(tmp, file);
3260
+ return file;
3261
+ }
3262
+ function readiness(profile, env = process.env) {
3263
+ if (profile.provider === "claude-cli") {
3264
+ const bin = profile.bin ?? "claude";
3265
+ return binaryFound(bin, env) ? { ready: true } : { ready: false, reason: `the \`${bin}\` command is not on PATH` };
3266
+ }
3267
+ const keyEnv = keyEnvOf(profile);
3268
+ if (env[keyEnv]) return { ready: true, keyEnv };
3269
+ if (profile.provider === "openai" && profile.baseUrl) return { ready: true, keyEnv, reason: "not set, and not needed with a base URL" };
3270
+ return { ready: false, keyEnv, reason: `${keyEnv} is not set in the environment` };
3271
+ }
3272
+
3273
+ // src/agent/agent-loop.ts
3274
+ var DEFAULT_MAX_ITERATIONS2 = 15;
3275
+ var TOOL_RESULT_CAP = 1e4;
3276
+ function truncateToolResult(result, cap = TOOL_RESULT_CAP) {
3277
+ if (result.length <= cap) return result;
3278
+ return `${result.slice(0, cap)}
3279
+ [truncated: ${result.length - cap} more characters]`;
3280
+ }
3281
+ async function runAgentLoop(provider, tools, executor, messages, options) {
3282
+ const maxIterations = options?.maxIterations ?? DEFAULT_MAX_ITERATIONS2;
3283
+ const signal = options?.signal;
3284
+ const onStreamEvent = options?.onStreamEvent;
3285
+ const onToolEvent = options?.onToolEvent;
3286
+ const conversation = [...messages];
3287
+ let totalPromptTokens = 0;
3288
+ let totalCompletionTokens = 0;
3289
+ let totalCacheReadTokens = 0;
3290
+ let totalCacheCreationTokens = 0;
3291
+ let totalCostUsd = 0;
3292
+ let toolCallCount = 0;
3293
+ for (let iteration = 0; iteration < maxIterations; iteration++) {
3294
+ if (signal?.aborted) {
3295
+ return buildResult(false, "Aborted", conversation, toolCallCount, totalPromptTokens, totalCompletionTokens, totalCacheReadTokens, totalCacheCreationTokens, totalCostUsd);
3296
+ }
3297
+ let text = "";
3298
+ let finishReason = "stop";
3299
+ const collectedToolCalls = [];
3300
+ const activeToolNames = /* @__PURE__ */ new Map();
3301
+ const stream = provider.stream(conversation, tools, {
3302
+ systemPrompt: options?.systemPrompt,
3303
+ model: options?.model,
3304
+ maxTokens: options?.maxTokens,
3305
+ signal,
3306
+ executor,
3307
+ onToolEvent
3308
+ });
3309
+ for await (const event of stream) {
3310
+ onStreamEvent?.(event);
3311
+ switch (event.type) {
3312
+ case "text_delta":
3313
+ text += event.text;
3314
+ break;
3315
+ case "thinking_delta":
3316
+ break;
3317
+ case "tool_use_start":
3318
+ activeToolNames.set(event.id, event.name);
3319
+ break;
3320
+ case "tool_use_delta":
3321
+ break;
3322
+ case "tool_use_end":
3323
+ collectedToolCalls.push({
3324
+ id: event.id,
3325
+ name: activeToolNames.get(event.id) ?? "unknown",
3326
+ arguments: event.arguments
3327
+ });
3328
+ activeToolNames.delete(event.id);
3329
+ break;
3330
+ case "tool_result":
3331
+ toolCallCount++;
3332
+ break;
3333
+ case "usage":
3334
+ totalPromptTokens += event.promptTokens;
3335
+ totalCompletionTokens += event.completionTokens;
3336
+ totalCacheReadTokens += event.cacheReadTokens ?? 0;
3337
+ totalCacheCreationTokens += event.cacheCreationTokens ?? 0;
3338
+ if (event.costUsd != null) totalCostUsd = event.costUsd;
3339
+ break;
3340
+ case "message_stop":
3341
+ finishReason = event.finishReason;
3342
+ break;
3343
+ }
3344
+ }
3345
+ if (collectedToolCalls.length > 0) {
3346
+ conversation.push({
3347
+ role: "assistant",
3348
+ content: text || "",
3349
+ toolCalls: collectedToolCalls
3350
+ });
3351
+ } else if (text) {
3352
+ conversation.push({ role: "assistant", content: text });
3353
+ }
3354
+ if (finishReason !== "tool_calls" || collectedToolCalls.length === 0) {
3355
+ if (options?.onTurnEnd) {
3356
+ await options.onTurnEnd({
3357
+ iteration,
3358
+ maxIterations,
3359
+ messages: conversation,
3360
+ toolCallCount,
3361
+ usage: { promptTokens: totalPromptTokens, completionTokens: totalCompletionTokens },
3362
+ isFinalTurn: true
3363
+ });
3364
+ }
3365
+ return buildResult(
3366
+ finishReason !== "error",
3367
+ text || "Task completed",
3368
+ conversation,
3369
+ toolCallCount,
3370
+ totalPromptTokens,
3371
+ totalCompletionTokens,
3372
+ totalCacheReadTokens,
3373
+ totalCacheCreationTokens,
3374
+ totalCostUsd
3375
+ );
3376
+ }
3377
+ for (const tc of collectedToolCalls) {
3378
+ if (signal?.aborted) break;
3379
+ toolCallCount++;
3380
+ onToolEvent?.({ type: "tool_call_start", name: tc.name, args: tc.arguments });
3381
+ let result;
3382
+ let isError;
3383
+ try {
3384
+ const res = await executor(tc.name, tc.arguments);
3385
+ result = res.result;
3386
+ isError = res.isError;
3387
+ } catch (err) {
3388
+ result = getErrorMessage(err);
3389
+ isError = true;
3390
+ }
3391
+ onToolEvent?.({ type: "tool_call_result", name: tc.name, args: tc.arguments, result: result.slice(0, 200), isError });
3392
+ conversation.push({
3393
+ role: "tool",
3394
+ content: truncateToolResult(result),
3395
+ toolCallId: tc.id
3396
+ });
3397
+ }
3398
+ if (options?.onTurnEnd) {
3399
+ const turnResult = await options.onTurnEnd({
3400
+ iteration,
3401
+ maxIterations,
3402
+ messages: conversation,
3403
+ toolCallCount,
3404
+ usage: { promptTokens: totalPromptTokens, completionTokens: totalCompletionTokens },
3405
+ isFinalTurn: false
3406
+ });
3407
+ if (turnResult?.continue === false) {
3408
+ return buildResult(
3409
+ true,
3410
+ turnResult.injectMessage ?? "Stopped by hook",
3411
+ conversation,
3412
+ toolCallCount,
3413
+ totalPromptTokens,
3414
+ totalCompletionTokens,
3415
+ totalCacheReadTokens,
3416
+ totalCacheCreationTokens,
3417
+ totalCostUsd
3418
+ );
3419
+ }
3420
+ if (turnResult?.injectMessage) {
3421
+ conversation.push({ role: "user", content: turnResult.injectMessage });
3422
+ }
3423
+ }
3424
+ }
3425
+ return buildResult(
3426
+ false,
3427
+ `Reached max iterations (${maxIterations})`,
3428
+ conversation,
3429
+ toolCallCount,
3430
+ totalPromptTokens,
3431
+ totalCompletionTokens,
3432
+ totalCacheReadTokens,
3433
+ totalCacheCreationTokens,
3434
+ totalCostUsd
3435
+ );
3436
+ }
3437
+ function buildResult(success, summary, messages, toolCallCount, promptTokens, completionTokens, cacheReadTokens = 0, cacheCreationTokens = 0, costUsd = 0) {
3438
+ return {
3439
+ success,
3440
+ summary,
3441
+ messages,
3442
+ toolCallCount,
3443
+ usage: { promptTokens, completionTokens, cacheReadTokens, cacheCreationTokens, costUsd }
3444
+ };
3445
+ }
3446
+
3447
+ // src/agent/providers/anthropic.ts
3448
+ function buildSystemBlocks(prompt) {
3449
+ const blocks = [
3450
+ { type: "text", text: prompt.prefix, cache_control: { type: "ephemeral" } }
3451
+ ];
3452
+ if (prompt.suffix) {
3453
+ blocks.push({ type: "text", text: prompt.suffix });
3454
+ }
3455
+ return blocks;
3456
+ }
3457
+ var AnthropicProvider = class {
3458
+ apiKey;
3459
+ model;
3460
+ maxTokens;
3461
+ baseUrl;
3462
+ constructor(options) {
3463
+ if (!options.apiKey) {
3464
+ throw new Error("AnthropicProvider requires an API key");
3465
+ }
3466
+ this.apiKey = options.apiKey;
3467
+ this.model = options.model ?? DEFAULT_MODEL.anthropic;
3468
+ this.maxTokens = options.maxTokens ?? 8192;
3469
+ this.baseUrl = options.baseUrl ?? "https://api.anthropic.com";
3470
+ }
3471
+ async *stream(messages, tools, options) {
3472
+ const model = options?.model ?? this.model;
3473
+ const maxTokens = options?.maxTokens ?? this.maxTokens;
3474
+ const apiMessages = messages.map((m) => {
3475
+ if (m.role === "tool") {
3476
+ return {
3477
+ role: "user",
3478
+ content: [{ type: "tool_result", tool_use_id: m.toolCallId, content: m.content }]
3479
+ };
3480
+ }
3481
+ if (m.role === "assistant" && m.toolCalls?.length) {
3482
+ const blocks = [];
3483
+ if (m.content) blocks.push({ type: "text", text: m.content });
3484
+ for (const tc of m.toolCalls) {
3485
+ blocks.push({ type: "tool_use", id: tc.id, name: tc.name, input: tc.arguments });
3486
+ }
3487
+ return { role: "assistant", content: blocks };
3488
+ }
3489
+ return { role: m.role, content: m.content };
3490
+ });
3491
+ const apiTools = tools.map((t) => ({
3492
+ name: t.name,
3493
+ description: t.description,
3494
+ input_schema: t.inputSchema
3495
+ }));
3496
+ const body = JSON.stringify({
3497
+ model,
3498
+ max_tokens: maxTokens,
3499
+ stream: true,
3500
+ ...options?.systemPrompt ? { system: buildSystemBlocks(options.systemPrompt) } : {},
3501
+ messages: apiMessages,
3502
+ ...apiTools.length > 0 ? { tools: apiTools } : {}
3503
+ });
3504
+ const response = await fetch(`${this.baseUrl}/v1/messages`, {
3505
+ method: "POST",
3506
+ headers: {
3507
+ "x-api-key": this.apiKey,
3508
+ "anthropic-version": "2025-04-15",
3509
+ "content-type": "application/json"
3510
+ },
3511
+ body,
3512
+ signal: options?.signal ?? AbortSignal.timeout(3e5)
3513
+ });
3514
+ if (!response.ok) {
3515
+ const err = await response.text();
3516
+ throw new Error(`Anthropic API error ${response.status}: ${err.slice(0, 200)}`);
3517
+ }
3518
+ if (!response.body) throw new Error("No response body");
3519
+ const reader = response.body.getReader();
3520
+ const decoder = new TextDecoder();
3521
+ let buffer = "";
3522
+ const activeToolUses = /* @__PURE__ */ new Map();
3523
+ try {
3524
+ while (true) {
3525
+ const { done, value } = await reader.read();
3526
+ if (done) break;
3527
+ buffer += decoder.decode(value, { stream: true });
3528
+ const lines = buffer.split("\n");
3529
+ buffer = lines.pop() || "";
3530
+ for (const line of lines) {
3531
+ if (!line.startsWith("data: ")) continue;
3532
+ const jsonStr = line.slice(6).trim();
3533
+ if (jsonStr === "[DONE]") continue;
3534
+ let event;
3535
+ try {
3536
+ event = JSON.parse(jsonStr);
3537
+ } catch {
3538
+ continue;
3539
+ }
3540
+ const eventType = event.type;
3541
+ if (eventType === "content_block_start") {
3542
+ const block = event.content_block;
3543
+ const index = event.index;
3544
+ if (block.type === "tool_use" && block.id && block.name) {
3545
+ activeToolUses.set(index, { id: block.id, name: block.name, jsonChunks: [] });
3546
+ yield { type: "tool_use_start", id: block.id, name: block.name };
3547
+ }
3548
+ }
3549
+ if (eventType === "content_block_delta") {
3550
+ const delta = event.delta;
3551
+ const index = event.index;
3552
+ if (delta.type === "text_delta" && delta.text) {
3553
+ yield { type: "text_delta", text: delta.text };
3554
+ }
3555
+ if (delta.type === "thinking_delta" && delta.thinking) {
3556
+ yield { type: "thinking_delta", text: delta.thinking };
3557
+ }
3558
+ if (delta.type === "input_json_delta" && delta.partial_json !== void 0) {
3559
+ const active = activeToolUses.get(index);
3560
+ if (active) {
3561
+ active.jsonChunks.push(delta.partial_json);
3562
+ yield { type: "tool_use_delta", id: active.id, partialJson: delta.partial_json };
3563
+ }
3564
+ }
3565
+ }
3566
+ if (eventType === "content_block_stop") {
3567
+ const index = event.index;
3568
+ const active = activeToolUses.get(index);
3569
+ if (active) {
3570
+ activeToolUses.delete(index);
3571
+ let args = {};
3572
+ try {
3573
+ args = JSON.parse(active.jsonChunks.join(""));
3574
+ } catch {
3575
+ }
3576
+ yield { type: "tool_use_end", id: active.id, arguments: args };
3577
+ }
3578
+ }
3579
+ if (eventType === "message_start" && event.message?.usage) {
3580
+ const usage = event.message.usage;
3581
+ yield {
3582
+ type: "usage",
3583
+ promptTokens: usage.input_tokens ?? 0,
3584
+ completionTokens: usage.output_tokens ?? 0
3585
+ };
3586
+ }
3587
+ if (eventType === "message_delta") {
3588
+ const delta = event.delta;
3589
+ if (event.usage) {
3590
+ const usage = event.usage;
3591
+ yield {
3592
+ type: "usage",
3593
+ promptTokens: 0,
3594
+ completionTokens: usage.output_tokens ?? 0
3595
+ };
3596
+ }
3597
+ if (delta?.stop_reason === "tool_use") {
3598
+ yield { type: "message_stop", finishReason: "tool_calls" };
3599
+ } else if (delta?.stop_reason === "end_turn") {
3600
+ yield { type: "message_stop", finishReason: "stop" };
3601
+ } else if (delta?.stop_reason === "max_tokens") {
3602
+ yield { type: "message_stop", finishReason: "length" };
3603
+ } else if (delta?.stop_reason) {
3604
+ yield { type: "message_stop", finishReason: "stop" };
3605
+ }
3606
+ }
3607
+ if (eventType === "error") {
3608
+ const errObj = event.error;
3609
+ throw new Error(`Anthropic stream error: ${errObj?.message ?? "unknown"}`);
3610
+ }
3611
+ }
3612
+ }
3613
+ } finally {
3614
+ reader.releaseLock();
3615
+ }
3616
+ }
3617
+ };
3618
+ function createAnthropicProvider(options) {
3619
+ return new AnthropicProvider(options);
3620
+ }
3621
+
3622
+ // src/agent/types.ts
3623
+ function joinSplitPrompt(prompt) {
3624
+ if (!prompt.suffix) return prompt.prefix;
3625
+ return prompt.prefix + "\n\n" + prompt.suffix;
3626
+ }
3627
+ function stripMcpToolPrefix(name) {
3628
+ return name.replace(/^mcp__[a-zA-Z0-9_-]+__/, "");
3629
+ }
3630
+
3631
+ // src/agent/providers/openai-compat.ts
3632
+ var OpenAICompatProvider = class {
3633
+ apiKey;
3634
+ model;
3635
+ maxTokens;
3636
+ baseUrl;
3637
+ constructor(options) {
3638
+ if (!options.apiKey) {
3639
+ throw new Error("OpenAICompatProvider requires an API key");
3640
+ }
3641
+ this.apiKey = options.apiKey;
3642
+ this.model = options.model ?? "gpt-4o";
3643
+ this.maxTokens = options.maxTokens ?? 4096;
3644
+ this.baseUrl = (options.baseUrl ?? "https://api.openai.com").replace(/\/+$/, "");
3645
+ }
3646
+ async *stream(messages, tools, options) {
3647
+ const model = options?.model ?? this.model;
3648
+ const maxTokens = options?.maxTokens ?? this.maxTokens;
3649
+ const apiMessages = messages.map((m) => formatMessage(m));
3650
+ const apiTools = tools.length > 0 ? tools.map((t) => ({
3651
+ type: "function",
3652
+ function: {
3653
+ name: t.name,
3654
+ description: t.description,
3655
+ parameters: t.inputSchema
3656
+ }
3657
+ })) : void 0;
3658
+ const body = {
3659
+ model,
3660
+ messages: [
3661
+ ...options?.systemPrompt ? [{ role: "system", content: joinSplitPrompt(options.systemPrompt) }] : [],
3662
+ ...apiMessages
3663
+ ],
3664
+ max_tokens: maxTokens,
3665
+ stream: true,
3666
+ // Without this OpenAI sends no usage on a stream, and token totals stay 0.
3667
+ stream_options: { include_usage: true }
3668
+ };
3669
+ if (apiTools && apiTools.length > 0) {
3670
+ body.tools = apiTools;
3671
+ }
3672
+ const response = await fetch(completionsUrl(this.baseUrl), {
3673
+ method: "POST",
3674
+ headers: {
3675
+ "Content-Type": "application/json",
3676
+ Authorization: `Bearer ${this.apiKey}`
3677
+ },
3678
+ body: JSON.stringify(body),
3679
+ signal: options?.signal
3680
+ });
3681
+ if (!response.ok) {
3682
+ const errText = await response.text().catch(() => "");
3683
+ yield { type: "text_delta", text: `OpenAI API error ${response.status}: ${errText.slice(0, 300)}` };
3684
+ yield { type: "message_stop", finishReason: "error" };
3685
+ return;
3686
+ }
3687
+ if (!response.body) {
3688
+ yield { type: "message_stop", finishReason: "error" };
3689
+ return;
3690
+ }
3691
+ const reader = response.body.getReader();
3692
+ const decoder = new TextDecoder();
3693
+ let buffer = "";
3694
+ let hasToolCalls = false;
3695
+ const activeToolCalls = /* @__PURE__ */ new Map();
3696
+ try {
3697
+ while (true) {
3698
+ const { done, value } = await reader.read();
3699
+ if (done) break;
3700
+ buffer += decoder.decode(value, { stream: true });
3701
+ const lines = buffer.split("\n");
3702
+ buffer = lines.pop() || "";
3703
+ for (const line of lines) {
3704
+ if (!line.startsWith("data: ")) continue;
3705
+ const data = line.slice(6).trim();
3706
+ if (data === "[DONE]") {
3707
+ for (const [, tc] of activeToolCalls) {
3708
+ let args = {};
3709
+ try {
3710
+ args = JSON.parse(tc.argsJson);
3711
+ } catch {
3712
+ }
3713
+ yield { type: "tool_use_end", id: tc.id, arguments: args };
3714
+ }
3715
+ yield { type: "message_stop", finishReason: hasToolCalls ? "tool_calls" : "stop" };
3716
+ return;
3717
+ }
3718
+ let parsed;
3719
+ try {
3720
+ parsed = JSON.parse(data);
3721
+ } catch {
3722
+ continue;
3723
+ }
3724
+ if (parsed.usage) {
3725
+ const usage = parsed.usage;
3726
+ yield {
3727
+ type: "usage",
3728
+ promptTokens: usage.prompt_tokens ?? 0,
3729
+ completionTokens: usage.completion_tokens ?? 0
3730
+ };
3731
+ }
3732
+ const choices = parsed.choices;
3733
+ if (!choices || choices.length === 0) continue;
3734
+ const choice = choices[0];
3735
+ const delta = choice.delta;
3736
+ if (!delta) continue;
3737
+ if (delta.content && typeof delta.content === "string") {
3738
+ yield { type: "text_delta", text: delta.content };
3739
+ }
3740
+ const toolCalls = delta.tool_calls;
3741
+ if (toolCalls) {
3742
+ for (const tc of toolCalls) {
3743
+ const index = tc.index ?? 0;
3744
+ const fn = tc.function;
3745
+ if (tc.id) {
3746
+ hasToolCalls = true;
3747
+ const name = fn?.name ? String(fn.name) : "unknown";
3748
+ activeToolCalls.set(index, { id: String(tc.id), name, argsJson: "" });
3749
+ yield { type: "tool_use_start", id: String(tc.id), name };
3750
+ }
3751
+ if (fn?.arguments && typeof fn.arguments === "string") {
3752
+ const existing = activeToolCalls.get(index);
3753
+ if (existing) {
3754
+ existing.argsJson += fn.arguments;
3755
+ yield { type: "tool_use_delta", id: existing.id, partialJson: fn.arguments };
3756
+ }
3757
+ }
3758
+ }
3759
+ }
3760
+ if (choice.finish_reason === "tool_calls") {
3761
+ hasToolCalls = true;
3762
+ }
3763
+ }
3764
+ }
3765
+ } finally {
3766
+ reader.releaseLock();
3767
+ }
3768
+ for (const [, tc] of activeToolCalls) {
3769
+ let args = {};
3770
+ try {
3771
+ args = JSON.parse(tc.argsJson);
3772
+ } catch {
3773
+ }
3774
+ yield { type: "tool_use_end", id: tc.id, arguments: args };
3775
+ }
3776
+ yield { type: "message_stop", finishReason: hasToolCalls ? "tool_calls" : "stop" };
3777
+ }
3778
+ };
3779
+ function completionsUrl(baseUrl) {
3780
+ const base = baseUrl.replace(/\/+$/, "");
3781
+ return /\/v\d+$/.test(base) ? `${base}/chat/completions` : `${base}/v1/chat/completions`;
3782
+ }
3783
+ function formatMessage(m) {
3784
+ if (m.role === "tool") {
3785
+ return {
3786
+ role: "tool",
3787
+ tool_call_id: m.toolCallId,
3788
+ content: typeof m.content === "string" ? m.content : JSON.stringify(m.content)
3789
+ };
3790
+ }
3791
+ if (m.role === "assistant" && m.toolCalls?.length) {
3792
+ return {
3793
+ role: "assistant",
3794
+ content: typeof m.content === "string" && m.content ? m.content : null,
3795
+ tool_calls: m.toolCalls.map((tc) => ({
3796
+ id: tc.id,
3797
+ type: "function",
3798
+ function: { name: tc.name, arguments: JSON.stringify(tc.arguments) }
3799
+ }))
3800
+ };
3801
+ }
3802
+ return {
3803
+ role: m.role,
3804
+ content: typeof m.content === "string" ? m.content : JSON.stringify(m.content)
3805
+ };
3806
+ }
3807
+ function createOpenAICompatProvider(options) {
3808
+ return new OpenAICompatProvider(options);
3809
+ }
3810
+
3811
+ // src/agent/streaming.ts
3812
+ var StreamJsonParser = class {
3813
+ constructor(pushEvent) {
3814
+ this.pushEvent = pushEvent;
3815
+ }
3816
+ pushEvent;
3817
+ hasAssistantText = false;
3818
+ insideToolUse = false;
3819
+ activeToolJsonChunks = /* @__PURE__ */ new Map();
3820
+ /** Reset per-turn state. Call before starting a new turn in persistent sessions. */
3821
+ reset() {
3822
+ this.hasAssistantText = false;
3823
+ this.insideToolUse = false;
3824
+ this.activeToolJsonChunks.clear();
3825
+ }
3826
+ /** Whether any text_delta events have been emitted this turn. */
3827
+ get hasText() {
3828
+ return this.hasAssistantText;
3829
+ }
3830
+ /**
3831
+ * Feed a single NDJSON line (without trailing newline).
3832
+ * Parses and emits StreamEvent(s) via the callback.
3833
+ */
3834
+ feed(line) {
3835
+ if (!line.trim()) return;
3836
+ let event;
3837
+ try {
3838
+ event = JSON.parse(line);
3839
+ } catch {
3840
+ if (line.trim() && !this.hasAssistantText) {
3841
+ this.pushEvent({ type: "text_delta", text: line });
3842
+ }
3843
+ return;
3844
+ }
3845
+ if (event.type === "stream_event" && event.event) {
3846
+ event = event.event;
3847
+ }
3848
+ this.processEvent(event);
3849
+ }
3850
+ processEvent(event) {
3851
+ const block = event.content_block;
3852
+ const delta = event.delta;
3853
+ if (event.type === "content_block_start" && block?.type === "tool_use") {
3854
+ this.insideToolUse = true;
3855
+ const id = block.id || `cli-tool-${Date.now()}`;
3856
+ const name = block.name || "unknown";
3857
+ this.pushEvent({ type: "tool_use_start", id, name });
3858
+ this.activeToolJsonChunks.set(id, { name, chunks: [] });
3859
+ return;
3860
+ }
3861
+ if (event.type === "content_block_start" && block?.type === "text") {
3862
+ this.insideToolUse = false;
3863
+ return;
3864
+ }
3865
+ if (event.type === "content_block_delta" && delta?.type === "input_json_delta") {
3866
+ const lastTool = [...this.activeToolJsonChunks.entries()].pop();
3867
+ if (lastTool) lastTool[1].chunks.push(delta.partial_json || "");
3868
+ return;
3869
+ }
3870
+ if (event.type === "content_block_delta" && delta?.type === "thinking_delta" && delta?.thinking) {
3871
+ this.pushEvent({ type: "thinking_delta", text: delta.thinking });
3872
+ return;
3873
+ }
3874
+ if (event.type === "content_block_delta" && delta?.text && !this.insideToolUse) {
3875
+ this.hasAssistantText = true;
3876
+ this.pushEvent({ type: "text_delta", text: delta.text });
3877
+ return;
3878
+ }
3879
+ if (event.type === "content_block_stop" && this.insideToolUse) {
3880
+ const lastTool = [...this.activeToolJsonChunks.entries()].pop();
3881
+ if (lastTool) {
3882
+ const [id, { chunks }] = lastTool;
3883
+ let args = {};
3884
+ try {
3885
+ args = JSON.parse(chunks.join(""));
3886
+ } catch {
3887
+ }
3888
+ this.pushEvent({ type: "tool_use_end", id, arguments: args });
3889
+ this.activeToolJsonChunks.delete(id);
3890
+ }
3891
+ this.insideToolUse = false;
3892
+ return;
3893
+ }
3894
+ if (event.type === "user" && event.message?.content) {
3895
+ const content = event.message.content;
3896
+ for (const contentBlock of content) {
3897
+ if (contentBlock.type === "tool_result" && contentBlock.tool_use_id) {
3898
+ const text = Array.isArray(contentBlock.content) ? contentBlock.content.map((c) => c.text || "").join("") : String(contentBlock.content || "");
3899
+ this.pushEvent({
3900
+ type: "tool_result",
3901
+ id: contentBlock.tool_use_id,
3902
+ result: text,
3903
+ isError: !!contentBlock.is_error
3904
+ });
3905
+ }
3906
+ }
3907
+ return;
3908
+ }
3909
+ if (event.type === "message_start" && event.message?.usage) {
3910
+ const usage = event.message.usage;
3911
+ this.pushEvent({
3912
+ type: "usage",
3913
+ promptTokens: usage.input_tokens ?? 0,
3914
+ completionTokens: usage.output_tokens ?? 0
3915
+ });
3916
+ return;
3917
+ }
3918
+ if (event.type === "message_delta" && event.usage) {
3919
+ const usage = event.usage;
3920
+ this.pushEvent({
3921
+ type: "usage",
3922
+ promptTokens: 0,
3923
+ completionTokens: usage.output_tokens ?? 0
3924
+ });
3925
+ return;
3926
+ }
3927
+ if (event.type === "message_stop") {
3928
+ this.pushEvent({ type: "message_stop", finishReason: "stop" });
3929
+ return;
3930
+ }
3931
+ if (event.type === "result") {
3932
+ if (event.is_error) {
3933
+ this.pushEvent({ type: "message_stop", finishReason: "error" });
3934
+ return;
3935
+ }
3936
+ if (event.result && !this.hasAssistantText) {
3937
+ this.pushEvent({ type: "text_delta", text: event.result });
3938
+ }
3939
+ if (event.usage) {
3940
+ const usage = event.usage;
3941
+ this.pushEvent({
3942
+ type: "usage",
3943
+ promptTokens: usage.input_tokens ?? 0,
3944
+ completionTokens: usage.output_tokens ?? 0,
3945
+ cacheReadTokens: usage.cache_read_input_tokens ?? void 0,
3946
+ cacheCreationTokens: usage.cache_creation_input_tokens ?? void 0,
3947
+ costUsd: typeof event.total_cost_usd === "number" ? event.total_cost_usd : void 0
3948
+ });
3949
+ }
3950
+ this.pushEvent({ type: "message_stop", finishReason: "stop" });
3951
+ return;
3952
+ }
3953
+ if (event.type === "assistant") {
3954
+ if (event.error === "authentication_failed") {
3955
+ this.pushEvent({ type: "message_stop", finishReason: "error" });
3956
+ }
3957
+ }
3958
+ }
3959
+ };
3960
+
3961
+ // src/agent/providers/claude-cli.ts
3962
+ import { spawn as nodeSpawn } from "node:child_process";
3963
+ import { createMcpBridge } from "../agent/mcp-bridge.js";
3964
+ var ClaudeCliProvider = class {
3965
+ binPath;
3966
+ cwd;
3967
+ env;
3968
+ model;
3969
+ mcpConfigPath;
3970
+ spawnFn;
3971
+ timeout;
3972
+ disallowedTools;
3973
+ allowedTools;
3974
+ constructor(options = {}) {
3975
+ this.binPath = options.binPath ?? "claude";
3976
+ this.cwd = options.cwd ?? process.cwd();
3977
+ this.env = options.env ?? process.env;
3978
+ this.model = options.model;
3979
+ this.mcpConfigPath = options.mcpConfigPath;
3980
+ this.disallowedTools = options.disallowedTools ?? [];
3981
+ this.allowedTools = options.allowedTools;
3982
+ this.spawnFn = options.spawnFn ?? ((cmd, args, opts) => nodeSpawn(cmd, args, { ...opts, stdio: opts.stdio }));
3983
+ this.timeout = options.timeout ?? 6e5;
3984
+ }
3985
+ async *stream(messages, tools, options) {
3986
+ const model = options?.model ?? this.model;
3987
+ const prompt = formatPrompt(messages);
3988
+ const systemPrompt = options?.systemPrompt ? joinSplitPrompt(options.systemPrompt) : void 0;
3989
+ let bridge = null;
3990
+ let mcpConfigPath = this.mcpConfigPath;
3991
+ if (tools.length > 0 && !mcpConfigPath) {
3992
+ const executor = options?.executor ?? (async () => ({ result: "Tool executor not provided", isError: true }));
3993
+ bridge = await createMcpBridge(
3994
+ tools,
3995
+ executor,
3996
+ options?.onToolEvent
3997
+ );
3998
+ mcpConfigPath = bridge.configPath;
3999
+ }
4000
+ const args = [
4001
+ "-p",
4002
+ "--verbose",
4003
+ "--output-format",
4004
+ "stream-json",
4005
+ "--include-partial-messages",
4006
+ "--setting-sources",
4007
+ "user,local",
4008
+ "--dangerously-skip-permissions",
4009
+ "--permission-mode",
4010
+ "bypassPermissions",
4011
+ ...systemPrompt ? ["--system-prompt", systemPrompt] : [],
4012
+ ...mcpConfigPath ? ["--mcp-config", mcpConfigPath, "--strict-mcp-config"] : [],
4013
+ ...this.disallowedTools.length > 0 ? ["--disallowed-tools", this.disallowedTools.join(" ")] : [],
4014
+ ...this.allowedTools ? ["--allowed-tools", this.allowedTools.join(" ")] : [],
4015
+ ...model ? ["--model", model] : []
4016
+ ];
4017
+ const spawnResult = this.spawnFn(
4018
+ this.binPath,
4019
+ args,
4020
+ { cwd: this.cwd, stdio: ["pipe", "pipe", "pipe"], env: this.env }
4021
+ );
4022
+ const child = "child" in spawnResult ? spawnResult.child : spawnResult;
4023
+ const spawnCleanup = "cleanup" in spawnResult ? spawnResult.cleanup : void 0;
4024
+ const signal = options?.signal;
4025
+ if (signal) {
4026
+ signal.addEventListener(
4027
+ "abort",
4028
+ () => {
4029
+ child.kill("SIGTERM");
4030
+ setTimeout(() => {
4031
+ if (!child.killed) child.kill("SIGKILL");
4032
+ }, 2e3);
4033
+ },
4034
+ { once: true }
4035
+ );
4036
+ }
4037
+ const timeout = options?.timeout ?? this.timeout;
4038
+ const timer = setTimeout(() => {
4039
+ child.kill("SIGTERM");
4040
+ }, timeout);
4041
+ child.stdin.write(prompt);
4042
+ child.stdin.end();
4043
+ const events = [];
4044
+ let done = false;
4045
+ const parser = new StreamJsonParser((event) => {
4046
+ events.push(event);
4047
+ });
4048
+ let stderrBuf = "";
4049
+ child.stderr.on("data", (chunk) => {
4050
+ stderrBuf += chunk.toString();
4051
+ });
4052
+ let stdoutBuffer = "";
4053
+ child.stdout.on("data", (chunk) => {
4054
+ stdoutBuffer += chunk.toString();
4055
+ const lines = stdoutBuffer.split("\n");
4056
+ stdoutBuffer = lines.pop() || "";
4057
+ for (const line of lines) {
4058
+ parser.feed(line);
4059
+ }
4060
+ });
4061
+ child.on("close", (code) => {
4062
+ clearTimeout(timer);
4063
+ if (stdoutBuffer.trim()) {
4064
+ parser.feed(stdoutBuffer);
4065
+ }
4066
+ if (code !== 0 && !parser.hasText && stderrBuf.trim()) {
4067
+ events.push({ type: "text_delta", text: `Claude CLI error: ${stderrBuf.trim().slice(0, 500)}` });
4068
+ }
4069
+ if (!events.some((e) => e.type === "message_stop")) {
4070
+ events.push({ type: "message_stop", finishReason: code === 0 ? "stop" : "error" });
4071
+ }
4072
+ done = true;
4073
+ });
4074
+ child.on("error", () => {
4075
+ clearTimeout(timer);
4076
+ events.push({ type: "message_stop", finishReason: "error" });
4077
+ done = true;
4078
+ });
4079
+ try {
4080
+ while (!done || events.length > 0) {
4081
+ if (events.length > 0) {
4082
+ yield events.shift();
4083
+ } else {
4084
+ await new Promise((r) => setTimeout(r, 10));
4085
+ }
4086
+ }
4087
+ } finally {
4088
+ bridge?.cleanup();
4089
+ spawnCleanup?.();
4090
+ }
4091
+ }
4092
+ };
4093
+ function formatPrompt(messages) {
4094
+ const parts = [];
4095
+ for (const msg of messages) {
4096
+ if (msg.role === "user") {
4097
+ parts.push(`User: ${typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content)}
4098
+ `);
4099
+ } else if (msg.role === "assistant") {
4100
+ parts.push(`Assistant: ${typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content)}
4101
+ `);
4102
+ } else if (msg.role === "tool") {
4103
+ parts.push(`Tool result (${msg.toolCallId}): ${typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content)}
4104
+ `);
4105
+ }
4106
+ }
4107
+ return parts.join("\n");
4108
+ }
4109
+ function createClaudeCliProvider(options) {
4110
+ return new ClaudeCliProvider(options);
4111
+ }
4112
+
4113
+ // src/agent/gate.ts
4114
+ var SUBMIT_TOOL = "submit_answer";
4115
+ var REJECT_TOOL = "reject";
4116
+ function providerFor(profile, env = process.env, cwd) {
4117
+ const ready = readiness(profile, env);
4118
+ if (!ready.ready) throw new Error(`agent profile ${profile.name} is not ready: ${ready.reason}`);
4119
+ const model = profile.model || DEFAULT_MODEL[profile.provider] || void 0;
4120
+ switch (profile.provider) {
4121
+ case "anthropic":
4122
+ return createAnthropicProvider({ apiKey: env[keyEnvOf(profile)], model, baseUrl: profile.baseUrl, maxTokens: profile.maxTokens });
4123
+ case "openai":
4124
+ return createOpenAICompatProvider({ apiKey: env[keyEnvOf(profile)] ?? "none", model, baseUrl: profile.baseUrl, maxTokens: profile.maxTokens });
4125
+ case "claude-cli":
4126
+ return createClaudeCliProvider({ binPath: profile.bin, model: model || void 0, cwd, env, allowedTools: [] });
4127
+ }
4128
+ }
4129
+ function fieldToJsonSchema(f) {
4130
+ if (!f) return {};
4131
+ switch (f.type) {
4132
+ case "string":
4133
+ return { type: "string" };
4134
+ case "number":
4135
+ return { type: "number" };
4136
+ case "boolean":
4137
+ return { type: "boolean" };
4138
+ case "enum":
4139
+ return { enum: f.values };
4140
+ case "array":
4141
+ return { type: "array", items: fieldToJsonSchema(f.items) };
4142
+ case "object": {
4143
+ if (!f.fields) return { type: "object", additionalProperties: true, ...f.text ? { description: f.text } : {} };
4144
+ const properties = {};
4145
+ const required = [];
4146
+ for (const [k, v] of Object.entries(f.fields)) {
4147
+ properties[k] = fieldToJsonSchema(v);
4148
+ if (!v.optional) required.push(k);
4149
+ }
4150
+ return { type: "object", properties, ...required.length ? { required } : {}, additionalProperties: false };
4151
+ }
4152
+ // An `any` field accepts every value, so its schema carries only the
4153
+ // description. A field type this function does not know is treated the same.
4154
+ case "any":
4155
+ default:
4156
+ return f.text ? { description: f.text } : {};
4157
+ }
4158
+ }
4159
+ function answerTool(gate) {
4160
+ const schemaOf = (o) => gate.outputSchema?.[o] ?? void 0;
4161
+ const describe = (o) => gate.outputTypes?.[o] ? ` (${gate.outputTypes[o]})` : "";
4162
+ if (gate.outputs.length === 0) {
4163
+ return { tool: { name: SUBMIT_TOOL, description: "Mark the task as done. It has no result to return.", inputSchema: { type: "object", properties: {} } }, unwrap: () => null };
4164
+ }
4165
+ if (gate.outputs.length === 1) {
4166
+ const o = gate.outputs[0];
4167
+ const s = schemaOf(o);
4168
+ const isObject = !s || s.type === "object" || s.type === "any";
4169
+ if (isObject) {
4170
+ const js = fieldToJsonSchema(s ?? { type: "object" });
4171
+ const properties2 = js.properties ?? {};
4172
+ const inputSchema = { type: "object", properties: properties2, ...js.required ? { required: js.required } : {}, ...js.additionalProperties === void 0 ? { additionalProperties: true } : { additionalProperties: js.additionalProperties } };
4173
+ return { tool: { name: SUBMIT_TOOL, description: `Return the result of the task: the value for \`${o}\`${describe(o)}.`, inputSchema }, unwrap: (args) => args };
4174
+ }
4175
+ return {
4176
+ tool: { name: SUBMIT_TOOL, description: `Return the result of the task as \`value\`: the gate's \`${o}\`${describe(o)}.`, inputSchema: { type: "object", properties: { value: fieldToJsonSchema(s) }, required: ["value"] } },
4177
+ unwrap: (args) => args.value
4178
+ };
4179
+ }
4180
+ const properties = {};
4181
+ for (const o of gate.outputs) properties[o] = { ...fieldToJsonSchema(schemaOf(o)), ...gate.outputTypes?.[o] ? { description: gate.outputTypes[o] } : {} };
4182
+ return {
4183
+ tool: { name: SUBMIT_TOOL, description: `Return the result of the task: one value per output (${gate.outputs.join(", ")}).`, inputSchema: { type: "object", properties, required: [...gate.outputs] } },
4184
+ unwrap: (args) => Object.fromEntries(gate.outputs.map((o) => [o, args[o]]))
4185
+ };
4186
+ }
4187
+ var rejectTool = {
4188
+ name: REJECT_TOOL,
4189
+ description: "Give the task up. The workflow continues along its failure path. Say why in one sentence.",
4190
+ inputSchema: { type: "object", properties: { reason: { type: "string" } }, required: ["reason"] }
4191
+ };
4192
+ function systemPromptFor(profile, workflow, gate) {
4193
+ const lines = [
4194
+ profile.system?.trim() ?? "",
4195
+ `You are completing one step of the workflow "${workflow.name}"${workflow.description ? ` (${workflow.description})` : ""}: the agent gate "${gate.node}".`,
4196
+ "You receive the gate's inputs as JSON: `agentId` names the task, `context` is the material to work from, `prompt` is the instruction when there is one.",
4197
+ `Do the task, then call \`${SUBMIT_TOOL}\` exactly once with the result.${gate.hasFailurePort ? ` If the task cannot be done from what you were given, call \`${REJECT_TOOL}\` with a short reason instead.` : ""}`,
4198
+ "Only the tool call counts. Anything you write in prose is discarded."
4199
+ ];
4200
+ return lines.filter(Boolean).join("\n\n");
4201
+ }
4202
+ function userMessageFor(gate) {
4203
+ const shown = { ...gate.inputs };
4204
+ const parts = [`Inputs:
4205
+ ${JSON.stringify(shown, null, 2)}`];
4206
+ if (typeof gate.inputs.prompt === "string" && gate.inputs.prompt.trim()) parts.push(`Instruction:
4207
+ ${gate.inputs.prompt}`);
4208
+ parts.push(`When done, call ${SUBMIT_TOOL}.`);
4209
+ return parts.join("\n\n");
4210
+ }
4211
+ async function tryProfile(profile, env = process.env, opts = {}) {
4212
+ const started = Date.now();
4213
+ let provider;
4214
+ try {
4215
+ provider = opts.provider ?? providerFor(profile, env, opts.cwd);
4216
+ } catch (e) {
4217
+ return { ok: false, ms: Date.now() - started, error: getErrorMessage(e) };
4218
+ }
4219
+ try {
4220
+ const result = await runAgentLoop(provider, [], async () => ({ result: "", isError: true }), [{ role: "user", content: "Reply with the single word OK." }], {
4221
+ systemPrompt: { prefix: profile.system?.trim() || "You are a terse assistant.", suffix: "" },
4222
+ maxIterations: 1,
4223
+ maxTokens: Math.min(profile.maxTokens ?? 64, 256),
4224
+ model: profile.model || void 0,
4225
+ signal: opts.signal
4226
+ });
4227
+ const text = result.summary.trim();
4228
+ const usage = { promptTokens: result.usage.promptTokens, completionTokens: result.usage.completionTokens, ...result.usage.costUsd ? { costUsd: result.usage.costUsd } : {} };
4229
+ if (!result.success) return { ok: false, ms: Date.now() - started, text, usage, error: text || "the provider returned an error" };
4230
+ return { ok: true, ms: Date.now() - started, text, usage };
4231
+ } catch (e) {
4232
+ return { ok: false, ms: Date.now() - started, error: getErrorMessage(e) };
4233
+ }
4234
+ }
4235
+ function answerFromText(text, gate) {
4236
+ const m = text.match(/```(?:json)?\s*([\s\S]*?)```/) ?? text.match(/(\{[\s\S]*\}|\[[\s\S]*\])/);
4237
+ if (!m) return void 0;
4238
+ let parsed;
4239
+ try {
4240
+ parsed = JSON.parse(m[1]);
4241
+ } catch {
4242
+ return void 0;
4243
+ }
4244
+ if (gate.outputs.length > 1) {
4245
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
4246
+ if (!gate.outputs.every((o) => o in parsed)) return void 0;
4247
+ return Object.fromEntries(gate.outputs.map((o) => [o, parsed[o]]));
4248
+ }
4249
+ if (gate.outputs.length === 1) {
4250
+ const s = gate.outputSchema?.[gate.outputs[0]];
4251
+ const one = parsed;
4252
+ if (s && s.type !== "object" && s.type !== "any" && typeof one === "object" && one !== null && gate.outputs[0] in one) return one[gate.outputs[0]];
4253
+ return parsed;
4254
+ }
4255
+ return null;
4256
+ }
4257
+ async function answerGate(opts) {
4258
+ const { gate, workflow, profile } = opts;
4259
+ const env = opts.env ?? process.env;
4260
+ const provider = opts.provider ?? providerFor(profile, env, opts.cwd);
4261
+ const started = Date.now();
4262
+ const emit = (e) => opts.onEvent?.(e);
4263
+ emit({ type: "agent", phase: "start", profile: profile.name, provider: profile.provider, model: profile.model || DEFAULT_MODEL[profile.provider] || void 0 });
4264
+ const { tool, unwrap } = answerTool(gate);
4265
+ const tools = gate.hasFailurePort ? [tool, rejectTool] : [tool];
4266
+ let captured;
4267
+ let usage = { promptTokens: 0, completionTokens: 0 };
4268
+ let text = "";
4269
+ const executor = async (rawName, args) => {
4270
+ const name = stripMcpToolPrefix(rawName);
4271
+ if (name === SUBMIT_TOOL) {
4272
+ captured = { kind: "answer", answer: unwrap(args ?? {}) };
4273
+ return { result: "Recorded. You are done.", isError: false };
4274
+ }
4275
+ if (name === REJECT_TOOL && gate.hasFailurePort) {
4276
+ captured = { kind: "reject", reason: typeof args?.reason === "string" && args.reason.trim() ? args.reason : "rejected by the agent" };
4277
+ return { result: "Recorded. You are done.", isError: false };
4278
+ }
4279
+ return { result: `Unknown tool ${name}. Call ${SUBMIT_TOOL}${gate.hasFailurePort ? ` or ${REJECT_TOOL}` : ""}.`, isError: true };
4280
+ };
4281
+ const onStreamEvent = (ev) => {
4282
+ if (ev.type === "text_delta") {
4283
+ text += ev.text;
4284
+ emit({ type: "agent", phase: "text", text: ev.text });
4285
+ } else if (ev.type === "thinking_delta") emit({ type: "agent", phase: "thinking", text: ev.text });
4286
+ else if (ev.type === "usage") emit({ type: "agent", phase: "usage", promptTokens: ev.promptTokens, completionTokens: ev.completionTokens, costUsd: ev.costUsd });
4287
+ };
4288
+ const onToolEvent = (ev) => {
4289
+ emit({ type: "agent", phase: "tool", stage: ev.type === "tool_call_start" ? "start" : "result", name: stripMcpToolPrefix(ev.name), args: ev.args, result: ev.result, isError: ev.isError });
4290
+ };
4291
+ const system = { prefix: systemPromptFor(profile, workflow, gate), suffix: "" };
4292
+ const messages = [{ role: "user", content: userMessageFor(gate) }];
4293
+ const maxIterations = profile.maxIterations ?? DEFAULT_MAX_ITERATIONS;
4294
+ const run = async (conversation, iterations) => runAgentLoop(provider, tools, executor, conversation, {
4295
+ systemPrompt: system,
4296
+ maxIterations: iterations,
4297
+ maxTokens: profile.maxTokens,
4298
+ model: profile.model || void 0,
4299
+ signal: opts.signal,
4300
+ onStreamEvent,
4301
+ onToolEvent,
4302
+ // Once the answer is in hand there is nothing more to ask. Stop before
4303
+ // another model turn is paid for.
4304
+ onTurnEnd: async () => captured ? { continue: false } : void 0
4305
+ });
4306
+ let transcript = messages;
4307
+ let toolCalls = 0;
4308
+ try {
4309
+ let result = await run(messages, maxIterations);
4310
+ transcript = result.messages;
4311
+ toolCalls = result.toolCallCount;
4312
+ usage = { promptTokens: result.usage.promptTokens, completionTokens: result.usage.completionTokens, ...result.usage.costUsd ? { costUsd: result.usage.costUsd } : {} };
4313
+ if (!captured && result.success && !opts.signal?.aborted) {
4314
+ const nudged = [...result.messages, { role: "user", content: `You have not called ${SUBMIT_TOOL}. Call it now with your result${gate.hasFailurePort ? `, or ${REJECT_TOOL} if you cannot` : ""}.` }];
4315
+ result = await run(nudged, 2);
4316
+ transcript = result.messages;
4317
+ toolCalls += result.toolCallCount;
4318
+ usage = { promptTokens: usage.promptTokens + result.usage.promptTokens, completionTokens: usage.completionTokens + result.usage.completionTokens, ...usage.costUsd || result.usage.costUsd ? { costUsd: (usage.costUsd ?? 0) + (result.usage.costUsd ?? 0) } : {} };
4319
+ }
4320
+ if (!captured) {
4321
+ const fromText = answerFromText(text, gate);
4322
+ if (fromText !== void 0) captured = { kind: "answer", answer: fromText };
4323
+ }
4324
+ if (!captured) {
4325
+ captured = { kind: "failed", error: opts.signal?.aborted ? "stopped before an answer was submitted" : result.success ? `the model did not call ${SUBMIT_TOOL}` : result.summary };
4326
+ }
4327
+ } catch (e) {
4328
+ captured = { kind: "failed", error: getErrorMessage(e) };
4329
+ }
4330
+ const ms = Date.now() - started;
4331
+ emit({ type: "agent", phase: "done", outcome: captured.kind, ms, ...captured.kind === "failed" ? { error: captured.error } : {}, ...captured.kind === "reject" ? { reason: captured.reason } : {} });
4332
+ return { outcome: captured, usage, toolCalls, ms, transcript, text };
4333
+ }
4334
+
4335
+ export {
4336
+ dump,
4337
+ DEFAULT_MODEL,
4338
+ DEFAULT_MAX_ITERATIONS,
4339
+ STARTER_AGENTS_YAML,
4340
+ agentsFile,
4341
+ loadAgentProfiles,
4342
+ profileForGate,
4343
+ keyEnvOf,
4344
+ SUGGESTED_MODELS,
4345
+ validateProfile,
4346
+ saveAgentProfiles,
4347
+ readiness,
4348
+ runAgentLoop,
4349
+ AnthropicProvider,
4350
+ createAnthropicProvider,
4351
+ joinSplitPrompt,
4352
+ stripMcpToolPrefix,
4353
+ OpenAICompatProvider,
4354
+ createOpenAICompatProvider,
4355
+ StreamJsonParser,
4356
+ ClaudeCliProvider,
4357
+ createClaudeCliProvider,
4358
+ SUBMIT_TOOL,
4359
+ REJECT_TOOL,
4360
+ providerFor,
4361
+ fieldToJsonSchema,
4362
+ answerTool,
4363
+ systemPromptFor,
4364
+ userMessageFor,
4365
+ tryProfile,
4366
+ answerFromText,
4367
+ answerGate
4368
+ };
4369
+ /*! Bundled license information:
4370
+
4371
+ js-yaml/dist/js-yaml.mjs:
4372
+ (*! js-yaml 5.4.2 https://github.com/nodeca/js-yaml @license MIT *)
4373
+ */