fnloom 0.1.0 → 0.3.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 (705) hide show
  1. package/README.md +133 -23
  2. package/package.json +13 -17
  3. package/packages/build/package.json +2 -2
  4. package/packages/cli/package.json +1 -1
  5. package/packages/cli/src/cli.ts +2 -1
  6. package/packages/cli/src/command.ts +2 -0
  7. package/packages/cli/src/commands/available.ts +63 -22
  8. package/packages/cli/src/commands/install.ts +182 -28
  9. package/packages/cli/src/commands/manage.ts +7 -5
  10. package/packages/cli/src/commands/store.ts +172 -0
  11. package/packages/cli/src/hub.ts +26 -7
  12. package/packages/cli/src/index.ts +3 -2
  13. package/packages/cli/src/io.ts +1 -0
  14. package/packages/cli/src/local.ts +6 -0
  15. package/packages/cli/src/premade.ts +80 -0
  16. package/packages/cli/src/testing.ts +2 -1
  17. package/packages/core/package.json +4 -4
  18. package/packages/core/src/context-files.ts +3 -1
  19. package/packages/core/src/context-graph.ts +4 -0
  20. package/packages/core/src/context-plan.ts +451 -0
  21. package/packages/core/src/context-questions.ts +305 -0
  22. package/packages/core/src/fn-facts.ts +32 -4
  23. package/packages/core/src/identity.ts +1 -1
  24. package/packages/core/src/index.ts +4 -1
  25. package/packages/core/src/link.ts +70 -0
  26. package/packages/core/src/manifest.ts +20 -1
  27. package/packages/core/src/model-calls.ts +11 -2
  28. package/packages/core/src/package.ts +10 -0
  29. package/packages/core/src/query.ts +3 -2
  30. package/packages/core/src/records/content.ts +10 -2
  31. package/packages/core/src/records/runs.ts +12 -0
  32. package/packages/core/src/records/systems.ts +87 -5
  33. package/packages/core/src/run.ts +5 -0
  34. package/packages/core/src/stores.ts +473 -0
  35. package/packages/core/src/suggestions.ts +3 -0
  36. package/packages/core/src/system-pages.ts +14 -1
  37. package/packages/core/src/web.ts +114 -9
  38. package/packages/hub/package.json +13 -12
  39. package/packages/hub/src/access/hits.ts +1 -1
  40. package/packages/hub/src/api/admin-ops.ts +36 -4
  41. package/packages/hub/src/api/auth.ts +8 -4
  42. package/packages/hub/src/api/person-ops.ts +6 -0
  43. package/packages/hub/src/api/store-ops.ts +54 -0
  44. package/packages/hub/src/api/testing/rig.ts +2 -2
  45. package/packages/hub/src/api/tls.ts +2 -2
  46. package/packages/hub/src/api/web/build5.ts +2 -1
  47. package/packages/hub/src/api/web/context-plans.ts +25 -0
  48. package/packages/hub/src/api/web/context-review.ts +43 -0
  49. package/packages/hub/src/api/web/index.ts +4 -0
  50. package/packages/hub/src/api/web/pages.ts +14 -1
  51. package/packages/hub/src/api/web/review.ts +16 -0
  52. package/packages/hub/src/api/web/systems.ts +14 -2
  53. package/packages/hub/src/boot/admin-fns.ts +8 -0
  54. package/packages/hub/src/boot/admin-secrets.ts +10 -4
  55. package/packages/hub/src/boot/env.ts +6 -1
  56. package/packages/hub/src/boot/hub-fns.ts +3 -3
  57. package/packages/hub/src/boot/hub-groups.ts +2 -2
  58. package/packages/hub/src/boot/identity.ts +1 -1
  59. package/packages/hub/src/boot/index.ts +9 -0
  60. package/packages/hub/src/boot/modules.ts +12 -3
  61. package/packages/hub/src/boot/person-fns.ts +5 -0
  62. package/packages/hub/src/boot/plan-fns.ts +39 -0
  63. package/packages/hub/src/boot/start.ts +2 -1
  64. package/packages/hub/src/catalog/catalog.ts +44 -14
  65. package/packages/hub/src/catalog/index.ts +6 -2
  66. package/packages/hub/src/chat/testing.ts +2 -2
  67. package/packages/hub/src/contextor/brought.ts +5 -3
  68. package/packages/hub/src/contextor/testing.ts +4 -4
  69. package/packages/hub/src/execution/create.ts +2 -0
  70. package/packages/hub/src/execution/env.ts +2 -0
  71. package/packages/hub/src/execution/errors.ts +12 -0
  72. package/packages/hub/src/execution/executors.ts +14 -2
  73. package/packages/hub/src/execution/index.ts +8 -0
  74. package/packages/hub/src/execution/link-handlers.ts +16 -4
  75. package/packages/hub/src/execution/runs.ts +212 -11
  76. package/packages/hub/src/execution/testing.ts +2 -1
  77. package/packages/hub/src/fns/search.ts +23 -4
  78. package/packages/hub/src/graph/graph.ts +2 -2
  79. package/packages/hub/src/index/index.ts +9 -2
  80. package/packages/hub/src/index/indexer.ts +67 -16
  81. package/packages/hub/src/index/search.ts +1 -0
  82. package/packages/hub/src/index/suggester.ts +2 -2
  83. package/packages/hub/src/link/build.ts +47 -10
  84. package/packages/hub/src/link/connections.ts +41 -3
  85. package/packages/hub/src/link/describer.ts +19 -2
  86. package/packages/hub/src/link/env.ts +10 -0
  87. package/packages/hub/src/link/handlers.ts +6 -0
  88. package/packages/hub/src/link/index.ts +16 -4
  89. package/packages/hub/src/link/lifecycle.ts +11 -4
  90. package/packages/hub/src/link/packages.ts +17 -4
  91. package/packages/hub/src/link/pairing.ts +2 -2
  92. package/packages/hub/src/link/process.ts +15 -4
  93. package/packages/hub/src/link/rig.ts +6 -2
  94. package/packages/hub/src/link/status.ts +14 -0
  95. package/packages/hub/src/link/supervisor.ts +17 -1
  96. package/packages/hub/src/link/systems.ts +16 -5
  97. package/packages/hub/src/models/roles.ts +74 -7
  98. package/packages/hub/src/query/columns.ts +4 -1
  99. package/packages/hub/src/query/contexts.ts +10 -3
  100. package/packages/hub/src/questions/apply.ts +163 -0
  101. package/packages/hub/src/questions/carry.ts +30 -0
  102. package/packages/hub/src/questions/duplicates.ts +181 -0
  103. package/packages/hub/src/questions/index.ts +112 -0
  104. package/packages/hub/src/questions/metadata.ts +142 -0
  105. package/packages/hub/src/questions/pending.ts +64 -0
  106. package/packages/hub/src/questions/plan-match.ts +79 -0
  107. package/packages/hub/src/questions/plan-prompts.ts +110 -0
  108. package/packages/hub/src/questions/planner.ts +382 -0
  109. package/packages/hub/src/questions/plans.ts +353 -0
  110. package/packages/hub/src/questions/review.ts +253 -0
  111. package/packages/hub/src/questions/setting.ts +50 -0
  112. package/packages/hub/src/questions/testing.ts +131 -0
  113. package/packages/hub/src/questions/worker.ts +182 -0
  114. package/packages/hub/src/resources/context.ts +58 -20
  115. package/packages/hub/src/resources/create.ts +16 -4
  116. package/packages/hub/src/resources/env.ts +4 -0
  117. package/packages/hub/src/resources/fns.ts +6 -2
  118. package/packages/hub/src/resources/index.ts +8 -2
  119. package/packages/hub/src/resources/testing.ts +18 -2
  120. package/packages/hub/src/store/codec.ts +23 -5
  121. package/packages/hub/src/store/context-status.ts +56 -0
  122. package/packages/hub/src/store/derived.ts +53 -0
  123. package/packages/hub/src/store/hybrid.ts +33 -6
  124. package/packages/hub/src/store/lists.ts +2 -1
  125. package/packages/hub/src/store/migrate-fn-names.ts +5 -2
  126. package/packages/hub/src/store/rows.ts +8 -1
  127. package/packages/hub/src/store/schema.ts +2 -1
  128. package/packages/hub/src/store/sqlite.ts +2 -1
  129. package/packages/hub/src/stores/backups.ts +163 -0
  130. package/packages/hub/src/stores/drivers.ts +100 -0
  131. package/packages/hub/src/stores/guard.ts +116 -0
  132. package/packages/hub/src/stores/host.ts +459 -0
  133. package/packages/hub/src/stores/moves.ts +380 -0
  134. package/packages/hub/src/stores/plugin.ts +42 -0
  135. package/packages/hub/src/stores/service.ts +340 -0
  136. package/packages/hub/src/stores/testing.ts +149 -0
  137. package/packages/sdk/AUTHORING.md +1813 -218
  138. package/packages/sdk/package.json +12 -8
  139. package/packages/sdk/src/build.ts +3 -0
  140. package/packages/sdk/src/client.ts +22 -0
  141. package/packages/sdk/src/ctx.ts +51 -17
  142. package/packages/sdk/src/declare.ts +36 -12
  143. package/packages/sdk/src/hub.ts +222 -10
  144. package/packages/sdk/src/impl.ts +3 -3
  145. package/packages/sdk/src/index.ts +6 -3
  146. package/packages/sdk/src/manifest.ts +5 -0
  147. package/packages/sdk/src/providers.ts +2 -2
  148. package/packages/sdk/src/server/asks.ts +12 -1
  149. package/packages/sdk/src/server/env.ts +13 -1
  150. package/packages/sdk/src/server/host.ts +81 -10
  151. package/packages/sdk/src/server/index.ts +21 -2
  152. package/packages/sdk/src/server/package.ts +11 -2
  153. package/packages/sdk/src/server/run.ts +6 -1
  154. package/packages/sdk/src/server/runtime.ts +78 -22
  155. package/packages/sdk/src/server/start-gate.ts +174 -0
  156. package/packages/sdk/src/server/store/checksum.ts +162 -0
  157. package/packages/sdk/src/server/store/engines.ts +400 -0
  158. package/packages/sdk/src/server/store/extend.ts +25 -0
  159. package/packages/sdk/src/server/store/keeper.ts +392 -0
  160. package/packages/sdk/src/server/store/link-driver.ts +142 -0
  161. package/packages/sdk/src/server/store/measure.ts +45 -0
  162. package/packages/sdk/src/server/store/migrations.ts +238 -0
  163. package/packages/sdk/src/server/store/move.ts +488 -0
  164. package/packages/sdk/src/server/store/portable.ts +288 -0
  165. package/packages/sdk/src/server/store/stable.ts +146 -0
  166. package/packages/sdk/src/server/store/tables.ts +28 -0
  167. package/packages/sdk/src/server/store/vectors.ts +185 -0
  168. package/packages/sdk/src/server/store/work-checks.ts +288 -0
  169. package/packages/sdk/src/server/store/work.ts +369 -0
  170. package/packages/sdk/src/server/table.ts +3 -1
  171. package/packages/sdk/src/server/testing.ts +116 -3
  172. package/packages/sdk/src/store.ts +91 -0
  173. package/packages/sdk/src/system.ts +58 -30
  174. package/packages/sdk/src/testing/hub.ts +18 -5
  175. package/packages/web/dist/assets/{ActorSettingsView-BuMYRDqv.js → ActorSettingsView-v2k7v454.js} +2 -2
  176. package/packages/web/dist/assets/{AdminLayout-sLjVTrmV.js → AdminLayout-B6Jrc_4W.js} +2 -2
  177. package/packages/web/dist/assets/{ApiServiceForm-BrMTU-7u.js → ApiServiceForm-CuuQgOJc.js} +2 -2
  178. package/packages/web/dist/assets/{ApiServiceView-BMF2zD6Q.js → ApiServiceView-7bTHSO_Z.js} +2 -2
  179. package/packages/web/dist/assets/{ApiServicesView-bjLAWO_j.js → ApiServicesView-BXi24n49.js} +2 -2
  180. package/packages/web/dist/assets/{AppPage-DSzDKCFz.js → AppPage-CFmKZS8G.js} +2 -2
  181. package/packages/web/dist/assets/{AutoPairPicker-nV38ALjl.js → AutoPairPicker-C61gihmh.js} +2 -2
  182. package/packages/web/dist/assets/{BrowserFrame-Bic7U7jN.js → BrowserFrame-Sq9EmQRT.js} +2 -2
  183. package/packages/web/dist/assets/{ChartVisual-DWw7WsfN.js → ChartVisual-C4mgw4wh.js} +4 -4
  184. package/packages/web/dist/assets/ChatPage-CAhHE03Z.js +4 -0
  185. package/packages/web/dist/assets/{CodeViewer-xHS3Xah9.js → CodeViewer-tUNXZB77.js} +2 -2
  186. package/packages/web/dist/assets/{ConfigWithCustom-DreTUdf0.js → ConfigWithCustom-D_-rY66L.js} +3 -3
  187. package/packages/web/dist/assets/{ConfirmDialog-DjQUzNqk.js → ConfirmDialog-Dd3E4sJt.js} +2 -2
  188. package/packages/web/dist/assets/{ConnectPage-CfRDrXvJ.js → ConnectPage-CX9acyQH.js} +2 -2
  189. package/packages/web/dist/assets/ContextItemPage-Cv4G0k_o.css +1 -0
  190. package/packages/web/dist/assets/ContextItemPage-rUI3-T_L.js +2 -0
  191. package/packages/web/dist/assets/ContextPage-C8u0UnYl.css +1 -0
  192. package/packages/web/dist/assets/ContextPage-CtefzyKg.js +3 -0
  193. package/packages/web/dist/assets/ContextRow-Chx99Xac.css +1 -0
  194. package/packages/web/dist/assets/ContextRow-DrtPumZ5.js +2 -0
  195. package/packages/web/dist/assets/{DataPage-wSIoGcb5.js → DataPage-DDSsxHro.js} +2 -2
  196. package/packages/web/dist/assets/DataTypePage-BW9fWaz8.js +2 -0
  197. package/packages/web/dist/assets/{DesignPage-DidMUX8m.js → DesignPage-6e0XbOFC.js} +2 -2
  198. package/packages/web/dist/assets/{ExplorePage-MUyVydVB.js → ExplorePage-B7ND0W0l.js} +2 -2
  199. package/packages/web/dist/assets/{FnList-CjQRwYaT.js → FnList-Bx6H-kux.js} +2 -2
  200. package/packages/web/dist/assets/{FnPill-BshAvm2I.js → FnPill-Cp3KuLmP.js} +2 -2
  201. package/packages/web/dist/assets/FnView-C0XZdnsS.js +2 -0
  202. package/packages/web/dist/assets/{FnsView-CeqIoaBT.js → FnsView-GTH3p7a0.js} +2 -2
  203. package/packages/web/dist/assets/{GinExprView-DYVUwZrd.js → GinExprView-DGxns6lH.js} +2 -2
  204. package/packages/web/dist/assets/{GinForm-D3mwMRTQ.js → GinForm-BDBUzuDP.js} +2 -2
  205. package/packages/web/dist/assets/{GinTypeView-C0YifSmE.js → GinTypeView-CUsymbVf.js} +2 -2
  206. package/packages/web/dist/assets/{GinValueView-HfEPq9le.js → GinValueView-jsKIfiEA.js} +2 -2
  207. package/packages/web/dist/assets/{GraphPage-ySnuA4Hp.js → GraphPage-BCcPPsHu.js} +2 -2
  208. package/packages/web/dist/assets/{GraphPanel-Cy5-KGo1.js → GraphPanel-9tztGHmu.js} +2 -2
  209. package/packages/web/dist/assets/{HubPicker-C_vA752L.js → HubPicker-EoOErgmk.js} +2 -2
  210. package/packages/web/dist/assets/{InboxApprovals-DcPCCmZ5.js → InboxApprovals-Dkq7DFp_.js} +2 -2
  211. package/packages/web/dist/assets/{InboxPage-C2DT2nuF.js → InboxPage-CHhslePq.js} +2 -2
  212. package/packages/web/dist/assets/{InjectedList-CJsEFEbz.js → InjectedList-CSWqRiON.js} +2 -2
  213. package/packages/web/dist/assets/InstallDialog-D-VwfZYF.js +2 -0
  214. package/packages/web/dist/assets/{InstallDialog-yWLZK_zN.css → InstallDialog-K-j0sdHm.css} +1 -1
  215. package/packages/web/dist/assets/InstanceTypes-CwVSAULg.css +1 -0
  216. package/packages/web/dist/assets/InstanceTypes-D3rAEiE7.js +2 -0
  217. package/packages/web/dist/assets/InstanceView-DoH8C-1j.js +2 -0
  218. package/packages/web/dist/assets/InstanceView-_9uE70tS.css +1 -0
  219. package/packages/web/dist/assets/{ItemHistory-CUGa8b6s.js → ItemHistory-NQAP69ma.js} +2 -2
  220. package/packages/web/dist/assets/LimitsView-DY2C9nYS.js +2 -0
  221. package/packages/web/dist/assets/ListSearch-BunVrDO0.js +2 -0
  222. package/packages/web/dist/assets/{LlmCallDetails-2yQftCqd.js → LlmCallDetails-BoVNDTVs.js} +2 -2
  223. package/packages/web/dist/assets/{LlmCallsView-DOHX3r0K.js → LlmCallsView-BGpV92RC.js} +2 -2
  224. package/packages/web/dist/assets/{LoadState-DeXfLvYv.js → LoadState-h-K9bTYc.js} +2 -2
  225. package/packages/web/dist/assets/{McpDialog-CA_0WKWF.js → McpDialog-DhOCk6_E.js} +2 -2
  226. package/packages/web/dist/assets/{McpServerForm-CAG8Wp2N.js → McpServerForm-Cor3fI7s.js} +2 -2
  227. package/packages/web/dist/assets/McpServerView-ewXRPEmZ.js +2 -0
  228. package/packages/web/dist/assets/McpServersView-Dd0xmfws.js +2 -0
  229. package/packages/web/dist/assets/{McpView-CC2oNOMa.js → McpView-GPXdCMne.js} +2 -2
  230. package/packages/web/dist/assets/{McpsView-CwJvyyxV.js → McpsView-DJIR2JX5.js} +2 -2
  231. package/packages/web/dist/assets/{MemoryDialog-Dbvh5uLq.js → MemoryDialog-BTeIHQyA.js} +2 -2
  232. package/packages/web/dist/assets/{ModelCallsView-RvnW3EBP.js → ModelCallsView-DMcnwF2S.js} +2 -2
  233. package/packages/web/dist/assets/{ModelPicker-DcjwQFHC.js → ModelPicker-CgkMFxSO.js} +2 -2
  234. package/packages/web/dist/assets/ModelsView-cMHygeiK.js +2 -0
  235. package/packages/web/dist/assets/{NotFoundPage-CeSwzTV-.js → NotFoundPage-Tk92K7HN.js} +2 -2
  236. package/packages/web/dist/assets/PairPage-D0BK8CCw.js +2 -0
  237. package/packages/web/dist/assets/PairPage-D_aPS1Ot.css +1 -0
  238. package/packages/web/dist/assets/{PanelHost-BkrFAnPa.js → PanelHost-C-gKrxAk.js} +2 -2
  239. package/packages/web/dist/assets/{PeopleView-D1QGPYp7.js → PeopleView-DRfeNWK5.js} +2 -2
  240. package/packages/web/dist/assets/PoliciesView-BRi-QAuo.js +2 -0
  241. package/packages/web/dist/assets/{RefusalList-DQoyUoPG.js → RefusalList-DVO0bmeB.js} +2 -2
  242. package/packages/web/dist/assets/{RemoteAuthFields-nxGWfmhf.js → RemoteAuthFields-CgiufuqQ.js} +2 -2
  243. package/packages/web/dist/assets/{ResourceViewer-Po24y4pj.js → ResourceViewer-Do0chYxU.js} +2 -2
  244. package/packages/web/dist/assets/ResourcesPage-BBx2u2mw.js +2 -0
  245. package/packages/web/dist/assets/{ResultGrid-uoq4yUYj.js → ResultGrid-Bj-0I5HY.js} +2 -2
  246. package/packages/web/dist/assets/{ReviewSummaryStrip-k3HevESg.js → ReviewSummaryStrip-DO3p64Qj.js} +2 -2
  247. package/packages/web/dist/assets/ReviewView-DZF9E1hb.js +3 -0
  248. package/packages/web/dist/assets/{RuleRow-CoXDA-SH.js → RuleRow-DX9v4iGP.js} +2 -2
  249. package/packages/web/dist/assets/{RunCard-CBSGdwdQ.js → RunCard-BnrtK2Yp.js} +2 -2
  250. package/packages/web/dist/assets/{RunDetails-CGhQQ6OI.js → RunDetails-DjR206q6.js} +2 -2
  251. package/packages/web/dist/assets/{RunDot-Ch_45985.js → RunDot-lHRICdM5.js} +2 -2
  252. package/packages/web/dist/assets/{RunPage-C_t20pB7.js → RunPage-CbAQ_WPR.js} +2 -2
  253. package/packages/web/dist/assets/{RunProgress-VrZUHUEC.js → RunProgress-C3-B4tQf.js} +2 -2
  254. package/packages/web/dist/assets/RunsView-DMkPmkqX.js +2 -0
  255. package/packages/web/dist/assets/ServiceRows-4WythFpF.js +2 -0
  256. package/packages/web/dist/assets/{ServiceRows-6BU4-MeL.css → ServiceRows-HPQ0pN6b.css} +1 -1
  257. package/packages/web/dist/assets/SettingsPage-BN4oSzoL.js +3 -0
  258. package/packages/web/dist/assets/{SignInPage-DrXZ1sG2.js → SignInPage-ByqGEZfj.js} +2 -2
  259. package/packages/web/dist/assets/{StatusBadge-Dpb9uG5e.js → StatusBadge-CXne0sRZ.js} +2 -2
  260. package/packages/web/dist/assets/StorePlacementStep-B6SwTmdM.js +2 -0
  261. package/packages/web/dist/assets/StorePlacementStep-D_G4e3ue.css +1 -0
  262. package/packages/web/dist/assets/{SystemConfig-72qKRkUk.js → SystemConfig-vQDL_eUl.js} +2 -2
  263. package/packages/web/dist/assets/{SystemPageHost-DLNg2FYK.js → SystemPageHost-DrMrEPyh.js} +2 -2
  264. package/packages/web/dist/assets/SystemView-Be6TBM4j.js +2 -0
  265. package/packages/web/dist/assets/{SystemView-C8ScHUe2.css → SystemView-_9q6eDfV.css} +1 -1
  266. package/packages/web/dist/assets/{SystemsView-B6HEL9VS.css → SystemsView-CWKnupLW.css} +1 -1
  267. package/packages/web/dist/assets/SystemsView-DZtT3laz.js +2 -0
  268. package/packages/web/dist/assets/{TableViewer-BQ7bYLOP.js → TableViewer-Boxx86f5.js} +3 -3
  269. package/packages/web/dist/assets/{ThemePicker-C2nJ21Vd.js → ThemePicker-CIg_oRQX.js} +2 -2
  270. package/packages/web/dist/assets/{TurnTree-CORdfTHj.js → TurnTree-Ecm0yA5g.js} +2 -2
  271. package/packages/web/dist/assets/UserMessage-BlnqZDVU.js +9 -0
  272. package/packages/web/dist/assets/{ValueVisual-aXEUaQ5Y.js → ValueVisual-C-MWpp7c.js} +2 -2
  273. package/packages/web/dist/assets/WidgetView-DX4ejNb6.js +3 -0
  274. package/packages/web/dist/assets/actor-names-OdvpVZeb.js +4 -0
  275. package/packages/web/dist/assets/{fn-modal-DqcxUhOQ.js → fn-modal-B98MR7JN.js} +2 -2
  276. package/packages/web/dist/assets/{fn-notices-BYaH6IoA.js → fn-notices-CfTa1E8y.js} +2 -2
  277. package/packages/web/dist/assets/{formats-DI__ADVG.js → formats-JwoKfXIq.js} +2 -2
  278. package/packages/web/dist/assets/index-6ScWTFy2.js +4 -0
  279. package/packages/web/dist/assets/{index-CSisx5mi.css → index-CEslGcrX.css} +1 -1
  280. package/packages/web/dist/assets/{labels-BhJpmLWA.js → labels-BFbk11BE.js} +2 -2
  281. package/packages/web/dist/assets/{layout-DQKldU13.js → layout-D1gf481r.js} +2 -2
  282. package/packages/web/dist/assets/{metrics-Cio5ykX6.js → metrics-CBPX3W5Y.js} +2 -2
  283. package/packages/web/dist/assets/{problems-BZY0Dwif.js → problems-t1E_ovSz.js} +2 -2
  284. package/packages/web/dist/assets/{push-payload-D5efGCzd.js → push-payload-BeU1ADYt.js} +64 -64
  285. package/packages/web/dist/assets/{record-edits-CveFEsal.js → record-edits-Bfsi4lU3.js} +2 -2
  286. package/packages/web/dist/assets/{remote-config-BkaarDf3.js → remote-config-BNQhSDzB.js} +2 -2
  287. package/packages/web/dist/assets/{review-CGUGvRV9.js → review-fP-l9D6H.js} +3 -3
  288. package/packages/web/dist/assets/routes-DV4IJpwe.js +4 -0
  289. package/packages/web/dist/assets/runs-CveC2kKo.js +2 -0
  290. package/packages/web/dist/assets/{shared-DTpYDMc_.js → shared-LbaIHjbV.js} +2 -2
  291. package/packages/web/dist/assets/{size-BwnshyOe.js → size-Bh__w5aI.js} +2 -2
  292. package/packages/web/dist/assets/{sources-Bm-TrxhL.js → sources-VPrtgLIi.js} +2 -2
  293. package/packages/web/dist/assets/src-CT3TeFaM.js +43 -0
  294. package/packages/web/dist/assets/state-xfQqaQPX.js +2 -0
  295. package/packages/web/dist/assets/{systems-DIp94AET.js → systems-BqE3WTSF.js} +2 -2
  296. package/packages/web/dist/assets/ui-BzgWquIU.js +17 -0
  297. package/packages/web/dist/assets/{ui-C7ZH_6oC.css → ui-DycHjPTZ.css} +1 -1
  298. package/packages/web/dist/assets/{url-BIg5IhGs.js → url-DKGcECT1.js} +2 -2
  299. package/packages/web/dist/assets/{widget-host-BCf6Tlt5.js → widget-host-B87MTaTn.js} +2 -2
  300. package/packages/web/dist/assets/{widgets-CrbkovMT.js → widgets-BBCuSS6E.js} +2 -2
  301. package/packages/web/dist/index.html +44 -44
  302. package/packages/web/dist/sw.js +1 -1
  303. package/packages/web/package.json +2 -2
  304. package/premade/claude.zip +0 -0
  305. package/premade/database.zip +0 -0
  306. package/premade/web.zip +0 -0
  307. package/scripts/dev-env.ts +4 -4
  308. package/scripts/run-stack.ts +3 -2
  309. package/scripts/stack.ts +115 -43
  310. package/scripts/start.ts +36 -17
  311. package/systems/api/package.json +3 -3
  312. package/systems/code/package.json +3 -3
  313. package/systems/embedder/package.json +1 -1
  314. package/systems/fs/client/fakes.ts +2 -0
  315. package/systems/fs/client/index.ts +4 -2
  316. package/systems/fs/client/machines/CoreHeatmap.vue +94 -0
  317. package/systems/fs/client/machines/MachineFiles.vue +121 -0
  318. package/systems/fs/client/machines/MachineMetrics.vue +330 -0
  319. package/systems/fs/client/machines/MachinesPage.vue +119 -0
  320. package/systems/fs/client/machines/TimeChart.vue +128 -0
  321. package/systems/fs/client/machines/fakes.ts +95 -0
  322. package/systems/fs/client/machines/files/ChangesPane.vue +90 -0
  323. package/systems/fs/client/machines/files/CodeView.vue +158 -0
  324. package/systems/fs/client/machines/files/CommentComposer.vue +86 -0
  325. package/systems/fs/client/machines/files/CommentThread.vue +115 -0
  326. package/systems/fs/client/machines/files/CommitPane.vue +80 -0
  327. package/systems/fs/client/machines/files/ComparePane.vue +81 -0
  328. package/systems/fs/client/machines/files/FileHistory.vue +89 -0
  329. package/systems/fs/client/machines/files/FilePane.vue +199 -0
  330. package/systems/fs/client/machines/files/FileTree.vue +26 -0
  331. package/systems/fs/client/machines/files/FolderPane.vue +154 -0
  332. package/systems/fs/client/machines/files/HistoryPane.vue +106 -0
  333. package/systems/fs/client/machines/files/ImageView.vue +160 -0
  334. package/systems/fs/client/machines/files/PatchView.vue +31 -0
  335. package/systems/fs/client/machines/files/QuickOpen.vue +67 -0
  336. package/systems/fs/client/machines/files/SearchPane.vue +87 -0
  337. package/systems/fs/client/machines/files/TreeNode.vue +72 -0
  338. package/systems/fs/client/machines/files/api.ts +127 -0
  339. package/systems/fs/client/machines/files/fake-kinds.ts +16 -0
  340. package/systems/fs/client/machines/files/fakes.ts +305 -0
  341. package/systems/fs/client/machines/files/ink.ts +117 -0
  342. package/systems/fs/client/machines/files/logic.ts +205 -0
  343. package/systems/fs/client/machines/files/state.ts +187 -0
  344. package/systems/fs/client/machines/files/viewers/CsvView.vue +29 -0
  345. package/systems/fs/client/machines/files/viewers/HexView.vue +27 -0
  346. package/systems/fs/client/machines/files/viewers/HtmlView.vue +17 -0
  347. package/systems/fs/client/machines/files/viewers/JsonNode.vue +45 -0
  348. package/systems/fs/client/machines/files/viewers/JsonView.vue +25 -0
  349. package/systems/fs/client/machines/metrics.ts +245 -0
  350. package/systems/fs/client/machines/palette.ts +97 -0
  351. package/systems/fs/client/preview/machines.ts +323 -0
  352. package/systems/fs/context/authoring/index.md +4 -0
  353. package/systems/fs/context/authoring/parts/actions.md +5 -1
  354. package/systems/fs/context/authoring/parts/actions.reference.md +6 -2
  355. package/systems/fs/context/authoring/parts/calling.md +5 -1
  356. package/systems/fs/context/authoring/parts/calling.reference.md +4 -0
  357. package/systems/fs/context/authoring/parts/client.md +9 -1
  358. package/systems/fs/context/authoring/parts/client.reference/client.md +4 -0
  359. package/systems/fs/context/authoring/parts/client.reference/resultview.md +56 -53
  360. package/systems/fs/context/authoring/parts/client.reference/{fnpillprops.md → textareaprops.md} +58 -4
  361. package/systems/fs/context/authoring/parts/client.reference.md +8 -4
  362. package/systems/fs/context/authoring/parts/context/questions.md +49 -0
  363. package/systems/fs/context/authoring/parts/context.md +23 -1
  364. package/systems/fs/context/authoring/parts/context.reference.md +27 -3
  365. package/systems/fs/context/authoring/parts/contract.md +10 -0
  366. package/systems/fs/context/authoring/parts/contract.reference.md +26 -9
  367. package/systems/fs/context/authoring/parts/core-types/access-ts.md +4 -0
  368. package/systems/fs/context/authoring/parts/core-types/admin-ts.md +5 -1
  369. package/systems/fs/context/authoring/parts/core-types/api-index-ts.md +4 -0
  370. package/systems/fs/context/authoring/parts/core-types/approvals-ts.md +11 -7
  371. package/systems/fs/context/authoring/parts/core-types/auto-pair-ts.md +4 -0
  372. package/systems/fs/context/authoring/parts/core-types/checks-ts.md +4 -0
  373. package/systems/fs/context/authoring/parts/core-types/claims-ts.md +4 -0
  374. package/systems/fs/context/authoring/parts/core-types/config-secrets-ts.md +4 -0
  375. package/systems/fs/context/authoring/parts/core-types/connections-ts.md +4 -0
  376. package/systems/fs/context/authoring/parts/core-types/context-files-ts.md +8 -0
  377. package/systems/fs/context/authoring/parts/core-types/context-graph-ts.md +5 -1
  378. package/systems/fs/context/authoring/parts/core-types/context-questions-ts.md +26 -0
  379. package/systems/fs/context/authoring/parts/core-types/contextdecl.md +9 -1
  380. package/systems/fs/context/authoring/parts/core-types/data-ts.md +4 -0
  381. package/systems/fs/context/authoring/parts/core-types/decisions-ts.md +4 -0
  382. package/systems/fs/context/authoring/parts/core-types/fn-block-ts.md +4 -0
  383. package/systems/fs/context/authoring/parts/core-types/fn-facts-ts.md +11 -0
  384. package/systems/fs/context/authoring/parts/core-types/gin-ts.md +4 -0
  385. package/systems/fs/context/authoring/parts/core-types/grants-ts.md +5 -1
  386. package/systems/fs/context/authoring/parts/core-types/lifecycle-ts.md +18 -5
  387. package/systems/fs/context/authoring/parts/core-types/link-ts.md +7 -3
  388. package/systems/fs/context/authoring/parts/core-types/llm-ts.md +4 -0
  389. package/systems/fs/context/authoring/parts/core-types/manifest.md +15 -2
  390. package/systems/fs/context/authoring/parts/core-types/manifestpatch.md +9 -1
  391. package/systems/fs/context/authoring/parts/core-types/mention-search-ts.md +4 -0
  392. package/systems/fs/context/authoring/parts/core-types/model-calls-ts.md +5 -1
  393. package/systems/fs/context/authoring/parts/core-types/model-names-ts.md +4 -0
  394. package/systems/fs/context/authoring/parts/core-types/modes-ts.md +4 -0
  395. package/systems/fs/context/authoring/parts/core-types/owner-runs-ts.md +4 -0
  396. package/systems/fs/context/authoring/parts/core-types/package-ts.md +9 -0
  397. package/systems/fs/context/authoring/parts/core-types/primitives-ts.md +4 -0
  398. package/systems/fs/context/authoring/parts/core-types/query-ts.md +4 -0
  399. package/systems/fs/context/authoring/parts/core-types/records-actors-ts.md +7 -3
  400. package/systems/fs/context/authoring/parts/core-types/records-chat-ts.md +4 -0
  401. package/systems/fs/context/authoring/parts/core-types/records-content-ts.md +4 -0
  402. package/systems/fs/context/authoring/parts/core-types/records-runs-ts.md +4 -0
  403. package/systems/fs/context/authoring/parts/core-types/records-systems-ts.md +4 -0
  404. package/systems/fs/context/authoring/parts/core-types/registries-ts.md +4 -0
  405. package/systems/fs/context/authoring/parts/core-types/remote-auth-ts.md +4 -0
  406. package/systems/fs/context/authoring/parts/core-types/resources-ts.md +5 -1
  407. package/systems/fs/context/authoring/parts/core-types/run-ts.md +7 -0
  408. package/systems/fs/context/authoring/parts/core-types/sensitivity-ts.md +5 -1
  409. package/systems/fs/context/authoring/parts/core-types/stores-ts.md +199 -0
  410. package/systems/fs/context/authoring/parts/core-types/system-events-ts.md +8 -1
  411. package/systems/fs/context/authoring/parts/core-types/system-pages-ts.md +4 -0
  412. package/systems/fs/context/authoring/parts/core-types/system-providers-ts.md +4 -0
  413. package/systems/fs/context/authoring/parts/core-types/validation-ts.md +4 -0
  414. package/systems/fs/context/authoring/parts/core-types/visuals-ts.md +4 -0
  415. package/systems/fs/context/authoring/parts/core-types/web-ts.md +4 -0
  416. package/systems/fs/context/authoring/parts/core-types/widgets-ts.md +4 -0
  417. package/systems/fs/context/authoring/parts/core-types.md +12 -2
  418. package/systems/fs/context/authoring/parts/ctx/update-result.md +33 -0
  419. package/systems/fs/context/authoring/parts/ctx.md +11 -1
  420. package/systems/fs/context/authoring/parts/ctx.reference/{hubai.md → adminnotices.md} +45 -4
  421. package/systems/fs/context/authoring/parts/ctx.reference/fnctx.md +21 -23
  422. package/systems/fs/context/authoring/parts/ctx.reference.md +8 -4
  423. package/systems/fs/context/authoring/parts/data.md +11 -6
  424. package/systems/fs/context/authoring/parts/data.reference.md +4 -0
  425. package/systems/fs/context/authoring/parts/examples/client-findview-vue.md +4 -0
  426. package/systems/fs/context/authoring/parts/examples/client-index-ts.md +4 -0
  427. package/systems/fs/context/authoring/parts/examples/client-notecard-vue.md +4 -0
  428. package/systems/fs/context/authoring/parts/examples/client-noteinput-vue.md +4 -0
  429. package/systems/fs/context/authoring/parts/examples/client-notespage-vue.md +4 -0
  430. package/systems/fs/context/authoring/parts/examples/client-reviewform-vue.md +4 -0
  431. package/systems/fs/context/authoring/parts/examples/client-wordcount-vue.md +4 -0
  432. package/systems/fs/context/authoring/parts/examples/package-json.md +4 -0
  433. package/systems/fs/context/authoring/parts/examples/server-env-ts.md +4 -0
  434. package/systems/fs/context/authoring/parts/examples/server-impl-ts.md +4 -0
  435. package/systems/fs/context/authoring/parts/examples/server-index-ts.md +4 -0
  436. package/systems/fs/context/authoring/parts/examples/server-main-ts.md +4 -0
  437. package/systems/fs/context/authoring/parts/examples/server-notes-test-ts.md +4 -0
  438. package/systems/fs/context/authoring/parts/examples/shared-index-ts.md +10 -0
  439. package/systems/fs/context/authoring/parts/examples/system-json.md +4 -0
  440. package/systems/fs/context/authoring/parts/examples/{systems-fs-shared-index-ts-lines-1-189.md → systems-fs-shared-index-ts-lines-1-178.md} +23 -30
  441. package/systems/fs/context/authoring/parts/examples/{systems-fs-shared-index-ts-lines-190-370.md → systems-fs-shared-index-ts-lines-179-382.md} +33 -6
  442. package/systems/fs/context/authoring/parts/examples/systems-fs-shared-index-ts-lines-383-567.md +210 -0
  443. package/systems/fs/context/authoring/parts/examples/systems-fs-shared-index-ts-lines-568-660.md +117 -0
  444. package/systems/fs/context/authoring/parts/examples/tsconfig-json.md +5 -1
  445. package/systems/fs/context/authoring/parts/examples.md +18 -11
  446. package/systems/fs/context/authoring/parts/fns.md +5 -1
  447. package/systems/fs/context/authoring/parts/fns.reference/fillclaims.md +5 -1
  448. package/systems/fs/context/authoring/parts/fns.reference/fn.md +6 -2
  449. package/systems/fs/context/authoring/parts/fns.reference.md +4 -0
  450. package/systems/fs/context/authoring/parts/folder.md +4 -0
  451. package/systems/fs/context/authoring/parts/gin.md +4 -0
  452. package/systems/fs/context/authoring/parts/gin.reference.md +4 -0
  453. package/systems/fs/context/authoring/parts/handlers-progress.md +5 -1
  454. package/systems/fs/context/authoring/parts/handlers-progress.reference.md +4 -0
  455. package/systems/fs/context/authoring/parts/hooks.md +5 -1
  456. package/systems/fs/context/authoring/parts/hooks.reference.md +5 -1
  457. package/systems/fs/context/authoring/parts/hub/context-questions.md +40 -0
  458. package/systems/fs/context/authoring/parts/hub/{hub-run-background.md → hub-ctx-from-resource.md} +51 -56
  459. package/systems/fs/context/authoring/parts/hub/hub-fns-load.md +35 -42
  460. package/systems/fs/context/authoring/parts/hub/hub-install-package.md +327 -0
  461. package/systems/fs/context/authoring/parts/hub/kinds-of-hub.md +8 -0
  462. package/systems/fs/context/authoring/parts/hub.md +14 -8
  463. package/systems/fs/context/authoring/parts/hub.reference.md +9 -0
  464. package/systems/fs/context/authoring/parts/internals/manifestof.md +4 -0
  465. package/systems/fs/context/authoring/parts/internals/permissionargs.md +4 -0
  466. package/systems/fs/context/authoring/parts/internals/usagefromwire.md +47 -2
  467. package/systems/fs/context/authoring/parts/internals.md +6 -2
  468. package/systems/fs/context/authoring/parts/kinds-agents.md +5 -1
  469. package/systems/fs/context/authoring/parts/kinds-agents.reference/authoringsession.md +4 -0
  470. package/systems/fs/context/authoring/parts/kinds-agents.reference/kind.md +7 -3
  471. package/systems/fs/context/authoring/parts/kinds-agents.reference.md +4 -0
  472. package/systems/fs/context/authoring/parts/lifecycle.md +8 -3
  473. package/systems/fs/context/authoring/parts/lifecycle.reference.md +6 -2
  474. package/systems/fs/context/authoring/parts/mentions.md +5 -1
  475. package/systems/fs/context/authoring/parts/mentions.reference.md +6 -2
  476. package/systems/fs/context/authoring/parts/mistakes.md +7 -2
  477. package/systems/fs/context/authoring/parts/named-types.md +4 -0
  478. package/systems/fs/context/authoring/parts/named-types.reference.md +6 -2
  479. package/systems/fs/context/authoring/parts/outcomes.md +5 -1
  480. package/systems/fs/context/authoring/parts/outcomes.reference.md +4 -0
  481. package/systems/fs/context/authoring/parts/owner-runs.md +5 -1
  482. package/systems/fs/context/authoring/parts/owner-runs.reference.md +36 -11
  483. package/systems/fs/context/authoring/parts/packaging.md +10 -3
  484. package/systems/fs/context/authoring/parts/packaging.reference.md +7 -2
  485. package/systems/fs/context/authoring/parts/providers.md +5 -1
  486. package/systems/fs/context/authoring/parts/providers.reference.md +5 -1
  487. package/systems/fs/context/authoring/parts/remote.md +5 -1
  488. package/systems/fs/context/authoring/parts/remote.reference.md +4 -0
  489. package/systems/fs/context/authoring/parts/resources.md +5 -1
  490. package/systems/fs/context/authoring/parts/resources.reference.md +4 -0
  491. package/systems/fs/context/authoring/parts/server.md +5 -1
  492. package/systems/fs/context/authoring/parts/server.reference.md +41 -20
  493. package/systems/fs/context/authoring/parts/settings-attachments.md +5 -1
  494. package/systems/fs/context/authoring/parts/settings-attachments.reference.md +4 -0
  495. package/systems/fs/context/authoring/parts/start.md +5 -1
  496. package/systems/fs/context/authoring/parts/state-forms.md +5 -1
  497. package/systems/fs/context/authoring/parts/state-forms.reference.md +4 -0
  498. package/systems/fs/context/authoring/parts/store/ctx-store.md +49 -0
  499. package/systems/fs/context/authoring/parts/store/declare.md +32 -0
  500. package/systems/fs/context/authoring/parts/store/engines.md +25 -0
  501. package/systems/fs/context/authoring/parts/store/migrations.md +53 -0
  502. package/systems/fs/context/authoring/parts/store/moves.md +38 -0
  503. package/systems/fs/context/authoring/parts/store/placement.md +25 -0
  504. package/systems/fs/context/authoring/parts/store/serve.md +30 -0
  505. package/systems/fs/context/authoring/parts/store/store-tables.md +24 -0
  506. package/systems/fs/context/authoring/parts/store/vectors.md +32 -0
  507. package/systems/fs/context/authoring/parts/store/when-to-use.md +27 -0
  508. package/systems/fs/context/authoring/parts/store/work.md +37 -0
  509. package/systems/fs/context/authoring/parts/store.md +65 -0
  510. package/systems/fs/context/authoring/parts/store.reference.md +459 -0
  511. package/systems/fs/context/authoring/parts/testing.md +14 -1
  512. package/systems/fs/context/authoring/parts/testing.reference/{memoryjournal.md → equal.md} +55 -48
  513. package/systems/fs/context/authoring/parts/testing.reference/fakehub.md +26 -45
  514. package/systems/fs/context/authoring/parts/testing.reference/{toolcall.md → kindprops.md} +111 -4
  515. package/systems/fs/context/authoring/parts/testing.reference/openmemorystore.md +105 -0
  516. package/systems/fs/context/authoring/parts/testing.reference.md +16 -9
  517. package/systems/fs/context/authoring/parts/widgets.md +5 -1
  518. package/systems/fs/context/authoring/parts/widgets.reference/hub-visuals.md +4 -0
  519. package/systems/fs/context/authoring/parts/widgets.reference/sourcecompatible.md +4 -0
  520. package/systems/fs/context/authoring/parts/widgets.reference.md +4 -0
  521. package/systems/fs/context/authoring/topics/begin.md +4 -0
  522. package/systems/fs/context/authoring/topics/client.md +4 -0
  523. package/systems/fs/context/authoring/topics/declare.md +4 -0
  524. package/systems/fs/context/authoring/topics/examples.md +4 -0
  525. package/systems/fs/context/authoring/topics/fns.md +4 -0
  526. package/systems/fs/context/authoring/topics/server.md +4 -0
  527. package/systems/fs/context/authoring/topics/types.md +8 -1
  528. package/systems/fs/context/comments/answer.md +21 -0
  529. package/systems/fs/context/comments/find.md +23 -0
  530. package/systems/fs/context/comments/read.md +26 -0
  531. package/systems/fs/context/comments.md +23 -0
  532. package/systems/fs/context/files-page.md +30 -0
  533. package/systems/fs/context/guide/attachments.md +16 -0
  534. package/systems/fs/context/guide/change.md +23 -0
  535. package/systems/fs/context/guide/commands.md +19 -0
  536. package/systems/fs/context/guide/documents.md +21 -0
  537. package/systems/fs/context/guide/find.md +25 -0
  538. package/systems/fs/context/guide/paths.md +24 -0
  539. package/systems/fs/context/guide/read.md +21 -0
  540. package/systems/fs/context/machine/history.md +25 -0
  541. package/systems/fs/context/machine/now.md +25 -0
  542. package/systems/fs/context/machine/processes.md +20 -0
  543. package/systems/fs/context/machine/recording.md +19 -0
  544. package/systems/fs/context/machine.md +24 -0
  545. package/systems/fs/package.json +5 -3
  546. package/systems/fs/server/files-page/browse.ts +391 -0
  547. package/systems/fs/server/files-page/comments.ts +439 -0
  548. package/systems/fs/server/files-page/fns.ts +158 -0
  549. package/systems/fs/server/files-page/git-view.ts +391 -0
  550. package/systems/fs/server/files-page/kinds.ts +56 -0
  551. package/systems/fs/server/impl.ts +66 -7
  552. package/systems/fs/server/main.ts +20 -4
  553. package/systems/fs/server/metrics/collector.ts +424 -0
  554. package/systems/fs/server/metrics/index.ts +181 -0
  555. package/systems/fs/server/metrics/os.ts +144 -0
  556. package/systems/fs/server/metrics/parsers.ts +268 -0
  557. package/systems/fs/server/metrics/rrd.ts +363 -0
  558. package/systems/fs/server/metrics/testing.ts +80 -0
  559. package/systems/fs/server/snapshots.ts +216 -33
  560. package/systems/fs/server/testing.ts +15 -9
  561. package/systems/fs/shared/files-page.ts +506 -0
  562. package/systems/fs/shared/index.ts +137 -10
  563. package/systems/fs/shared/metrics.ts +179 -0
  564. package/systems/fs/system.json +10 -1
  565. package/systems/google-calendar/package.json +1 -1
  566. package/systems/input/package.json +3 -3
  567. package/systems/mcp/package.json +3 -3
  568. package/systems/mcp/server/oauth.ts +1 -1
  569. package/systems/ollama/package.json +3 -3
  570. package/systems/schedule/package.json +3 -4
  571. package/systems/schedule/server/env.ts +1 -1
  572. package/systems/schedule/server/fns.ts +5 -4
  573. package/systems/schedule/server/impl.ts +2 -2
  574. package/systems/schedule/server/import.ts +189 -0
  575. package/systems/schedule/server/index.ts +2 -0
  576. package/systems/schedule/server/main.ts +3 -1
  577. package/systems/schedule/server/placements.ts +41 -0
  578. package/systems/schedule/server/store.ts +159 -79
  579. package/systems/schedule/server/timer.ts +142 -107
  580. package/systems/schedule/shared/index.ts +2 -1
  581. package/systems/schedule/system.json +5 -1
  582. package/systems/schedule/tsconfig.json +1 -1
  583. package/systems/template/package.json +1 -1
  584. package/systems/widgets/package.json +3 -3
  585. package/packages/web/dist/assets/ChatPage-7Yebk7rl.js +0 -4
  586. package/packages/web/dist/assets/ContextItemPage-B6rJG3OT.js +0 -2
  587. package/packages/web/dist/assets/ContextItemPage-BRsWxOmu.css +0 -1
  588. package/packages/web/dist/assets/ContextPage-CloIZ_2y.js +0 -2
  589. package/packages/web/dist/assets/ContextPage-rYKxjiVI.css +0 -1
  590. package/packages/web/dist/assets/ContextRow-Byz_7HG-.css +0 -1
  591. package/packages/web/dist/assets/ContextRow-Dvv8CTFk.js +0 -2
  592. package/packages/web/dist/assets/DataTypePage-Ba_zBV4b.js +0 -4
  593. package/packages/web/dist/assets/FnView-B8MGAOoB.js +0 -2
  594. package/packages/web/dist/assets/InstallDialog-C9GDoUI2.js +0 -2
  595. package/packages/web/dist/assets/InstanceTypes-D8Jcxn70.js +0 -2
  596. package/packages/web/dist/assets/InstanceTypes-DAowwLB7.css +0 -1
  597. package/packages/web/dist/assets/InstanceView-CuBD3JPU.css +0 -1
  598. package/packages/web/dist/assets/InstanceView-p7tMaylE.js +0 -2
  599. package/packages/web/dist/assets/LimitsView-DsZG6u5P.js +0 -2
  600. package/packages/web/dist/assets/ListSearch-BK4p7Nxa.js +0 -2
  601. package/packages/web/dist/assets/McpServerView-CD8qw6W_.js +0 -2
  602. package/packages/web/dist/assets/McpServersView-DNycG35u.js +0 -2
  603. package/packages/web/dist/assets/ModelsView-C_iN19xt.js +0 -2
  604. package/packages/web/dist/assets/PairPage-Bs2KuRjC.css +0 -1
  605. package/packages/web/dist/assets/PairPage-TEXPpsqi.js +0 -2
  606. package/packages/web/dist/assets/PoliciesView-BU1fudNF.js +0 -2
  607. package/packages/web/dist/assets/ResourcesPage-YluNBqIv.js +0 -2
  608. package/packages/web/dist/assets/ReviewView-79Z5rU1v.js +0 -3
  609. package/packages/web/dist/assets/RunsView-Dz9Xsvu5.js +0 -2
  610. package/packages/web/dist/assets/ServiceRows-DNzDiutg.js +0 -2
  611. package/packages/web/dist/assets/SettingsPage-CykfuYj1.js +0 -3
  612. package/packages/web/dist/assets/SystemView-Es5wtkYU.js +0 -2
  613. package/packages/web/dist/assets/SystemsView-CeuSFhlF.js +0 -2
  614. package/packages/web/dist/assets/UserMessage-qyc8dG5D.js +0 -9
  615. package/packages/web/dist/assets/WidgetView-BZyDyYRI.js +0 -3
  616. package/packages/web/dist/assets/index-Bv42jNvr.js +0 -4
  617. package/packages/web/dist/assets/routes-qP_j74V5.js +0 -4
  618. package/packages/web/dist/assets/runs-k76usGfd.js +0 -2
  619. package/packages/web/dist/assets/src-DLK1P7oz.js +0 -43
  620. package/packages/web/dist/assets/state-CjE-qA2w.js +0 -2
  621. package/packages/web/dist/assets/ui-W12UYhVu.js +0 -17
  622. package/systems/claude/client/FleetPage.vue +0 -132
  623. package/systems/claude/client/NewSessionForm.vue +0 -62
  624. package/systems/claude/client/SessionList.vue +0 -64
  625. package/systems/claude/client/SessionPage.vue +0 -199
  626. package/systems/claude/client/TaskList.vue +0 -61
  627. package/systems/claude/client/fakes.ts +0 -186
  628. package/systems/claude/client/host.ts +0 -23
  629. package/systems/claude/client/index.ts +0 -15
  630. package/systems/claude/client/logic.ts +0 -270
  631. package/systems/claude/client/state.ts +0 -344
  632. package/systems/claude/package.json +0 -23
  633. package/systems/claude/server/agent-sdk.ts +0 -379
  634. package/systems/claude/server/driver.ts +0 -153
  635. package/systems/claude/server/env.ts +0 -64
  636. package/systems/claude/server/fake-driver.ts +0 -112
  637. package/systems/claude/server/fleet.ts +0 -376
  638. package/systems/claude/server/impl.ts +0 -568
  639. package/systems/claude/server/index.ts +0 -8
  640. package/systems/claude/server/main.ts +0 -38
  641. package/systems/claude/server/preview.ts +0 -76
  642. package/systems/claude/server/questions.ts +0 -117
  643. package/systems/claude/server/transcript.ts +0 -83
  644. package/systems/claude/shared/index.ts +0 -262
  645. package/systems/claude/shared/session.ts +0 -284
  646. package/systems/claude/shared/shapes.ts +0 -106
  647. package/systems/claude/system.json +0 -18
  648. package/systems/claude/tsconfig.json +0 -6
  649. package/systems/database/package.json +0 -25
  650. package/systems/database/server/author.ts +0 -41
  651. package/systems/database/server/authoring.ts +0 -322
  652. package/systems/database/server/catalog.ts +0 -117
  653. package/systems/database/server/compile.ts +0 -332
  654. package/systems/database/server/dialects.ts +0 -17
  655. package/systems/database/server/drivers/database.ts +0 -71
  656. package/systems/database/server/drivers/index.ts +0 -23
  657. package/systems/database/server/drivers/postgres.ts +0 -157
  658. package/systems/database/server/drivers/sqlite.ts +0 -151
  659. package/systems/database/server/drivers/sqlserver.ts +0 -176
  660. package/systems/database/server/env.ts +0 -35
  661. package/systems/database/server/fixture.ts +0 -169
  662. package/systems/database/server/impl.ts +0 -793
  663. package/systems/database/server/index.ts +0 -7
  664. package/systems/database/server/instance.ts +0 -398
  665. package/systems/database/server/main.ts +0 -47
  666. package/systems/database/server/pick.ts +0 -97
  667. package/systems/database/server/queries.ts +0 -390
  668. package/systems/database/server/results.ts +0 -39
  669. package/systems/database/server/schema.ts +0 -59
  670. package/systems/database/server/table-fns.ts +0 -237
  671. package/systems/database/server/types.ts +0 -253
  672. package/systems/database/shared/index.ts +0 -544
  673. package/systems/database/shared/shapes.ts +0 -413
  674. package/systems/database/system.json +0 -14
  675. package/systems/database/tsconfig.json +0 -6
  676. package/systems/fs/context/authoring/parts/examples/systems-fs-shared-index-ts-lines-371-533.md +0 -183
  677. package/systems/fs/context/authoring/parts/hub/hub-auto-pair-revoke.md +0 -189
  678. package/systems/web/client/ReadView.vue +0 -110
  679. package/systems/web/client/SearchView.vue +0 -215
  680. package/systems/web/client/StatusChip.vue +0 -38
  681. package/systems/web/client/fakes.ts +0 -48
  682. package/systems/web/client/index.ts +0 -15
  683. package/systems/web/client/view.ts +0 -131
  684. package/systems/web/package.json +0 -22
  685. package/systems/web/server/chrome.ts +0 -121
  686. package/systems/web/server/crawl.ts +0 -333
  687. package/systems/web/server/env.ts +0 -63
  688. package/systems/web/server/guard.ts +0 -60
  689. package/systems/web/server/http.ts +0 -89
  690. package/systems/web/server/impl.ts +0 -203
  691. package/systems/web/server/index.ts +0 -71
  692. package/systems/web/server/loader.ts +0 -104
  693. package/systems/web/server/main.ts +0 -70
  694. package/systems/web/server/mentions.ts +0 -111
  695. package/systems/web/server/problem.ts +0 -72
  696. package/systems/web/server/renderer.ts +0 -243
  697. package/systems/web/server/robots.ts +0 -75
  698. package/systems/web/server/searches.ts +0 -29
  699. package/systems/web/server/tavily.ts +0 -144
  700. package/systems/web/server/testing.ts +0 -165
  701. package/systems/web/server/uploads.ts +0 -33
  702. package/systems/web/shared/index.ts +0 -343
  703. package/systems/web/shared/urls.ts +0 -60
  704. package/systems/web/system.json +0 -15
  705. package/systems/web/tsconfig.json +0 -6
@@ -52,72 +52,72 @@ function e(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object
52
52
 
53
53
  `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},s,c=ae,l=!rt.jitless,u=l&&oe.value,d=t.catchall,f;e._zod.parse=(i,a)=>{f??=r.value;let p=i.value;return c(p)?l&&u&&a?.async===!1&&a.jitless!==!0?(s||=o(t.shape),i=s(i,a),d?zr([],p,i,a,f,e,a?.abortEarly===!0):i):n(i,a):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function Hr(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Ee(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Me(e,r,it())))}),t)}var Ur=_(`$ZodUnion`,(e,t)=>{Fn.init(e,t),qe(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),qe(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),qe(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),qe(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>o(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Hr(t,r,e,i)):Hr(o,r,e,i)}});function Wr(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}var Gr=_(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Ur.init(e,t);let n=e._zod.parse;qe(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||u(t,e,new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=d(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=i(()=>Wr(t));e._zod.parse=(i,a)=>{let o=i.value;if(!ae(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),Kr=_(`$ZodIntersection`,(e,t)=>{Fn.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Jr(e,t,n)):Jr(e,i,a)}});function qr(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(se(e)&&se(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=qr(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=qr(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Jr(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=qr(t.value,n.value);if(!c.valid){if(Ee(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Yr=_(`$ZodTuple`,(e,t)=>{Fn.init(e,t);let n=t.items,r=rt.memoizer;r?.attach(e),e._zod.parse=(i,a)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:`tuple`,code:`invalid_type`}),i;i.value=r?r.alloc(e,i,[],a):[];let s=[],c=Xr(n,`optin`),l=Xr(n,`optout`);if(!t.rest){if(o.length<c)return i.issues.push({code:`too_small`,minimum:c,inclusive:!0,input:o,inst:e,origin:`array`}),i;o.length>n.length&&i.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:o,inst:e,origin:`array`})}let u=Array(n.length),d=t.rest?a?.abortEarly:void 0,f=!1;for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:o[e],issues:[]},a);t instanceof Promise?s.push(t.then(t=>{u[e]=t})):(u[e]=t,d&&!f&&t.issues.length&&(f=Ee(t)))}if(t.rest&&!f){let e=n.length-1,r=o.slice(n.length),c=i.issues.length;for(let n of r){if(d&&i.issues.length!==c){if(Ee(i,c))break;c=i.issues.length}e++;let r=t.rest._zod.run({value:n,issues:[]},a);r instanceof Promise?s.push(r.then(t=>Zr(t,i,e))):Zr(r,i,e)}}return s.length?Promise.all(s).then(()=>Qr(u,i,n,o,l)):Qr(u,i,n,o,l)}});function Xr(e,t){for(let n=e.length-1;n>=0;n--)if(!(t===`optin`?e[n]._zod.optin!==void 0:e[n]._zod.optout===`optional`))return n+1;return 0}function Zr(e,t,n){e.issues.length&&t.issues.push(...Oe(n,e.issues)),t.value[n]=e.value}function Qr(e,t,n,r,i){for(let a=0;a<n.length;a++){let o=e[a],s=a<r.length;if(!s&&a>=i&&n[a]._zod.optin===`optional`){t.value.length=a;break}if(o.issues.length){if(!s&&a>=i){t.value.length=a;break}t.issues.push(...Oe(a,o.issues))}t.value[a]=o.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var $r=_(`$ZodRecord`,(e,t)=>{Fn.init(e,t);let n=rt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!se(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Me(e,i,it())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...Oe(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...Oe(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&un.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>Me(e,i,it())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...Oe(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...Oe(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),ei=_(`$ZodEnum`,(t,n)=>{Fn.init(t,n);let r=e(n.entries),i=new Set(r);t._zod.values=i,qe(t,`pattern`,t=>{let n=e(t.def.entries).filter(e=>le.has(typeof e));return RegExp(n.length?`^(${n.map(e=>de(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),t._zod.parse=(e,n)=>{let a=e.value;return i.has(a)||e.issues.push({code:`invalid_value`,values:r,input:a,inst:t}),e}}),ti=_(`$ZodLiteral`,(e,t)=>{Fn.init(e,t);let n=new Set(t.values);e._zod.values=n,qe(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?de(e):e?de(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),ni=_(`$ZodTransform`,(e,t)=>{Fn.init(e,t),e._zod.optin=`optional`,rt.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nt(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new tt;return n.value=i,n}});function ri(e,t){return e.value=t.issues.length?void 0:t.value,e}var ii=_(`$ZodOptional`,(e,t)=>{Fn.init(e,t),qe(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,qe(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),qe(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${o(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>ri(e,t)):ri(e,r)}return t.innerType._zod.run(e,n)}}),ai=_(`$ZodExactOptional`,(e,t)=>{ii.init(e,t),qe(e,`values`,e=>e.def.innerType._zod.values),qe(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),oi=_(`$ZodNullable`,(e,t)=>{Fn.init(e,t),qe(e,`optin`,e=>e.def.innerType._zod.optin),qe(e,`optout`,e=>e.def.innerType._zod.optout),qe(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${o(t.source)}|null)$`):void 0}),qe(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),si=_(`$ZodDefault`,(e,t)=>{Fn.init(e,t),e._zod.optin=`defaulted`,qe(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>ci(e,t)):ci(r,t)}});function ci(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var li=_(`$ZodPrefault`,(e,t)=>{Fn.init(e,t),e._zod.optin=`defaulted`,qe(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),ui=_(`$ZodNonOptional`,(e,t)=>{Fn.init(e,t),qe(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>di(t,e)):di(i,e)}});function di(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function fi(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>Me(e,r,it()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var pi=_(`$ZodCatch`,(e,t)=>{Fn.init(e,t),qe(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),qe(e,`optout`,e=>e.def.innerType._zod.optout),qe(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>fi(e,r,t,n)):fi(e,r,t,n)}}),mi=_(`$ZodPipe`,(e,t)=>{Fn.init(e,t),qe(e,`values`,e=>e.def.in._zod.values),qe(e,`optin`,e=>e.def.in._zod.optin),qe(e,`optout`,e=>e.def.out._zod.optout),qe(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>hi(e,t.in,n)):hi(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>hi(e,t.out,n)):hi(r,t.out,n)}});function hi(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var gi=_(`$ZodReadonly`,(e,t)=>{Fn.init(e,t),qe(e,`propValues`,e=>e.def.innerType._zod.propValues),qe(e,`values`,e=>e.def.innerType._zod.values),qe(e,`optin`,e=>e.def.innerType?._zod?.optin),qe(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(_i):_i(r)}});function _i(e){return e.memo||(e.value=Object.freeze(e.value)),e}function vi(e){let t=e._zod.def,n=t.pattern,r=!!t.format?.includes(`int`),i,a;for(let e of t.checks??[]){let t=e._zod.def;t.pattern&&(n=t.pattern),r||=!!t.format?.includes(`int`);let o=t.minimum??t.length,s=t.maximum??t.length;o!==void 0&&(i===void 0||o>i)&&(i=o),s!==void 0&&(a===void 0||s<a)&&(a=s)}if(n)return n.source;if(i!==void 0&&a!==void 0&&i>a)return`(?!)`;if(i!==void 0||a!==void 0)return cn({minimum:i,maximum:a}).source;let o=e._zod.pattern;return(r&&o===un?ln:o)?.source}function yi(e){let t=e._zod.def,n=e._zod.pattern?.source,r=t.innerType??e._zod.innerType;if(r){let e=r._zod.pattern?.source,t=yi(r);return n&&e&&t&&t!==e?n.replace(o(e),()=>o(t)):n}if(t.options){let e=t.options.map(yi);if(e.every(Boolean))return`^(${e.map(e=>o(e)).join(`|`)})$`}return vi(e)}var bi=_(`$ZodTemplateLiteral`,(e,t)=>{Fn.init(e,t);let n=[];for(let e of t.parts)if(typeof e==`object`&&e){let t=yi(e);if(!t)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);n.push(o(t))}else if(e===null||ue.has(typeof e))n.push(de(`${e}`));else throw Error(`Invalid template literal part: ${e}`);e._zod.pattern=RegExp(`^${n.join(``)}$`),e._zod.parse=(n,r)=>typeof n.value==`string`?(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:`invalid_format`,format:t.format??`template_literal`,pattern:e._zod.pattern.source}),n):(n.issues.push({input:n.value,inst:e,expected:`string`,code:`invalid_type`}),n)}),xi=_(`$ZodLazy`,(e,t)=>{Fn.init(e,t),l(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),qe(e,`pattern`,e=>e.innerType?._zod?.pattern),qe(e,`propValues`,e=>e.innerType?._zod?.propValues),qe(e,`optin`,e=>e.innerType?._zod?.optin??void 0),qe(e,`optout`,e=>e.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Si=_(`$ZodCustom`,(e,t)=>{hn.init(e,t),Fn.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Ci(t,n,r,e));Ci(i,n,r,e)}});function Ci(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Le(e))}}var wi=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},Ti=`~memo`,Ei=[];function Di(e){return typeof e==`object`&&!!e}function Oi(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var ki=new WeakMap,Ai=0,ji=1,Mi=2;function Ni(e,t,n){let r=ki.get(e);if(r!==void 0)return r?Mi:Ai;if(t.has(e))return Mi;t.add(e);let i=Ai,a=e=>{if(i!==Mi&&e?._zod){let r=Ni(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=Ai;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?ji:o.value?._zod?Ni(o.value,t,n):Ai;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=d(c);s(e?o(e,!0):ji),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?Ni(r,t,!1):ji);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),Pi(e,i)}function Pi(e,t){return t!==ji&&ki.set(e,t===Mi),t}function Fi(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var Ii,Li=[],Ri={alloc(e,t,n){let r=Ii;if(!r)return n;Ii=void 0;let i={value:n,issues:null};return r.set(t.value,i),Li.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&Bi(n,e.value))throw new wi;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=Ni(e,new Set,!1);if(i===Ai)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===Mi||r?n=!0:r=!0}let l=s.value;if(!Di(l))return t(s,c);let u=c[Ti];u||(u={buckets:new WeakMap,backEdges:void 0},c[Ti]=u);let d;i===c?d=a:(d=Fi(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...Oi(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;Ii=d;let p=Li.length,m=t(s,c);Ii=void 0;let h=Li.length>p?Li.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?Oi(e.issues):Ei),e)):(h&&(h.issues=m.issues.length?Oi(m.issues):Ei),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function zi(){return Ri}function Bi(e,t){let n=e[Ti]?.backEdges;return n!==void 0&&Di(t)&&n.has(t)}var Vi=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function n(t){return e[t]??null}let r={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},i={nan:`NaN`};function a(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):i[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${a(e.expected)}, received ${a(Ie(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${pe(e.values[0])}`:`Invalid option: expected one of ${t(e.values,`|`)}`;case`too_big`:{let t=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=n(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${t}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${t}${e.maximum.toString()}`}case`too_small`:{let t=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=n(e.origin);return r?`Too small: expected ${e.origin} to have ${t}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${t}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${t(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Hi(){return{localeError:Vi()}}var Ui,Wi=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Gi(){return new Wi}(Ui=globalThis).__zod_globalRegistry??(Ui.__zod_globalRegistry=Gi());var Ki=globalThis.__zod_globalRegistry;function qi(e){return e.checks&&=[...e.checks],e}function Ji(e,t){return new e(qi({type:`string`,...g(t)}))}function Yi(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...g(t)})}function Xi(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...g(t)})}function Zi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...g(t)})}function Qi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...g(t)})}function $i(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...g(t)})}function ea(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...g(t)})}function ta(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...g(t)})}function na(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...g(t)})}function ra(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...g(t)})}function ia(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...g(t)})}function aa(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...g(t)})}function oa(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...g(t)})}function sa(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...g(t)})}function ca(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...g(t)})}function la(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...g(t)})}function ua(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...g(t)})}function da(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...g(t)})}function fa(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...g(t)})}function pa(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...g(t)})}function ma(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...g(t)})}function ha(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...g(t)})}function ga(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...g(t)})}function _a(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...g(t)})}function va(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...g(t)})}function ya(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...g(t)})}function ba(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...g(t)})}function xa(e,t){return new e(qi({type:`number`,checks:[],...g(t)}))}function Sa(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...g(t)})}function Ca(e,t){return new e({type:`boolean`,...g(t)})}function wa(e,t){return new e({type:`null`,...g(t)})}function Ta(e){return new e({type:`unknown`})}function Ea(e,t){return new e({type:`never`,...g(t)})}function Da(e,t){return new vn({check:`less_than`,...g(t),value:e,inclusive:!1})}function Oa(e,t){return new vn({check:`less_than`,...g(t),value:e,inclusive:!0})}function ka(e,t){return new yn({check:`greater_than`,...g(t),value:e,inclusive:!1})}function Aa(e,t){return new yn({check:`greater_than`,...g(t),value:e,inclusive:!0})}function ja(e,t){return new bn({check:`multiple_of`,...g(t),value:e})}function Ma(e,t){return new Sn({check:`max_length`,...g(t),maximum:e})}function Na(e,t){return new Cn({check:`min_length`,...g(t),minimum:e})}function Pa(e,t){return new wn({check:`length_equals`,...g(t),length:e})}function Fa(e,t){return new En({check:`string_format`,format:`regex`,...g(t),pattern:e})}function Ia(e){return new Dn({check:`string_format`,format:`lowercase`,...g(e)})}function La(e){return new On({check:`string_format`,format:`uppercase`,...g(e)})}function Ra(e,t){return new kn({check:`string_format`,format:`includes`,...g(t),includes:e})}function za(e,t){return new An({check:`string_format`,format:`starts_with`,...g(t),prefix:e})}function Ba(e,t){return new jn({check:`string_format`,format:`ends_with`,...g(t),suffix:e})}function Va(e){return new Mn({check:`overwrite`,tx:e})}function Ha(e){return Va(t=>t.normalize(e))}function Ua(){return Va(e=>e.trim())}function Wa(){return Va(e=>e.toLowerCase())}function Ga(){return Va(e=>e.toUpperCase())}function Ka(){return Va(e=>re(e))}function qa(e,t,n){return new e({type:`array`,element:t,...g(n)})}function Ja(e,t,n){let r=g(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function Ya(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...g(n)})}function Xa(e,t){let n=Za(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Le(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Le(r))}},e(t.value,t)),t);return n}function Za(e,t){let n=new hn({check:`custom`,...g(t)});return n._zod.check=e,n}function Qa(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&u(e,t,n[t]);return e}function $a(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Ki,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function eo(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function to(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,to(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Qa(o.schema,c),t.io===`input`&&fo(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function no(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ro(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${no(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+no(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
54
54
 
55
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function io(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;io(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ao=new Set([`type`,`properties`,`required`,`additionalProperties`]),oo=[`oneOf`,`anyOf`];function so(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function co(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ao.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??so(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}u(n,r,e.length===1?e[0]:co(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=so(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function lo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ao)if(t in e)return;let n=t.filter(e=>oo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=co(t);else{let e=n[0],i=oo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>co([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Qa(e,r))}function uo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Qa(i,s),Qa(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())io(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])lo(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Qa(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,u(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:mo(t,`input`,e.processors),output:mo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function fo(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return fo(r.element,n);if(r.type===`set`)return fo(r.valueType,n);if(r.type===`lazy`)return fo(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return fo(r.innerType,n);if(r.type===`intersection`)return fo(r.left,n)||fo(r.right,n);if(r.type===`record`||r.type===`map`)return fo(r.keyType,n)||fo(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:fo(r.in,n)||fo(r.out,n);if(r.type===`object`){for(let e in r.shape)if(fo(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(fo(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(fo(e,n))return!0;return!!(r.rest&&fo(r.rest,n))}return!1}var po=(e,t={})=>n=>{let r=$a({...n,processors:t});return to(e,r),ro(r,e),uo(r,e)},mo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=$a({...i??{},target:a,io:t,processors:n});return to(e,o),ro(o,e),uo(o,e)},ho=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},go=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},_o=(e,t)=>{ho(e,`minimum`,t),go(e,`maximum`,t)},vo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},yo=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},bo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},xo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},So=(e,t)=>ho(e,`minimum`,t.minimum),Co=(e,t)=>go(e,`maximum`,t.maximum),wo=e=>(t,n)=>{xo(t,n.format);let[r,i]=e[n.format];ho(t,`minimum`,r),go(t,`maximum`,i)},To={greater_than:(e,t)=>ho(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>go(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>vo(e,t.value),number_format:wo(he),bigint_format:wo(ge),min_length:So,max_length:Co,length_equals:(e,t)=>_o(e,t.length),min_size:So,max_size:Co,size_equals:(e,t)=>_o(e,t.size),string_format:(e,t)=>{xo(e,t.format),t.pattern&&yo(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>bo(e,t.mime)};function Eo(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)To[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&ho(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&ho(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&go(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&go(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&vo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&bo(t,i.mime);for(let e of i.patterns??[])yo(t,e);return t}var Do={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Oo=new Map([[_r,Xt],[yr,Zt]]),ko=e=>Oo.get(e)??e,Ao=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=Eo(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Do[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(ko);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},jo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Eo(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):eo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Mo=(e,t,n,r)=>{n.type=`boolean`},No=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Po=(e,t,n,r)=>{n.not={}},Fo=(t,n,r,i)=>{let a=t._zod.def,o=e(a.entries);o.length===0?r.not={}:(o.every(e=>typeof e==`number`)&&(r.type=`number`),o.every(e=>typeof e==`string`)&&(r.type=`string`),r.enum=o)},Io=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(eo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(eo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Lo=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Ro=(e,t,n,r)=>{eo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},zo=(e,t,n,r)=>{eo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Bo=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=Eo(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=to(a.element,t,{...r,path:[...r.path,`items`]})};function Vo(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Vo(t.out):t.type===`catch`?Vo(t.innerType):e._zod.optin}var Ho=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&eo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)u(i.properties,e,to(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Vo(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=to(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Uo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>to(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Wo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=to(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},Go=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>to(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?to(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?Vo(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=Eo(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function Ko(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Ko(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Ko(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?un:ln).source)),p}var qo=new WeakMap;function Jo(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of qo.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Ko(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var Yo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=Eo(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=to(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)u(i.patternProperties,ko(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=to(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=qo.get(t);n||(n=[],qo.set(t,n),t.deferred.push(()=>Jo(t))),n.push(e)}i.additionalProperties=to(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Vo(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Xo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Zo=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Qo=Symbol();function $o(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(eo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Qo):JSON.parse(o)}var es=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n.default=o)},ts=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n._prefault=o)},ns=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{eo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},rs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;to(o,t,r);let s=t.seen.get(e);s.ref=o},is=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},as=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},os=(e,t,n,r)=>{let i=e._zod.innerType;to(i,t,r);let a=t.seen.get(e);a.ref=i},ss=new WeakSet([Object.prototype,Error.prototype]);function cs(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var ls=_(`ZodError`,(e,t)=>{ut.init(e,t),e.name=`ZodError`;let r=Object.getPrototypeOf(e);ss.has(r)||(ss.add(r),cs(r,`format`,e=>t=>pt(e,t)),cs(r,`flatten`,e=>t=>ft(e,t)),cs(r,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,n,2)}),cs(r,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,n,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),us=ht(ls),ds=gt(ls),fs=_t(ls),ps=yt(ls),ms=Tt(ls),hs=Et(ls),gs=Dt(ls),_s=Ot(ls),vs=kt(ls),ys=At(ls),bs=jt(ls),xs=Mt(ls);function Ss(){rt.localeError||it(Hi())}function Cs(){rt.memoizer||it({memoizer:zi()})}var ws=_(`ZodType`,(e,t)=>(Ss(),Fn.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(te(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return fe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Yc(e,t))},superRefine(e,t){return this.check(Xc(e,t))},overwrite(e){return this.check(Va(e))},optional(){return Ec(this)},exactOptional(){return Oc(this)},nullable(){return Ac(this)},nullish(){return Ec(Ac(this))},nonoptional(e){return Ic(this,e)},array(){return x(this)},or(e){return C([this,e])},and(e){return gc(this,e)},transform(e){return Bc(this,wc(e))},default(e){return Mc(this,e)},prefault(e){return Pc(this,e)},catch(e){return Rc(this,e)},pipe(e){return Bc(this,e)},readonly(){return Hc(this)},describe(e){let t=this.clone();return Ki.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ki.get(this);let t=this.clone();return Ki.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Be(this,`~standard`,{...Rn(this),jsonSchema:{input:mo(this,`input`),output:mo(this,`output`)}})},set"~standard"(e){ze(this,`~standard`,e)},parse:function e(t,n){return us(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await ds(this,t,n,{callee:e})},safeParse(e,t){return fs(this,e,t)},async safeParseAsync(e,t){return ps(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){ze(this,`spa`,e)},validate(e,t){return St(this,e,t)},validateAsync(e,t){return wt(this,e,t)},encode:function e(t,n){return ms(this,t,n,{callee:e})},decode:function e(t,n){return hs(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await gs(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await _s(this,t,n,{callee:e})},safeEncode(e,t){return vs(this,e,t)},safeDecode(e,t){return ys(this,e,t)},async safeEncodeAsync(e,t){return bs(this,e,t)},async safeDecodeAsync(e,t){return xs(this,e,t)},toJSONSchema(e){return po(this,{})(e)},get description(){return Ki.get(this)?.description},get _def(){return this._zod.def}}),Ts=_(`_ZodString`,(e,t)=>{zn.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r)},Ve({format:e=>Eo(e).format??null,minLength:e=>Eo(e).minimum??null,maxLength:e=>Eo(e).maximum??null},{regex(...e){return this.check(Fa(...e))},includes(...e){return this.check(Ra(...e))},startsWith(...e){return this.check(za(...e))},endsWith(...e){return this.check(Ba(...e))},min(...e){return this.check(Na(...e))},max(...e){return this.check(Ma(...e))},length(...e){return this.check(Pa(...e))},nonempty(...e){return this.check(Na(1,...e))},lowercase(e){return this.check(Ia(e))},uppercase(e){return this.check(La(e))},trim(){return this.check(Ua())},normalize(...e){return this.check(Ha(...e))},toLowerCase(){return this.check(Wa())},toUpperCase(){return this.check(Ga())},slugify(){return this.check(Ka())}})),Es=_(`ZodString`,(e,t)=>{zn.init(e,t),Ts.init(e,t)},{email(e){return this.check(Yi(Ms,e))},url(e){return this.check(ta(Is,e))},jwt(e){return this.check(ga(Qs,e))},emoji(e){return this.check(na(Rs,e))},guid(e){return this.check(Xi(Ps,e))},uuid(e){return this.check(Zi(Fs,e))},uuidv4(e){return this.check(Qi(Fs,e))},uuidv6(e){return this.check($i(Fs,e))},uuidv7(e){return this.check(ea(Fs,e))},nanoid(e){return this.check(ra(zs,e))},cuid(e){return this.check(ia(Bs,e))},cuid2(e){return this.check(aa(Vs,e))},ulid(e){return this.check(oa(Hs,e))},base64(e){return this.check(pa(Ys,e))},base64url(e){return this.check(ma(Xs,e))},xid(e){return this.check(sa(Us,e))},ksuid(e){return this.check(ca(Ws,e))},ipv4(e){return this.check(la(Gs,e))},ipv6(e){return this.check(ua(Ks,e))},cidrv4(e){return this.check(da(qs,e))},cidrv6(e){return this.check(fa(Js,e))},e164(e){return this.check(ha(Zs,e))},datetime(e){return this.check(_a(Os,e))},date(e){return this.check(va(ks,e))},time(e){return this.check(ya(As,e))},duration(e){return this.check(ba(js,e))}});function v(e){return Ji(Es,e)}var Ds=_(`ZodStringFormat`,(e,t)=>{Bn.init(e,t),Ts.init(e,t)}),Os=_(`ZodISODateTime`,(e,t)=>{ar.init(e,t),Ds.init(e,t)}),ks=_(`ZodISODate`,(e,t)=>{or.init(e,t),Ds.init(e,t)}),As=_(`ZodISOTime`,(e,t)=>{sr.init(e,t),Ds.init(e,t)}),js=_(`ZodISODuration`,(e,t)=>{cr.init(e,t),Ds.init(e,t)}),Ms=_(`ZodEmail`,(e,t)=>{Un.init(e,t),Ds.init(e,t)});function Ns(e){return Yi(Ms,e)}var Ps=_(`ZodGUID`,(e,t)=>{Vn.init(e,t),Ds.init(e,t)}),Fs=_(`ZodUUID`,(e,t)=>{Hn.init(e,t),Ds.init(e,t)}),Is=_(`ZodURL`,(e,t)=>{Zn.init(e,t),Ds.init(e,t)});function Ls(e){return ta(Is,e)}var Rs=_(`ZodEmoji`,(e,t)=>{Qn.init(e,t),Ds.init(e,t)}),zs=_(`ZodNanoID`,(e,t)=>{$n.init(e,t),Ds.init(e,t)}),Bs=_(`ZodCUID`,(e,t)=>{er.init(e,t),Ds.init(e,t)}),Vs=_(`ZodCUID2`,(e,t)=>{tr.init(e,t),Ds.init(e,t)}),Hs=_(`ZodULID`,(e,t)=>{nr.init(e,t),Ds.init(e,t)}),Us=_(`ZodXID`,(e,t)=>{rr.init(e,t),Ds.init(e,t)}),Ws=_(`ZodKSUID`,(e,t)=>{ir.init(e,t),Ds.init(e,t)}),Gs=_(`ZodIPv4`,(e,t)=>{lr.init(e,t),Ds.init(e,t)}),Ks=_(`ZodIPv6`,(e,t)=>{fr.init(e,t),Ds.init(e,t)}),qs=_(`ZodCIDRv4`,(e,t)=>{pr.init(e,t),Ds.init(e,t)}),Js=_(`ZodCIDRv6`,(e,t)=>{hr.init(e,t),Ds.init(e,t)}),Ys=_(`ZodBase64`,(e,t)=>{vr.init(e,t),Ds.init(e,t)}),Xs=_(`ZodBase64URL`,(e,t)=>{xr.init(e,t),Ds.init(e,t)}),Zs=_(`ZodE164`,(e,t)=>{Sr.init(e,t),Ds.init(e,t)}),Qs=_(`ZodJWT`,(e,t)=>{wr.init(e,t),Ds.init(e,t)}),$s=_(`ZodNumber`,(e,t)=>{Tr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jo(e,t,n,r),e.isFinite=!0},Ve({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Eo(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Eo(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=Eo(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Eo(e).format??null},{gt(e,t){return this.check(ka(e,t))},gte(e,t){return this.check(Aa(e,t))},min(e,t){return this.check(Aa(e,t))},lt(e,t){return this.check(Da(e,t))},lte(e,t){return this.check(Oa(e,t))},max(e,t){return this.check(Oa(e,t))},int(e){return this.check(tc(e))},safe(e){return this.check(tc(e))},positive(e){return this.check(ka(0,e))},nonnegative(e){return this.check(Aa(0,e))},negative(e){return this.check(Da(0,e))},nonpositive(e){return this.check(Oa(0,e))},multipleOf(e,t){return this.check(ja(e,t))},step(e,t){return this.check(ja(e,t))},finite(){return this}}));function y(e){return xa($s,e)}var ec=_(`ZodNumberFormat`,(e,t)=>{Er.init(e,t),$s.init(e,t)});function tc(e){return Sa(ec,e)}var nc=_(`ZodBoolean`,(e,t)=>{Dr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mo(e,t,n,r)});function b(e){return Ca(nc,e)}var rc=_(`ZodNull`,(e,t)=>{Or.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>No(e,t,n,r)});function ic(e){return wa(rc,e)}var ac=_(`ZodAny`,(e,t)=>{kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0}),oc=_(`ZodUnknown`,(e,t)=>{Ar.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function sc(){return Ta(oc)}var cc=_(`ZodNever`,(e,t)=>{jr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Po(e,t,n,r)});function lc(e){return Ea(cc,e)}var uc=_(`ZodArray`,(e,t)=>{Cs(),Fr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Na(e,t))},nonempty(e){return this.check(Na(1,e))},max(e,t){return this.check(Ma(e,t))},length(e,t){return this.check(Pa(e,t))},unwrap(){return this.element}});function x(e,t){return qa(uc,e,t)}var dc=_(`ZodObject`,(e,t)=>{Cs(),Vr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ho(e,t,n,r),Je(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return E(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(te(this._zod.def,{catchall:e}))},passthrough(){return this.clone(te(this._zod.def,{catchall:sc()}))},loose(){return this.clone(te(this._zod.def,{catchall:sc()}))},strict(){return this.clone(te(this._zod.def,{catchall:lc()}))},strip(){return this.clone(te(this._zod.def,{catchall:void 0}))},extend(e){return be(this,e)},safeExtend(e){return Se(this,e)},merge(e){return Ce(this,e)},pick(e){return _e(this,e)},omit(e){return ye(this,e)},partial(...e){return we(Tc,this,e[0])},exactPartial(...e){return we(Dc,this,e[0],`exactPartial`)},required(...e){return Te(Fc,this,e[0])}});function S(e,t){return new dc({type:`object`,shape:e??{},...g(t)})}function fc(e,t){return new dc({type:`object`,shape:e,catchall:sc(),...g(t)})}var pc=_(`ZodUnion`,(e,t)=>{Ur.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uo(e,t,n,r),e.options=t.options});function C(e,t){return new pc({type:`union`,options:e,...g(t)})}var mc=_(`ZodDiscriminatedUnion`,(e,t)=>{pc.init(e,t),Gr.init(e,t)});function w(e,t,n){return new mc({type:`union`,options:t,discriminator:e,...g(n)})}var hc=_(`ZodIntersection`,(e,t)=>{Kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wo(e,t,n,r)});function gc(e,t){return new hc({type:`intersection`,left:e,right:t})}var _c=_(`ZodTuple`,(e,t)=>{Cs(),Yr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Go(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Tc({type:`optional`,innerType:e}))})}});function vc(e,t,n){let r=t instanceof Fn;return new _c({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}var yc=_(`ZodRecord`,(e,t)=>{Cs(),$r.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function T(e,t,n){return!t||!t._zod?new yc({type:`record`,keyType:v(),valueType:e,...g(t)}):new yc({type:`record`,keyType:e,valueType:t,...g(n)})}function bc(e,t,n){return new yc({type:`record`,keyType:e,valueType:t,...g(n),partial:!0})}var xc=_(`ZodEnum`,(e,t)=>{ei.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})}});function E(e,t){return new xc({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...g(t)})}var Sc=_(`ZodLiteral`,(e,t)=>{ti.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Io(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function D(e,t){return new Sc({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}var Cc=_(`ZodTransform`,(e,t)=>{Cs(),ni.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zo(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Le(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Le(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function wc(e){return new Cc({type:`transform`,transform:e})}var Tc=_(`ZodOptional`,(e,t)=>{ii.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ec(e){return new Tc({type:`optional`,innerType:e})}var Dc=_(`ZodExactOptional`,(e,t)=>{ai.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Oc(e){return new Dc({type:`optional`,innerType:e})}var kc=_(`ZodNullable`,(e,t)=>{oi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ac(e){return new kc({type:`nullable`,innerType:e})}var jc=_(`ZodDefault`,(e,t)=>{si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mc(e,t){return new jc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Nc=_(`ZodPrefault`,(e,t)=>{li.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pc(e,t){return new Nc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Fc=_(`ZodNonOptional`,(e,t)=>{ui.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e,t){return new Fc({type:`nonoptional`,innerType:e,...g(t)})}var Lc=_(`ZodCatch`,(e,t)=>{pi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Rc(e,t){return new Lc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Xe(t)})}var zc=_(`ZodPipe`,(e,t)=>{mi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),e.in=t.in,e.out=t.out});function Bc(e,t){return new zc({type:`pipe`,in:e,out:t})}var Vc=_(`ZodReadonly`,(e,t)=>{gi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e){return new Vc({type:`readonly`,innerType:e})}var Uc=_(`ZodTemplateLiteral`,(e,t)=>{bi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lo(e,t,n,r)});function Wc(e,t){return new Uc({type:`template_literal`,parts:e,...g(t)})}var Gc=_(`ZodLazy`,(e,t)=>{xi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Kc(e){return new Gc({type:`lazy`,getter:e})}var qc=_(`ZodCustom`,(e,t)=>{Si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ro(e,t,n,r)});function Jc(e,t){return Ja(qc,e??(()=>!0),t)}function Yc(e,t={}){return Ya(qc,e,t)}function Xc(e,t){return Xa(e,t)}function Zc(e){let t=Kc(()=>C([v(e),y(),b(),ic(),x(t),T(v(),t)]));return t}var O=Zc(),Qc=T(v(),O);function $c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var el={run:`run`,turn:`trn`,session:`ses`,actor:`act`,message:`msg`,delivery:`dlv`,handlerCall:`hcl`,llmInteraction:`llm`,pairing:`par`,pairingToken:`ptk`,policy:`pol`,approval:`apr`,budget:`bgt`,priorityRule:`pri`,reservation:`rsv`,ledger:`led`,notification:`ntf`,push:`psh`,secret:`sec`,modelCategory:`mct`,provider:`prv`,sectionRule:`srl`,authSession:`aus`,modelCall:`mdl`,mcp:`mcp`,autoPair:`apk`,connection:`cnx`,fnExample:`fex`,refusal:`rfs`,record:`rec`,mentionRequest:`mrq`},tl=e=>v().regex(RegExp(`^${el[e]}_.+$`),`expected a ${e} id starting with "${el[e]}_"`).brand().describe(`${e} id`),nl=e=>Object.hasOwn(el,e);function rl(){return Object.fromEntries(Object.keys(el).filter(nl).map(e=>[e,tl(e)]))}var k=v().regex(/^[A-Za-z_][A-Za-z0-9_.-]*$/),il=rl(),A=il.run,al=il.turn,j=il.session,M=il.actor,ol=il.message,sl=il.delivery,cl=il.handlerCall,ll=il.llmInteraction,ul=il.pairing,dl=il.pairingToken,fl=il.policy,pl=il.approval,ml=il.budget,hl=il.priorityRule,gl=il.reservation,_l=il.ledger,vl=il.notification,yl=il.push,bl=il.secret,xl=il.modelCategory,Sl=il.provider,Cl=il.sectionRule,wl=il.authSession,Tl=il.modelCall,El=il.mcp,Dl=il.autoPair,Ol=il.connection,kl=y().int().min(0),N=y().int(),P=y(),Al=/^[a-z][a-z0-9-]*$/,F=v().regex(Al).brand(),I=Wc([v().regex(Al),`/`,v().min(1)]),jl=C([D(`native`),I]);function Ml(e,t){return`${e}/${t}`}function Nl(e){let t=e.indexOf(`/`);return{system:e.slice(0,t),local:e.slice(t+1)}}var Pl=[`urgent`,`interactive`,`normal`,`background`],Fl=E(Pl),Il=E([`user`,`llm`,`both`,`none`]),Ll=E([`user`,`group`,`agent`,`system`,`mcp`]),Rl=e=>S({items:x(e),cursor:v().optional()}),zl=S({cursor:v().optional(),limit:y().int().min(1).max(200).optional()});function Bl(e){return e instanceof Error?e.message:String(e)}var Vl=`read`,Hl=`admin`,L=v().regex(Al).brand(),Ul=L.parse(`main`),Wl=S({system:F,instance:L}),Gl=v().regex(/^[a-z*][a-z0-9*-]*\/[A-Za-z0-9_.*-]+$/).brand(),Kl=Object.defineProperty,ql=(e,t)=>{for(var n in t)Kl(e,n,{get:t[n],enumerable:!0})},R={};ql(R,{array:()=>dp,boolean:()=>rp,codec:()=>Tp,conditional:()=>vp,declare:()=>Op,default:()=>xp,define:()=>Dp,dependent:()=>yp,discriminatedUnion:()=>hp,dispatch:()=>Ep,enum:()=>op,fromJSONSchema:()=>Qf,int:()=>np,intersection:()=>gp,json:()=>lp,literal:()=>ap,module:()=>kp,never:()=>sp,not:()=>_p,null:()=>ip,nullable:()=>Sp,number:()=>tp,object:()=>up,optional:()=>bp,record:()=>pp,ref:()=>Cp,refOf:()=>wp,string:()=>ep,tuple:()=>fp,union:()=>mp,unknown:()=>cp});var Jl=Object.freeze({length:!0,range:!0,items:`all`,pattern:`full`}),Yl=Object.freeze({length:!1,range:!1,items:`none`,pattern:`none`}),Xl=Object.freeze({id:`lenient`,family:`lenient`,strict:!1,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!0,conditionals:!0,patternProperties:!0,defs:!0,recursion:!0,any:`empty`,constraints:Jl,formats:`all`,examples:`keyword`,propertyOrdering:!1,rootObject:!1}),Zl=Object.freeze({...Xl,id:`people`,family:`people`,audience:`people`}),Ql=Object.freeze({...Xl,id:`openai`,family:`openai`,rootObject:!0,request:Object.freeze({maxTools:128})}),$l=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`ipv4`,`ipv6`,`uuid`]),eu=Object.freeze({id:`openai-strict`,family:`openai`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`anyOf`,nulls:`anyOf`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,refSiblings:!1,recursion:!0,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:$l,examples:`description`,propertyOrdering:!1,maxDepth:10,rootObject:!0,limits:Object.freeze({maxProperties:5e3,maxDepth:10,maxStringChars:12e4,maxEnumValues:1e3,largeEnumValues:250,maxLargeEnumChars:15e3}),request:Object.freeze({maxTools:128}),loose:Ql}),tu=Object.freeze({...eu,id:`openai-finetuned-strict`,constraints:Yl,formats:new Set}),nu=Object.freeze({...Xl,id:`anthropic`,family:`anthropic`,rootObject:!0}),ru=Object.freeze({id:`anthropic-strict`,family:`anthropic`,strict:!0,optional:`omit`,closedObjects:!0,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!1,range:!1,items:`min-0-1`,pattern:`basic`}),formats:new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]),examples:`description`,propertyOrdering:!1,rootObject:!0,request:Object.freeze({maxStrictTools:20,totals:Object.freeze({maxOptional:24,maxUnions:16})}),loose:nu,alwaysStrictOutput:!0}),iu=`Return ONLY a single raw JSON object that conforms to the schema above. Do NOT wrap it in markdown code fences, do NOT add any prose before or after it, and do NOT echo the schema itself: emit only the JSON instance.`,au=Object.freeze({...Xl,id:`google`,family:`google`,recursion:`guarded`,maxEnumValues:40,rootObject:!0,jsonInstruction:iu}),ou=Object.freeze({id:`google-strict`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:`guarded`,any:`empty`,constraints:Object.freeze({length:!1,range:!0,items:`all`,pattern:`none`}),formats:new Set([`date-time`,`date`,`time`]),examples:`description`,propertyOrdering:!1,maxEnumValues:40,rootObject:!0,loose:au,jsonInstruction:iu}),su=Object.freeze({id:`google-openapi`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`nullable`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:new Set([`date-time`,`date`,`time`,`duration`]),examples:`description`,propertyOrdering:!0,maxEnumValues:40,maxDepth:10,rootObject:!0,loose:au,jsonInstruction:iu}),cu=new Set([`date`,`time`,`date-time`,`email`,`uuid`,`ipv4`,`ipv6`,`uri`]),lu=Object.freeze({id:`xai-strict`,family:`xai`,strict:!0,optional:`omit`,closedObjects:!0,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`flat`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:cu,examples:`description`,propertyOrdering:!1,rootObject:!0}),uu=Object.freeze({...lu,id:`xai`,strict:!1}),du=Object.freeze({...Xl,id:`ollama`,family:`ollama`,rootObject:!0}),fu=Object.freeze({id:`minimal`,family:`minimal`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`tagged`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Yl,formats:new Set,examples:`description`,propertyOrdering:!1,maxDepth:6,maxEnumValues:8,rootObject:!0}),pu=new Map,mu=new Map;function hu(e){pu.set(e.id,e);let t=mu.get(e.family)??{};e.strict?t.strict??=e:t.loose??=e,mu.set(e.family,t)}for(let e of[Xl,Zl,Ql,eu,tu,nu,ru,au,ou,su,lu,uu,du,fu])hu(e);var gu=new WeakMap;function _u(e){let t=gu.get(e);return t||(t=Object.freeze({profile:e,records:e.records,optional:e.optional,recordWord:e.records===`pairs`?`a list of {key, value} entries`:`an object`}),gu.set(e,t)),t}Object.freeze({properties:0,depth:0,stringChars:0,enumValues:0,enums:Object.freeze([]),optional:0,unions:0});function vu(e){let t=0,n=0,r=0,i=0,a=0,o=[],s=e.$defs??{};for(let e of Object.keys(s))n+=e.length;let c=e=>{if(!e||typeof e!=`object`)return;if(Array.isArray(e)){for(let t of e)c(t);return}let s=e;if(s.properties&&typeof s.properties==`object`){let e=s.properties,r=new Set(Array.isArray(s.required)?s.required:[]);for(let[a,o]of Object.entries(e))t++,n+=a.length,r.has(a)||i++,c(o)}if(Array.isArray(s.enum)){let e=0;for(let t of s.enum)typeof t==`string`&&(e+=t.length);r+=s.enum.length,n+=e,o.push({values:s.enum.length,chars:e})}typeof s.const==`string`&&(n+=s.const.length);let l=s.anyOf??s.oneOf;(Array.isArray(l)&&l.length>1||Array.isArray(s.type)&&s.type.length>1)&&a++;for(let e of[`items`,`prefixItems`,`anyOf`,`oneOf`,`allOf`,`additionalProperties`,`not`,`if`,`then`,`else`])e in s&&c(s[e]);if(s.patternProperties&&typeof s.patternProperties==`object`)for(let e of Object.values(s.patternProperties))c(e)},{$defs:l,...u}=e;c(u);for(let e of Object.values(s))c(e);let d=e=>{if(typeof e.$ref==`string`)return/^#\/\$defs\/(.+)$/.exec(e.$ref)?.[1]?.replace(/~1/g,`/`).replace(/~0/g,`~`)},f=yu(s,d),p=new Set,m=new Map,h=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e;if(typeof t.$ref==`string`){let e=d(t);if(!e||p.has(e)||!s[e])return 0;let n=f.get(e),r=e;if(n){r+=`|`;for(let e of n)r+=p.has(e)?`1`:`0`}let i=m.get(r);if(i!==void 0)return i;p.add(e);let a=h(s[e]);return p.delete(e),m.set(r,a),a}let n=t.type===`object`||t.type===`array`||Array.isArray(t.type)&&(t.type.includes(`object`)||t.type.includes(`array`)),r=0,i=e=>{let t=h(e);t>r&&(r=t)};if(t.properties&&typeof t.properties==`object`)for(let e of Object.values(t.properties))i(e);for(let e of[`items`,`additionalProperties`,`not`])e in t&&i(t[e]);for(let e of[`prefixItems`,`anyOf`,`oneOf`,`allOf`])if(Array.isArray(t[e]))for(let n of t[e])i(n);return+!!n+r},ee=h(u);return{properties:t,depth:ee,stringChars:n,enumValues:r,enums:o,optional:i,unions:a}}function yu(e,t){let n=new Map,r=(n,i)=>{if(!n||typeof n!=`object`)return;if(Array.isArray(n)){for(let e of n)r(e,i);return}let a=t(n);a!==void 0&&e[a]&&i.add(a);for(let e of Object.values(n))r(e,i)};for(let t of Object.keys(e)){let i=new Set;r(e[t],i),n.set(t,[...i])}let i=new Map,a=new Map,o=new Set,s=[],c=new Map,l=0;for(let e of n.keys()){if(i.has(e))continue;let t=[[e,0]];for(;t.length;){let e=t[t.length-1],[r,u]=e;u===0&&(i.set(r,l),a.set(r,l),l++,s.push(r),o.add(r));let d=n.get(r);if(u<d.length){e[1]++;let n=d[u];i.has(n)?o.has(n)&&a.set(r,Math.min(a.get(r),i.get(n))):t.push([n,0]);continue}t.pop();let f=t[t.length-1];if(f&&a.set(f[0],Math.min(a.get(f[0]),a.get(r))),a.get(r)===i.get(r)){let e=[],t;do t=s.pop(),o.delete(t),e.push(t);while(t!==r);if(e.length>1||d.includes(r))for(let t of e)c.set(t,e)}}}return c}var bu=class extends Error{constructor(e){super(`@aeye/schema: ${e}`),this.name=`SchemaDefinitionError`}},xu=class extends Error{constructor(e,t=Vd(e)){super(t),this.issues=e,this.name=`SchemaParseError`}issues};function Su(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function Cu(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function wu(e,t,n=Cu(e.length)){let r=e.toLowerCase(),i=[];for(let a=0;a<t.length;a++){let o=t[a];if(Math.abs(o.length-e.length)>n)continue;let s=Su(r,o.toLowerCase());s<=n&&i.push({candidate:o,index:a,ci:s,exact:Su(e,o)})}return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function Tu(e,t,n){return wu(e,t,n)[0]}var Eu=Object.freeze({detail:`full`,maxErrors:5,maxChars:2e3,suggestions:!0,context:3,depth:6,header:!0});function Du(...e){let t;for(let n of e)n!==void 0&&(t={...t,...ku(typeof n==`string`?{detail:n}:n)});return t}function Ou(...e){let t=Du(...e)??{},n=t.detail??Eu.detail;return{...Eu,...t,detail:n,expected:t.expected??n===`full`}}function ku(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Au(e){let t=typeof e==`string`?e:e?.detail??Eu.detail;return t===`markers`||t===`full`}var ju=new WeakMap;function Mu(e,t){ju.set(e,t)}function Nu(e,t,n){for(let r=t;r<e.length;r++){let t=ju.get(e[r]);t&&!t.node&&(t.node=n)}}var Pu=/^[A-Za-z_$][\w$]*$/;function Fu(e){let t=``,n=``;for(let r of e)r===`(json)`?(t+=`${n||`(root)`} \u2192 JSON text \u2192 `,n=``):n+=typeof r==`number`?`[${r}]`:Pu.test(r)?n?`.${r}`:r:`[${JSON.stringify(r)}]`;return t&&!n?t.slice(0,-3):t+(n||(t?``:`(root)`))}var Iu=Symbol(`absent`);function Lu(e,t){let n=e;for(let e of t)if(e===`(json)`){if(typeof n!=`string`)continue;if(n=zu(n),n===Iu)return Iu}else{if(typeof n==`string`&&(n=zu(n)),typeof n!=`object`||!n||!Object.prototype.hasOwnProperty.call(n,e))return Iu;n=n[e]}return n}var Ru;function zu(e){let t=Ru?.get(e);if(t!==void 0)return t;let n;try{n=JSON.parse(e)}catch{n=Iu}return Ru?.set(e,n),n}function Bu(e,t=160){for(let n of[2,1,0]){let r=Hu(e,n,6);if(r.length<=t)return r}let n=Hu(e,0,3);return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Vu(e){return e.replace(/^#\/\$defs\//,``).replace(/~1/g,`/`).replace(/~0/g,`~`)}function Hu(e,t,n){if(typeof e.$ref==`string`)return Vu(e.$ref);if(`const`in e)return JSON.stringify(e.const);if(Array.isArray(e.enum))return Wu(e.enum.map(e=>JSON.stringify(e)),n,` | `);let r=e.anyOf??e.oneOf;if(Array.isArray(r))return Wu([...new Set(r.map(e=>Hu(e,t,n)))],n,` | `,`options`);if(Array.isArray(e.allOf))return e.allOf.map(e=>Uu(Hu(e,t,n))).join(` & `);if(Array.isArray(e.type))return e.type.map(r=>Hu({...e,type:r},t,n)).join(` | `);if(e.nullable===!0)return`${Uu(Hu({...e,nullable:!1},t,n))} | null`;switch(e.type){case`string`:if(typeof e.description==`string`&&/JSON text/.test(e.description)){let t=/TypeScript type: ([^\n(]+?)(?: \(its named types|\.\s*$)/.exec(e.description);return t?`string (JSON text of ${t[1].trim()})`:`string (JSON text)`}return typeof e.format==`string`?`string (${e.format})`:`string`;case`integer`:return`integer`;case`number`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:return Array.isArray(e.prefixItems)?`[${e.prefixItems.map(e=>Hu(e,t-1,n)).join(`, `)}]`:`${Uu(e.items&&typeof e.items==`object`?Hu(e.items,t-1,n):`any`)}[]`;case`object`:{let r=e.properties??{},i=Object.keys(r),a=e.additionalProperties&&typeof e.additionalProperties==`object`?e.additionalProperties:void 0;if(!i.length&&!a)return e.additionalProperties===!1?`{}`:`object`;if(t<=0)return`{…}`;let o=new Set(e.required??[]),s=i.slice(0,n).map(e=>`${Pu.test(e)?e:JSON.stringify(e)}${o.has(e)?``:`?`}: ${Hu(r[e],t-1,n)}`);return i.length>n&&s.push(`\u2026 ${i.length-n} more`),a&&s.push(`[key: string]: ${Hu(a,t-1,n)}`),`{ ${s.join(`; `)} }`}default:return`any JSON value`}}function Uu(e){return/ \| | & /.test(e)&&!/^[{[(]/.test(e)?`(${e})`:e}function Wu(e,t,n,r=`more`){return e.length<=t?e.join(n):`${e.slice(0,t).join(n)}${n}\u2026 (${e.length} ${r===`more`?`values`:r})`}function Gu(e,t){let n=t?.node;if(n&&t&&t.kind!==`enum`&&t.kind!==`literal`&&t.kind!==`tag`&&t.kind!==`tool`&&t.kind!==`rule`&&t.kind!==`unknown-key`&&t.kind!==`not-allowed`)try{if(n.jsonText&&n.schema){let e=n.typeText();return`string (JSON text of ${e.length>120?`${e.slice(0,119)}\u2026`:e})`}let e=Bu(n.json());return t.kind===`type`&&/^(string|number|integer|boolean|null)$/.test(e)?void 0:e}catch{return}}function Ku(e){let t=e.message;for(let n of e.path)t+=`\0${typeof n==`number`?`#`:n}`;return t}function qu(e){let t=[],n=new Map;for(let r of e){let e=Ku(r),i=n.get(e);if(i){i.paths.push(r.path);continue}let a={issue:r,info:ju.get(r),paths:[r.path]};n.set(e,a),t.push(a)}return t}function Ju(e,t){let n=e.issue.message,r=e.info?.kind;if(t.terse&&e.info?.candidates&&(r===`enum`||r===`tag`||r===`tool`)){let t=e.info.candidates().length;n=n.replace(/ one of: .*$/s,` one of ${t} value${t===1?``:`s`}.`)}if(t.suggestions&&e.info?.candidates){let t=Yu(e.issue,e.info);t&&(n=n.replace(/\.$/,``)+t)}if(e.paths.length>1){if(t.terse)n+=` (the same at ${e.paths.length-1} more place${e.paths.length===2?``:`s`})`;else{let t=e.paths.slice(1,3).map(Fu),r=e.paths.length-1-t.length;n+=` (the same at ${t.join(`, `)}${r>0?` and ${r} more place${r===1?``:`s`}`:``})`}}return n.length>400?`${n.slice(0,399)}\u2026`:n}function Yu(e,t){let n=t.candidates();if(!n.length)return``;if(t.kind===`required`){let t=e.path[e.path.length-1];if(typeof t!=`string`)return``;let r=Tu(t,n);return r?` \u2014 you wrote \`${r}\`; did you mean \`${t}\`?`:``}let r=t.kind===`unknown-key`?e.path[e.path.length-1]:t.received;if(typeof r!=`string`)return``;let i=wu(r,n)[0];return i!==void 0&&i!==r?` \u2014 did you mean \`${i}\`?`:``}function Xu(e,t,n,r=`your answer`){if(!e.length)return``;let i=Qu(n)?n:Ou(n),a=qu(i.suggestions?Zu(e):e),o=Ru;Ru=new Map;try{for(let e of $u(i)){let n=td(a,t,e,r);if(n.length<=i.maxChars)return n}let e=td(a,t,{...i,detail:`summary`,maxErrors:1,terse:!0},r);return e.length<=i.maxChars?e:`${e.slice(0,Math.max(0,i.maxChars-1))}\u2026`}finally{Ru=o}}function Zu(e){let t,n=0;for(let r of e){let e=ju.get(r);if(e?.kind!==`required`||!e.candidates||++n>50)continue;let i=r.path[r.path.length-1],a=typeof i==`string`?Tu(i,e.candidates()):void 0;a!==void 0&&(t??=new Set).add(nd([...r.path.slice(0,-1),a]))}return t?e.filter(e=>!(ju.get(e)?.kind===`unknown-key`&&t.has(nd(e.path)))):e}function Qu(e){return typeof e==`object`&&!!e&&`detail`in e&&`maxChars`in e&&`expected`in e&&`context`in e&&`depth`in e&&`header`in e&&`suggestions`in e&&`maxErrors`in e}function*$u(e){for(let t of ed(e))yield t,yield{...t,terse:!0}}function*ed(e){let t=e;if(yield t,t.detail===`markers`||t.detail===`full`){for(t.expected&&(yield t={...t,expected:!1}),t.context>0&&(yield t={...t,context:0}),t.depth>2&&(yield t={...t,depth:2});t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};yield t={...t,detail:`list`,maxErrors:e.maxErrors}}for(;t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};t.detail!==`summary`&&(yield{...t,detail:`summary`})}function td(e,t,n,r){let i=e.slice(0,Math.max(1,n.maxErrors)),a=e.reduce((e,t)=>e+t.paths.length,0),o=e.length-i.length,s=e.slice(i.length).reduce((e,t)=>e+t.paths.length,0),c=`${a} problem${a===1?``:`s`}`;if(n.detail===`summary`){let e=i[0],t=a-e.paths.length;return`${n.header?`${a===1?`A problem`:c} in ${r}: `:``}at ${Fu(e.issue.path)}: ${Ju(e,n)}${t>0?` (and ${t} more problem${t===1?``:`s`})`:``}`}let l=[];if(n.header&&l.push(`${c} in ${r}:`),n.detail===`list`)for(let e of i){let t=n.expected?Gu(e.issue,e.info):void 0;l.push(`- at ${Fu(e.issue.path)}: ${Ju(e,n)}${t?` (expected: ${t})`:``}`)}else n.header&&l.push(``),l.push(...od(i,t,n));return s>0&&l.push(`\u2026 and ${s} more problem${s===1?``:`s`}${o>1?` (${o} kinds)`:``} not shown.`),l.join(`
56
- `)}var nd=e=>{let t=``;for(let n of e)t+=`${typeof n==`number`?`#`:`$`}${n}\0`;return t};function rd(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n];if(r!==i)return typeof r==`number`&&typeof i==`number`?r-i:String(r)<String(i)?-1:1}return e.length-t.length}function id(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}var ad=e=>e.filter(e=>e!==`(json)`).length;function od(e,t,n){let r=[],i=[];for(let n of e){let e=n.issue.path,a=n.info?.kind;t===void 0?i.push(n):Lu(t,e)===Iu?e.length&&sd(Lu(t,e.slice(0,-1)))?r.push({p:n,at:e.slice(0,-1),where:`missing`}):i.push(n):r.push({p:n,at:e,where:a===`unknown-key`||a===`not-allowed`?`key`:`value`})}r.sort((e,t)=>rd(e.p.issue.path,t.p.issue.path));let a=[],o=e=>{let t=[];for(let r of e){if(ad(e)-ad(t)<=n.depth)break;t.push(r)}return t};for(let e of r){let t=a[a.length-1];if(t){let r=id(t.anchor,e.at);if([...t.members,e].every(e=>ad(e.at)-ad(r)<=n.depth+1)){t.anchor=r,t.members.push(e);continue}}a.push({anchor:o(e.at),members:[e]})}let s=[];for(let e of a){let r=e.anchor;for(;r.length&&Lu(t,r)===Iu;)r=r.slice(0,-1);let i=new Map,a=new Map;for(let t of e.members){let e=nd(t.at),n=i.get(e);n?n.push({p:t.p,where:t.where}):i.set(e,[{p:t.p,where:t.where}]);for(let e=r.length;e<t.at.length;e++){let n=nd(t.at.slice(0,e)),r=a.get(n);r?r.add(t.at[e]):a.set(n,new Set([t.at[e]]))}}s.length&&s.push(``),r.length&&s.push(`at ${Fu(r)}:`),new ld(i,a,n,s,r.length).node(Lu(t,r),r,``,``,``)}for(let e of i)s.push(`- at ${Fu(e.issue.path)}: ${Ju(e,n)}`);return s}var sd=e=>typeof e==`object`&&!!e;function cd(e){if(!e.length)return`…`;let t=e[0],n=Fu(e);return t===`(json)`?`\u2026 \u2192 ${n.replace(/^\(root\) → /,``)}`:typeof t==`number`||!Pu.test(t)?`\u2026${n}`:`\u2026.${n}`}var ld=class{constructor(e,t,n,r,i=0){this.marks=e,this.below=t,this.f=n,this.out=r,this.from=i}marks;below;f;out;from;node(e,t,n,r,i){let a=nd(t),o=this.below.has(a);if(typeof e==`string`&&o){let a=zu(e);if(a!==Iu){let e=[...t,`(json)`],o=nd(e);return this.marks.has(o)||this.below.has(o)?this.node(a,e,n,`${r}/* JSON text */ `,i):this.node(a,t,n,r,i)}}let s=this.marks.get(a)??[];if(!(sd(e)&&(o||s.some(e=>e.where===`missing`)))){let t=ud(e,60);this.out.push(n+r+t+i);for(let e of s)e.where===`key`?this.mark(e.p,n.length,r.length+t.length):this.mark(e.p,n.length+r.length,t.length);return}let c=Array.isArray(e);this.out.push(`${n}${r}${c?`[`:`{`}`);for(let e of s)this.mark(e.p,n.length+r.length,1);let l=`${n} `;c?this.items(e,t,l):this.keys(e,t,l),this.out.push(`${n}${c?`]`:`}`}${i}`)}keys(e,t,n){let r=Object.keys(e),i=this.below.get(nd(t)),a=r.filter(e=>i?.has(e)),o=r.filter(e=>!a.includes(e)),s=new Set(o.filter(t=>ud(e[t],40).length<=40&&!sd(e[t])).slice(0,this.f.context));for(let e of o)s.size<this.f.context&&!s.has(e)&&s.add(e);let c=r.filter(e=>a.includes(e)||s.has(e)),l=r.length-c.length;c.forEach((r,i)=>{let a=i===c.length-1&&!l;this.node(e[r],[...t,r],n,`${JSON.stringify(r)}: `,a?``:`,`)}),l&&this.out.push(`${n}\u2026 ${l} more key${l===1?``:`s`}`)}items(e,t,n){let r=new Set;for(let n of this.below.get(nd(t))??[])typeof n==`number`&&n<e.length&&r.add(n);let i=e.length-r.size<=this.f.context&&e.every((e,t)=>r.has(t)||ud(e,40).length<=40),a=0,o=!1,s=()=>{a&&(this.out.push(`${n}\u2026 ${a} item${a===1?``:`s`}`),a=0,o=!0)};for(let c=0;c<e.length;c++){if(!i&&!r.has(c)){a++;continue}s();let l=c===e.length-1,u=o||!i&&c>0?`/* ${c} */ `:``;this.node(e[c],[...t,c],n,u,l?``:`,`)}s()}mark(e,t,n){let r=Math.max(1,Math.min(n,40)),i=`${this.from?cd(e.issue.path.slice(this.from)):Fu(e.issue.path)}: ${Ju(e,this.f)}`;this.out.push(`${` `.repeat(t)}${`^`.repeat(r)} ${i}`);let a=this.f.expected?Gu(e.issue,e.info):void 0;a&&this.out.push(`${` `.repeat(t+r+1)}expected: ${a}`)}};function ud(e,t){if(typeof e==`string`){let n=JSON.stringify(e);return n.length<=t?n:`${n.slice(0,t-2)}\u2026"`}if(!sd(e))return e===void 0?`undefined`:JSON.stringify(e);let n=dd(e,t);if(n!==void 0)return n;if(Array.isArray(e))return`[\u2026 ${e.length} item${e.length===1?``:`s`}]`;let r=Object.keys(e).length;return`{\u2026 ${r} key${r===1?``:`s`}}`}function dd(e,t){let n=``,r=e=>{if(n.length>t)return!1;if(Array.isArray(e)){n+=`[`;for(let t=0;t<e.length;t++)if(t&&(n+=`,`),!r(e[t]))return!1;return n+=`]`,n.length<=t}if(sd(e)){n+=`{`;let i=!0;for(let t of Object.keys(e)){let a=e[t];if(a!==void 0&&(i||(n+=`,`),i=!1,n+=`${JSON.stringify(t)}:`,!r(a)))return!1}return n+=`}`,n.length<=t}return n+=e===void 0?`null`:JSON.stringify(e),n.length<=t};return r(e)?n:void 0}var fd=class{constructor(e){this.issues=e}issues};function pd(){return{objects:0,arrays:0,edits:0,parsed:0,repaired:0}}function md(e){let t=``;for(let n of e)t+=typeof n==`number`?`[${n}]`:/^[A-Za-z_$][\w$]*$/.test(n)?t?`.${n}`:n:`[${JSON.stringify(n)}]`;return t||`(root)`}var hd=Object.freeze({path:[],codePath:[],message:``}),gd=pd(),_d=Symbol(`absent`),vd=Symbol(`order`),yd,bd=class e{constructor(e,t,n,r=!0,i=!1){this.inPlace=e,this.dry=t,this.stats=n,this.repair=r,this.countOnly=i}inPlace;dry;stats;repair;countOnly;errors=[];undo;undoN=0;wire=[];code=[];wd=0;cd=0;fail(e,t=`other`,n,r,i){if(this.countOnly){this.errors.push(hd);return}let a={path:this.wire.slice(0,this.wd),codePath:this.code.slice(0,this.cd),message:e};this.errors.push(a),Mu(a,{kind:t,node:i,received:n,candidates:r})}failAt(e,t,n=`rule`){if(!e.length)return this.fail(t,n);if(this.countOnly){this.errors.push(hd);return}let r={path:[...this.wire.slice(0,this.wd),...e],codePath:[...this.code.slice(0,this.cd),...e],message:t};this.errors.push(r),Mu(r,{kind:n})}enter(e,t=e){this.wire[this.wd++]=e,t!==null&&(this.code[this.cd++]=t)}leave(e=!0){this.wd--,e&&this.cd--}dryRun(t=!1){if(!t)return new e(!1,!0,gd,this.repair,!0);let n=new e(!1,!0,gd,this.repair);for(let e=0;e<this.wd;e++)n.wire[n.wd++]=this.wire[e];for(let e=0;e<this.cd;e++)n.code[n.cd++]=this.code[e];return n}saving(e,t,n=!1){let r=this.undo;if(!r)return;n&&this.ordered!==e&&(this.ordered=e,r[this.undoN++]=e,r[this.undoN++]=vd,r[this.undoN++]=Object.keys(e));let i=Object.prototype.hasOwnProperty.call(e,t);r[this.undoN++]=e,r[this.undoN++]=t,r[this.undoN++]=i?e[t]:_d}ordered;restore(){let e=this.undo;if(e)for(let t=this.undoN-3;t>=0;t-=3){let n=e[t],r=e[t+1],i=e[t+2];if(r===vd)for(let e of i){let t=n[e];delete n[e],n[e]=t}else i===_d?delete n[r]:n[r]=i}}keepUndo(){this.undo=yd??[],yd=void 0,this.undoN=0}releaseUndo(){let e=this.undo;if(e){for(let t=0;t<this.undoN;t++)e[t]=void 0;this.undo=void 0,this.undoN=0,e.length<=65536&&(yd=e)}}},xd=class{constructor(e,t){this.impl=e,this.compiler=t}impl;compiler;needs=!1;schema;outer;jsonText=!1;_json;get own(){return!!this.impl?.own}get deps(){return this.impl?.deps??[]}json(){return this._json||=this.compiler.decorate(this,this.impl.emit()),this._json}run(e,t){let n=t.errors,r=n.length,i=this.impl.run(e,t);return n.length===r&&(this.schema?.checks.length&&this.check(i,t,this.schema),this.outer?.checks.length&&n.length===r&&this.check(i,t,this.outer),n.length===r)||t.countOnly||Nu(n,r,this),i}check(e,t,n){if(n)for(let r of n.checks){let n=r.fn(e);if(n!==!0){if(Array.isArray(n))for(let e of n)typeof e==`string`?t.fail(e,`rule`):t.failAt(e.path,e.message,`rule`);else t.fail(typeof n==`string`?n:r.message??`Failed a check.`,`rule`)}}}typeText(){return this.schema?this.schema.print(new Sd(this.compiler.env)):`any JSON value`}encode(e,t=pd()){return this.needs?this.impl.encode(e,t):e}child(e){return this.impl?.child?.(e)}},Sd=class{constructor(e){this.env=e}env;names=new Set;print(e){return e.print(this)}ref(e){return this.names.add(e),e}used(){return[...this.names]}definitions(e){for(let t of e)this.names.add(t);let t=[],n=new Set;for(let e=!0;e;){e=!1;for(let r of[...this.names]){if(n.has(r))continue;n.add(r),e=!0;let i=this.env.get(r);i&&t.push(`type ${r} = ${i.print(this)}`)}}return t.join(`
55
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function io(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;io(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ao=new Set([`type`,`properties`,`required`,`additionalProperties`]),oo=[`oneOf`,`anyOf`];function so(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function co(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ao.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??so(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}u(n,r,e.length===1?e[0]:co(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=so(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function lo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ao)if(t in e)return;let n=t.filter(e=>oo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=co(t);else{let e=n[0],i=oo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>co([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Qa(e,r))}function uo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Qa(i,s),Qa(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())io(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])lo(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Qa(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,u(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:mo(t,`input`,e.processors),output:mo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function fo(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return fo(r.element,n);if(r.type===`set`)return fo(r.valueType,n);if(r.type===`lazy`)return fo(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return fo(r.innerType,n);if(r.type===`intersection`)return fo(r.left,n)||fo(r.right,n);if(r.type===`record`||r.type===`map`)return fo(r.keyType,n)||fo(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:fo(r.in,n)||fo(r.out,n);if(r.type===`object`){for(let e in r.shape)if(fo(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(fo(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(fo(e,n))return!0;return!!(r.rest&&fo(r.rest,n))}return!1}var po=(e,t={})=>n=>{let r=$a({...n,processors:t});return to(e,r),ro(r,e),uo(r,e)},mo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=$a({...i??{},target:a,io:t,processors:n});return to(e,o),ro(o,e),uo(o,e)},ho=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},go=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},_o=(e,t)=>{ho(e,`minimum`,t),go(e,`maximum`,t)},vo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},yo=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},bo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},xo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},So=(e,t)=>ho(e,`minimum`,t.minimum),Co=(e,t)=>go(e,`maximum`,t.maximum),wo=e=>(t,n)=>{xo(t,n.format);let[r,i]=e[n.format];ho(t,`minimum`,r),go(t,`maximum`,i)},To={greater_than:(e,t)=>ho(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>go(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>vo(e,t.value),number_format:wo(he),bigint_format:wo(ge),min_length:So,max_length:Co,length_equals:(e,t)=>_o(e,t.length),min_size:So,max_size:Co,size_equals:(e,t)=>_o(e,t.size),string_format:(e,t)=>{xo(e,t.format),t.pattern&&yo(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>bo(e,t.mime)};function Eo(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)To[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&ho(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&ho(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&go(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&go(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&vo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&bo(t,i.mime);for(let e of i.patterns??[])yo(t,e);return t}var Do={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Oo=new Map([[_r,Xt],[yr,Zt]]),ko=e=>Oo.get(e)??e,Ao=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=Eo(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Do[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(ko);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},jo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Eo(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):eo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Mo=(e,t,n,r)=>{n.type=`boolean`},No=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Po=(e,t,n,r)=>{n.not={}},Fo=(t,n,r,i)=>{let a=t._zod.def,o=e(a.entries);o.length===0?r.not={}:(o.every(e=>typeof e==`number`)&&(r.type=`number`),o.every(e=>typeof e==`string`)&&(r.type=`string`),r.enum=o)},Io=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(eo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(eo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Lo=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Ro=(e,t,n,r)=>{eo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},zo=(e,t,n,r)=>{eo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Bo=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=Eo(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=to(a.element,t,{...r,path:[...r.path,`items`]})};function Vo(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Vo(t.out):t.type===`catch`?Vo(t.innerType):e._zod.optin}var Ho=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&eo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)u(i.properties,e,to(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Vo(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=to(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Uo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>to(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Wo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=to(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},Go=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>to(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?to(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?Vo(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=Eo(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function Ko(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Ko(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Ko(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?un:ln).source)),p}var qo=new WeakMap;function Jo(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of qo.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Ko(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var Yo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=Eo(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=to(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)u(i.patternProperties,ko(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=to(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=qo.get(t);n||(n=[],qo.set(t,n),t.deferred.push(()=>Jo(t))),n.push(e)}i.additionalProperties=to(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Vo(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Xo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Zo=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Qo=Symbol();function $o(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(eo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Qo):JSON.parse(o)}var es=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n.default=o)},ts=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n._prefault=o)},ns=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{eo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},rs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;to(o,t,r);let s=t.seen.get(e);s.ref=o},is=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},as=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},os=(e,t,n,r)=>{let i=e._zod.innerType;to(i,t,r);let a=t.seen.get(e);a.ref=i},ss=new WeakSet([Object.prototype,Error.prototype]);function cs(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var ls=_(`ZodError`,(e,t)=>{ut.init(e,t),e.name=`ZodError`;let r=Object.getPrototypeOf(e);ss.has(r)||(ss.add(r),cs(r,`format`,e=>t=>pt(e,t)),cs(r,`flatten`,e=>t=>ft(e,t)),cs(r,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,n,2)}),cs(r,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,n,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),us=ht(ls),ds=gt(ls),fs=_t(ls),ps=yt(ls),ms=Tt(ls),hs=Et(ls),gs=Dt(ls),_s=Ot(ls),vs=kt(ls),ys=At(ls),bs=jt(ls),xs=Mt(ls);function Ss(){rt.localeError||it(Hi())}function Cs(){rt.memoizer||it({memoizer:zi()})}var ws=_(`ZodType`,(e,t)=>(Ss(),Fn.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(te(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return fe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Yc(e,t))},superRefine(e,t){return this.check(Xc(e,t))},overwrite(e){return this.check(Va(e))},optional(){return Ec(this)},exactOptional(){return Oc(this)},nullable(){return Ac(this)},nullish(){return Ec(Ac(this))},nonoptional(e){return Ic(this,e)},array(){return x(this)},or(e){return C([this,e])},and(e){return gc(this,e)},transform(e){return Bc(this,wc(e))},default(e){return Mc(this,e)},prefault(e){return Pc(this,e)},catch(e){return Rc(this,e)},pipe(e){return Bc(this,e)},readonly(){return Hc(this)},describe(e){let t=this.clone();return Ki.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ki.get(this);let t=this.clone();return Ki.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Be(this,`~standard`,{...Rn(this),jsonSchema:{input:mo(this,`input`),output:mo(this,`output`)}})},set"~standard"(e){ze(this,`~standard`,e)},parse:function e(t,n){return us(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await ds(this,t,n,{callee:e})},safeParse(e,t){return fs(this,e,t)},async safeParseAsync(e,t){return ps(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){ze(this,`spa`,e)},validate(e,t){return St(this,e,t)},validateAsync(e,t){return wt(this,e,t)},encode:function e(t,n){return ms(this,t,n,{callee:e})},decode:function e(t,n){return hs(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await gs(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await _s(this,t,n,{callee:e})},safeEncode(e,t){return vs(this,e,t)},safeDecode(e,t){return ys(this,e,t)},async safeEncodeAsync(e,t){return bs(this,e,t)},async safeDecodeAsync(e,t){return xs(this,e,t)},toJSONSchema(e){return po(this,{})(e)},get description(){return Ki.get(this)?.description},get _def(){return this._zod.def}}),Ts=_(`_ZodString`,(e,t)=>{zn.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r)},Ve({format:e=>Eo(e).format??null,minLength:e=>Eo(e).minimum??null,maxLength:e=>Eo(e).maximum??null},{regex(...e){return this.check(Fa(...e))},includes(...e){return this.check(Ra(...e))},startsWith(...e){return this.check(za(...e))},endsWith(...e){return this.check(Ba(...e))},min(...e){return this.check(Na(...e))},max(...e){return this.check(Ma(...e))},length(...e){return this.check(Pa(...e))},nonempty(...e){return this.check(Na(1,...e))},lowercase(e){return this.check(Ia(e))},uppercase(e){return this.check(La(e))},trim(){return this.check(Ua())},normalize(...e){return this.check(Ha(...e))},toLowerCase(){return this.check(Wa())},toUpperCase(){return this.check(Ga())},slugify(){return this.check(Ka())}})),Es=_(`ZodString`,(e,t)=>{zn.init(e,t),Ts.init(e,t)},{email(e){return this.check(Yi(Ms,e))},url(e){return this.check(ta(Is,e))},jwt(e){return this.check(ga(Qs,e))},emoji(e){return this.check(na(Rs,e))},guid(e){return this.check(Xi(Ps,e))},uuid(e){return this.check(Zi(Fs,e))},uuidv4(e){return this.check(Qi(Fs,e))},uuidv6(e){return this.check($i(Fs,e))},uuidv7(e){return this.check(ea(Fs,e))},nanoid(e){return this.check(ra(zs,e))},cuid(e){return this.check(ia(Bs,e))},cuid2(e){return this.check(aa(Vs,e))},ulid(e){return this.check(oa(Hs,e))},base64(e){return this.check(pa(Ys,e))},base64url(e){return this.check(ma(Xs,e))},xid(e){return this.check(sa(Us,e))},ksuid(e){return this.check(ca(Ws,e))},ipv4(e){return this.check(la(Gs,e))},ipv6(e){return this.check(ua(Ks,e))},cidrv4(e){return this.check(da(qs,e))},cidrv6(e){return this.check(fa(Js,e))},e164(e){return this.check(ha(Zs,e))},datetime(e){return this.check(_a(Os,e))},date(e){return this.check(va(ks,e))},time(e){return this.check(ya(As,e))},duration(e){return this.check(ba(js,e))}});function v(e){return Ji(Es,e)}var Ds=_(`ZodStringFormat`,(e,t)=>{Bn.init(e,t),Ts.init(e,t)}),Os=_(`ZodISODateTime`,(e,t)=>{ar.init(e,t),Ds.init(e,t)}),ks=_(`ZodISODate`,(e,t)=>{or.init(e,t),Ds.init(e,t)}),As=_(`ZodISOTime`,(e,t)=>{sr.init(e,t),Ds.init(e,t)}),js=_(`ZodISODuration`,(e,t)=>{cr.init(e,t),Ds.init(e,t)}),Ms=_(`ZodEmail`,(e,t)=>{Un.init(e,t),Ds.init(e,t)});function Ns(e){return Yi(Ms,e)}var Ps=_(`ZodGUID`,(e,t)=>{Vn.init(e,t),Ds.init(e,t)}),Fs=_(`ZodUUID`,(e,t)=>{Hn.init(e,t),Ds.init(e,t)}),Is=_(`ZodURL`,(e,t)=>{Zn.init(e,t),Ds.init(e,t)});function Ls(e){return ta(Is,e)}var Rs=_(`ZodEmoji`,(e,t)=>{Qn.init(e,t),Ds.init(e,t)}),zs=_(`ZodNanoID`,(e,t)=>{$n.init(e,t),Ds.init(e,t)}),Bs=_(`ZodCUID`,(e,t)=>{er.init(e,t),Ds.init(e,t)}),Vs=_(`ZodCUID2`,(e,t)=>{tr.init(e,t),Ds.init(e,t)}),Hs=_(`ZodULID`,(e,t)=>{nr.init(e,t),Ds.init(e,t)}),Us=_(`ZodXID`,(e,t)=>{rr.init(e,t),Ds.init(e,t)}),Ws=_(`ZodKSUID`,(e,t)=>{ir.init(e,t),Ds.init(e,t)}),Gs=_(`ZodIPv4`,(e,t)=>{lr.init(e,t),Ds.init(e,t)}),Ks=_(`ZodIPv6`,(e,t)=>{fr.init(e,t),Ds.init(e,t)}),qs=_(`ZodCIDRv4`,(e,t)=>{pr.init(e,t),Ds.init(e,t)}),Js=_(`ZodCIDRv6`,(e,t)=>{hr.init(e,t),Ds.init(e,t)}),Ys=_(`ZodBase64`,(e,t)=>{vr.init(e,t),Ds.init(e,t)}),Xs=_(`ZodBase64URL`,(e,t)=>{xr.init(e,t),Ds.init(e,t)}),Zs=_(`ZodE164`,(e,t)=>{Sr.init(e,t),Ds.init(e,t)}),Qs=_(`ZodJWT`,(e,t)=>{wr.init(e,t),Ds.init(e,t)}),$s=_(`ZodNumber`,(e,t)=>{Tr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jo(e,t,n,r),e.isFinite=!0},Ve({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Eo(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Eo(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=Eo(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Eo(e).format??null},{gt(e,t){return this.check(ka(e,t))},gte(e,t){return this.check(Aa(e,t))},min(e,t){return this.check(Aa(e,t))},lt(e,t){return this.check(Da(e,t))},lte(e,t){return this.check(Oa(e,t))},max(e,t){return this.check(Oa(e,t))},int(e){return this.check(tc(e))},safe(e){return this.check(tc(e))},positive(e){return this.check(ka(0,e))},nonnegative(e){return this.check(Aa(0,e))},negative(e){return this.check(Da(0,e))},nonpositive(e){return this.check(Oa(0,e))},multipleOf(e,t){return this.check(ja(e,t))},step(e,t){return this.check(ja(e,t))},finite(){return this}}));function y(e){return xa($s,e)}var ec=_(`ZodNumberFormat`,(e,t)=>{Er.init(e,t),$s.init(e,t)});function tc(e){return Sa(ec,e)}var nc=_(`ZodBoolean`,(e,t)=>{Dr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mo(e,t,n,r)});function b(e){return Ca(nc,e)}var rc=_(`ZodNull`,(e,t)=>{Or.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>No(e,t,n,r)});function ic(e){return wa(rc,e)}var ac=_(`ZodAny`,(e,t)=>{kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0}),oc=_(`ZodUnknown`,(e,t)=>{Ar.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function sc(){return Ta(oc)}var cc=_(`ZodNever`,(e,t)=>{jr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Po(e,t,n,r)});function lc(e){return Ea(cc,e)}var uc=_(`ZodArray`,(e,t)=>{Cs(),Fr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Na(e,t))},nonempty(e){return this.check(Na(1,e))},max(e,t){return this.check(Ma(e,t))},length(e,t){return this.check(Pa(e,t))},unwrap(){return this.element}});function x(e,t){return qa(uc,e,t)}var dc=_(`ZodObject`,(e,t)=>{Cs(),Vr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ho(e,t,n,r),Je(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return E(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(te(this._zod.def,{catchall:e}))},passthrough(){return this.clone(te(this._zod.def,{catchall:sc()}))},loose(){return this.clone(te(this._zod.def,{catchall:sc()}))},strict(){return this.clone(te(this._zod.def,{catchall:lc()}))},strip(){return this.clone(te(this._zod.def,{catchall:void 0}))},extend(e){return be(this,e)},safeExtend(e){return Se(this,e)},merge(e){return Ce(this,e)},pick(e){return _e(this,e)},omit(e){return ye(this,e)},partial(...e){return we(Tc,this,e[0])},exactPartial(...e){return we(Dc,this,e[0],`exactPartial`)},required(...e){return Te(Fc,this,e[0])}});function S(e,t){return new dc({type:`object`,shape:e??{},...g(t)})}function fc(e,t){return new dc({type:`object`,shape:e,catchall:sc(),...g(t)})}var pc=_(`ZodUnion`,(e,t)=>{Ur.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uo(e,t,n,r),e.options=t.options});function C(e,t){return new pc({type:`union`,options:e,...g(t)})}var mc=_(`ZodDiscriminatedUnion`,(e,t)=>{pc.init(e,t),Gr.init(e,t)});function w(e,t,n){return new mc({type:`union`,options:t,discriminator:e,...g(n)})}var hc=_(`ZodIntersection`,(e,t)=>{Kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wo(e,t,n,r)});function gc(e,t){return new hc({type:`intersection`,left:e,right:t})}var _c=_(`ZodTuple`,(e,t)=>{Cs(),Yr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Go(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Tc({type:`optional`,innerType:e}))})}});function vc(e,t,n){let r=t instanceof Fn;return new _c({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}var yc=_(`ZodRecord`,(e,t)=>{Cs(),$r.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function T(e,t,n){return!t||!t._zod?new yc({type:`record`,keyType:v(),valueType:e,...g(t)}):new yc({type:`record`,keyType:e,valueType:t,...g(n)})}function bc(e,t,n){return new yc({type:`record`,keyType:e,valueType:t,...g(n),partial:!0})}var xc=_(`ZodEnum`,(e,t)=>{ei.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})}});function E(e,t){return new xc({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...g(t)})}var Sc=_(`ZodLiteral`,(e,t)=>{ti.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Io(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function D(e,t){return new Sc({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}var Cc=_(`ZodTransform`,(e,t)=>{Cs(),ni.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zo(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Le(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Le(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function wc(e){return new Cc({type:`transform`,transform:e})}var Tc=_(`ZodOptional`,(e,t)=>{ii.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ec(e){return new Tc({type:`optional`,innerType:e})}var Dc=_(`ZodExactOptional`,(e,t)=>{ai.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Oc(e){return new Dc({type:`optional`,innerType:e})}var kc=_(`ZodNullable`,(e,t)=>{oi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ac(e){return new kc({type:`nullable`,innerType:e})}var jc=_(`ZodDefault`,(e,t)=>{si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mc(e,t){return new jc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Nc=_(`ZodPrefault`,(e,t)=>{li.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pc(e,t){return new Nc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Fc=_(`ZodNonOptional`,(e,t)=>{ui.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e,t){return new Fc({type:`nonoptional`,innerType:e,...g(t)})}var Lc=_(`ZodCatch`,(e,t)=>{pi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Rc(e,t){return new Lc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Xe(t)})}var zc=_(`ZodPipe`,(e,t)=>{mi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),e.in=t.in,e.out=t.out});function Bc(e,t){return new zc({type:`pipe`,in:e,out:t})}var Vc=_(`ZodReadonly`,(e,t)=>{gi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e){return new Vc({type:`readonly`,innerType:e})}var Uc=_(`ZodTemplateLiteral`,(e,t)=>{bi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lo(e,t,n,r)});function Wc(e,t){return new Uc({type:`template_literal`,parts:e,...g(t)})}var Gc=_(`ZodLazy`,(e,t)=>{xi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Kc(e){return new Gc({type:`lazy`,getter:e})}var qc=_(`ZodCustom`,(e,t)=>{Si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ro(e,t,n,r)});function Jc(e,t){return Ja(qc,e??(()=>!0),t)}function Yc(e,t={}){return Ya(qc,e,t)}function Xc(e,t){return Xa(e,t)}function Zc(e){let t=Kc(()=>C([v(e),y(),b(),ic(),x(t),T(v(),t)]));return t}function Qc(e){return _a(Os,e)}function $c(e){return va(ks,e)}var O=Zc(),el=T(v(),O);function tl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var nl={run:`run`,turn:`trn`,session:`ses`,actor:`act`,message:`msg`,delivery:`dlv`,handlerCall:`hcl`,llmInteraction:`llm`,pairing:`par`,pairingToken:`ptk`,policy:`pol`,approval:`apr`,budget:`bgt`,priorityRule:`pri`,reservation:`rsv`,ledger:`led`,notification:`ntf`,push:`psh`,secret:`sec`,modelCategory:`mct`,provider:`prv`,sectionRule:`srl`,authSession:`aus`,modelCall:`mdl`,mcp:`mcp`,autoPair:`apk`,connection:`cnx`,fnExample:`fex`,refusal:`rfs`,record:`rec`,mentionRequest:`mrq`},rl=e=>v().regex(RegExp(`^${nl[e]}_.+$`),`expected a ${e} id starting with "${nl[e]}_"`).brand().describe(`${e} id`),il=e=>Object.hasOwn(nl,e);function al(){return Object.fromEntries(Object.keys(nl).filter(il).map(e=>[e,rl(e)]))}var k=v().regex(/^[A-Za-z_][A-Za-z0-9_.-]*$/),ol=al(),A=ol.run,sl=ol.turn,j=ol.session,M=ol.actor,cl=ol.message,ll=ol.delivery,ul=ol.handlerCall,dl=ol.llmInteraction,fl=ol.pairing,pl=ol.pairingToken,ml=ol.policy,hl=ol.approval,gl=ol.budget,_l=ol.priorityRule,vl=ol.reservation,yl=ol.ledger,bl=ol.notification,xl=ol.push,Sl=ol.secret,Cl=ol.modelCategory,wl=ol.provider,Tl=ol.sectionRule,El=ol.authSession,Dl=ol.modelCall,Ol=ol.mcp,kl=ol.autoPair,Al=ol.connection,jl=y().int().min(0),N=y().int(),P=y(),Ml=/^[a-z][a-z0-9-]*$/,F=v().regex(Ml).brand(),I=Wc([v().regex(Ml),`/`,v().min(1)]),Nl=C([D(`native`),I]);function Pl(e,t){return`${e}/${t}`}function Fl(e){let t=e.indexOf(`/`);return{system:e.slice(0,t),local:e.slice(t+1)}}var Il=[`urgent`,`interactive`,`normal`,`background`],Ll=E(Il),Rl=E([`user`,`llm`,`both`,`none`]),zl=E([`user`,`group`,`agent`,`system`,`mcp`]),Bl=e=>S({items:x(e),cursor:v().optional()}),Vl=S({cursor:v().optional(),limit:y().int().min(1).max(200).optional()});function Hl(e){return e instanceof Error?e.message:String(e)}var Ul=`read`,Wl=`admin`,L=v().regex(Ml).brand(),Gl=L.parse(`main`),Kl=S({system:F,instance:L}),ql=v().regex(/^[a-z*][a-z0-9*-]*\/[A-Za-z0-9_.*-]+$/).brand(),Jl=Object.defineProperty,Yl=(e,t)=>{for(var n in t)Jl(e,n,{get:t[n],enumerable:!0})},R={};Yl(R,{array:()=>pp,boolean:()=>ap,codec:()=>Dp,conditional:()=>bp,declare:()=>Ap,default:()=>Cp,define:()=>kp,dependent:()=>xp,discriminatedUnion:()=>_p,dispatch:()=>Op,enum:()=>cp,fromJSONSchema:()=>ep,int:()=>ip,intersection:()=>vp,json:()=>dp,literal:()=>sp,module:()=>jp,never:()=>lp,not:()=>yp,null:()=>op,nullable:()=>wp,number:()=>rp,object:()=>fp,optional:()=>Sp,record:()=>hp,ref:()=>Tp,refOf:()=>Ep,string:()=>np,tuple:()=>mp,union:()=>gp,unknown:()=>up});var Xl=Object.freeze({length:!0,range:!0,items:`all`,pattern:`full`}),Zl=Object.freeze({length:!1,range:!1,items:`none`,pattern:`none`}),Ql=Object.freeze({id:`lenient`,family:`lenient`,strict:!1,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!0,conditionals:!0,patternProperties:!0,defs:!0,recursion:!0,any:`empty`,constraints:Xl,formats:`all`,examples:`keyword`,propertyOrdering:!1,rootObject:!1}),$l=Object.freeze({...Ql,id:`people`,family:`people`,audience:`people`}),eu=Object.freeze({...Ql,id:`openai`,family:`openai`,rootObject:!0,request:Object.freeze({maxTools:128})}),tu=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`ipv4`,`ipv6`,`uuid`]),nu=Object.freeze({id:`openai-strict`,family:`openai`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`anyOf`,nulls:`anyOf`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,refSiblings:!1,recursion:!0,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:tu,examples:`description`,propertyOrdering:!1,maxDepth:10,rootObject:!0,limits:Object.freeze({maxProperties:5e3,maxDepth:10,maxStringChars:12e4,maxEnumValues:1e3,largeEnumValues:250,maxLargeEnumChars:15e3}),request:Object.freeze({maxTools:128}),loose:eu}),ru=Object.freeze({...nu,id:`openai-finetuned-strict`,constraints:Zl,formats:new Set}),iu=Object.freeze({...Ql,id:`anthropic`,family:`anthropic`,rootObject:!0}),au=Object.freeze({id:`anthropic-strict`,family:`anthropic`,strict:!0,optional:`omit`,closedObjects:!0,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!1,range:!1,items:`min-0-1`,pattern:`basic`}),formats:new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]),examples:`description`,propertyOrdering:!1,rootObject:!0,request:Object.freeze({maxStrictTools:20,totals:Object.freeze({maxOptional:24,maxUnions:16})}),loose:iu,alwaysStrictOutput:!0}),ou=`Return ONLY a single raw JSON object that conforms to the schema above. Do NOT wrap it in markdown code fences, do NOT add any prose before or after it, and do NOT echo the schema itself: emit only the JSON instance.`,su=Object.freeze({...Ql,id:`google`,family:`google`,recursion:`guarded`,maxEnumValues:40,rootObject:!0,jsonInstruction:ou}),cu=Object.freeze({id:`google-strict`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:`guarded`,any:`empty`,constraints:Object.freeze({length:!1,range:!0,items:`all`,pattern:`none`}),formats:new Set([`date-time`,`date`,`time`]),examples:`description`,propertyOrdering:!1,maxEnumValues:40,rootObject:!0,loose:su,jsonInstruction:ou}),lu=Object.freeze({id:`google-openapi`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`nullable`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:new Set([`date-time`,`date`,`time`,`duration`]),examples:`description`,propertyOrdering:!0,maxEnumValues:40,maxDepth:10,rootObject:!0,loose:su,jsonInstruction:ou}),uu=new Set([`date`,`time`,`date-time`,`email`,`uuid`,`ipv4`,`ipv6`,`uri`]),du=Object.freeze({id:`xai-strict`,family:`xai`,strict:!0,optional:`omit`,closedObjects:!0,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`flat`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:uu,examples:`description`,propertyOrdering:!1,rootObject:!0}),fu=Object.freeze({...du,id:`xai`,strict:!1}),pu=Object.freeze({...Ql,id:`ollama`,family:`ollama`,rootObject:!0}),mu=Object.freeze({id:`minimal`,family:`minimal`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`tagged`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Zl,formats:new Set,examples:`description`,propertyOrdering:!1,maxDepth:6,maxEnumValues:8,rootObject:!0}),hu=new Map,gu=new Map;function _u(e){hu.set(e.id,e);let t=gu.get(e.family)??{};e.strict?t.strict??=e:t.loose??=e,gu.set(e.family,t)}for(let e of[Ql,$l,eu,nu,ru,iu,au,su,cu,lu,du,fu,pu,mu])_u(e);var vu=new WeakMap;function yu(e){let t=vu.get(e);return t||(t=Object.freeze({profile:e,records:e.records,optional:e.optional,recordWord:e.records===`pairs`?`a list of {key, value} entries`:`an object`}),vu.set(e,t)),t}Object.freeze({properties:0,depth:0,stringChars:0,enumValues:0,enums:Object.freeze([]),optional:0,unions:0});function bu(e){let t=0,n=0,r=0,i=0,a=0,o=[],s=e.$defs??{};for(let e of Object.keys(s))n+=e.length;let c=e=>{if(!e||typeof e!=`object`)return;if(Array.isArray(e)){for(let t of e)c(t);return}let s=e;if(s.properties&&typeof s.properties==`object`){let e=s.properties,r=new Set(Array.isArray(s.required)?s.required:[]);for(let[a,o]of Object.entries(e))t++,n+=a.length,r.has(a)||i++,c(o)}if(Array.isArray(s.enum)){let e=0;for(let t of s.enum)typeof t==`string`&&(e+=t.length);r+=s.enum.length,n+=e,o.push({values:s.enum.length,chars:e})}typeof s.const==`string`&&(n+=s.const.length);let l=s.anyOf??s.oneOf;(Array.isArray(l)&&l.length>1||Array.isArray(s.type)&&s.type.length>1)&&a++;for(let e of[`items`,`prefixItems`,`anyOf`,`oneOf`,`allOf`,`additionalProperties`,`not`,`if`,`then`,`else`])e in s&&c(s[e]);if(s.patternProperties&&typeof s.patternProperties==`object`)for(let e of Object.values(s.patternProperties))c(e)},{$defs:l,...u}=e;c(u);for(let e of Object.values(s))c(e);let d=e=>{if(typeof e.$ref==`string`)return/^#\/\$defs\/(.+)$/.exec(e.$ref)?.[1]?.replace(/~1/g,`/`).replace(/~0/g,`~`)},f=xu(s,d),p=new Set,m=new Map,h=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e;if(typeof t.$ref==`string`){let e=d(t);if(!e||p.has(e)||!s[e])return 0;let n=f.get(e),r=e;if(n){r+=`|`;for(let e of n)r+=p.has(e)?`1`:`0`}let i=m.get(r);if(i!==void 0)return i;p.add(e);let a=h(s[e]);return p.delete(e),m.set(r,a),a}let n=t.type===`object`||t.type===`array`||Array.isArray(t.type)&&(t.type.includes(`object`)||t.type.includes(`array`)),r=0,i=e=>{let t=h(e);t>r&&(r=t)};if(t.properties&&typeof t.properties==`object`)for(let e of Object.values(t.properties))i(e);for(let e of[`items`,`additionalProperties`,`not`])e in t&&i(t[e]);for(let e of[`prefixItems`,`anyOf`,`oneOf`,`allOf`])if(Array.isArray(t[e]))for(let n of t[e])i(n);return+!!n+r},ee=h(u);return{properties:t,depth:ee,stringChars:n,enumValues:r,enums:o,optional:i,unions:a}}function xu(e,t){let n=new Map,r=(n,i)=>{if(!n||typeof n!=`object`)return;if(Array.isArray(n)){for(let e of n)r(e,i);return}let a=t(n);a!==void 0&&e[a]&&i.add(a);for(let e of Object.values(n))r(e,i)};for(let t of Object.keys(e)){let i=new Set;r(e[t],i),n.set(t,[...i])}let i=new Map,a=new Map,o=new Set,s=[],c=new Map,l=0;for(let e of n.keys()){if(i.has(e))continue;let t=[[e,0]];for(;t.length;){let e=t[t.length-1],[r,u]=e;u===0&&(i.set(r,l),a.set(r,l),l++,s.push(r),o.add(r));let d=n.get(r);if(u<d.length){e[1]++;let n=d[u];i.has(n)?o.has(n)&&a.set(r,Math.min(a.get(r),i.get(n))):t.push([n,0]);continue}t.pop();let f=t[t.length-1];if(f&&a.set(f[0],Math.min(a.get(f[0]),a.get(r))),a.get(r)===i.get(r)){let e=[],t;do t=s.pop(),o.delete(t),e.push(t);while(t!==r);if(e.length>1||d.includes(r))for(let t of e)c.set(t,e)}}}return c}var Su=class extends Error{constructor(e){super(`@aeye/schema: ${e}`),this.name=`SchemaDefinitionError`}},Cu=class extends Error{constructor(e,t=Ud(e)){super(t),this.issues=e,this.name=`SchemaParseError`}issues};function wu(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function Tu(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function Eu(e,t,n=Tu(e.length)){let r=e.toLowerCase(),i=[];for(let a=0;a<t.length;a++){let o=t[a];if(Math.abs(o.length-e.length)>n)continue;let s=wu(r,o.toLowerCase());s<=n&&i.push({candidate:o,index:a,ci:s,exact:wu(e,o)})}return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function Du(e,t,n){return Eu(e,t,n)[0]}var Ou=Object.freeze({detail:`full`,maxErrors:5,maxChars:2e3,suggestions:!0,context:3,depth:6,header:!0});function ku(...e){let t;for(let n of e)n!==void 0&&(t={...t,...ju(typeof n==`string`?{detail:n}:n)});return t}function Au(...e){let t=ku(...e)??{},n=t.detail??Ou.detail;return{...Ou,...t,detail:n,expected:t.expected??n===`full`}}function ju(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Mu(e){let t=typeof e==`string`?e:e?.detail??Ou.detail;return t===`markers`||t===`full`}var Nu=new WeakMap;function Pu(e,t){Nu.set(e,t)}function Fu(e,t,n){for(let r=t;r<e.length;r++){let t=Nu.get(e[r]);t&&!t.node&&(t.node=n)}}var Iu=/^[A-Za-z_$][\w$]*$/;function Lu(e){let t=``,n=``;for(let r of e)r===`(json)`?(t+=`${n||`(root)`} \u2192 JSON text \u2192 `,n=``):n+=typeof r==`number`?`[${r}]`:Iu.test(r)?n?`.${r}`:r:`[${JSON.stringify(r)}]`;return t&&!n?t.slice(0,-3):t+(n||(t?``:`(root)`))}var Ru=Symbol(`absent`);function zu(e,t){let n=e;for(let e of t)if(e===`(json)`){if(typeof n!=`string`)continue;if(n=Vu(n),n===Ru)return Ru}else{if(typeof n==`string`&&(n=Vu(n)),typeof n!=`object`||!n||!Object.prototype.hasOwnProperty.call(n,e))return Ru;n=n[e]}return n}var Bu;function Vu(e){let t=Bu?.get(e);if(t!==void 0)return t;let n;try{n=JSON.parse(e)}catch{n=Ru}return Bu?.set(e,n),n}function Hu(e,t=160){for(let n of[2,1,0]){let r=Wu(e,n,6);if(r.length<=t)return r}let n=Wu(e,0,3);return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Uu(e){return e.replace(/^#\/\$defs\//,``).replace(/~1/g,`/`).replace(/~0/g,`~`)}function Wu(e,t,n){if(typeof e.$ref==`string`)return Uu(e.$ref);if(`const`in e)return JSON.stringify(e.const);if(Array.isArray(e.enum))return Ku(e.enum.map(e=>JSON.stringify(e)),n,` | `);let r=e.anyOf??e.oneOf;if(Array.isArray(r))return Ku([...new Set(r.map(e=>Wu(e,t,n)))],n,` | `,`options`);if(Array.isArray(e.allOf))return e.allOf.map(e=>Gu(Wu(e,t,n))).join(` & `);if(Array.isArray(e.type))return e.type.map(r=>Wu({...e,type:r},t,n)).join(` | `);if(e.nullable===!0)return`${Gu(Wu({...e,nullable:!1},t,n))} | null`;switch(e.type){case`string`:if(typeof e.description==`string`&&/JSON text/.test(e.description)){let t=/TypeScript type: ([^\n(]+?)(?: \(its named types|\.\s*$)/.exec(e.description);return t?`string (JSON text of ${t[1].trim()})`:`string (JSON text)`}return typeof e.format==`string`?`string (${e.format})`:`string`;case`integer`:return`integer`;case`number`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:return Array.isArray(e.prefixItems)?`[${e.prefixItems.map(e=>Wu(e,t-1,n)).join(`, `)}]`:`${Gu(e.items&&typeof e.items==`object`?Wu(e.items,t-1,n):`any`)}[]`;case`object`:{let r=e.properties??{},i=Object.keys(r),a=e.additionalProperties&&typeof e.additionalProperties==`object`?e.additionalProperties:void 0;if(!i.length&&!a)return e.additionalProperties===!1?`{}`:`object`;if(t<=0)return`{…}`;let o=new Set(e.required??[]),s=i.slice(0,n).map(e=>`${Iu.test(e)?e:JSON.stringify(e)}${o.has(e)?``:`?`}: ${Wu(r[e],t-1,n)}`);return i.length>n&&s.push(`\u2026 ${i.length-n} more`),a&&s.push(`[key: string]: ${Wu(a,t-1,n)}`),`{ ${s.join(`; `)} }`}default:return`any JSON value`}}function Gu(e){return/ \| | & /.test(e)&&!/^[{[(]/.test(e)?`(${e})`:e}function Ku(e,t,n,r=`more`){return e.length<=t?e.join(n):`${e.slice(0,t).join(n)}${n}\u2026 (${e.length} ${r===`more`?`values`:r})`}function qu(e,t){let n=t?.node;if(n&&t&&t.kind!==`enum`&&t.kind!==`literal`&&t.kind!==`tag`&&t.kind!==`tool`&&t.kind!==`rule`&&t.kind!==`unknown-key`&&t.kind!==`not-allowed`)try{if(n.jsonText&&n.schema){let e=n.typeText();return`string (JSON text of ${e.length>120?`${e.slice(0,119)}\u2026`:e})`}let e=Hu(n.json());return t.kind===`type`&&/^(string|number|integer|boolean|null)$/.test(e)?void 0:e}catch{return}}function Ju(e){let t=e.message;for(let n of e.path)t+=`\0${typeof n==`number`?`#`:n}`;return t}function Yu(e){let t=[],n=new Map;for(let r of e){let e=Ju(r),i=n.get(e);if(i){i.paths.push(r.path);continue}let a={issue:r,info:Nu.get(r),paths:[r.path]};n.set(e,a),t.push(a)}return t}function Xu(e,t){let n=e.issue.message,r=e.info?.kind;if(t.terse&&e.info?.candidates&&(r===`enum`||r===`tag`||r===`tool`)){let t=e.info.candidates().length;n=n.replace(/ one of: .*$/s,` one of ${t} value${t===1?``:`s`}.`)}if(t.suggestions&&e.info?.candidates){let t=Zu(e.issue,e.info);t&&(n=n.replace(/\.$/,``)+t)}if(e.paths.length>1){if(t.terse)n+=` (the same at ${e.paths.length-1} more place${e.paths.length===2?``:`s`})`;else{let t=e.paths.slice(1,3).map(Lu),r=e.paths.length-1-t.length;n+=` (the same at ${t.join(`, `)}${r>0?` and ${r} more place${r===1?``:`s`}`:``})`}}return n.length>400?`${n.slice(0,399)}\u2026`:n}function Zu(e,t){let n=t.candidates();if(!n.length)return``;if(t.kind===`required`){let t=e.path[e.path.length-1];if(typeof t!=`string`)return``;let r=Du(t,n);return r?` \u2014 you wrote \`${r}\`; did you mean \`${t}\`?`:``}let r=t.kind===`unknown-key`?e.path[e.path.length-1]:t.received;if(typeof r!=`string`)return``;let i=Eu(r,n)[0];return i!==void 0&&i!==r?` \u2014 did you mean \`${i}\`?`:``}function Qu(e,t,n,r=`your answer`){if(!e.length)return``;let i=ed(n)?n:Au(n),a=Yu(i.suggestions?$u(e):e),o=Bu;Bu=new Map;try{for(let e of td(i)){let n=rd(a,t,e,r);if(n.length<=i.maxChars)return n}let e=rd(a,t,{...i,detail:`summary`,maxErrors:1,terse:!0},r);return e.length<=i.maxChars?e:`${e.slice(0,Math.max(0,i.maxChars-1))}\u2026`}finally{Bu=o}}function $u(e){let t,n=0;for(let r of e){let e=Nu.get(r);if(e?.kind!==`required`||!e.candidates||++n>50)continue;let i=r.path[r.path.length-1],a=typeof i==`string`?Du(i,e.candidates()):void 0;a!==void 0&&(t??=new Set).add(id([...r.path.slice(0,-1),a]))}return t?e.filter(e=>!(Nu.get(e)?.kind===`unknown-key`&&t.has(id(e.path)))):e}function ed(e){return typeof e==`object`&&!!e&&`detail`in e&&`maxChars`in e&&`expected`in e&&`context`in e&&`depth`in e&&`header`in e&&`suggestions`in e&&`maxErrors`in e}function*td(e){for(let t of nd(e))yield t,yield{...t,terse:!0}}function*nd(e){let t=e;if(yield t,t.detail===`markers`||t.detail===`full`){for(t.expected&&(yield t={...t,expected:!1}),t.context>0&&(yield t={...t,context:0}),t.depth>2&&(yield t={...t,depth:2});t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};yield t={...t,detail:`list`,maxErrors:e.maxErrors}}for(;t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};t.detail!==`summary`&&(yield{...t,detail:`summary`})}function rd(e,t,n,r){let i=e.slice(0,Math.max(1,n.maxErrors)),a=e.reduce((e,t)=>e+t.paths.length,0),o=e.length-i.length,s=e.slice(i.length).reduce((e,t)=>e+t.paths.length,0),c=`${a} problem${a===1?``:`s`}`;if(n.detail===`summary`){let e=i[0],t=a-e.paths.length;return`${n.header?`${a===1?`A problem`:c} in ${r}: `:``}at ${Lu(e.issue.path)}: ${Xu(e,n)}${t>0?` (and ${t} more problem${t===1?``:`s`})`:``}`}let l=[];if(n.header&&l.push(`${c} in ${r}:`),n.detail===`list`)for(let e of i){let t=n.expected?qu(e.issue,e.info):void 0;l.push(`- at ${Lu(e.issue.path)}: ${Xu(e,n)}${t?` (expected: ${t})`:``}`)}else n.header&&l.push(``),l.push(...cd(i,t,n));return s>0&&l.push(`\u2026 and ${s} more problem${s===1?``:`s`}${o>1?` (${o} kinds)`:``} not shown.`),l.join(`
56
+ `)}var id=e=>{let t=``;for(let n of e)t+=`${typeof n==`number`?`#`:`$`}${n}\0`;return t};function ad(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n];if(r!==i)return typeof r==`number`&&typeof i==`number`?r-i:String(r)<String(i)?-1:1}return e.length-t.length}function od(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}var sd=e=>e.filter(e=>e!==`(json)`).length;function cd(e,t,n){let r=[],i=[];for(let n of e){let e=n.issue.path,a=n.info?.kind;t===void 0?i.push(n):zu(t,e)===Ru?e.length&&ld(zu(t,e.slice(0,-1)))?r.push({p:n,at:e.slice(0,-1),where:`missing`}):i.push(n):r.push({p:n,at:e,where:a===`unknown-key`||a===`not-allowed`?`key`:`value`})}r.sort((e,t)=>ad(e.p.issue.path,t.p.issue.path));let a=[],o=e=>{let t=[];for(let r of e){if(sd(e)-sd(t)<=n.depth)break;t.push(r)}return t};for(let e of r){let t=a[a.length-1];if(t){let r=od(t.anchor,e.at);if([...t.members,e].every(e=>sd(e.at)-sd(r)<=n.depth+1)){t.anchor=r,t.members.push(e);continue}}a.push({anchor:o(e.at),members:[e]})}let s=[];for(let e of a){let r=e.anchor;for(;r.length&&zu(t,r)===Ru;)r=r.slice(0,-1);let i=new Map,a=new Map;for(let t of e.members){let e=id(t.at),n=i.get(e);n?n.push({p:t.p,where:t.where}):i.set(e,[{p:t.p,where:t.where}]);for(let e=r.length;e<t.at.length;e++){let n=id(t.at.slice(0,e)),r=a.get(n);r?r.add(t.at[e]):a.set(n,new Set([t.at[e]]))}}s.length&&s.push(``),r.length&&s.push(`at ${Lu(r)}:`),new dd(i,a,n,s,r.length).node(zu(t,r),r,``,``,``)}for(let e of i)s.push(`- at ${Lu(e.issue.path)}: ${Xu(e,n)}`);return s}var ld=e=>typeof e==`object`&&!!e;function ud(e){if(!e.length)return`…`;let t=e[0],n=Lu(e);return t===`(json)`?`\u2026 \u2192 ${n.replace(/^\(root\) → /,``)}`:typeof t==`number`||!Iu.test(t)?`\u2026${n}`:`\u2026.${n}`}var dd=class{constructor(e,t,n,r,i=0){this.marks=e,this.below=t,this.f=n,this.out=r,this.from=i}marks;below;f;out;from;node(e,t,n,r,i){let a=id(t),o=this.below.has(a);if(typeof e==`string`&&o){let a=Vu(e);if(a!==Ru){let e=[...t,`(json)`],o=id(e);return this.marks.has(o)||this.below.has(o)?this.node(a,e,n,`${r}/* JSON text */ `,i):this.node(a,t,n,r,i)}}let s=this.marks.get(a)??[];if(!(ld(e)&&(o||s.some(e=>e.where===`missing`)))){let t=fd(e,60);this.out.push(n+r+t+i);for(let e of s)e.where===`key`?this.mark(e.p,n.length,r.length+t.length):this.mark(e.p,n.length+r.length,t.length);return}let c=Array.isArray(e);this.out.push(`${n}${r}${c?`[`:`{`}`);for(let e of s)this.mark(e.p,n.length+r.length,1);let l=`${n} `;c?this.items(e,t,l):this.keys(e,t,l),this.out.push(`${n}${c?`]`:`}`}${i}`)}keys(e,t,n){let r=Object.keys(e),i=this.below.get(id(t)),a=r.filter(e=>i?.has(e)),o=r.filter(e=>!a.includes(e)),s=new Set(o.filter(t=>fd(e[t],40).length<=40&&!ld(e[t])).slice(0,this.f.context));for(let e of o)s.size<this.f.context&&!s.has(e)&&s.add(e);let c=r.filter(e=>a.includes(e)||s.has(e)),l=r.length-c.length;c.forEach((r,i)=>{let a=i===c.length-1&&!l;this.node(e[r],[...t,r],n,`${JSON.stringify(r)}: `,a?``:`,`)}),l&&this.out.push(`${n}\u2026 ${l} more key${l===1?``:`s`}`)}items(e,t,n){let r=new Set;for(let n of this.below.get(id(t))??[])typeof n==`number`&&n<e.length&&r.add(n);let i=e.length-r.size<=this.f.context&&e.every((e,t)=>r.has(t)||fd(e,40).length<=40),a=0,o=!1,s=()=>{a&&(this.out.push(`${n}\u2026 ${a} item${a===1?``:`s`}`),a=0,o=!0)};for(let c=0;c<e.length;c++){if(!i&&!r.has(c)){a++;continue}s();let l=c===e.length-1,u=o||!i&&c>0?`/* ${c} */ `:``;this.node(e[c],[...t,c],n,u,l?``:`,`)}s()}mark(e,t,n){let r=Math.max(1,Math.min(n,40)),i=`${this.from?ud(e.issue.path.slice(this.from)):Lu(e.issue.path)}: ${Xu(e,this.f)}`;this.out.push(`${` `.repeat(t)}${`^`.repeat(r)} ${i}`);let a=this.f.expected?qu(e.issue,e.info):void 0;a&&this.out.push(`${` `.repeat(t+r+1)}expected: ${a}`)}};function fd(e,t){if(typeof e==`string`){let n=JSON.stringify(e);return n.length<=t?n:`${n.slice(0,t-2)}\u2026"`}if(!ld(e))return e===void 0?`undefined`:JSON.stringify(e);let n=pd(e,t);if(n!==void 0)return n;if(Array.isArray(e))return`[\u2026 ${e.length} item${e.length===1?``:`s`}]`;let r=Object.keys(e).length;return`{\u2026 ${r} key${r===1?``:`s`}}`}function pd(e,t){let n=``,r=e=>{if(n.length>t)return!1;if(Array.isArray(e)){n+=`[`;for(let t=0;t<e.length;t++)if(t&&(n+=`,`),!r(e[t]))return!1;return n+=`]`,n.length<=t}if(ld(e)){n+=`{`;let i=!0;for(let t of Object.keys(e)){let a=e[t];if(a!==void 0&&(i||(n+=`,`),i=!1,n+=`${JSON.stringify(t)}:`,!r(a)))return!1}return n+=`}`,n.length<=t}return n+=e===void 0?`null`:JSON.stringify(e),n.length<=t};return r(e)?n:void 0}var md=class{constructor(e){this.issues=e}issues};function hd(){return{objects:0,arrays:0,edits:0,parsed:0,repaired:0}}function gd(e){let t=``;for(let n of e)t+=typeof n==`number`?`[${n}]`:/^[A-Za-z_$][\w$]*$/.test(n)?t?`.${n}`:n:`[${JSON.stringify(n)}]`;return t||`(root)`}var _d=Object.freeze({path:[],codePath:[],message:``}),vd=hd(),yd=Symbol(`absent`),bd=Symbol(`order`),xd,Sd=class e{constructor(e,t,n,r=!0,i=!1){this.inPlace=e,this.dry=t,this.stats=n,this.repair=r,this.countOnly=i}inPlace;dry;stats;repair;countOnly;errors=[];undo;undoN=0;wire=[];code=[];wd=0;cd=0;fail(e,t=`other`,n,r,i){if(this.countOnly){this.errors.push(_d);return}let a={path:this.wire.slice(0,this.wd),codePath:this.code.slice(0,this.cd),message:e};this.errors.push(a),Pu(a,{kind:t,node:i,received:n,candidates:r})}failAt(e,t,n=`rule`){if(!e.length)return this.fail(t,n);if(this.countOnly){this.errors.push(_d);return}let r={path:[...this.wire.slice(0,this.wd),...e],codePath:[...this.code.slice(0,this.cd),...e],message:t};this.errors.push(r),Pu(r,{kind:n})}enter(e,t=e){this.wire[this.wd++]=e,t!==null&&(this.code[this.cd++]=t)}leave(e=!0){this.wd--,e&&this.cd--}dryRun(t=!1){if(!t)return new e(!1,!0,vd,this.repair,!0);let n=new e(!1,!0,vd,this.repair);for(let e=0;e<this.wd;e++)n.wire[n.wd++]=this.wire[e];for(let e=0;e<this.cd;e++)n.code[n.cd++]=this.code[e];return n}saving(e,t,n=!1){let r=this.undo;if(!r)return;n&&this.ordered!==e&&(this.ordered=e,r[this.undoN++]=e,r[this.undoN++]=bd,r[this.undoN++]=Object.keys(e));let i=Object.prototype.hasOwnProperty.call(e,t);r[this.undoN++]=e,r[this.undoN++]=t,r[this.undoN++]=i?e[t]:yd}ordered;restore(){let e=this.undo;if(e)for(let t=this.undoN-3;t>=0;t-=3){let n=e[t],r=e[t+1],i=e[t+2];if(r===bd)for(let e of i){let t=n[e];delete n[e],n[e]=t}else i===yd?delete n[r]:n[r]=i}}keepUndo(){this.undo=xd??[],xd=void 0,this.undoN=0}releaseUndo(){let e=this.undo;if(e){for(let t=0;t<this.undoN;t++)e[t]=void 0;this.undo=void 0,this.undoN=0,e.length<=65536&&(xd=e)}}},Cd=class{constructor(e,t){this.impl=e,this.compiler=t}impl;compiler;needs=!1;schema;outer;jsonText=!1;_json;get own(){return!!this.impl?.own}get deps(){return this.impl?.deps??[]}json(){return this._json||=this.compiler.decorate(this,this.impl.emit()),this._json}run(e,t){let n=t.errors,r=n.length,i=this.impl.run(e,t);return n.length===r&&(this.schema?.checks.length&&this.check(i,t,this.schema),this.outer?.checks.length&&n.length===r&&this.check(i,t,this.outer),n.length===r)||t.countOnly||Fu(n,r,this),i}check(e,t,n){if(n)for(let r of n.checks){let n=r.fn(e);if(n!==!0){if(Array.isArray(n))for(let e of n)typeof e==`string`?t.fail(e,`rule`):t.failAt(e.path,e.message,`rule`);else t.fail(typeof n==`string`?n:r.message??`Failed a check.`,`rule`)}}}typeText(){return this.schema?this.schema.print(new wd(this.compiler.env)):`any JSON value`}encode(e,t=hd()){return this.needs?this.impl.encode(e,t):e}child(e){return this.impl?.child?.(e)}},wd=class{constructor(e){this.env=e}env;names=new Set;print(e){return e.print(this)}ref(e){return this.names.add(e),e}used(){return[...this.names]}definitions(e){for(let t of e)this.names.add(t);let t=[],n=new Set;for(let e=!0;e;){e=!1;for(let r of[...this.names]){if(n.has(r))continue;n.add(r),e=!0;let i=this.env.get(r);i&&t.push(`type ${r} = ${i.print(this)}`)}}return t.join(`
57
57
  `)}full(e){let t=this.print(e),n=[],r=new Set;for(let e=!0;e;){e=!1;for(let t of[...this.names]){if(r.has(t))continue;r.add(t),e=!0;let i=this.env.get(t);i&&n.push(`type ${t} = ${i.print(this)}`)}}return n.length?`${t}
58
58
  where
59
59
  ${n.join(`
60
- `)}`:t}},Cd=new Set([`object`,`array`,`record`,`tuple`]),wd=new WeakMap;function Td(e){let t=wd.get(e);return t===void 0&&(t=e.kind===`dependent`||e.children().some(Td),wd.set(e,t)),t}var Ed=new WeakMap;function Dd(e){let t=Ed.get(e);return t===void 0&&(t=+!!Cd.has(e.kind)+Math.max(0,...e.children().map(Dd)),Ed.set(e,t)),t}var Od=new WeakMap,kd=new WeakMap;function Ad(e){let t=kd.get(e);return t||kd.set(e,t=new Fd(e,jd,Nd,!1,!0)),t}var jd=new Map,Md;function Nd(){if(!Md){let e=Ad(Xl);Md=new zd(e,e.node({emit:()=>({}),run:e=>e,encode:e=>e}))}return Md}var Pd=class extends Error{},Fd=class{constructor(e,t,n,r=!1,i=!1){this.profile=e,this.env=t,this.lenient=n,this.inlineOnce=r,this.shared=i,this.view=_u(e)}profile;env;lenient;inlineOnce;shared;nodes=[];defs=new Map;glossary=new Set;inlined=new Set;recursive=new Map;view;stack=[];depth=0;guard=0;isRecursive(e){let t=this.recursive.get(e);if(t===void 0){let n=new Set,r=[...this.env.get(e)?.refNames()??[]];for(t=!1;r.length;){let i=r.pop();if(i===e){t=!0;break}n.has(i)||(n.add(i),r.push(...this.env.get(i)?.refNames()??[]))}this.recursive.set(e,t)}return t}node(e){return new xd(e,this)}compile(e,t){if(this.profile.audience!==`people`&&e.meta.forModels){let{forModels:t,...n}=e.meta,r=t;e=r.meta.description===void 0&&n.description!==void 0?r.describe(n.description):r}let n=Cd.has(e.kind);if(n&&this.profile.maxDepth!==void 0&&this.depth>=this.profile.maxDepth)return this.escape(e,`Nested too deep for this model to describe directly.`);let r=!t&&e.refNames().size===0&&!Td(e)&&(this.profile.maxDepth===void 0||this.depth+Dd(e)<this.profile.maxDepth);if(r){let t=Od.get(e)?.get(this.profile.id);if(t)return t;if(!this.shared){let t=Ad(this.profile),n=t.compile(e);return t.finish(),n}}n&&this.depth++;let i=e.compile(this);if(n&&this.depth--,i.schema=e,i.outer=t,this.nodes.push(i),r){let t=Od.get(e);t||Od.set(e,t=new Map),t.set(this.profile.id,i)}return i}guarded(e,t){this.guard++;try{return this.compile(e,t)}finally{this.guard--}}ref(e){let t=this.env.get(e);if(!t)throw new bu(`ref "${e}" is not defined (the chain's types should have prevented this).`);let n=this.profile,r=this.stack.find(t=>t.name===e);if(r)return n.defs&&(n.recursion===!0||n.recursion===`guarded`&&this.guard>r.guard)?this.defRef(e,this.defs.get(e)):this.escape(t,`"${e}" contains itself, which this model cannot describe directly.`,e);if(n.defs){let n=this.defs.get(e);if(n)return this.defRef(e,n);let r=new Id(this);return this.defs.set(e,r),this.stack.push({name:e,guard:this.guard}),r.target=this.compile(t),this.stack.pop(),this.nodes.push(r),this.defRef(e,r)}if(this.inlineOnce&&this.isRecursive(e)){if(this.inlined.has(e))return this.escape(t,`"${e}" is written out once elsewhere in this schema.`,e);this.inlined.add(e)}else if(!this.inlineOnce&&this.nodes.length>4e3)throw new Pd;this.stack.push({name:e,guard:this.guard});let i=this.compile(t);return this.stack.pop(),i}defRef(e,t){let n=this.node({deps:[t],emit:()=>({$ref:`#/$defs/${e.replace(/~/g,`~0`).replace(/\//g,`~1`)}`}),run:(e,n)=>t.run(e,n),encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)});return this.nodes.push(n),n.refName=e,n}escape(e,t,n){let r=new Sd(this.env),i=n??r.print(e);for(let e of n?[n]:r.used())this.glossary.add(e);let a=n||r.used().length?` (its named types are defined in the description of the whole schema)`:``,o,s=()=>o??=this.lenient().nodeFor(e),c=this.node({own:!0,emit:()=>({type:`string`,description:`${t} Write it as JSON text of this TypeScript type: ${i}${a}.`}),run:(e,t)=>{let n=Rd(e,t);if(n===Ld)return e;t.enter(`(json)`,null);let r=s().run(n,t);return t.leave(!1),r},encode:e=>JSON.stringify(e)});return c.jsonText=!0,this.nodes.push(c),c}late(e){let t=this.compile(e);return this.finish(),t}finish(){for(let e=!0;e;){e=!1;for(let t of this.nodes)t.needs||(t.own||t.deps.some(e=>e.needs))&&(t.needs=!0,e=!0)}this.shared&&(this.nodes.length=0)}text(e){return e===void 0?void 0:typeof e==`function`?e(this.view):e}nullable(e){let t=this.profile.nulls;if(e.nullable===!0||Array.isArray(e.type)&&e.type.includes(`null`)||e.type===`null`)return e;if(t===`nullable`)return{...e,nullable:!0};if(t===`type-array`&&typeof e.type==`string`&&!(`$ref`in e)&&!(`anyOf`in e)){let t={...e,type:[e.type,`null`]};return Array.isArray(e.enum)&&(t.enum=[...e.enum,null]),t}if(Array.isArray(e.anyOf)&&!(`$ref`in e))return e.anyOf.some(e=>e.type===`null`)?e:{...e,anyOf:[...e.anyOf,{type:`null`}]};let{description:n,...r}=e;return n===void 0?{anyOf:[r,{type:`null`}]}:{anyOf:[r,{type:`null`}],description:n}}object(e,t,n=this.profile.closedObjects){let r={type:`object`,properties:e,required:[...t]};return n&&(r.additionalProperties=!1),this.profile.propertyOrdering&&(r.propertyOrdering=Object.keys(e)),r}decorate(e,t){let n=[],r=[e.schema?.meta,e.outer?.meta],i,a=[];for(let t of r){if(!t)continue;let r=this.text(t.description);if(r&&n.push(r),t.title&&(i=t.title),t.examples)for(let n of t.examples)this.checkExample(e,n),a.push(e.encode(n))}let o=e.impl?.hint?.(this.view);o&&n.push(o);let s=typeof t.description==`string`?t.description:void 0;s&&n.push(s);let c={...t};if(i&&(c.title=i),a.length&&(this.profile.examples===`keyword`?c.examples=a:this.profile.examples===`description`&&n.push(`Example${a.length>1?`s`:``}: ${a.map(e=>JSON.stringify(e)).join(` ; `)}`)),n.length&&(c.description=n.join(`
61
- `)),this.profile.refSiblings===!1&&typeof c.$ref==`string`&&(c.description!==void 0||c.title!==void 0||c.examples!==void 0)){let{$ref:e,...t}=c;return{anyOf:[{$ref:e}],...t}}return c}checkExample(e,t){let n=e.schema;if(!n)return;let r=new bd(!1,!0,pd(),!1);if(this.lenient().nodeFor(n).run(t,r),r.errors.length)throw new bu(`example ${JSON.stringify(t)} does not fit its schema:
62
- ${Vd(r.errors)}`)}},Id=class extends xd{target;constructor(e){super(void 0,e)}get own(){return!1}get deps(){return this.target?[this.target]:[]}json(){return this.target.json()}run(e,t){return this.target.run(e,t)}encode(e,t=pd()){return this.target.encode(e,t)}child(e){return this.target.child(e)}},Ld=Symbol(`failed`);function Rd(e,t){if(typeof e!=`string`)return t.repair&&e!==void 0?(t.dry||t.stats.repaired++,e):(t.fail(`Expected a string of JSON text.`,`type`),Ld);try{let n=JSON.parse(e);return t.dry||t.stats.parsed++,n}catch(e){return t.fail(`Not valid JSON text: ${e.message}`,`json`),Ld}}var zd=class{constructor(e,t){this.compiler=e,this.root=t}compiler;root;_json;_body;_wrapped;_measure;_encoder;get profile(){return this.compiler.profile}body(){if(!this._body){let e=this.root.refName;this._body=e?this.compiler.defs.get(e).json():this.root.json()}return this._body}get wrapped(){if(this._wrapped===void 0){let e=this.body();this._wrapped=this.profile.rootObject&&!(e.type===`object`&&!(`anyOf`in e))}return this._wrapped}get jsonSchema(){if(this._json)return this._json;let e=this.body();if(this.wrapped&&(e=this.compiler.object({input:e},[`input`],this.profile.closedObjects||this.profile.strict)),this.compiler.glossary.size){let t=`Named types used by the fields written as JSON text:
63
- ${new Sd(this.compiler.env).definitions(this.compiler.glossary)}`;e={...e,description:typeof e.description==`string`?`${e.description}
64
- ${t}`:t}}let t={};for(let[e,n]of this.compiler.defs)t[e]=n.json();return this._json=this.compiler.defs.size?{...e,$defs:t}:e,this._json}get measure(){return this._measure??=vu(this.jsonSchema)}parse(e,t){return this.decode(e,t,void 0)}decode(e,t,n){let r=pd(),i=t?.inPlace??!0,a=new bd(i,!1,r,t?.repair??!0),o=i&&!n&&Au(t?.errorFormat);o&&a.keepUndo();let s;if(this.wrapped?typeof e!=`object`||!e||Array.isArray(e)||!(`input`in e)?a.fail(`Expected an object with an "input" field.`,`type`):(a.enter(`input`,null),s=this.root.run(e.input,a),a.leave(!1)):s=this.root.run(e,a),a.errors.length){a.restore(),a.releaseUndo();let i=n?n():e;return{ok:!1,issues:a.errors,message:Xu(a.errors,i,Ou(t?.errorFormat),t?.label),stats:r}}return o&&a.releaseUndo(),{ok:!0,value:s,stats:r}}parseText(e,t){let n;try{n=JSON.parse(e)}catch(e){let n=[{path:[],codePath:[],message:`Not valid JSON: ${e.message}`}];return Mu(n[0],{kind:`json`}),{ok:!1,issues:n,message:Xu(n,void 0,Ou(t?.errorFormat),t?.label),stats:pd()}}return this.decode(n,t,()=>JSON.parse(e))}parseOrThrow(e,t){let n=this.parse(e,t);if(!n.ok)throw new xu(n.issues,n.message);return n.value}encode(e,t=pd()){let n=this.root.encode(e,t);return this.wrapped?(t.objects++,{input:n}):n}encodeAt(e,t,n=pd()){let r=Bd(t);if(!r.length)return this.encode(e,n);let i=this.root;for(let e of r)if(i=i?.child(e),!i)throw new bu(`no schema at path ${md(r)}.`);return i.encode(e,n)}encodeText(e,t={}){let n=t.path===void 0?this.encode(e):this.encodeAt(e,t.path),r=t.pretty===!0?2:typeof t.pretty==`number`?t.pretty:void 0;return JSON.stringify(n,null,r)}get encoder(){if(!this._encoder){let e=((e,t)=>this.encodeText(e,t));e.wire=(e,t)=>t===void 0?this.encode(e):this.encodeAt(e,t),this._encoder=Object.freeze(e)}return this._encoder}nodeFor(e){let t=this.lateNodes.get(e);return t||this.lateNodes.set(e,t=this.compiler.late(e)),t}lateNodes=new WeakMap;typescript(){let e=this.root.schema;return new Sd(this.compiler.env).full(e)}};function Bd(e){return e===void 0||e===``?[]:typeof e==`string`?e.split(`.`).map(e=>/^\d+$/.test(e)?Number(e):e):[...e]}function Vd(e){return e.map(e=>`- at ${md(e.path)}: ${e.message}`).join(`
65
- `)}var Hd=class e{constructor(e={}){this.defs=e}defs;define(t){for(let e of Object.keys(t))if(e in this.defs)throw new bu(`"${e}" is already defined.`);return new e({...this.defs,...t})}declare(){return this}dynamic(e,t={}){return new Ud(this.defs,e,t)}result(e){return new Gd(this.defs,Wd(e))}},Ud=class{constructor(e,t,n){this.defs=e,this.fn=t,this.opts=n}defs;fn;opts;result(e){return new Gd(this.defs,Wd(e),{fn:this.fn,opts:this.opts})}};function Wd(e){return typeof e==`string`?new Of(e):e}var Gd=class e{constructor(e,t,n){this.defs=e,this.root=t,this.dyn=n}defs;root;dyn;cache=new Map;staticBound;bind=(...e)=>{let t=this.dyn;if(!t)return this.staticBound??=new Kd(new Map(Object.entries(this.defs)),this.root);let n=t.opts.key?.(...e);if(n!==void 0){let e=this.cache.get(n);if(e)return this.cache.delete(n),this.cache.set(n,e),e}let r=t.fn(...e),i=new Map(Object.entries(this.defs));for(let[e,t]of Object.entries(r)){if(i.has(e))throw new bu(`the dynamic step redefined "${e}".`);i.set(e,t)}let a=new Kd(i,this.root);if(n!==void 0){this.cache.set(n,a);let e=t.opts.cacheSize??4;for(;this.cache.size>e;)this.cache.delete(this.cache.keys().next().value)}return a};adapt(t){let n=this.dyn;if(!n)return this;let r=n.opts.key;return new e(this.defs,this.root,{fn:(...e)=>n.fn(...t(...e)),opts:{...n.opts,...r?{key:(...e)=>r(...t(...e))}:{}}})}render(e,...t){return this.bind(...t).render(e)}},Kd=class{constructor(e,t){this.env=e,this.root=t;let n=[],r=t=>{for(let r of t.refNames())!e.has(r)&&!n.includes(r)&&n.push(r)};r(t);for(let t of e.values())r(t);if(n.length)throw new bu(`unresolved ref(s) ${n.join(`, `)}.`)}env;root;rendered=new Map;render(e){let t=this.rendered.get(e.id);if(!t){let n=()=>this.render(Xl),r=new Fd(e,this.env,n),i;try{i=r.compile(this.root)}catch(t){if(!(t instanceof Pd))throw t;r=new Fd(e,this.env,n,!0),i=r.compile(this.root)}r.finish(),t=new zd(r,i),this.rendered.set(e.id,t)}return t}},qd=new WeakMap;function Jd(e){let t=qd.get(e);return t||qd.set(e,t=new Gd({},e)),t}var Yd=Object.freeze({}),Xd=Object.freeze([]),Zd=class{meta=Yd;checks=Xd;_refNames;refNames(){if(!this._refNames){let e=new Set;this instanceof Of&&e.add(this.name);for(let t of this.children())for(let n of t.refNames())e.add(n);if(this.meta.forModels)for(let t of this.meta.forModels.refNames())e.add(t);this._refNames=e}return this._refNames}with(e){let t=Object.create(Object.getPrototypeOf(this));return Object.assign(t,this,e,{_refNames:void 0}),t}describe(e){return this.with({meta:{...this.meta,description:e}})}title(e){return this.with({meta:{...this.meta,title:e}})}example(...e){return this.with({meta:{...this.meta,examples:[...this.meta.examples??[],...e]}})}refine(e,t,n){let r={fn:e,...t===void 0?{}:{message:t},visible:n?.visible??t!==void 0};return this.with({checks:[...this.checks,r]})}brand(){return this}forPeople(){return this.with({meta:{...this.meta,audience:`people`}})}forModels(e){return this.with({meta:{...this.meta,forModels:e}})}optional(){return new Ef(this)}nullable(){return new Df(this)}default(e){return new Tf(this,e)}bind(){return Jd(this).bind()}render(e){return Jd(this).bind().render(e)}ruleHint(){let e=this.checks.filter(e=>e.visible&&e.message).map(e=>e.message);return e.length?`Rules: ${e.join(` `)}`:void 0}hintOf(e){let t=[...e],n=this.ruleHint();return n&&t.push(n),t.length?t.join(` `):void 0}},Qd={"date-time":/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,date:/^\d{4}-\d{2}-\d{2}$/,time:/^\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,duration:/^-?P(?=\d|T\d)(\d+(\.\d+)?Y)?(\d+(\.\d+)?M)?(\d+(\.\d+)?W)?(\d+(\.\d+)?D)?(T(?=\d)(\d+(\.\d+)?H)?(\d+(\.\d+)?M)?(\d+(\.\d+)?S)?)?$/,email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,uuid:/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,uri:/^[a-zA-Z][a-zA-Z\d+.-]*:\S*$/,hostname:/^(?=.{1,253}$)[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,ipv4:/^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:{test:e=>e.includes(`:`)&&/^[0-9a-fA-F:.]+$/.test(e)&&$d(`[${e}]`)}};function $d(e){try{return new URL(`http://${e}/`),!0}catch{return!1}}function ef(e){if(/\(\?<?[=!]|\\[bB]|\\[pP]\{|\\[1-9]|\\k</.test(e))return!1;for(let t of e.matchAll(/\{(\d+)(?:,(\d*))?\}/g))if(Number(t[1])>100||Number(t[2]||0)>100)return!1;return!0}var tf=class extends Zd{constructor(e={}){super(),this.options=e}options;kind=`string`;children(){return[]}min(e){return this.opts({minLength:e})}max(e){return this.opts({maxLength:e})}pattern(e,t){let n=typeof e==`string`?t:t??(e.flags||void 0);return this.opts({pattern:typeof e==`string`?e:e.source,...n?{flags:n}:{}})}format(e){return this.opts({format:e})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`string`}compile(e){let t=this.options,n=e.profile,r=t.pattern===void 0?void 0:new RegExp(t.pattern,t.flags?.replace(/[gy]/g,``)),i=`/${t.pattern}/${t.flags??``}`,a=t.format===void 0?void 0:Qd[t.format],o=[];return e.node({hint:()=>this.hintOf(o),emit:()=>{let e={type:`string`};Kf(e,o,`minLength`,t.minLength,n.constraints.length,`At least ${t.minLength} characters.`),Kf(e,o,`maxLength`,t.maxLength,n.constraints.length,`At most ${t.maxLength} characters.`);let r=!t.flags&&(n.constraints.pattern===`full`||n.constraints.pattern===`basic`&&t.pattern!==void 0&&ef(t.pattern));return Kf(e,o,`pattern`,t.pattern,r,`Must match ${i}.`),Kf(e,o,`format`,t.format,n.formats===`all`||t.format!==void 0&&n.formats.has(t.format),`Format: ${t.format}.`),e},run:(e,n)=>typeof e==`string`?(t.minLength!==void 0&&e.length<t.minLength&&n.fail(`Must be at least ${t.minLength} characters.`,`rule`),t.maxLength!==void 0&&e.length>t.maxLength&&n.fail(`Must be at most ${t.maxLength} characters.`,`rule`),r&&!r.test(e)&&n.fail(`Must match ${i}.`,`rule`),a&&!a.test(e)&&n.fail(`Must be a valid ${t.format}.`,`rule`),e):Pf(n,e,`Expected a string, got ${jf(e)}.`),encode:e=>e})}},nf=class extends Zd{constructor(e={}){super(),this.options=e}options;kind=`number`;children(){return[]}min(e){return this.opts({minimum:e})}max(e){return this.opts({maximum:e})}gt(e){return this.opts({exclusiveMinimum:e})}lt(e){return this.opts({exclusiveMaximum:e})}positive(){return this.gt(0)}negative(){return this.lt(0)}nonnegative(){return this.min(0)}int(){return this.opts({int:!0})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`number`}compile(e){let t=this.options,n=e.profile.constraints.range,r=[];return e.node({hint:()=>this.hintOf(r),emit:()=>{let e={type:t.int?`integer`:`number`};return Kf(e,r,`minimum`,t.minimum,n,`At least ${t.minimum}.`),Kf(e,r,`maximum`,t.maximum,n,`At most ${t.maximum}.`),Kf(e,r,`exclusiveMinimum`,t.exclusiveMinimum,n,`Greater than ${t.exclusiveMinimum}.`),Kf(e,r,`exclusiveMaximum`,t.exclusiveMaximum,n,`Less than ${t.exclusiveMaximum}.`),e},run:(e,n)=>typeof e!=`number`||!Number.isFinite(e)?Pf(n,e,`Expected a number, got ${jf(e)}.`):(t.int&&!Number.isInteger(e)&&n.fail(`Expected a whole number.`,`type`),t.minimum!==void 0&&e<t.minimum&&n.fail(`Must be at least ${t.minimum}.`,`rule`),t.exclusiveMinimum!==void 0&&e<=t.exclusiveMinimum&&n.fail(`Must be greater than ${t.exclusiveMinimum}.`,`rule`),t.exclusiveMaximum!==void 0&&e>=t.exclusiveMaximum&&n.fail(`Must be less than ${t.exclusiveMaximum}.`,`rule`),t.maximum!==void 0&&e>t.maximum&&n.fail(`Must be at most ${t.maximum}.`,`rule`),e),encode:e=>e})}},rf=class extends Zd{kind=`boolean`;children(){return[]}print(){return`boolean`}compile(e){return e.node({hint:()=>this.ruleHint(),emit:()=>({type:`boolean`}),run:(e,t)=>typeof e==`boolean`?e:Pf(t,e,`Expected true or false, got ${jf(e)}.`),encode:e=>e})}},af=class extends Zd{kind=`null`;children(){return[]}print(){return`null`}compile(e){return e.node({emit:()=>({type:`null`}),run:(e,t)=>e===null?e:Pf(t,e,`Expected null, got ${jf(e)}.`),encode:e=>e})}},of=class extends Zd{constructor(e){super(),this.value=e}value;kind=`literal`;children(){return[]}print(){return JSON.stringify(this.value)}compile(e){let t=this.value;return e.node({hint:()=>this.ruleHint(),emit:()=>t===null?{type:`null`}:{type:Nf(t),enum:[t]},run:(e,n)=>e===t?e:Pf(n,e,`Expected ${JSON.stringify(t)}.`,`literal`,typeof t==`string`?()=>[t]:void 0),encode:e=>e})}},sf=class extends Zd{constructor(e){super(),this.values=e}values;kind=`enum`;children(){return[]}print(){return this.values.length?this.values.map(e=>JSON.stringify(e)).join(` | `):`never`}compile(e){let t=this.values;if(!t.length)return wf(e,()=>this.ruleHint());let n=new Set(t),r=e.profile.maxEnumValues,i=r!==void 0&&t.length>r;return e.node({hint:()=>this.hintOf(i?[`One of: ${t.join(`, `)}.`]:[]),emit:()=>i?{type:`string`}:{type:`string`,enum:[...t]},run:(e,r)=>typeof e!=`string`||!n.has(e)?Pf(r,e,`Expected one of: ${Ff(t)}.`,`enum`,()=>t):e,encode:e=>e})}},cf=class extends Zd{kind=`any`;children(){return[]}print(){return`any JSON value`}compile(e){let t=e.profile.any;return t===`empty`||t===`flat`?e.node({hint:()=>this.ruleHint(),emit:()=>t===`empty`?{}:{anyOf:uf.map(e=>({...e}))},run:(e,t)=>e===void 0?Pf(t,e,`Required.`,`required`):e,encode:e=>e}):lf(e.node({own:!0,hint:()=>this.hintOf([`Write the value as JSON text.`]),emit:()=>({type:`string`}),run:(e,t)=>{let n=Rd(e,t);return n===Ld?e:n},encode:e=>JSON.stringify(e)}))}};function lf(e){return e.jsonText=!0,e}var uf=Object.freeze([{type:`string`},{type:`number`},{type:`boolean`},{type:`null`},{type:`array`},{type:`object`,additionalProperties:!0}]),df=class extends Zd{constructor(e,t={}){super(),this.element=e,this.options=t}element;options;kind=`array`;children(){return[this.element]}min(e){return this.with({options:{...this.options,minItems:e}})}max(e){return this.with({options:{...this.options,maxItems:e}})}print(e){let t=e.print(this.element);return/[|&]/.test(t)?`(${t})[]`:`${t}[]`}compile(e){let t=Cf(this.element,e.env)?{...this.options,maxItems:0}:this.options,n=(t.minItems??0)>0?e.compile(this.element):e.guarded(this.element),r=e.profile.constraints.items,i=[];return e.node({deps:[n],hint:()=>this.hintOf(i),emit:()=>{let e={type:`array`,items:n.json()};return Kf(e,i,`minItems`,t.minItems,r===`all`||r===`min-0-1`&&(t.minItems??0)<=1,`At least ${t.minItems} items.`),Kf(e,i,`maxItems`,t.maxItems,r===`all`,`At most ${t.maxItems} items.`),e},run:(e,r)=>{let i=qf(e,r,`array`);if(!Array.isArray(i))return Pf(r,i,`Expected a list, got ${jf(i)}.`);t.minItems!==void 0&&i.length<t.minItems&&r.fail(`Must have at least ${t.minItems} items.`,`rule`),t.maxItems!==void 0&&i.length>t.maxItems&&r.fail(`Must have at most ${t.maxItems} items.`,`rule`);let a=i;for(let e=0;e<i.length;e++){r.enter(e);let t=n.run(i[e],r);r.leave(),t!==i[e]&&!r.dry&&(a=Zf(a,i,e,t,r))}return a},encode:(e,t)=>Jf(e,e=>n.encode(e,t),t),child:()=>n})}},ff=class extends Zd{constructor(e){super(),this.items=e}items;kind=`tuple`;children(){return this.items}print(e){return`[${this.items.map(t=>e.print(t)).join(`, `)}]`}compile(e){let t=this.items.map(t=>e.compile(t)),n=e.profile.tuples,r=t.length,i=(e,n,i)=>{let a=e;for(let o=0;o<r;o++){n.enter(i(o),o);let r=t[o].run(e[o],n);n.leave(),r!==e[o]&&!n.dry&&(a=Zf(a,e,o,r,n))}return a};return e.node({own:n===`object`,deps:t,hint:()=>this.hintOf(n===`object`?[`Positions are written as keys "0".."${r-1}".`]:n===`array`?[`Exactly ${r} items, in order: ${this.items.map(t=>t.print(new Sd(e.env))).join(`, `)}.`]:[]),emit:()=>{if(n===`object`){let n={};return t.forEach((e,t)=>n[String(t)]=e.json()),e.object(n,Object.keys(n))}return n===`prefixItems`?{type:`array`,prefixItems:t.map(e=>e.json()),minItems:r,maxItems:r}:{type:`array`,items:{anyOf:t.map(e=>e.json())}}},run:(e,t)=>{if(n===`object`){let n=qf(e,t,`object`);if(!Af(n))return Pf(t,n,`Expected an object with keys "0".."`+(r-1)+`".`);let a=Array(r);for(let e=0;e<r;e++)a[e]=n[String(e)];t.dry||t.stats.arrays++;let o=i(a,t,e=>String(e));return t.dry?n:o}let a=qf(e,t,`array`);return Array.isArray(a)?(a.length!==r&&t.fail(`Expected exactly ${r} items.`,`rule`),i(a,t,e=>e)):Pf(t,a,`Expected a list of ${r} items.`)},encode:(e,r)=>{let i=e;if(n!==`object`)return Jf(i,(e,n)=>t[n].encode(e,r),r);let a={};return r.objects++,i.forEach((e,n)=>a[String(n)]=t[n].encode(e,r)),a},child:e=>t[Number(e)]})}},pf=class e extends Zd{constructor(e,t=!1,n={}){super(),this.shape=e,this.closed=t,this.extras=n}shape;closed;extras;kind=`object`;children(){let e=Object.values(this.shape);this.extras.rest&&e.push(this.extras.rest);for(let t of this.extras.patterns??[])e.push(t.schema);return e}strict(){return this.with({closed:!0})}extend(t){return new e({...this.shape,...t},this.closed,this.extras)}rest(t){return new e(this.shape,this.closed,{...this.extras,rest:t})}patterns(t){let n=Object.entries(t).map(([e,t])=>({pattern:e,schema:t}));return new e(this.shape,this.closed,{...this.extras,patterns:[...this.extras.patterns??[],...n]})}dependent(t,n,r,i){let a=new bf(n,r,i??new cf);return new e({...this.shape,[t]:a},this.closed,this.extras)}print(e){let t=Object.entries(this.shape).map(([t,n])=>{let r=n instanceof Ef||n instanceof Tf;return`${/^[A-Za-z_$][\w$]*$/.test(t)?t:JSON.stringify(t)}${r?`?`:``}: ${e.print(r?n.inner:n)}`}),n=this.extraValue();return n&&t.push(`[key: string]: ${e.print(n)}`),`{ ${t.join(`; `)} }`}_extraValue;extraValue(){if(this._extraValue===void 0){let e=[...(this.extras.patterns??[]).map(e=>e.schema),...this.extras.rest?[this.extras.rest]:[]];this._extraValue=e.length===0?null:e.length===1?e[0]:new gf(e)}return this._extraValue??void 0}compile(e){let t=e.profile,n=t.optional===`null`,r=t.audience!==`people`,i=[],a=new Set;for(let[t,n]of Object.entries(this.shape)){let o=r?n.meta.forModels:void 0,s=o?o.meta.description===void 0&&n.meta.description!==void 0?o.describe(n.meta.description):o:n;if(r&&n.meta.audience===`people`){a.add(t);continue}let c=s instanceof Tf?s:void 0,l=s instanceof Ef||!!c,u=s instanceof Ef?s.inner:c?c.inner:s;if(l&&Cf(u,e.env)){a.add(t);continue}let d=l?e.guarded(u,s):e.compile(u);i.push({key:t,optional:l,node:d,nullable:u instanceof Df,...u instanceof bf?{dep:u}:{},...c?{dflt:c}:{}})}let o=i.filter(e=>!e.dep),s=i.filter(e=>e.dep),c=new Set(Object.keys(this.shape)),l=this.extraValue(),u=(this.extras.patterns??[]).map(t=>({re:new RegExp(t.pattern),pattern:t.pattern,node:e.guarded(t.schema)})),d=this.extras.rest?e.guarded(this.extras.rest):void 0,f=l?t.records===`pairs`?`pairs`:t.patternProperties?`keywords`:`open`:`none`,p=f===`pairs`?c.has(`extra`)?`_extra`:`extra`:``,m=l&&f!==`keywords`?e.guarded(l):void 0,h=e=>u.find(t=>t.re.test(e))?.node??d;return e.node({own:n&&i.some(e=>e.optional&&!e.nullable)||a.size>0||f===`pairs`||i.some(e=>e.dflt),deps:[...i.map(e=>e.node),...u.map(e=>e.node),...d?[d]:[],...m?[m]:[]],hint:()=>this.hintOf(f===`pairs`?[`Other keys go in "${p}" as a list of {key, value} entries.`]:f===`open`&&u.length?[`Other keys: ${u.map(t=>`keys matching /${t.pattern}/ hold ${t.node.schema?.print(new Sd(e.env))??`a value`}`).join(`; `)}${d?`; any other key holds the rest`:``}.`]:[]),emit:()=>{let r={},a=[];for(let t of i){let i=t.node.json();t.dep&&(i={...i,description:[i.description,`Its type is given by "${t.dep.on}".`].filter(Boolean).join(`
60
+ `)}`:t}},Td=new Set([`object`,`array`,`record`,`tuple`]),Ed=new WeakMap;function Dd(e){let t=Ed.get(e);return t===void 0&&(t=e.kind===`dependent`||e.children().some(Dd),Ed.set(e,t)),t}var Od=new WeakMap;function kd(e){let t=Od.get(e);return t===void 0&&(t=+!!Td.has(e.kind)+Math.max(0,...e.children().map(kd)),Od.set(e,t)),t}var Ad=new WeakMap,jd=new WeakMap;function Md(e){let t=jd.get(e);return t||jd.set(e,t=new Ld(e,Nd,Fd,!1,!0)),t}var Nd=new Map,Pd;function Fd(){if(!Pd){let e=Md(Ql);Pd=new Vd(e,e.node({emit:()=>({}),run:e=>e,encode:e=>e}))}return Pd}var Id=class extends Error{},Ld=class{constructor(e,t,n,r=!1,i=!1){this.profile=e,this.env=t,this.lenient=n,this.inlineOnce=r,this.shared=i,this.view=yu(e)}profile;env;lenient;inlineOnce;shared;nodes=[];defs=new Map;glossary=new Set;inlined=new Set;recursive=new Map;view;stack=[];depth=0;guard=0;isRecursive(e){let t=this.recursive.get(e);if(t===void 0){let n=new Set,r=[...this.env.get(e)?.refNames()??[]];for(t=!1;r.length;){let i=r.pop();if(i===e){t=!0;break}n.has(i)||(n.add(i),r.push(...this.env.get(i)?.refNames()??[]))}this.recursive.set(e,t)}return t}node(e){return new Cd(e,this)}compile(e,t){if(this.profile.audience!==`people`&&e.meta.forModels){let{forModels:t,...n}=e.meta,r=t;e=r.meta.description===void 0&&n.description!==void 0?r.describe(n.description):r}let n=Td.has(e.kind);if(n&&this.profile.maxDepth!==void 0&&this.depth>=this.profile.maxDepth)return this.escape(e,`Nested too deep for this model to describe directly.`);let r=!t&&e.refNames().size===0&&!Dd(e)&&(this.profile.maxDepth===void 0||this.depth+kd(e)<this.profile.maxDepth);if(r){let t=Ad.get(e)?.get(this.profile.id);if(t)return t;if(!this.shared){let t=Md(this.profile),n=t.compile(e);return t.finish(),n}}n&&this.depth++;let i=e.compile(this);if(n&&this.depth--,i.schema=e,i.outer=t,this.nodes.push(i),r){let t=Ad.get(e);t||Ad.set(e,t=new Map),t.set(this.profile.id,i)}return i}guarded(e,t){this.guard++;try{return this.compile(e,t)}finally{this.guard--}}ref(e){let t=this.env.get(e);if(!t)throw new Su(`ref "${e}" is not defined (the chain's types should have prevented this).`);let n=this.profile,r=this.stack.find(t=>t.name===e);if(r)return n.defs&&(n.recursion===!0||n.recursion===`guarded`&&this.guard>r.guard)?this.defRef(e,this.defs.get(e)):this.escape(t,`"${e}" contains itself, which this model cannot describe directly.`,e);if(n.defs){let n=this.defs.get(e);if(n)return this.defRef(e,n);let r=new Rd(this);return this.defs.set(e,r),this.stack.push({name:e,guard:this.guard}),r.target=this.compile(t),this.stack.pop(),this.nodes.push(r),this.defRef(e,r)}if(this.inlineOnce&&this.isRecursive(e)){if(this.inlined.has(e))return this.escape(t,`"${e}" is written out once elsewhere in this schema.`,e);this.inlined.add(e)}else if(!this.inlineOnce&&this.nodes.length>4e3)throw new Id;this.stack.push({name:e,guard:this.guard});let i=this.compile(t);return this.stack.pop(),i}defRef(e,t){let n=this.node({deps:[t],emit:()=>({$ref:`#/$defs/${e.replace(/~/g,`~0`).replace(/\//g,`~1`)}`}),run:(e,n)=>t.run(e,n),encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)});return this.nodes.push(n),n.refName=e,n}escape(e,t,n){let r=new wd(this.env),i=n??r.print(e);for(let e of n?[n]:r.used())this.glossary.add(e);let a=n||r.used().length?` (its named types are defined in the description of the whole schema)`:``,o,s=()=>o??=this.lenient().nodeFor(e),c=this.node({own:!0,emit:()=>({type:`string`,description:`${t} Write it as JSON text of this TypeScript type: ${i}${a}.`}),run:(e,t)=>{let n=Bd(e,t);if(n===zd)return e;t.enter(`(json)`,null);let r=s().run(n,t);return t.leave(!1),r},encode:e=>JSON.stringify(e)});return c.jsonText=!0,this.nodes.push(c),c}late(e){let t=this.compile(e);return this.finish(),t}finish(){for(let e=!0;e;){e=!1;for(let t of this.nodes)t.needs||(t.own||t.deps.some(e=>e.needs))&&(t.needs=!0,e=!0)}this.shared&&(this.nodes.length=0)}text(e){return e===void 0?void 0:typeof e==`function`?e(this.view):e}nullable(e){let t=this.profile.nulls;if(e.nullable===!0||Array.isArray(e.type)&&e.type.includes(`null`)||e.type===`null`)return e;if(t===`nullable`)return{...e,nullable:!0};if(t===`type-array`&&typeof e.type==`string`&&!(`$ref`in e)&&!(`anyOf`in e)){let t={...e,type:[e.type,`null`]};return Array.isArray(e.enum)&&(t.enum=[...e.enum,null]),t}if(Array.isArray(e.anyOf)&&!(`$ref`in e))return e.anyOf.some(e=>e.type===`null`)?e:{...e,anyOf:[...e.anyOf,{type:`null`}]};let{description:n,...r}=e;return n===void 0?{anyOf:[r,{type:`null`}]}:{anyOf:[r,{type:`null`}],description:n}}object(e,t,n=this.profile.closedObjects){let r={type:`object`,properties:e,required:[...t]};return n&&(r.additionalProperties=!1),this.profile.propertyOrdering&&(r.propertyOrdering=Object.keys(e)),r}decorate(e,t){let n=[],r=[e.schema?.meta,e.outer?.meta],i,a=[];for(let t of r){if(!t)continue;let r=this.text(t.description);if(r&&n.push(r),t.title&&(i=t.title),t.examples)for(let n of t.examples)this.checkExample(e,n),a.push(e.encode(n))}let o=e.impl?.hint?.(this.view);o&&n.push(o);let s=typeof t.description==`string`?t.description:void 0;s&&n.push(s);let c={...t};if(i&&(c.title=i),a.length&&(this.profile.examples===`keyword`?c.examples=a:this.profile.examples===`description`&&n.push(`Example${a.length>1?`s`:``}: ${a.map(e=>JSON.stringify(e)).join(` ; `)}`)),n.length&&(c.description=n.join(`
61
+ `)),this.profile.refSiblings===!1&&typeof c.$ref==`string`&&(c.description!==void 0||c.title!==void 0||c.examples!==void 0)){let{$ref:e,...t}=c;return{anyOf:[{$ref:e}],...t}}return c}checkExample(e,t){let n=e.schema;if(!n)return;let r=new Sd(!1,!0,hd(),!1);if(this.lenient().nodeFor(n).run(t,r),r.errors.length)throw new Su(`example ${JSON.stringify(t)} does not fit its schema:
62
+ ${Ud(r.errors)}`)}},Rd=class extends Cd{target;constructor(e){super(void 0,e)}get own(){return!1}get deps(){return this.target?[this.target]:[]}json(){return this.target.json()}run(e,t){return this.target.run(e,t)}encode(e,t=hd()){return this.target.encode(e,t)}child(e){return this.target.child(e)}},zd=Symbol(`failed`);function Bd(e,t){if(typeof e!=`string`)return t.repair&&e!==void 0?(t.dry||t.stats.repaired++,e):(t.fail(`Expected a string of JSON text.`,`type`),zd);try{let n=JSON.parse(e);return t.dry||t.stats.parsed++,n}catch(e){return t.fail(`Not valid JSON text: ${e.message}`,`json`),zd}}var Vd=class{constructor(e,t){this.compiler=e,this.root=t}compiler;root;_json;_body;_wrapped;_measure;_encoder;get profile(){return this.compiler.profile}body(){if(!this._body){let e=this.root.refName;this._body=e?this.compiler.defs.get(e).json():this.root.json()}return this._body}get wrapped(){if(this._wrapped===void 0){let e=this.body();this._wrapped=this.profile.rootObject&&!(e.type===`object`&&!(`anyOf`in e))}return this._wrapped}get jsonSchema(){if(this._json)return this._json;let e=this.body();if(this.wrapped&&(e=this.compiler.object({input:e},[`input`],this.profile.closedObjects||this.profile.strict)),this.compiler.glossary.size){let t=`Named types used by the fields written as JSON text:
63
+ ${new wd(this.compiler.env).definitions(this.compiler.glossary)}`;e={...e,description:typeof e.description==`string`?`${e.description}
64
+ ${t}`:t}}let t={};for(let[e,n]of this.compiler.defs)t[e]=n.json();return this._json=this.compiler.defs.size?{...e,$defs:t}:e,this._json}get measure(){return this._measure??=bu(this.jsonSchema)}parse(e,t){return this.decode(e,t,void 0)}decode(e,t,n){let r=hd(),i=t?.inPlace??!0,a=new Sd(i,!1,r,t?.repair??!0),o=i&&!n&&Mu(t?.errorFormat);o&&a.keepUndo();let s;if(this.wrapped?typeof e!=`object`||!e||Array.isArray(e)||!(`input`in e)?a.fail(`Expected an object with an "input" field.`,`type`):(a.enter(`input`,null),s=this.root.run(e.input,a),a.leave(!1)):s=this.root.run(e,a),a.errors.length){a.restore(),a.releaseUndo();let i=n?n():e;return{ok:!1,issues:a.errors,message:Qu(a.errors,i,Au(t?.errorFormat),t?.label),stats:r}}return o&&a.releaseUndo(),{ok:!0,value:s,stats:r}}parseText(e,t){let n;try{n=JSON.parse(e)}catch(e){let n=[{path:[],codePath:[],message:`Not valid JSON: ${e.message}`}];return Pu(n[0],{kind:`json`}),{ok:!1,issues:n,message:Qu(n,void 0,Au(t?.errorFormat),t?.label),stats:hd()}}return this.decode(n,t,()=>JSON.parse(e))}parseOrThrow(e,t){let n=this.parse(e,t);if(!n.ok)throw new Cu(n.issues,n.message);return n.value}encode(e,t=hd()){let n=this.root.encode(e,t);return this.wrapped?(t.objects++,{input:n}):n}encodeAt(e,t,n=hd()){let r=Hd(t);if(!r.length)return this.encode(e,n);let i=this.root;for(let e of r)if(i=i?.child(e),!i)throw new Su(`no schema at path ${gd(r)}.`);return i.encode(e,n)}encodeText(e,t={}){let n=t.path===void 0?this.encode(e):this.encodeAt(e,t.path),r=t.pretty===!0?2:typeof t.pretty==`number`?t.pretty:void 0;return JSON.stringify(n,null,r)}get encoder(){if(!this._encoder){let e=((e,t)=>this.encodeText(e,t));e.wire=(e,t)=>t===void 0?this.encode(e):this.encodeAt(e,t),this._encoder=Object.freeze(e)}return this._encoder}nodeFor(e){let t=this.lateNodes.get(e);return t||this.lateNodes.set(e,t=this.compiler.late(e)),t}lateNodes=new WeakMap;typescript(){let e=this.root.schema;return new wd(this.compiler.env).full(e)}};function Hd(e){return e===void 0||e===``?[]:typeof e==`string`?e.split(`.`).map(e=>/^\d+$/.test(e)?Number(e):e):[...e]}function Ud(e){return e.map(e=>`- at ${gd(e.path)}: ${e.message}`).join(`
65
+ `)}var Wd=class e{constructor(e={}){this.defs=e}defs;define(t){for(let e of Object.keys(t))if(e in this.defs)throw new Su(`"${e}" is already defined.`);return new e({...this.defs,...t})}declare(){return this}dynamic(e,t={}){return new Gd(this.defs,e,t)}result(e){return new qd(this.defs,Kd(e))}},Gd=class{constructor(e,t,n){this.defs=e,this.fn=t,this.opts=n}defs;fn;opts;result(e){return new qd(this.defs,Kd(e),{fn:this.fn,opts:this.opts})}};function Kd(e){return typeof e==`string`?new Af(e):e}var qd=class e{constructor(e,t,n){this.defs=e,this.root=t,this.dyn=n}defs;root;dyn;cache=new Map;staticBound;bind=(...e)=>{let t=this.dyn;if(!t)return this.staticBound??=new Jd(new Map(Object.entries(this.defs)),this.root);let n=t.opts.key?.(...e);if(n!==void 0){let e=this.cache.get(n);if(e)return this.cache.delete(n),this.cache.set(n,e),e}let r=t.fn(...e),i=new Map(Object.entries(this.defs));for(let[e,t]of Object.entries(r)){if(i.has(e))throw new Su(`the dynamic step redefined "${e}".`);i.set(e,t)}let a=new Jd(i,this.root);if(n!==void 0){this.cache.set(n,a);let e=t.opts.cacheSize??4;for(;this.cache.size>e;)this.cache.delete(this.cache.keys().next().value)}return a};adapt(t){let n=this.dyn;if(!n)return this;let r=n.opts.key;return new e(this.defs,this.root,{fn:(...e)=>n.fn(...t(...e)),opts:{...n.opts,...r?{key:(...e)=>r(...t(...e))}:{}}})}render(e,...t){return this.bind(...t).render(e)}},Jd=class{constructor(e,t){this.env=e,this.root=t;let n=[],r=t=>{for(let r of t.refNames())!e.has(r)&&!n.includes(r)&&n.push(r)};r(t);for(let t of e.values())r(t);if(n.length)throw new Su(`unresolved ref(s) ${n.join(`, `)}.`)}env;root;rendered=new Map;render(e){let t=this.rendered.get(e.id);if(!t){let n=()=>this.render(Ql),r=new Ld(e,this.env,n),i;try{i=r.compile(this.root)}catch(t){if(!(t instanceof Id))throw t;r=new Ld(e,this.env,n,!0),i=r.compile(this.root)}r.finish(),t=new Vd(r,i),this.rendered.set(e.id,t)}return t}},Yd=new WeakMap;function Xd(e){let t=Yd.get(e);return t||Yd.set(e,t=new qd({},e)),t}var Zd=Object.freeze({}),Qd=Object.freeze([]),$d=class{meta=Zd;checks=Qd;_refNames;refNames(){if(!this._refNames){let e=new Set;this instanceof Af&&e.add(this.name);for(let t of this.children())for(let n of t.refNames())e.add(n);if(this.meta.forModels)for(let t of this.meta.forModels.refNames())e.add(t);this._refNames=e}return this._refNames}with(e){let t=Object.create(Object.getPrototypeOf(this));return Object.assign(t,this,e,{_refNames:void 0}),t}describe(e){return this.with({meta:{...this.meta,description:e}})}title(e){return this.with({meta:{...this.meta,title:e}})}example(...e){return this.with({meta:{...this.meta,examples:[...this.meta.examples??[],...e]}})}refine(e,t,n){let r={fn:e,...t===void 0?{}:{message:t},visible:n?.visible??t!==void 0};return this.with({checks:[...this.checks,r]})}brand(){return this}forPeople(){return this.with({meta:{...this.meta,audience:`people`}})}forModels(e){return this.with({meta:{...this.meta,forModels:e}})}optional(){return new Of(this)}nullable(){return new kf(this)}default(e){return new Df(this,e)}bind(){return Xd(this).bind()}render(e){return Xd(this).bind().render(e)}ruleHint(){let e=this.checks.filter(e=>e.visible&&e.message).map(e=>e.message);return e.length?`Rules: ${e.join(` `)}`:void 0}hintOf(e){let t=[...e],n=this.ruleHint();return n&&t.push(n),t.length?t.join(` `):void 0}},ef={"date-time":/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,date:/^\d{4}-\d{2}-\d{2}$/,time:/^\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,duration:/^-?P(?=\d|T\d)(\d+(\.\d+)?Y)?(\d+(\.\d+)?M)?(\d+(\.\d+)?W)?(\d+(\.\d+)?D)?(T(?=\d)(\d+(\.\d+)?H)?(\d+(\.\d+)?M)?(\d+(\.\d+)?S)?)?$/,email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,uuid:/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,uri:/^[a-zA-Z][a-zA-Z\d+.-]*:\S*$/,hostname:/^(?=.{1,253}$)[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,ipv4:/^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:{test:e=>e.includes(`:`)&&/^[0-9a-fA-F:.]+$/.test(e)&&tf(`[${e}]`)}};function tf(e){try{return new URL(`http://${e}/`),!0}catch{return!1}}function nf(e){if(/\(\?<?[=!]|\\[bB]|\\[pP]\{|\\[1-9]|\\k</.test(e))return!1;for(let t of e.matchAll(/\{(\d+)(?:,(\d*))?\}/g))if(Number(t[1])>100||Number(t[2]||0)>100)return!1;return!0}var rf=class extends $d{constructor(e={}){super(),this.options=e}options;kind=`string`;children(){return[]}min(e){return this.opts({minLength:e})}max(e){return this.opts({maxLength:e})}pattern(e,t){let n=typeof e==`string`?t:t??(e.flags||void 0);return this.opts({pattern:typeof e==`string`?e:e.source,...n?{flags:n}:{}})}format(e){return this.opts({format:e})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`string`}compile(e){let t=this.options,n=e.profile,r=t.pattern===void 0?void 0:new RegExp(t.pattern,t.flags?.replace(/[gy]/g,``)),i=`/${t.pattern}/${t.flags??``}`,a=t.format===void 0?void 0:ef[t.format],o=[];return e.node({hint:()=>this.hintOf(o),emit:()=>{let e={type:`string`};Jf(e,o,`minLength`,t.minLength,n.constraints.length,`At least ${t.minLength} characters.`),Jf(e,o,`maxLength`,t.maxLength,n.constraints.length,`At most ${t.maxLength} characters.`);let r=!t.flags&&(n.constraints.pattern===`full`||n.constraints.pattern===`basic`&&t.pattern!==void 0&&nf(t.pattern));return Jf(e,o,`pattern`,t.pattern,r,`Must match ${i}.`),Jf(e,o,`format`,t.format,n.formats===`all`||t.format!==void 0&&n.formats.has(t.format),`Format: ${t.format}.`),e},run:(e,n)=>typeof e==`string`?(t.minLength!==void 0&&e.length<t.minLength&&n.fail(`Must be at least ${t.minLength} characters.`,`rule`),t.maxLength!==void 0&&e.length>t.maxLength&&n.fail(`Must be at most ${t.maxLength} characters.`,`rule`),r&&!r.test(e)&&n.fail(`Must match ${i}.`,`rule`),a&&!a.test(e)&&n.fail(`Must be a valid ${t.format}.`,`rule`),e):If(n,e,`Expected a string, got ${Nf(e)}.`),encode:e=>e})}},af=class extends $d{constructor(e={}){super(),this.options=e}options;kind=`number`;children(){return[]}min(e){return this.opts({minimum:e})}max(e){return this.opts({maximum:e})}gt(e){return this.opts({exclusiveMinimum:e})}lt(e){return this.opts({exclusiveMaximum:e})}positive(){return this.gt(0)}negative(){return this.lt(0)}nonnegative(){return this.min(0)}int(){return this.opts({int:!0})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`number`}compile(e){let t=this.options,n=e.profile.constraints.range,r=[];return e.node({hint:()=>this.hintOf(r),emit:()=>{let e={type:t.int?`integer`:`number`};return Jf(e,r,`minimum`,t.minimum,n,`At least ${t.minimum}.`),Jf(e,r,`maximum`,t.maximum,n,`At most ${t.maximum}.`),Jf(e,r,`exclusiveMinimum`,t.exclusiveMinimum,n,`Greater than ${t.exclusiveMinimum}.`),Jf(e,r,`exclusiveMaximum`,t.exclusiveMaximum,n,`Less than ${t.exclusiveMaximum}.`),e},run:(e,n)=>typeof e!=`number`||!Number.isFinite(e)?If(n,e,`Expected a number, got ${Nf(e)}.`):(t.int&&!Number.isInteger(e)&&n.fail(`Expected a whole number.`,`type`),t.minimum!==void 0&&e<t.minimum&&n.fail(`Must be at least ${t.minimum}.`,`rule`),t.exclusiveMinimum!==void 0&&e<=t.exclusiveMinimum&&n.fail(`Must be greater than ${t.exclusiveMinimum}.`,`rule`),t.exclusiveMaximum!==void 0&&e>=t.exclusiveMaximum&&n.fail(`Must be less than ${t.exclusiveMaximum}.`,`rule`),t.maximum!==void 0&&e>t.maximum&&n.fail(`Must be at most ${t.maximum}.`,`rule`),e),encode:e=>e})}},of=class extends $d{kind=`boolean`;children(){return[]}print(){return`boolean`}compile(e){return e.node({hint:()=>this.ruleHint(),emit:()=>({type:`boolean`}),run:(e,t)=>typeof e==`boolean`?e:If(t,e,`Expected true or false, got ${Nf(e)}.`),encode:e=>e})}},sf=class extends $d{kind=`null`;children(){return[]}print(){return`null`}compile(e){return e.node({emit:()=>({type:`null`}),run:(e,t)=>e===null?e:If(t,e,`Expected null, got ${Nf(e)}.`),encode:e=>e})}},cf=class extends $d{constructor(e){super(),this.value=e}value;kind=`literal`;children(){return[]}print(){return JSON.stringify(this.value)}compile(e){let t=this.value;return e.node({hint:()=>this.ruleHint(),emit:()=>t===null?{type:`null`}:{type:Ff(t),enum:[t]},run:(e,n)=>e===t?e:If(n,e,`Expected ${JSON.stringify(t)}.`,`literal`,typeof t==`string`?()=>[t]:void 0),encode:e=>e})}},lf=class extends $d{constructor(e){super(),this.values=e}values;kind=`enum`;children(){return[]}print(){return this.values.length?this.values.map(e=>JSON.stringify(e)).join(` | `):`never`}compile(e){let t=this.values;if(!t.length)return Ef(e,()=>this.ruleHint());let n=new Set(t),r=e.profile.maxEnumValues,i=r!==void 0&&t.length>r;return e.node({hint:()=>this.hintOf(i?[`One of: ${t.join(`, `)}.`]:[]),emit:()=>i?{type:`string`}:{type:`string`,enum:[...t]},run:(e,r)=>typeof e!=`string`||!n.has(e)?If(r,e,`Expected one of: ${Lf(t)}.`,`enum`,()=>t):e,encode:e=>e})}},uf=class extends $d{kind=`any`;children(){return[]}print(){return`any JSON value`}compile(e){let t=e.profile.any;return t===`empty`||t===`flat`?e.node({hint:()=>this.ruleHint(),emit:()=>t===`empty`?{}:{anyOf:ff.map(e=>({...e}))},run:(e,t)=>e===void 0?If(t,e,`Required.`,`required`):e,encode:e=>e}):df(e.node({own:!0,hint:()=>this.hintOf([`Write the value as JSON text.`]),emit:()=>({type:`string`}),run:(e,t)=>{let n=Bd(e,t);return n===zd?e:n},encode:e=>JSON.stringify(e)}))}};function df(e){return e.jsonText=!0,e}var ff=Object.freeze([{type:`string`},{type:`number`},{type:`boolean`},{type:`null`},{type:`array`},{type:`object`,additionalProperties:!0}]),pf=class extends $d{constructor(e,t={}){super(),this.element=e,this.options=t}element;options;kind=`array`;children(){return[this.element]}min(e){return this.with({options:{...this.options,minItems:e}})}max(e){return this.with({options:{...this.options,maxItems:e}})}print(e){let t=e.print(this.element);return/[|&]/.test(t)?`(${t})[]`:`${t}[]`}compile(e){let t=Tf(this.element,e.env)?{...this.options,maxItems:0}:this.options,n=(t.minItems??0)>0?e.compile(this.element):e.guarded(this.element),r=e.profile.constraints.items,i=[];return e.node({deps:[n],hint:()=>this.hintOf(i),emit:()=>{let e={type:`array`,items:n.json()};return Jf(e,i,`minItems`,t.minItems,r===`all`||r===`min-0-1`&&(t.minItems??0)<=1,`At least ${t.minItems} items.`),Jf(e,i,`maxItems`,t.maxItems,r===`all`,`At most ${t.maxItems} items.`),e},run:(e,r)=>{let i=Yf(e,r,`array`);if(!Array.isArray(i))return If(r,i,`Expected a list, got ${Nf(i)}.`);t.minItems!==void 0&&i.length<t.minItems&&r.fail(`Must have at least ${t.minItems} items.`,`rule`),t.maxItems!==void 0&&i.length>t.maxItems&&r.fail(`Must have at most ${t.maxItems} items.`,`rule`);let a=i;for(let e=0;e<i.length;e++){r.enter(e);let t=n.run(i[e],r);r.leave(),t!==i[e]&&!r.dry&&(a=$f(a,i,e,t,r))}return a},encode:(e,t)=>Xf(e,e=>n.encode(e,t),t),child:()=>n})}},mf=class extends $d{constructor(e){super(),this.items=e}items;kind=`tuple`;children(){return this.items}print(e){return`[${this.items.map(t=>e.print(t)).join(`, `)}]`}compile(e){let t=this.items.map(t=>e.compile(t)),n=e.profile.tuples,r=t.length,i=(e,n,i)=>{let a=e;for(let o=0;o<r;o++){n.enter(i(o),o);let r=t[o].run(e[o],n);n.leave(),r!==e[o]&&!n.dry&&(a=$f(a,e,o,r,n))}return a};return e.node({own:n===`object`,deps:t,hint:()=>this.hintOf(n===`object`?[`Positions are written as keys "0".."${r-1}".`]:n===`array`?[`Exactly ${r} items, in order: ${this.items.map(t=>t.print(new wd(e.env))).join(`, `)}.`]:[]),emit:()=>{if(n===`object`){let n={};return t.forEach((e,t)=>n[String(t)]=e.json()),e.object(n,Object.keys(n))}return n===`prefixItems`?{type:`array`,prefixItems:t.map(e=>e.json()),minItems:r,maxItems:r}:{type:`array`,items:{anyOf:t.map(e=>e.json())}}},run:(e,t)=>{if(n===`object`){let n=Yf(e,t,`object`);if(!Mf(n))return If(t,n,`Expected an object with keys "0".."`+(r-1)+`".`);let a=Array(r);for(let e=0;e<r;e++)a[e]=n[String(e)];t.dry||t.stats.arrays++;let o=i(a,t,e=>String(e));return t.dry?n:o}let a=Yf(e,t,`array`);return Array.isArray(a)?(a.length!==r&&t.fail(`Expected exactly ${r} items.`,`rule`),i(a,t,e=>e)):If(t,a,`Expected a list of ${r} items.`)},encode:(e,r)=>{let i=e;if(n!==`object`)return Xf(i,(e,n)=>t[n].encode(e,r),r);let a={};return r.objects++,i.forEach((e,n)=>a[String(n)]=t[n].encode(e,r)),a},child:e=>t[Number(e)]})}},hf=class e extends $d{constructor(e,t=!1,n={}){super(),this.shape=e,this.closed=t,this.extras=n}shape;closed;extras;kind=`object`;children(){let e=Object.values(this.shape);this.extras.rest&&e.push(this.extras.rest);for(let t of this.extras.patterns??[])e.push(t.schema);return e}strict(){return this.with({closed:!0})}extend(t){return new e({...this.shape,...t},this.closed,this.extras)}rest(t){return new e(this.shape,this.closed,{...this.extras,rest:t})}patterns(t){let n=Object.entries(t).map(([e,t])=>({pattern:e,schema:t}));return new e(this.shape,this.closed,{...this.extras,patterns:[...this.extras.patterns??[],...n]})}dependent(t,n,r,i){let a=new Sf(n,r,i??new uf);return new e({...this.shape,[t]:a},this.closed,this.extras)}print(e){let t=Object.entries(this.shape).map(([t,n])=>{let r=n instanceof Of||n instanceof Df;return`${/^[A-Za-z_$][\w$]*$/.test(t)?t:JSON.stringify(t)}${r?`?`:``}: ${e.print(r?n.inner:n)}`}),n=this.extraValue();return n&&t.push(`[key: string]: ${e.print(n)}`),`{ ${t.join(`; `)} }`}_extraValue;extraValue(){if(this._extraValue===void 0){let e=[...(this.extras.patterns??[]).map(e=>e.schema),...this.extras.rest?[this.extras.rest]:[]];this._extraValue=e.length===0?null:e.length===1?e[0]:new vf(e)}return this._extraValue??void 0}compile(e){let t=e.profile,n=t.optional===`null`,r=t.audience!==`people`,i=[],a=new Set;for(let[t,n]of Object.entries(this.shape)){let o=r?n.meta.forModels:void 0,s=o?o.meta.description===void 0&&n.meta.description!==void 0?o.describe(n.meta.description):o:n;if(r&&n.meta.audience===`people`){a.add(t);continue}let c=s instanceof Df?s:void 0,l=s instanceof Of||!!c,u=s instanceof Of?s.inner:c?c.inner:s;if(l&&Tf(u,e.env)){a.add(t);continue}let d=l?e.guarded(u,s):e.compile(u);i.push({key:t,optional:l,node:d,nullable:u instanceof kf,...u instanceof Sf?{dep:u}:{},...c?{dflt:c}:{}})}let o=i.filter(e=>!e.dep),s=i.filter(e=>e.dep),c=new Set(Object.keys(this.shape)),l=this.extraValue(),u=(this.extras.patterns??[]).map(t=>({re:new RegExp(t.pattern),pattern:t.pattern,node:e.guarded(t.schema)})),d=this.extras.rest?e.guarded(this.extras.rest):void 0,f=l?t.records===`pairs`?`pairs`:t.patternProperties?`keywords`:`open`:`none`,p=f===`pairs`?c.has(`extra`)?`_extra`:`extra`:``,m=l&&f!==`keywords`?e.guarded(l):void 0,h=e=>u.find(t=>t.re.test(e))?.node??d;return e.node({own:n&&i.some(e=>e.optional&&!e.nullable)||a.size>0||f===`pairs`||i.some(e=>e.dflt),deps:[...i.map(e=>e.node),...u.map(e=>e.node),...d?[d]:[],...m?[m]:[]],hint:()=>this.hintOf(f===`pairs`?[`Other keys go in "${p}" as a list of {key, value} entries.`]:f===`open`&&u.length?[`Other keys: ${u.map(t=>`keys matching /${t.pattern}/ hold ${t.node.schema?.print(new wd(e.env))??`a value`}`).join(`; `)}${d?`; any other key holds the rest`:``}.`]:[]),emit:()=>{let r={},a=[];for(let t of i){let i=t.node.json();t.dep&&(i={...i,description:[i.description,`Its type is given by "${t.dep.on}".`].filter(Boolean).join(`
66
66
  `)}),t.dflt&&(i={...i,description:[i.description,`Default when left out: ${JSON.stringify(t.node.encode(t.dflt.value))}.`].filter(Boolean).join(`
67
67
  `)}),t.optional&&n&&(i=e.nullable(i),i.description=[i.description,`Write null to leave it out.`].filter(Boolean).join(`
68
- `)),r[t.key]=i,(!t.optional||n)&&a.push(t.key)}f===`pairs`&&(r[p]={type:`array`,items:e.object({key:{type:`string`},value:m.json()},[`key`,`value`],!0)},n&&a.push(p));let o=e.object(r,a,this.closed||t.closedObjects);return f===`keywords`?(u.length&&(o.patternProperties=Object.fromEntries(u.map(e=>[e.pattern,e.node.json()]))),d&&(o.additionalProperties=d.json())):f===`open`&&(o.additionalProperties=m.json()),o},run:(t,r)=>{let i=qf(t,r,`object`);if(!Af(i))return Pf(r,i,`Expected an object, got ${jf(i)}.`);let u=i,d=u;for(let e=0;e<o.length;e++){let t=o[e],i=Object.prototype.hasOwnProperty.call(u,t.key)?u[t.key]:void 0;if(i===void 0){t.dflt?r.dry||(d=Yf(d,u,t.key,t.dflt.fresh(r.stats),r)):t.optional||(r.enter(t.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),t.node),r.leave());continue}if(i===null&&t.optional&&n&&!t.nullable){r.dry||(d=t.dflt?Yf(d,u,t.key,t.dflt.fresh(r.stats),r):Xf(d,u,t.key,r));continue}r.enter(t.key);let a=t.node.run(i,r);r.leave(),a!==i&&!r.dry&&(d=Yf(d,u,t.key,a,r))}for(let t=0;t<s.length;t++){let i=s[t],a=u[i.key];if(a===void 0||a===null&&i.optional&&n){a===null&&!r.dry?d=Xf(d,u,i.key,r):i.optional||(r.enter(i.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),i.node),r.leave());continue}r.enter(i.key);let o=r.errors.length,l=i.node.run(a,r);if(r.errors.length===o){let t=i.dep.schemaFor(d[i.dep.on]);t&&(l=e.lenient().nodeFor(t).run(l,r))}r.leave(),l!==a&&!r.dry&&(d=Yf(d,u,i.key,l,r))}if(a.size)for(let e of a)Object.prototype.hasOwnProperty.call(u,e)&&(r.enter(e),r.fail(`Not allowed.`,`not-allowed`),r.leave());if(f===`pairs`){let e=u[p];if(e!=null){r.enter(p,null);let t=qf(e,r,`array`);if(!Array.isArray(t))Pf(r,t,`Expected a list of {key, value} entries.`);else{r.dry||(d=Xf(d,u,p,r));for(let e=0;e<t.length;e++){let n=t[e];if(r.enter(e,null),!Af(n)||typeof n.key!=`string`){r.fail(`Expected a {key, value} entry with a string key.`,`type`),r.leave(!1);continue}let i=n.key;if(c.has(i)||Object.prototype.hasOwnProperty.call(d,i)){r.enter(`key`,null),r.fail(`Duplicate key "${i}".`,`rule`),r.leave(!1),r.leave(!1);continue}let a=h(i);r.enter(`value`,i);let o=a?a.run(n.value,r):this.closed?Pf(r,n.value,`Key "${i}" is not allowed.`,`not-allowed`):n.value;r.leave(),r.dry||(d=Yf(d,u,i,o,r)),r.leave(!1)}}r.leave(!1)}else p&&e===null&&!r.dry&&(d=Xf(d,u,p,r))}else if(l||this.closed){let e=Object.keys(u);for(let t=0;t<e.length;t++){let n=e[t];if(c.has(n))continue;let i=l?h(n):void 0;if(i){r.enter(n);let e=i.run(u[n],r);r.leave(),e!==u[n]&&!r.dry&&(d=Yf(d,u,n,e,r))}else this.closed&&(r.enter(n),r.fail(`Unknown field "${n}".`,`unknown-key`,n,()=>[...c].filter(e=>!Object.prototype.hasOwnProperty.call(u,e))),r.leave())}}return d},encode:(e,t)=>{let r=e,o={};t.objects++;let s=[];for(let e of Object.keys(r)){if(a.has(e)||c.has(e))continue;let n=h(e),i=n?n.encode(r[e],t):r[e];f===`pairs`?s.push({key:e,value:i}):o[e]=i}for(let e of i){let i=r[e.key];i===void 0?e.optional&&n&&(o[e.key]=null):o[e.key]=e.node.encode(i,t)}return f===`pairs`&&(s.length||n)&&(t.arrays++,t.objects+=s.length,o[p]=s),o},child:e=>i.find(t=>t.key===e)?.node??(typeof e==`string`?h(e):void 0)})}},mf=class extends Zd{constructor(e,t){super(),this.value=e,this.key=t}value;key;kind=`record`;children(){return this.key?[this.key,this.value]:[this.value]}print(e){return`{ [key: ${this.key?e.print(this.key):`string`}]: ${e.print(this.value)} }`}compile(e){let t=e.guarded(this.value),n=e.compile(this.key??hf),r=e.profile.records===`pairs`;return e.node({own:r,deps:[t,n],hint:e=>this.hintOf(r?[`A map written as ${e.recordWord}; each key at most once.`]:[]),emit:()=>{if(r)return{type:`array`,items:e.object({key:n.json(),value:t.json()},[`key`,`value`],!0)};let i={type:`object`,additionalProperties:t.json()};return this.key&&!e.profile.closedObjects&&!(this.key instanceof tf&&!Object.keys(this.key.options).length)&&(i.propertyNames=n.json()),i},run:(i,a)=>{if(r){let r=qf(i,a,`array`);if(!Array.isArray(r)){let t=a.repair?qf(i,a,`object`):i;if(a.repair&&!a.dry&&Af(t)){t===i&&a.stats.repaired++;let r=t,o=e.lenient().nodeFor(this.value),s=r;for(let e of Object.keys(r)){a.enter(e),n.run(e,a);let t=o.run(r[e],a);a.leave(),t!==r[e]&&!a.dry&&(s=Yf(s,r,e,t,a))}return s}return Pf(a,r,`Expected a list of {key, value} entries, got ${jf(r)}.`)}let o={};a.dry||a.stats.objects++;for(let e=0;e<r.length;e++){let i=r[e];if(a.enter(e,null),!Af(i)){Pf(a,i,`Expected a {key, value} entry.`),a.leave(!1);continue}let s=i.key;a.enter(`key`,null),s===void 0?a.fail(`Required.`,`required`,void 0,()=>Object.keys(i).filter(e=>e!==`key`&&e!==`value`),n):n.run(s,a),a.leave(!1),typeof s==`string`&&(Object.prototype.hasOwnProperty.call(o,s)&&(a.enter(`key`,null),a.fail(`Duplicate key "${s}".`,`rule`),a.leave(!1)),a.enter(`value`,s),o[s]=t.run(i.value,a),a.leave()),a.leave(!1)}return a.dry?r:o}let o=qf(i,a,`object`);if(!Af(o))return Pf(a,o,`Expected an object, got ${jf(o)}.`);let s=o,c=s;for(let e of Object.keys(s)){this.key&&(a.enter(e),n.run(e,a),a.leave()),a.enter(e);let r=t.run(s[e],a);a.leave(),r!==s[e]&&!a.dry&&(c=Yf(c,s,e,r,a))}return c},encode:(e,n)=>{let i=e;if(r){let e=Object.keys(i);return n.arrays++,n.objects+=e.length,e.map(e=>({key:e,value:t.encode(i[e],n)}))}let a=i;for(let e of Object.keys(i)){let r=t.encode(i[e],n);r!==i[e]&&(a===i&&(a={...i},n.objects++),a[e]=r)}return a},child:()=>t})}},hf=new tf,gf=class extends Zd{constructor(e,t){super(),this.options=e,this.tag=t}options;tag;kind=`union`;children(){return this.options}print(e){return this.options.map(t=>e.print(t)).join(` | `)}tagIndex(e,t){let n=this.tag??Vf(this.options,e);if(!n)return;let r=new Map,i=[];return this.options.forEach((a,o)=>{let s=t.has(o)?void 0:Lf(a,n,e);if(s)for(let e of s)r.has(e)||r.set(e,o);else i.push(o)}),{tag:n,byTag:r,fallback:i}}label(e,t){let n=this.tag?Wf(this.options[e],t).shape?.[this.tag]:void 0;return n instanceof of&&typeof n.value==`string`?n.value:`option${e+1}`}compile(e){if(this.options.some(t=>Cf(t,e.env))){let t=this.options.filter(t=>!Cf(t,e.env));return t.length?this.with({options:t}).compile(e):wf(e,()=>this.ruleHint())}let t=e.profile.unions===`tagged`,n=new Set,r=this.options.map(t=>e.compile(t));if(r.length>1&&r.every(e=>e.jsonText))return e.escape(this,`Nested too deep for this model to describe directly.`);let i=t=>Wf(t,e.env)?.kind,a=this.options.some(t=>i(t)===`array`||i(t)===`tuple`&&e.profile.tuples!==`object`),o=r.map((r,o,s)=>t||s.length<2?r:r.jsonText?(n.add(o),Uf(e,r)):a&&e.profile.records===`pairs`&&i(this.options[o])===`record`?(n.add(o),Uf(e,r,`entries`)):r),s=this.tagIndex(e.env,n),c=s?.byTag,l=s?.tag,u=this.options.map((t,n)=>this.label(n,e.env)),d=t=>Wf(this.options[t],e.env)instanceof af,f=(t,n)=>{if(c&&Af(t)){let r=c.get(t[l]);if(r!==void 0){let i=new Set(zf(this.options[r],e.env));if(e.profile.closedObjects&&i.size&&s.fallback.length&&Object.keys(t).some(e=>!i.has(e)))for(let e of s.fallback){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return r}}let r=!Af(t)||t[l]===void 0;for(let e of s&&!r?s.fallback:o.keys()){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return-1},p=()=>new Sd(e.env);return e.node({own:t,deps:o,hint:()=>this.hintOf(t?[`Fill exactly one of these fields and set the others to null.`]:[]),emit:()=>{if(t){let t={};return o.forEach((n,r)=>t[u[r]]=e.nullable(d(r)?{type:`boolean`,enum:[!0],description:`true for null`}:n.json())),e.object(t,u)}return{anyOf:o.map(e=>e.json())}},run:(n,r)=>{if(t){if(!Af(n))return Pf(r,n,`Expected an object with one of: ${u.join(`, `)}.`);let e=u.filter(e=>n[e]!=null);if(e.length!==1)return Pf(r,n,`Fill exactly one of: ${u.join(`, `)} (got ${e.length}).`,`union`);let t=u.indexOf(e[0]);if(d(t))return n[e[0]]===!0?null:Pf(r,n,`Set ${e[0]} to true for null.`,`literal`);r.enter(e[0],null);let i=o[t].run(n[e[0]],r);return r.leave(!1),i}let i=f(n,r);if(i<0){if(c&&!s.fallback.length&&Af(n)&&n[l]!==void 0){r.enter(l);let e=n[l];return r.fail(`Expected ${l} to be one of: ${Ff([...c.keys()].map(e=>JSON.stringify(e)))}.`,`tag`,e,()=>[...c.keys()].filter(e=>typeof e==`string`)),r.leave(),n}let t=Hf(this.options,n,e.env);return t>=0?o[t].run(n,r):Pf(r,n,`Did not match any of: ${If(this.options.map(e=>e.print(p())).join(` | `),300)}.`,`union`,typeof n==`string`?()=>Rf(this.options,e.env):void 0)}return o[i].run(n,r)},encode:(n,r)=>{let i=this.optionOf(n,e,c,l);if(i<0)return n;let a=d(i)&&t?!0:o[i].encode(n,r);return t?(r.objects++,Object.fromEntries(u.map((e,t)=>[e,t===i?a:null]))):a},child:t=>{let n=o.map(e=>e.child(t)).filter(e=>!!e);if(n.length<=1)return n[0];let r=t=>n.find(n=>!n.schema||Gf(e,n.schema,t))??n[0],i=e.node({deps:n,emit:()=>({anyOf:n.map(e=>e.json())}),run:(e,t)=>r(e).run(e,t),encode:(e,t)=>r(e).encode(e,t),child:e=>n[0].child(e)});return i.needs=n.some(e=>e.needs),i}})}optionOf(e,t,n,r){if(n&&Af(e)){let t=n.get(e[r]);if(t!==void 0)return t}let i=t.lenient();return this.options.findIndex(t=>{let n=new bd(!1,!0,pd(),!1,!0);return i.nodeFor(t).run(e,n),n.errors.length===0})}},_f=class extends Zd{constructor(e){super(),this.members=e}members;kind=`intersection`;children(){return this.members}print(e){return this.members.map(t=>e.print(t)).join(` & `)}mergedByEnv=new WeakMap;merged(e){let t=this.mergedByEnv.get(e);if(t===void 0){let n=this.members.map(t=>Wf(t,e));if(n.every(e=>e instanceof pf)){let e=n,r={};for(let t of e)Object.assign(r,t.shape);let i=e.map(e=>e.extras.rest).filter(Boolean).at(-1),a=e.flatMap(e=>e.extras.patterns??[]);t=new pf(r,e.some(e=>e.closed),{...i?{rest:i}:{},...a.length?{patterns:a}:{}}).with({checks:[...e.flatMap(e=>e.checks),...this.checks],meta:this.meta})}else t=null;this.mergedByEnv.set(e,t)}return t??void 0}compile(e){let t=this.merged(e.env);if(t){let n=e.compile(t);return e.node({deps:[n],emit:()=>n.json(),run:(e,t)=>n.run(e,t),encode:(e,t)=>n.encode(e,t),child:e=>n.child(e)})}let n=this.members.map(t=>e.compile(t)),r=this.members.slice(1),i=()=>e.profile.allOf&&n.every(e=>!e.needs);return e.node({deps:n,hint:()=>this.hintOf(i()?[]:[`Must also be: ${r.map(t=>t.print(new Sd(e.env))).join(` & `)}.`]),emit:()=>i()?{allOf:n.map(e=>e.json())}:n[0].json(),run:(t,i)=>{let a=i.errors.length,o=n[0].run(t,i);if(i.errors.length!==a)return o;let s=e.lenient();for(let e of r){let t=i.dryRun(!0);s.nodeFor(e).run(o,t);for(let e of t.errors)i.errors.push(e)}return o},encode:(e,t)=>n[0].encode(e,t),child:e=>n[0].child(e)})}},vf=class extends Zd{constructor(e,t){super(),this.excluded=e,this.base=t}excluded;base;kind=`not`;children(){return[this.base,this.excluded]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=()=>e.profile.conditionals?[]:[`Must not be: ${this.excluded.print(new Sd(e.env))}.`];return e.node({deps:[t],hint:()=>this.hintOf(n()),emit:()=>e.profile.conditionals?{...t.json(),not:e.lenient().nodeFor(this.excluded).json()}:t.json(),run:(n,r)=>{let i=r.errors.length,a=t.run(n,r);return r.errors.length===i&&Gf(e,this.excluded,a)&&r.fail(`Must not be: ${this.excluded.print(new Sd(e.env))}.`,`rule`),a},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},yf=class extends Zd{constructor(e,t,n,r){super(),this.base=e,this.when=t,this.then=n,this.otherwise=r}base;when;then;otherwise;kind=`conditional`;children(){return[this.base,this.when,...this.then?[this.then]:[],...this.otherwise?[this.otherwise]:[]]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=t=>t.print(new Sd(e.env)),r=[this.then?`If it is ${n(this.when)}, it must also be ${n(this.then)}.`:``,this.otherwise?`${this.then?`Otherwise`:`If it is not ${n(this.when)}`}, it must be ${n(this.otherwise)}.`:``].filter(Boolean).join(` `);return e.node({deps:[t],hint:()=>this.hintOf(e.profile.conditionals?[]:[r]),emit:()=>{if(!e.profile.conditionals)return t.json();let n=e.lenient();return{...t.json(),if:n.nodeFor(this.when).json(),...this.then?{then:n.nodeFor(this.then).json()}:{},...this.otherwise?{else:n.nodeFor(this.otherwise).json()}:{}}},run:(n,i)=>{let a=i.errors.length,o=t.run(n,i);if(i.errors.length!==a)return o;let s=Gf(e,this.when,o)?this.then:this.otherwise;return s&&!Gf(e,s,o)&&i.fail(r,`rule`),o},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},bf=class extends Zd{constructor(e,t,n=new cf){super(),this.on=e,this.schemaFor=t,this.base=n}on;schemaFor;base;kind=`dependent`;children(){return[this.base]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>t.run(e,n),encode:(e,n)=>t.encode(e,n)})}},xf=class extends Zd{constructor(e,t=`tool`,n=`args`){super(),this.cases=e,this.tagKey=t,this.argsKey=n}cases;tagKey;argsKey;kind=`dispatch`;children(){return this.cases.map(e=>e.schema)}print(e){return this.cases.map(t=>`{ ${this.tagKey}: ${JSON.stringify(t.name)}; ${this.argsKey}: ${e.print(t.schema)} }`).join(` | `)}compile(e){let t=this.cases.map(e=>e.name),n=new Map(t.map((e,t)=>[e,t])),r=this.cases.map(t=>e.compile(t.schema)),i=e.compile(new sf(t)),a=e.profile.unions===`tagged`,{tagKey:o,argsKey:s}=this,c=this.cases.map(e=>`- ${e.name}${e.description?`: ${e.description}`:``}`).join(`
68
+ `)),r[t.key]=i,(!t.optional||n)&&a.push(t.key)}f===`pairs`&&(r[p]={type:`array`,items:e.object({key:{type:`string`},value:m.json()},[`key`,`value`],!0)},n&&a.push(p));let o=e.object(r,a,this.closed||t.closedObjects);return f===`keywords`?(u.length&&(o.patternProperties=Object.fromEntries(u.map(e=>[e.pattern,e.node.json()]))),d&&(o.additionalProperties=d.json())):f===`open`&&(o.additionalProperties=m.json()),o},run:(t,r)=>{let i=Yf(t,r,`object`);if(!Mf(i))return If(r,i,`Expected an object, got ${Nf(i)}.`);let u=i,d=u;for(let e=0;e<o.length;e++){let t=o[e],i=Object.prototype.hasOwnProperty.call(u,t.key)?u[t.key]:void 0;if(i===void 0){t.dflt?r.dry||(d=Zf(d,u,t.key,t.dflt.fresh(r.stats),r)):t.optional||(r.enter(t.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),t.node),r.leave());continue}if(i===null&&t.optional&&n&&!t.nullable){r.dry||(d=t.dflt?Zf(d,u,t.key,t.dflt.fresh(r.stats),r):Qf(d,u,t.key,r));continue}r.enter(t.key);let a=t.node.run(i,r);r.leave(),a!==i&&!r.dry&&(d=Zf(d,u,t.key,a,r))}for(let t=0;t<s.length;t++){let i=s[t],a=u[i.key];if(a===void 0||a===null&&i.optional&&n){a===null&&!r.dry?d=Qf(d,u,i.key,r):i.optional||(r.enter(i.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),i.node),r.leave());continue}r.enter(i.key);let o=r.errors.length,l=i.node.run(a,r);if(r.errors.length===o){let t=i.dep.schemaFor(d[i.dep.on]);t&&(l=e.lenient().nodeFor(t).run(l,r))}r.leave(),l!==a&&!r.dry&&(d=Zf(d,u,i.key,l,r))}if(a.size)for(let e of a)Object.prototype.hasOwnProperty.call(u,e)&&(r.enter(e),r.fail(`Not allowed.`,`not-allowed`),r.leave());if(f===`pairs`){let e=u[p];if(e!=null){r.enter(p,null);let t=Yf(e,r,`array`);if(!Array.isArray(t))If(r,t,`Expected a list of {key, value} entries.`);else{r.dry||(d=Qf(d,u,p,r));for(let e=0;e<t.length;e++){let n=t[e];if(r.enter(e,null),!Mf(n)||typeof n.key!=`string`){r.fail(`Expected a {key, value} entry with a string key.`,`type`),r.leave(!1);continue}let i=n.key;if(c.has(i)||Object.prototype.hasOwnProperty.call(d,i)){r.enter(`key`,null),r.fail(`Duplicate key "${i}".`,`rule`),r.leave(!1),r.leave(!1);continue}let a=h(i);r.enter(`value`,i);let o=a?a.run(n.value,r):this.closed?If(r,n.value,`Key "${i}" is not allowed.`,`not-allowed`):n.value;r.leave(),r.dry||(d=Zf(d,u,i,o,r)),r.leave(!1)}}r.leave(!1)}else p&&e===null&&!r.dry&&(d=Qf(d,u,p,r))}else if(l||this.closed){let e=Object.keys(u);for(let t=0;t<e.length;t++){let n=e[t];if(c.has(n))continue;let i=l?h(n):void 0;if(i){r.enter(n);let e=i.run(u[n],r);r.leave(),e!==u[n]&&!r.dry&&(d=Zf(d,u,n,e,r))}else this.closed&&(r.enter(n),r.fail(`Unknown field "${n}".`,`unknown-key`,n,()=>[...c].filter(e=>!Object.prototype.hasOwnProperty.call(u,e))),r.leave())}}return d},encode:(e,t)=>{let r=e,o={};t.objects++;let s=[];for(let e of Object.keys(r)){if(a.has(e)||c.has(e))continue;let n=h(e),i=n?n.encode(r[e],t):r[e];f===`pairs`?s.push({key:e,value:i}):o[e]=i}for(let e of i){let i=r[e.key];i===void 0?e.optional&&n&&(o[e.key]=null):o[e.key]=e.node.encode(i,t)}return f===`pairs`&&(s.length||n)&&(t.arrays++,t.objects+=s.length,o[p]=s),o},child:e=>i.find(t=>t.key===e)?.node??(typeof e==`string`?h(e):void 0)})}},gf=class extends $d{constructor(e,t){super(),this.value=e,this.key=t}value;key;kind=`record`;children(){return this.key?[this.key,this.value]:[this.value]}print(e){return`{ [key: ${this.key?e.print(this.key):`string`}]: ${e.print(this.value)} }`}compile(e){let t=e.guarded(this.value),n=e.compile(this.key??_f),r=e.profile.records===`pairs`;return e.node({own:r,deps:[t,n],hint:e=>this.hintOf(r?[`A map written as ${e.recordWord}; each key at most once.`]:[]),emit:()=>{if(r)return{type:`array`,items:e.object({key:n.json(),value:t.json()},[`key`,`value`],!0)};let i={type:`object`,additionalProperties:t.json()};return this.key&&!e.profile.closedObjects&&!(this.key instanceof rf&&!Object.keys(this.key.options).length)&&(i.propertyNames=n.json()),i},run:(i,a)=>{if(r){let r=Yf(i,a,`array`);if(!Array.isArray(r)){let t=a.repair?Yf(i,a,`object`):i;if(a.repair&&!a.dry&&Mf(t)){t===i&&a.stats.repaired++;let r=t,o=e.lenient().nodeFor(this.value),s=r;for(let e of Object.keys(r)){a.enter(e),n.run(e,a);let t=o.run(r[e],a);a.leave(),t!==r[e]&&!a.dry&&(s=Zf(s,r,e,t,a))}return s}return If(a,r,`Expected a list of {key, value} entries, got ${Nf(r)}.`)}let o={};a.dry||a.stats.objects++;for(let e=0;e<r.length;e++){let i=r[e];if(a.enter(e,null),!Mf(i)){If(a,i,`Expected a {key, value} entry.`),a.leave(!1);continue}let s=i.key;a.enter(`key`,null),s===void 0?a.fail(`Required.`,`required`,void 0,()=>Object.keys(i).filter(e=>e!==`key`&&e!==`value`),n):n.run(s,a),a.leave(!1),typeof s==`string`&&(Object.prototype.hasOwnProperty.call(o,s)&&(a.enter(`key`,null),a.fail(`Duplicate key "${s}".`,`rule`),a.leave(!1)),a.enter(`value`,s),o[s]=t.run(i.value,a),a.leave()),a.leave(!1)}return a.dry?r:o}let o=Yf(i,a,`object`);if(!Mf(o))return If(a,o,`Expected an object, got ${Nf(o)}.`);let s=o,c=s;for(let e of Object.keys(s)){this.key&&(a.enter(e),n.run(e,a),a.leave()),a.enter(e);let r=t.run(s[e],a);a.leave(),r!==s[e]&&!a.dry&&(c=Zf(c,s,e,r,a))}return c},encode:(e,n)=>{let i=e;if(r){let e=Object.keys(i);return n.arrays++,n.objects+=e.length,e.map(e=>({key:e,value:t.encode(i[e],n)}))}let a=i;for(let e of Object.keys(i)){let r=t.encode(i[e],n);r!==i[e]&&(a===i&&(a={...i},n.objects++),a[e]=r)}return a},child:()=>t})}},_f=new rf,vf=class extends $d{constructor(e,t){super(),this.options=e,this.tag=t}options;tag;kind=`union`;children(){return this.options}print(e){return this.options.map(t=>e.print(t)).join(` | `)}tagIndex(e,t){let n=this.tag??Uf(this.options,e);if(!n)return;let r=new Map,i=[];return this.options.forEach((a,o)=>{let s=t.has(o)?void 0:zf(a,n,e);if(s)for(let e of s)r.has(e)||r.set(e,o);else i.push(o)}),{tag:n,byTag:r,fallback:i}}label(e,t){let n=this.tag?Kf(this.options[e],t).shape?.[this.tag]:void 0;return n instanceof cf&&typeof n.value==`string`?n.value:`option${e+1}`}compile(e){if(this.options.some(t=>Tf(t,e.env))){let t=this.options.filter(t=>!Tf(t,e.env));return t.length?this.with({options:t}).compile(e):Ef(e,()=>this.ruleHint())}let t=e.profile.unions===`tagged`,n=new Set,r=this.options.map(t=>e.compile(t));if(r.length>1&&r.every(e=>e.jsonText))return e.escape(this,`Nested too deep for this model to describe directly.`);let i=t=>Kf(t,e.env)?.kind,a=this.options.some(t=>i(t)===`array`||i(t)===`tuple`&&e.profile.tuples!==`object`),o=r.map((r,o,s)=>t||s.length<2?r:r.jsonText?(n.add(o),Gf(e,r)):a&&e.profile.records===`pairs`&&i(this.options[o])===`record`?(n.add(o),Gf(e,r,`entries`)):r),s=this.tagIndex(e.env,n),c=s?.byTag,l=s?.tag,u=this.options.map((t,n)=>this.label(n,e.env)),d=t=>Kf(this.options[t],e.env)instanceof sf,f=(t,n)=>{if(c&&Mf(t)){let r=c.get(t[l]);if(r!==void 0){let i=new Set(Vf(this.options[r],e.env));if(e.profile.closedObjects&&i.size&&s.fallback.length&&Object.keys(t).some(e=>!i.has(e)))for(let e of s.fallback){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return r}}let r=!Mf(t)||t[l]===void 0;for(let e of s&&!r?s.fallback:o.keys()){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return-1},p=()=>new wd(e.env);return e.node({own:t,deps:o,hint:()=>this.hintOf(t?[`Fill exactly one of these fields and set the others to null.`]:[]),emit:()=>{if(t){let t={};return o.forEach((n,r)=>t[u[r]]=e.nullable(d(r)?{type:`boolean`,enum:[!0],description:`true for null`}:n.json())),e.object(t,u)}return{anyOf:o.map(e=>e.json())}},run:(n,r)=>{if(t){if(!Mf(n))return If(r,n,`Expected an object with one of: ${u.join(`, `)}.`);let e=u.filter(e=>n[e]!=null);if(e.length!==1)return If(r,n,`Fill exactly one of: ${u.join(`, `)} (got ${e.length}).`,`union`);let t=u.indexOf(e[0]);if(d(t))return n[e[0]]===!0?null:If(r,n,`Set ${e[0]} to true for null.`,`literal`);r.enter(e[0],null);let i=o[t].run(n[e[0]],r);return r.leave(!1),i}let i=f(n,r);if(i<0){if(c&&!s.fallback.length&&Mf(n)&&n[l]!==void 0){r.enter(l);let e=n[l];return r.fail(`Expected ${l} to be one of: ${Lf([...c.keys()].map(e=>JSON.stringify(e)))}.`,`tag`,e,()=>[...c.keys()].filter(e=>typeof e==`string`)),r.leave(),n}let t=Wf(this.options,n,e.env);return t>=0?o[t].run(n,r):If(r,n,`Did not match any of: ${Rf(this.options.map(e=>e.print(p())).join(` | `),300)}.`,`union`,typeof n==`string`?()=>Bf(this.options,e.env):void 0)}return o[i].run(n,r)},encode:(n,r)=>{let i=this.optionOf(n,e,c,l);if(i<0)return n;let a=d(i)&&t?!0:o[i].encode(n,r);return t?(r.objects++,Object.fromEntries(u.map((e,t)=>[e,t===i?a:null]))):a},child:t=>{let n=o.map(e=>e.child(t)).filter(e=>!!e);if(n.length<=1)return n[0];let r=t=>n.find(n=>!n.schema||qf(e,n.schema,t))??n[0],i=e.node({deps:n,emit:()=>({anyOf:n.map(e=>e.json())}),run:(e,t)=>r(e).run(e,t),encode:(e,t)=>r(e).encode(e,t),child:e=>n[0].child(e)});return i.needs=n.some(e=>e.needs),i}})}optionOf(e,t,n,r){if(n&&Mf(e)){let t=n.get(e[r]);if(t!==void 0)return t}let i=t.lenient();return this.options.findIndex(t=>{let n=new Sd(!1,!0,hd(),!1,!0);return i.nodeFor(t).run(e,n),n.errors.length===0})}},yf=class extends $d{constructor(e){super(),this.members=e}members;kind=`intersection`;children(){return this.members}print(e){return this.members.map(t=>e.print(t)).join(` & `)}mergedByEnv=new WeakMap;merged(e){let t=this.mergedByEnv.get(e);if(t===void 0){let n=this.members.map(t=>Kf(t,e));if(n.every(e=>e instanceof hf)){let e=n,r={};for(let t of e)Object.assign(r,t.shape);let i=e.map(e=>e.extras.rest).filter(Boolean).at(-1),a=e.flatMap(e=>e.extras.patterns??[]);t=new hf(r,e.some(e=>e.closed),{...i?{rest:i}:{},...a.length?{patterns:a}:{}}).with({checks:[...e.flatMap(e=>e.checks),...this.checks],meta:this.meta})}else t=null;this.mergedByEnv.set(e,t)}return t??void 0}compile(e){let t=this.merged(e.env);if(t){let n=e.compile(t);return e.node({deps:[n],emit:()=>n.json(),run:(e,t)=>n.run(e,t),encode:(e,t)=>n.encode(e,t),child:e=>n.child(e)})}let n=this.members.map(t=>e.compile(t)),r=this.members.slice(1),i=()=>e.profile.allOf&&n.every(e=>!e.needs);return e.node({deps:n,hint:()=>this.hintOf(i()?[]:[`Must also be: ${r.map(t=>t.print(new wd(e.env))).join(` & `)}.`]),emit:()=>i()?{allOf:n.map(e=>e.json())}:n[0].json(),run:(t,i)=>{let a=i.errors.length,o=n[0].run(t,i);if(i.errors.length!==a)return o;let s=e.lenient();for(let e of r){let t=i.dryRun(!0);s.nodeFor(e).run(o,t);for(let e of t.errors)i.errors.push(e)}return o},encode:(e,t)=>n[0].encode(e,t),child:e=>n[0].child(e)})}},bf=class extends $d{constructor(e,t){super(),this.excluded=e,this.base=t}excluded;base;kind=`not`;children(){return[this.base,this.excluded]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=()=>e.profile.conditionals?[]:[`Must not be: ${this.excluded.print(new wd(e.env))}.`];return e.node({deps:[t],hint:()=>this.hintOf(n()),emit:()=>e.profile.conditionals?{...t.json(),not:e.lenient().nodeFor(this.excluded).json()}:t.json(),run:(n,r)=>{let i=r.errors.length,a=t.run(n,r);return r.errors.length===i&&qf(e,this.excluded,a)&&r.fail(`Must not be: ${this.excluded.print(new wd(e.env))}.`,`rule`),a},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},xf=class extends $d{constructor(e,t,n,r){super(),this.base=e,this.when=t,this.then=n,this.otherwise=r}base;when;then;otherwise;kind=`conditional`;children(){return[this.base,this.when,...this.then?[this.then]:[],...this.otherwise?[this.otherwise]:[]]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=t=>t.print(new wd(e.env)),r=[this.then?`If it is ${n(this.when)}, it must also be ${n(this.then)}.`:``,this.otherwise?`${this.then?`Otherwise`:`If it is not ${n(this.when)}`}, it must be ${n(this.otherwise)}.`:``].filter(Boolean).join(` `);return e.node({deps:[t],hint:()=>this.hintOf(e.profile.conditionals?[]:[r]),emit:()=>{if(!e.profile.conditionals)return t.json();let n=e.lenient();return{...t.json(),if:n.nodeFor(this.when).json(),...this.then?{then:n.nodeFor(this.then).json()}:{},...this.otherwise?{else:n.nodeFor(this.otherwise).json()}:{}}},run:(n,i)=>{let a=i.errors.length,o=t.run(n,i);if(i.errors.length!==a)return o;let s=qf(e,this.when,o)?this.then:this.otherwise;return s&&!qf(e,s,o)&&i.fail(r,`rule`),o},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},Sf=class extends $d{constructor(e,t,n=new uf){super(),this.on=e,this.schemaFor=t,this.base=n}on;schemaFor;base;kind=`dependent`;children(){return[this.base]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>t.run(e,n),encode:(e,n)=>t.encode(e,n)})}},Cf=class extends $d{constructor(e,t=`tool`,n=`args`){super(),this.cases=e,this.tagKey=t,this.argsKey=n}cases;tagKey;argsKey;kind=`dispatch`;children(){return this.cases.map(e=>e.schema)}print(e){return this.cases.map(t=>`{ ${this.tagKey}: ${JSON.stringify(t.name)}; ${this.argsKey}: ${e.print(t.schema)} }`).join(` | `)}compile(e){let t=this.cases.map(e=>e.name),n=new Map(t.map((e,t)=>[e,t])),r=this.cases.map(t=>e.compile(t.schema)),i=e.compile(new lf(t)),a=e.profile.unions===`tagged`,{tagKey:o,argsKey:s}=this,c=this.cases.map(e=>`- ${e.name}${e.description?`: ${e.description}`:``}`).join(`
69
69
  `);return e.node({own:!0,deps:[i,...r],hint:()=>this.hintOf([`Set "${o}" to the tool to run and "${s}" to its arguments.`]),emit:()=>{let n={...i.json(),description:[i.json().description,`The tool to run:
70
70
  ${c}`].filter(Boolean).join(`
71
- `)},l;if(a){let n={};t.forEach((t,i)=>n[t]=e.nullable(r[i].json())),l={...e.object(n,t),description:`Fill only the field named by "${o}"; set the others to null.`}}else l=r.length===1?r[0].json():{anyOf:r.map(e=>e.json())};return e.object({[o]:n,[s]:l},[o,s])},run:(e,i)=>{let c=qf(e,i,`object`);if(!Af(c))return Pf(i,c,`Expected an object with "${o}" and "${s}".`);let l=c,u=l[o],d=typeof u==`string`?n.get(u):void 0;if(d===void 0)return i.enter(o),i.fail(`Expected one of: ${Ff(t)}.`,`tool`,u,()=>t),i.leave(),c;let f=l[s];if(a){let e=qf(f,i,`object`);f=Af(e)?e[u]:void 0,i.enter(s),i.enter(u,null)}else i.enter(s);let p=f===void 0?Pf(i,f,`Required.`,`required`,r[d]):r[d].run(f,i);return a&&i.leave(!1),i.leave(),p!==l[s]&&!i.dry?Yf(l,l,s,p,i):l},encode:(e,i)=>{let c=e,l=c[o],u=n.get(l);if(u===void 0)return e;let d=r[u].encode(c[s],i);return i.objects++,a?(i.objects++,{[o]:l,[s]:Object.fromEntries(t.map(e=>[e,e===l?d:null]))}):{[o]:l,[s]:d}}})}},Sf=class extends Zd{kind=`never`;children(){return[]}print(){return`never`}compile(e){return wf(e,()=>this.ruleHint())}};function Cf(e,t){let n=Wf(e,t);return n?n.kind===`never`?!0:n instanceof sf?n.values.length===0:n instanceof gf&&n.options.every(e=>Cf(e,t)):!1}function wf(e,t){return e.node({hint:()=>[`No value is allowed here.`,t()].filter(Boolean).join(` `),emit:()=>e.profile.conditionals?{not:{}}:{type:`null`},run:(e,t)=>Pf(t,e,`No value is allowed here.`,`not-allowed`),encode:e=>e})}var Tf=class extends Zd{constructor(e,t){super(),this.inner=e,this.value=t}inner;value;kind=`default`;children(){return[this.inner]}print(e){return e.print(this.inner)}fresh(e){let t=this.value;return typeof t!=`object`||!t?t:(e&&(Array.isArray(t)?e.arrays++:e.objects++),structuredClone(t))}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`,r=this.inner instanceof Df;return e.node({own:!0,deps:[t],hint:()=>this.hintOf([`Default when left out: ${JSON.stringify(t.encode(this.value))}.`]),emit:()=>n&&!r?e.nullable(t.json()):t.json(),run:(e,i)=>e===void 0||e===null&&n&&!r?this.fresh(i.dry?void 0:i.stats):t.run(e,i),encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},Ef=class extends Zd{constructor(e){super(),this.inner=e}inner;kind=`optional`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | undefined`}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`;return e.node({own:n,deps:[t],emit:()=>n?e.nullable(t.json()):t.json(),run:(e,r)=>e===void 0?e:e===null&&n&&!(this.inner instanceof Df)?void 0:t.run(e,r),encode:(e,r)=>e===void 0?n?null:void 0:t.encode(e,r),child:e=>t.child(e)})}},Df=class extends Zd{constructor(e){super(),this.inner=e}inner;kind=`nullable`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | null`}compile(e){let t=e.guarded(this.inner);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>e.nullable(t.json()),run:(e,n)=>e===null?e:t.run(e,n),encode:(e,n)=>e===null?null:t.encode(e,n),child:e=>t.child(e)})}},Of=class extends Zd{constructor(e){super(),this.name=e}name;kind=`ref`;children(){return[]}print(e){return e.ref(this.name)}compile(e){return e.ref(this.name)}},kf=class extends Zd{constructor(e,t){super(),this.wire=e,this.codec=t}wire;codec;kind=`codec`;children(){return[this.wire]}print(e){return e.print(this.wire)}compile(e){let t=e.compile(this.wire);return e.node({own:!0,deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>{let r=n.errors.length,i=t.run(e,n);if(n.errors.length!==r)return e;let a=this.codec.decode(i);if(a instanceof Error)return Pf(n,e,a.message,`other`);if(a instanceof fd){if(!a.issues.length)return Pf(n,e,`Rejected.`,`rule`);for(let e of a.issues)n.failAt(e.path,e.message,`rule`);return e}return a},encode:(e,n)=>t.encode(this.codec.encode(e),n)})}};function Af(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jf(e){return typeof e==`string`?Mf(e)??`string`:e===null?`null`:Array.isArray(e)?`a list`:typeof e==`object`?`an object`:typeof e}function Mf(e){let t=e.trimStart()[0];if(t===`{`||t===`[`)try{JSON.parse(e);return}catch(e){return`a string of JSON text that doesn't parse (${e.message}); send the value itself, not as a string`}}function Nf(e){return typeof e==`string`?`string`:typeof e==`number`?`number`:typeof e==`boolean`?`boolean`:`null`}function Pf(e,t,n,r=`type`,i){return typeof i==`function`?e.fail(n,r,t,i):e.fail(n,r,t,void 0,i),t}function Ff(e,t=30){return e.length<=t?e.join(`, `):`${e.slice(0,t).join(`, `)}, \u2026 (${e.length-t} more)`}function If(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Lf(e,t,n,r=0){let i=Wf(e,n);if(i instanceof pf){let e=Wf(i.shape[t],n);return e instanceof of?[e.value]:e instanceof sf?[...e.values]:void 0}if(i instanceof gf&&r<8){let e=[];for(let a of i.options){let i=Lf(a,t,n,r+1);if(!i)return;e.push(...i)}return e}}function Rf(e,t,n=0){let r=[];for(let i of e){let e=Wf(i,t);e instanceof sf?r.push(...e.values):e instanceof of&&typeof e.value==`string`?r.push(e.value):e instanceof gf&&n<8&&r.push(...Rf(e.options,t,n+1))}return r}function zf(e,t,n=0){let r=Wf(e,t);return r instanceof pf?Object.keys(r.shape):r instanceof gf&&n<8?zf(r.options[0],t,n+1):[]}var Bf=new WeakMap;function Vf(e,t){let n=Bf.get(e);n||Bf.set(e,n=new WeakMap);let r=n.get(t);if(r===void 0){if(r=null,e.length>1)for(let n of zf(e[0],t)){let i=new Set,a=!0;for(let r of e){let e=Lf(r,n,t);if(!e||e.some(e=>i.has(e))){a=!1;break}for(let t of e)i.add(t)}if(a){r=n;break}}n.set(t,r)}return r??void 0}function Hf(e,t,n){if(!Af(t))return-1;let r=t,i=-1,a=0,o=!1;if(e.forEach((e,t)=>{let s=0;for(let t of zf(e,n)){let i=Lf(e,t,n);i&&t in r&&(s+=i.includes(r[t])?1:-1)}s>a?(i=t,a=s,o=!1):s===a&&s>0&&(o=!0)}),!o&&i>=0)return i;let s=Object.keys(r);return s.length?(i=-1,a=0,o=!1,e.forEach((e,t)=>{let r=new Set(zf(e,n));if(!r.size||s.some(e=>!r.has(e)))return;let c=s.length;c>a?(i=t,a=c,o=!1):c===a&&(o=!0)}),o?-1:i):-1}function Uf(e,t,n=`json`){let r=e.node({own:!0,deps:[t],emit:()=>e.object({[n]:t.json()},[n]),run:(e,r)=>{if(!Af(e)||!(n in e))return Pf(r,e,n===`json`?`Expected {"json": "<JSON text>"}.`:`Expected {"${n}": [...]}.`);r.enter(n,null);let i=t.run(e[n],r);return r.leave(!1),i},encode:(e,r)=>(r.objects++,{[n]:t.encode(e,r)})});return e.nodes.push(r),r}function Wf(e,t){for(let n=0;e instanceof Of&&n<16;n++)e=t.get(e.name);return e}function Gf(e,t,n){let r=new bd(!1,!0,pd(),!1,!0);return e.lenient().nodeFor(t).run(n,r),r.errors.length===0}function Kf(e,t,n,r,i,a){r!==void 0&&(i?e[n]=r:t.includes(a)||t.push(a))}function qf(e,t,n){if(!t.repair||typeof e!=`string`)return e;let r=e;for(let t=0;t<2&&typeof r==`string`;t++){let t=r.trim();if(!/^[[{"]/.test(t))return e;try{r=JSON.parse(t)}catch{return e}}return(n===`array`?Array.isArray(r):Af(r))?(t.dry||t.stats.repaired++,r):e}function Jf(e,t,n){let r=e;for(let i=0;i<e.length;i++){let a=t(e[i],i);a!==e[i]&&(r===e&&(r=e.slice(),n.arrays++),r[i]=a)}return r}function Yf(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e={...t},i.stats.objects++),e[n]=r,e)}function Xf(e,t,n,r){return r.inPlace?(r.saving(t,n,!0),delete t[n],r.stats.edits++,t):(e===t&&(e={...t},r.stats.objects++),delete e[n],e)}function Zf(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e=t.slice(),i.stats.arrays++),e[n]=r,e)}function Qf(e,t={unsupported:[]}){let n=typeof e==`object`?e:{},r={...n.definitions??{},...n.$defs??{}},i={},a=!1,o=e=>{if(e===`#`)return a=!0,`__root`;let n=/^#\/(?:\$defs|definitions)\/(.+)$/.exec(e);return n?n[1].replace(/~1/g,`/`).replace(/~0/g,`~`):(t.unsupported.push(`$ref ${e}`),`__any`)},s=e=>{if(e===!0||e===void 0)return new cf;if(e===!1)return new gf([new af]).refine(()=>!1,`No value is allowed here.`);let{allOf:n,not:r,if:i,then:a,else:o,...l}=e,u=Object.keys(l).every(e=>[`description`,`title`,`examples`,`$comment`,`default`].includes(e)),d=c(l);if(Array.isArray(n)&&n.length){let e=n.map(s),t=u?e:[d,...e];d=t.length===1?t[0]:new _f(t)}r!==void 0&&(d=new vf(s(r),d)),i!==void 0&&(d=new yf(d,s(i),a===void 0?void 0:s(a),o===void 0?void 0:s(o)));for(let n of[`dependentSchemas`,`dependentRequired`])n in e&&t.unsupported.push(n);return typeof e.description==`string`&&(d=d.describe(e.description)),typeof e.title==`string`&&(d=d.title(e.title)),Array.isArray(e.examples)&&(d=d.example(...e.examples)),d},c=e=>{if(typeof e.$ref==`string`)return new Of(o(e.$ref));if(`const`in e)return new of(e.const);if(Array.isArray(e.enum)){let t=e.enum,n=t.filter(e=>typeof e==`string`),r=t.includes(null),i=n.length===t.length-+!!r&&n.length?new sf(n):new gf(t.filter(e=>e!==null).map(e=>new of(e)));return r?new Df(i):i}let t=e.anyOf??e.oneOf;if(Array.isArray(t)){let e=t.map(s),n=e.filter(e=>!(e instanceof af)),r=n.length===1?n[0]:new gf(n);return n.length<e.length?new Df(r):r}if(Array.isArray(e.type)){let t=e.type,n=t.filter(e=>e!==`null`).map(t=>c({...e,type:t})),r=n.length===1?n[0]:n.length?new gf(n):new af;return t.includes(`null`)&&n.length?new Df(r):r}let n=e.type??$f(e);switch(n){case`string`:{let t=new tf;return typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),typeof e.pattern==`string`&&(t=t.pattern(e.pattern)),typeof e.format==`string`&&(t=t.format(e.format)),t}case`number`:case`integer`:{let t=new nf({int:e.type===`integer`});return typeof e.minimum==`number`&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&(t=t.max(e.maximum)),t}case`boolean`:return new rf;case`null`:return new af;case`array`:{if(Array.isArray(e.prefixItems)&&e.prefixItems.length)return new ff(e.prefixItems.map(s));let t=new df(s(e.items??!0));return typeof e.minItems==`number`&&(t=t.min(e.minItems)),typeof e.maxItems==`number`&&(t=t.max(e.maxItems)),t}default:{if(n===void 0&&!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new cf;if(!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new mf(new cf);let t=e.properties??{},r=new Set(e.required??[]),i=e.additionalProperties,a=e.patternProperties;if(!Object.keys(t).length&&!a&&i!==void 0&&i!==!1)return new mf(i===!0?new cf:s(i));let o={};for(let[e,n]of Object.entries(t))o[e]=r.has(e)?s(n):new Ef(s(n));for(let e of r)e in o||(o[e]=new cf);let c=new pf(o);return a&&(c=c.patterns(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,s(t)])))),i===!0?c=c.rest(new cf):i!==void 0&&typeof i==`object`&&(c=c.rest(s(i))),i===!1?c.strict():c}}};for(let[e,t]of Object.entries(r))i[e]=s(t);let{$defs:l,definitions:u,...d}=n,f=s(d);a&&(i.__root=f),(t.unsupported.includes(`$ref`)||Object.values(i).some(()=>!1))&&(i.__any=new cf);for(let e of[f,...Object.values(i)].flatMap(e=>[...e.refNames()]))e in i||(e.startsWith(`__`)||t.unsupported.push(`$ref to a missing definition "${e}" (any JSON instead)`),i[e]=new cf().describe(`Unknown reference ${e}.`));return new Gd(i,a?new Of(`__root`):f)}function $f(e){if([`minLength`,`maxLength`,`pattern`,`format`].some(t=>t in e))return`string`;if([`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`].some(t=>t in e))return`number`;if([`items`,`prefixItems`,`minItems`,`maxItems`].some(t=>t in e))return`array`;if([`properties`,`required`,`patternProperties`,`additionalProperties`].some(t=>t in e))return`object`}var ep=()=>new tf,tp=()=>new nf,np=()=>new nf({int:!0}),rp=()=>new rf,ip=()=>new af,ap=e=>new of(e);function op(e){return new sf([...e])}var sp=()=>new Sf,cp=()=>new cf,lp=()=>new cf,up=e=>new pf(e),dp=e=>new df(e),fp=e=>new ff(e);function pp(e,t){return t?new mf(t,e):new mf(e)}function mp(e){return new gf([...e])}function hp(e,t){return new gf([...t],e)}var gp=e=>new _f(e);function _p(e,t){return new vf(e,t??new cf)}function vp(e,t){return new yf(e,t.if,t.then,t.else)}function yp(e,t,n){return new bf(e,t,n)}var bp=e=>new Ef(e),xp=(e,t)=>new Tf(e,t),Sp=e=>new Df(e),Cp=e=>new Of(e),wp=e=>new Of(e),Tp=(e,t)=>new kf(e,t),Ep=(e,t={})=>new xf(e,t.tag??`tool`,t.args??`args`),Dp=e=>new Hd(e),Op=()=>new Hd,kp=()=>new Hd;function Ap(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function jp(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function Mp(e,t,n){let r=e.toLowerCase(),i=t.map((t,n)=>({candidate:t,index:n,ci:Ap(r,t.toLowerCase()),exact:Ap(e,t)})).filter(e=>e.ci<=n);return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function Np(e,t,n=jp(e.length)){return Mp(e,t,n)[0]}function Pp(e,t,n={}){let r=Math.max(1,n.max??1),i=Mp(e,t,jp(e.length)).slice(0,r);return i.length===0?``:` \u2014 did you mean ${Fp(i.map(e=>`\`${e}\``))}?`}function Fp(e){return e.length===2?`${e[0]} or ${e[1]}`:e.length>2?`${e.slice(0,-1).join(`, `)}, or ${e[e.length-1]}`:e.join(`, `)}function Ip(e,t,n=2){let r=e.length,i=t.length,a=[];for(let e=0;e<=i;e++)a[e]=e*n;for(let o=1;o<=r;o++){let r=a[0];a[0]=o*n;let s=e[o-1].toLowerCase();for(let e=1;e<=i;e++){let i=a[e],o=r+Ap(s,t[e-1].toLowerCase());a[e]=Math.min(a[e]+n,a[e-1]+n,o),r=i}}return a[i]}function Lp(e,t,n,r,i={}){if(r.length===0)return;let a=i.maxDepth??Math.min(6,r.length+1),o=r[r.length-1].toLowerCase(),s=jp(o.length),c=r.reduce((e,t)=>e+jp(t.length),0)+2,l=i.nodeBudget??2e3,u,d=new Set,f=(e,i)=>{if(!(l<=0)){for(let n of t(e)){if(l<=0)return;if(l--,Ap(n.toLowerCase(),o)>s)continue;let e=[...i,n],t=Ip(e,r);t>c||(!u||t<u.score||t===u.score&&e.length<u.path.length)&&(u={score:t,path:e})}if(!(i.length>=a||d.has(e))){d.add(e);for(let[t,r]of n(e)){if(l<=0)break;f(r,[...i,t])}d.delete(e)}}};return f(e,[]),u?.path}var Rp=[`name`,`docs`,`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`],zp=[`docs`,`type`,`get`,`default`,`set`],Bp=[`docs`,`key`,`value`,`get`,`set`,`loop`,`loopDynamic`],Vp=[`docs`,`types`,`args`,`returns`,`throws`,`get`,`set`],Hp=[`docs`,`args`,`run`];function Up(e,t,n,r){let i=e;for(let n of Jp(i))if(!Rp.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown key '${n}'`+Qp(n,i[n],Rp,t,`top`,r));let a=Yp(e.options)?e.options:void 0;if(t?.optionKeys&&a){for(let n of Jp(a))if(!t.optionKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown options key '${n}'`+Qp(n,a[n],t.optionKeys,t,`options`,r))}let o=Yp(e.generic)?e.generic:void 0;if(n&&t?.genericKeys&&o){for(let n of Jp(o))if(!t.genericKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown generic parameter '${n}'`+Qp(n,o[n],t.genericKeys,t,`generic`,r))}}function Wp(e,t,n,r,i){if(Yp(t))for(let a of Jp(t)){if(n.includes(a))continue;let o=r?.[a],s=typeof o==`function`?o(t[a],i):o,c=Np(a,n);throw Error(`gin.parse: ${e} has unknown key '${a}'`+(s?` \u2014 ${s}`:c?` \u2014 did you mean \`${c}\`?`:` \u2014 valid keys: ${n.join(`, `)}`))}}var Gp={generic:`a fn declares its type parameters on the TYPE, not the call: {"name":"fn","generic":{"T":{"name":"any"}},"call":{"args":…,"returns":…}}`},Kp=[{by:`prop`,keys:[`prop`],example:`{"prop":"name"}`},{by:`args`,keys:[`args`,`generic`,`catch`],example:`{"args":{…}}`},{by:`key`,keys:[`key`],example:`{"key":<expr>}`}];function qp(e){if(!Yp(e))return;let t=Kp.filter(t=>e[t.by]!==void 0);if(t.length===0){let t=Jp(e),n=Kp.map(e=>e.by),r=t.map(e=>Np(e,n)).find(e=>e!==void 0);throw Error(`gin.parse: path step selects no form (keys: ${t.join(`, `)||`none`})`+(r?` \u2014 did you mean \`${r}\`?`:``)+` \u2014 a step is one of ${Kp.map(e=>e.example).join(`, `)}`)}if(t.length>1){let n=t.map(e=>`'${e.by}'`).join(` and `),r=t.map(t=>t.by===`prop`?JSON.stringify({prop:e.prop}):t.example).join(`, `);throw Error(`gin.parse: path step names ${t.length} forms (${n}) \u2014 each is its own step: [${r}]`)}Wp(`path step`,e,t[0].keys)}function Jp(e){return Object.keys(e).filter(t=>e[t]!==void 0)}function Yp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xp(e){return Array.isArray(e)?e.length>0&&Xp(e[0]):Yp(e)&&typeof e.name==`string`}function Zp(e){return Yp(e)&&`type`in e}function Qp(e,t,n,r,i,a){let o=[],s=Np(e,n);if(s)return` \u2014 did you mean \`${s}\`?`;let c=r?.genericKeys??[],l=i===`options`?em(t,r,a):void 0;return l?o.push(l):r&&i!==`generic`&&c.length>0&&Xp(t)?o.push(`that value is a TypeDef, and '${r.NAME}' takes its type argument${c.length>1?`s`:``} in \`generic\` (${c.join(`, `)})`):i===`top`&&Zp(t)&&(r?.consumes??[]).includes(`props`)&&o.push("that value is a PropDef — declare it under `props`"),o.push(rm(n,r,i)),` \u2014 ${o.join(`; `)}`}var $p=12;function em(e,t,n){if(!(!t||t.NAME===`enum`||(t.genericKeys?.length??0)>0))return nm(e,n,"an `enum` in gin, not an option")}var tm={values:(e,t)=>t?nm(e,t,`the prop's TYPE in gin, not a key beside it`,e=>`{"type":${e}}`):"a closed set of constants is the prop's TYPE in gin, not a key beside it: declare `type` as an `enum`"};function nm(e,t,n,r=e=>e){let i=!Array.isArray(e)&&Yp(e),a=Array.isArray(e)?e:i?Object.values(e):void 0;if(!a||a.length===0)return;let o=typeof a[0];if(!a.every(e=>typeof e===o)||o!==`number`&&o!==`boolean`&&o!==`string`)return;let s=`a closed set of constants is ${n}`;if(a.length>$p)return s;let c=i?e:Object.fromEntries(a.map(e=>[String(e),e])),l=o===`number`?t.enum(c,t.num()):o===`boolean`?t.enum(c,t.bool()):o===`string`?t.enum(c,t.text()):void 0;if(l)return`${s}: ${r(JSON.stringify(l.toJSON()))}`}function rm(e,t,n){let r=t?`'${t.NAME}'`:`this type`;return n===`top`?`valid keys: ${e.join(`, `)}`:n===`options`?e.length===0?`${r} takes no options`:`valid options for ${r}: ${e.join(`, `)}`:e.length===0?`${r} is not generic`:`valid generic parameters for ${r}: ${e.join(`, `)}`}var im=/^(?:\w[\w-]*\/)*\w+$/;function am(e){return typeof e==`string`&&im.test(e)}var om={any:`Type_any`,void:`Type_void`,null:`Type_null`,bool:`Type_bool`,num:`Type_num`,text:`Type_text`,list:`Type_list`,map:`Type_map`,tuple:`Type_tuple`,obj:`Type_object`,optional:`Type_optional`,nullable:`Type_nullable`,not:`Type_not`,or:`Type_or`,and:`Type_and`,enum:`Type_enum`,literal:`Type_literal`,fn:`Type_function`,interface:`Type_interface`,typ:`Type_typ`,date:`Type_date`,timestamp:`Type_timestamp`,duration:`Type_duration`,color:`Type_color`},sm=()=>R.string().pattern(im.source).describe(`A type name: an identifier, optionally namespaced as ns/Name.`);function cm(e,t){let n=om[t],r=e.typeClass(t);return r!==void 0&&n!==void 0&&e.namedTypeList().every(e=>e.name!==t)?R.ref(n):r===void 0?R.object({name:R.literal(t)}):r.toA?.()??R.object({name:R.literal(t)})}function lm(){return R.object({name:sm()}).strict().describe(`A named type, by its name.`)}function um(e){return R.object({name:sm(),extends:e.length>0?R.enum([...new Set(e)]):R.never(),docs:R.string().optional(),satisfies:R.array(sm()).optional(),generic:R.ref(`Generic`).optional(),options:R.record(R.unknown()).optional(),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional(),init:R.ref(`InitDef`).optional(),constraint:R.ref(`Expr`).optional()}).describe(`A NEW named type declared inline: a name, the type it extends, and what it adds.`)}var dm=R.ref(`TypeDef`),z=R.ref(`Expr`),fm=R.string().optional().describe("Optional one-line note explaining why this expression exists. Travels with the node, surfaces in `toCode` as a `/* … */` annotation, and shows up in error paths. Use for non-obvious steps; skip for trivial reads."),pm={Generic:R.record(dm).describe(`Generic-parameter bindings: parameter name → TypeDef.`),PathStep:R.union([R.object({prop:R.string().describe("Named-property access. First step looks up a scope variable by name; subsequent steps read the previous value's prop / method. Reject if the name isn't on the type's `props()`.")}).describe("PROP step — `.<name>` access (scope var on first step, prop/method on later steps)."),R.object({args:R.record(z).describe("Map of arg-name → ExprDef. Calls the previous step (a method or any callable). Each arg expression is evaluated in the caller scope before the call; the result obj is bound as `args` inside the call body."),generic:R.ref(`Generic`).optional().describe("Optional generic-parameter map for parameterized callables (e.g. `list.map<R>` binds `R` to the element type of the result list). Usually unnecessary — most callables infer generics."),catch:z.optional().describe("Optional handler expression evaluated if this call throws. The thrown value is bound under `error` in the handler scope.")}).describe("CALL step — invoke the previous step, as its OWN step. Comes after a method (e.g. `list.push`) or any callable value; never fused into the prop step as `{prop, args}`."),R.object({key:z.describe("Indexed-access key expression. Evaluated at run time and passed to the previous value's `[key]` get/set surface.")}).describe("INDEX step — `[<key>]` access for types with index signatures (lists by `num`, maps by their key type).")]),PropDef:R.object({docs:R.string().optional(),type:dm,get:z.optional(),default:z.optional(),set:z.optional()}),GetSetDef:R.object({docs:R.string().optional(),key:dm,value:dm,get:z.optional(),set:z.optional(),loop:z.optional(),loopDynamic:R.boolean().optional().describe("When true, `loop over: <this-typed value>` re-evaluates the expression each iteration and exits when the result's raw is falsy. Bool uses this for while-loop semantics. The type may have either `loop` (for static iterables) OR `loopDynamic` set; with loopDynamic, no `loop` ExprDef is required.")}),CallDef:R.object({docs:R.string().optional(),types:R.record(dm).optional().describe('Call-local type aliases. Declare reusable named types here ONCE and reference them inside `args` / `returns` / `throws` / `get` / `set` as a bare `{name: "<alias>"}`. Aliases process AFTER any enclosing generics (so they may reference generic placeholders) and BEFORE the call slots — the call slots resolve them at parse time. Sequential: later aliases may reference earlier ones. Use this whenever the same composite type appears more than once in a signature — instead of writing `num{whole:true, min:1}` four times, declare `{ counter: { name:"num", options:{whole:true,min:1} } }` once and reference `{name:"counter"}`.'),args:dm,returns:dm.optional(),throws:dm.optional(),get:z.optional(),set:z.optional()}),InitDef:R.object({docs:R.string().optional(),args:dm,run:z})},mm=[`any`,`void`,`null`,`bool`,`num`,`text`,`list`,`map`,`tuple`,`obj`,`optional`,`nullable`,`not`,`or`,`and`,`enum`,`literal`,`fn`,`interface`,`typ`,`date`,`timestamp`,`duration`,`color`],hm={Type_any:R.object({name:R.literal(`any`)}),Type_void:R.object({name:R.literal(`void`)}),Type_null:R.object({name:R.literal(`null`)}),Type_bool:R.object({name:R.literal(`bool`),options:R.object({trueText:R.string().optional(),falseText:R.string().optional()}).optional()}),Type_num:R.object({name:R.literal(`num`),options:R.object({min:R.number().optional().describe('Only set when a real lower bound is part of the spec — e.g. "positive count" → min: 1, "age" → min: 0. Do NOT add `min: 0` to every num just because most numbers happen to be non-negative.'),max:R.number().optional().describe(`Only set when there is an actual upper bound — a percentage capped at 100, a year capped at 9999. Do NOT pick a generic ceiling like 1000/9999 to fill the field.`),whole:R.boolean().optional().describe(`Only set to true when the value is genuinely integral (counts, indices, ids). Leave unset (allow fractions) for measurements, ratios, etc.`),minPrecision:R.number().optional().describe(`Decimal-place floor. Almost never needed; omit unless the spec explicitly requires N decimal places.`),maxPrecision:R.number().optional().describe(`Decimal-place ceiling. Same rule as minPrecision — omit unless explicitly required.`),prefix:R.string().optional().describe(`Display-only prefix (e.g. "$"). Has no effect on validation. Omit unless rendering needs it.`),suffix:R.string().optional().describe(`Display-only suffix (e.g. "%"). Same as prefix — omit unless rendering needs it.`)}).optional().describe(`Omit entirely for ordinary numbers. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_text:R.object({name:R.literal(`text`),options:R.object({minLength:R.number().optional().describe(`Only set when a real lower bound is part of the spec — e.g. "non-empty input" → minLength: 1. Do NOT default to 0.`),maxLength:R.number().optional().describe(`Only set when there is an actual upper bound — a database column width, an API limit, an explicit "no longer than X chars" rule. Do NOT pick a generic ceiling like 100/200/1000 just to fill the field.`),pattern:R.string().optional().describe(`Only set for actual format constraints (UUID, ISO date, slug, etc.). Do NOT use ".*" or other accept-anything patterns — they add zero validation and clutter the schema.`),flags:R.string().optional().describe('Regex flags (e.g. "i"). Omit unless `pattern` is set AND requires flags.')}).optional().describe(`Omit entirely for ordinary strings. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_list:R.object({name:R.literal(`list`),generic:R.object({V:dm}).optional(),options:R.object({minLength:R.number().optional(),maxLength:R.number().optional()}).optional()}),Type_map:R.object({name:R.literal(`map`),generic:R.object({K:dm,V:dm}).optional()}),Type_tuple:R.object({name:R.literal(`tuple`),options:R.object({elements:R.array(dm)})}),Type_object:R.object({name:R.literal(`obj`),props:R.record(R.ref(`PropDef`)).optional()}),Type_optional:R.object({name:R.literal(`optional`),generic:R.object({T:dm}).optional()}),Type_nullable:R.object({name:R.literal(`nullable`),generic:R.object({T:dm}).optional()}),Type_not:R.object({name:R.literal(`not`),options:R.object({excluded:dm})}),Type_or:R.object({name:R.literal(`or`),options:R.object({types:R.array(dm)})}),Type_and:R.object({name:R.literal(`and`),options:R.object({types:R.array(dm)})}),Type_enum:R.object({name:R.literal(`enum`),generic:R.object({V:dm}).optional(),options:R.object({values:R.record(R.unknown())})}),Type_literal:R.object({name:R.literal(`literal`),generic:R.object({T:dm}).optional(),options:R.object({value:R.unknown()})}),Type_function:R.object({name:R.literal(`fn`),call:R.ref(`CallDef`).optional()}),Type_interface:R.object({name:R.literal(`interface`),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional()}),Type_typ:R.object({name:R.literal(`typ`),generic:R.object({T:dm}).optional()}),Type_date:R.object({name:R.literal(`date`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional()}).optional()}),Type_timestamp:R.object({name:R.literal(`timestamp`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional(),precision:R.enum([`ms`,`s`,`us`]).optional()}).optional()}),Type_duration:R.object({name:R.literal(`duration`)}),Type_color:R.object({name:R.literal(`color`),options:R.object({hasAlpha:R.boolean().optional()}).optional()})},gm={Expr_block:R.object({kind:R.literal(`block`),comment:fm,lines:R.array(z).describe(`Sequence of expressions evaluated in order. The block's value is the LAST line's value (an empty block returns void). Earlier lines run for their side effects (set, fns.fetch, etc.).`)}),Expr_define:R.object({kind:R.literal(`define`),comment:fm,vars:R.array(R.object({name:R.string().describe(`Variable name. Must NOT be a reserved name (args, recurse, this, super, key, value, yield, error) and must NOT shadow anything already in scope.`),type:dm.optional().describe("Optional declared type. OMIT this field when the value already determines the type — every value Expr (`new`, `get`, `if`, ...) is typed, and the var inherits that type. Set this only when you need to widen / narrow / annotate beyond what the value alone produces; a mismatch with the value's inferred type is reported as `define.var.type-mismatch`."),value:z.describe("The expression whose result is bound under `name`. May reference any earlier var in this define — each var is added to scope before the next var's value is evaluated.")})).describe("Bindings introduced before `body`. Evaluated sequentially, so `vars[i].value` may reference any of `vars[0..i-1]`."),body:z}),Expr_flow:R.object({kind:R.literal(`flow`),action:R.enum([`break`,`continue`,`return`,`exit`,`throw`]).describe("Which control-flow signal to raise. `break`/`continue` only valid inside a loop. `return` only valid inside a fn body / lambda; unwinds to the enclosing call with `value`. `exit` unwinds all the way to `engine.run`, returning `value` as the program result. `throw` raises `error` (caught by a path step's `catch:` handler)."),value:z.optional().describe("Required for `return` and `exit` (the value being returned). Ignored by `break` / `continue` / `throw`."),error:z.optional().describe("Required for `throw` — the value to raise. Ignored otherwise.")}),Expr_get:R.object({kind:R.literal(`get`),path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right starting from a scope variable. Step shapes: `{prop:"name"}` for prop/method access, `{args:{…}}` to call the previous step, `{key:Expr}` for index access. The first step MUST be a prop step (the scope-var name). A step names exactly ONE shape — a call is its own step, so a method with arguments is `[{"prop":"m"},{"args":{…}}]` and never `{"prop":"m","args":{…}}`. Result is the final step\'s value.')}),Expr_if:R.object({kind:R.literal(`if`),comment:fm,ifs:R.array(R.object({condition:z.describe("Bool-typed expression. First branch whose condition is `true` wins; the rest are skipped."),body:z.describe(`Evaluated when this branch's condition is true. The if-expression's value is this body's value.`)})).describe("Ordered list of `{condition, body}` branches — first true condition wins. Each `condition` must be bool-typed (warned otherwise). With multiple branches this is the gin equivalent of `if / else if / else if`."),else:z.optional().describe("Optional fallback evaluated when every `ifs[i].condition` is false. Without an else, a no-match if-expression evaluates to void.")}),Expr_lambda:R.object({kind:R.literal(`lambda`),comment:fm,type:dm.describe('The lambda\'s function type — `{ name: "fn", call: { args, returns } }` (or a registered named fn type). The `args` obj defines what the body sees under the `args` scope variable; `returns` is what the body must produce.'),body:z.describe('The lambda body. At runtime, scope contains the lexical scope at definition site PLUS `args` (the call arguments) and `recurse` (this same lambda, for self-calls). Read params via `[{prop:"args"},{prop:"<name>"}]`.'),constraint:z.optional().describe("Optional bool-typed precondition evaluated before the body on every call (with `args` in scope). If it returns false, the call throws. Use for input invariants you want enforced regardless of caller.")}),Expr_loop:R.object({kind:R.literal(`loop`),comment:fm,over:z.describe("The iterable expression. Two evaluation modes: (1) iterable types (list, map, etc. — anything whose `get().loop` is defined) iterate once; the expression is evaluated ONCE at the start. (2) bool — while-loop semantics: the expression is RE-EVALUATED each iteration; the loop continues while the value is `true` and exits the moment it becomes `false`. Use `flow:break` / `flow:continue` inside the body to control iteration regardless of mode."),body:z.describe("Evaluated once per iteration with the current `key` and `value` bound in scope. Use `{kind:'flow', action:'break'}` or `'continue'` for early-exit. The loop expression itself returns void."),key:R.string().optional().describe("Override the scope-variable name the iteration index/key is bound under (default: `key`). Must NOT be reserved or shadow an outer scope var. Use to disambiguate when looping inside another loop."),value:R.string().optional().describe("Override the scope-variable name the iteration value is bound under (default: `value`). Same rules as `key`."),parallel:R.object({concurrent:z.optional().describe(`Max in-flight iterations as a num (omit / 1 → strictly sequential). Use when iterations are independent I/O — e.g. fetching N URLs concurrently.`),rate:z.optional().describe(`Minimum interval between iteration starts. Accepts a num (milliseconds) or a duration. Use to rate-limit fan-out (e.g. avoid hammering an API).`)}).optional().describe("Opt-in parallelism. Both fields are optional and independent: `concurrent` caps fan-out width, `rate` paces start times. Iterations may finish out of order; the body should not assume sequential ordering. Composes with dynamic (bool while-loop) iteration: the body fans out up to `concurrent`, and `over` is re-evaluated against the outer scope each time a task completes — so accumulating side effects of earlier tasks decide whether more tasks spawn.")}),Expr_native:R.object({kind:R.literal(`native`),comment:fm,id:R.string().describe("Identifier of a native impl registered via `registry.setNative(id, fn)` (e.g. `list.push`, `num.add`). The model should NOT generate `native` expressions directly — methods on built-in types are reached via `get` paths, which gin resolves to natives internally."),type:dm.optional().describe("Optional type to wrap the native's raw return value with when the impl returns a non-Value. Defaults to `any` if omitted.")}),Expr_set:R.object({kind:R.literal(`set`),comment:fm,path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right to a writable target. Single-step `[{prop:"x"}]` re-assigns scope variable `x`. Multi-step targets need the type to support set on the final step (a prop with a `set` ExprDef, an indexed slot, or a method whose call has `set:`).'),value:z.describe("The expression evaluated and assigned to the path target. Its type must be compatible with the target's declared type — checked statically as `set.type-mismatch`.")}),Expr_switch:R.object({kind:R.literal(`switch`),comment:fm,value:z.describe("Expression whose result is compared against each case's `equals` candidates. Evaluated once."),cases:R.array(R.object({equals:R.array(z).describe("Candidate values for this case. The case wins if `value` equals ANY one of them (logical OR). Each candidate's type must be compatible with `value`'s type — checked as `switch.case.type`."),body:z.describe(`Evaluated when this case wins. The switch expression's value is this body's value.`)})).describe(`Ordered list of cases — first match wins. Cases are NOT fall-through; only the matching case's body runs.`),else:z.optional().describe(`Optional fallback evaluated when no case matches. Without an else, a no-match switch evaluates to void.`)}),Expr_template:R.object({kind:R.literal(`template`),template:R.union([z,R.string()]).describe("The template string — either a literal string (auto-wrapped as `new text`) or an Expr that evaluates to text. Placeholders use `{name}` syntax; each `name` is looked up first in `params` (when supplied) and then in the surrounding scope."),params:z.optional().describe("Optional obj-typed expression supplying placeholder values. When omitted or when a key is missing, `{name}` falls back to a scope lookup of the same name — so a `${baseUrl}` placeholder resolves to a surrounding `define baseUrl = ...`. Provide `params` only when placeholders need values not already in scope (or to override scope values).")})},_m=[`new`,`get`,`set`,`define`,`block`,`if`,`switch`,`loop`,`lambda`,`template`,`flow`,`native`],vm={any:R.unknown(),void:R.null(),null:R.null(),bool:R.boolean(),num:R.number(),text:R.string(),list:R.array(z),map:R.array(R.object({key:z,value:z})),tuple:R.array(z),obj:R.record(z),optional:z,nullable:R.nullable(z),not:R.unknown(),or:z,and:z,enum:R.union([R.string(),R.number()]),literal:R.unknown(),fn:R.union([R.string(),R.object({kind:R.string()})]),interface:R.record(z),typ:dm,date:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`),timestamp:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`),duration:R.object({days:R.number().optional(),hours:R.number().optional(),minutes:R.number().optional(),seconds:R.number().optional(),ms:R.number().optional()}),color:R.object({r:R.int().min(0).max(255),g:R.int().min(0).max(255),b:R.int().min(0).max(255),a:R.number().min(0).max(1).optional()})},ym=(e,t,n)=>R.object({kind:R.literal(`new`),type:t.describe(`Full TypeDef for a \`${e}\` instance (name + options + per-class fields).`),value:R.optional(n).describe(`Initial value matching this \`${e}\` instance. Composites accept Expr slots; primitives accept their raw form.`)}),bm=Object.fromEntries(mm.map(e=>[`New_${e}`,ym(e,R.ref(om[e]),vm[e])])),xm=R.object({kind:R.literal(`new`),type:dm.describe("TypeDef of the value being constructed. The `value` field is interpreted relative to this type — primitives take their raw form (`new num` → number), composites take Expr slots (`new list` → Expr[])."),value:R.unknown().optional().describe("Initial value matching `type`. Optional when the type has a defined `init` constructor or a sensible default (empty list, zero num with no constraints, etc.).")}),Sm=new Set([...Object.keys(pm),...Object.keys(hm),...Object.keys(gm),...Object.keys(bm),`TypeDef`,`Type_Extension`,`Expr_new`,`Expr`]),Cm=(e,t)=>t.length===0?R.never():t.length===1?t[0]:R.discriminatedUnion(e,t);function wm(e,t){let n=new Map;for(let e of t?.types??[])n.set(e.name,e);for(let t of e.namedTypeList())n.has(t.name)||n.set(t.name,t);return n}function Tm(e,t){let n=wm(e,t),r=[...n.keys()],i=e.typeClasses(),a=[...r.map(e=>R.object({name:R.literal(e)}).describe(`The registered named type \`${e}\`, by name.`)),...i.map(t=>cm(e,t.NAME)),R.ref(`Type_Extension`)];t?.namedRefs&&a.push(lm());let o=um([...i.map(e=>e.NAME),...r]),s=e.exprClassList().map(e=>_m.includes(e.KIND)&&e.KIND!==`new`?R.ref(`Expr_${e.KIND}`):e.KIND===`new`?R.ref(`Expr_new`):e.toA?.()??R.object({kind:R.literal(e.KIND)}).describe(`A \`${e.KIND}\` expression.`)),c=xm,l={};if(t?.newStrict){let t=[...n].map(([e,t])=>{let r=R.object({kind:R.literal(`new`),type:R.object({name:R.literal(e)}).describe(`Reference to the registered named type \`${e}\` \u2014 name-only, the registry resolves it to its full definition.`),value:R.optional(t.toNewA()).describe(`Initial value for the new \`${e}\` instance. Each composite slot accepts an Expr (Get, NewExpr, etc.); per-slot type correctness is enforced at runtime.`)});return Sm.has(`New_${e}`)||n.has(`New_${e}`)?r:(l[`New_${e}`]=r,R.ref(`New_${e}`))}),r=i.map(t=>om[t.NAME]!==void 0&&mm.includes(t.NAME)?R.ref(`New_${t.NAME}`):ym(t.NAME,cm(e,t.NAME),t.toNewA?.()??R.unknown()));c=R.union([...t,...r])}let u={};for(let[e,t]of n)Sm.has(e)||(u[e]=t.defineA({includeDocs:`all`}));return{...u,...l,TypeDef:Cm(`name`,a),Type_Extension:o,Expr_new:c,Expr:Cm(`kind`,s)}}var Em=new WeakMap,Dm=0,Om=e=>{let t=Em.get(e);return t===void 0&&Em.set(e,t=++Dm),t},km=(e,t)=>`${Om(e)}:${e.version}|${t?.newStrict?`s`:``}${t?.namedRefs?`r`:``}|${(t?.types??[]).map(e=>e.name).join(`,`)}`,Am=R.define(pm).define(hm).define(gm).define(bm).declare(),jm=Am.dynamic((e,t)=>Tm(e,t),{key:km,cacheSize:8});jm.result(`TypeDef`),jm.result(`Expr`);var Mm=class{list=[];stack=[];enter(e){return Array.isArray(e)?this.stack.push(...e):this.stack.push(e),this}leave(e=1){return this.stack.length=Math.max(0,this.stack.length-e),this}at(e,t){let n=Array.isArray(e)?e.length:1;this.enter(e);try{return t()}finally{this.leave(n)}}push(e,t,n=`error`,r){this.list.push({path:this.stack.slice(),code:e,message:t,severity:n,source:r})}error(e,t,n){this.push(e,t,`error`,n)}warn(e,t,n){this.push(e,t,`warning`,n)}info(e,t,n){this.push(e,t,`info`,n)}get hasErrors(){return this.list.some(e=>e.severity===`error`)}},Nm=class extends Error{constructor(e){super(`${e.code}: ${e.message} at ${e.path.join(`.`)}`),this.problem=e,this.name=`TypeError`}problem},B={NONE:0,STATE:1,SYSTEM:2,EXTERNAL:4};function Pm(...e){let t=B.NONE;for(let n of e)t|=n;return t}var V=class e{constructor(e,t=[]){this.text=e,this.spans=t}text;spans;toString(){return this.text}concat(t){if(typeof t==`string`)return new e(this.text+t,this.spans);let n=this.text.length,r=t.spans.map(e=>({...e,start:e.start+n,end:e.end+n}));return new e(this.text+t.text,[...this.spans,...r])}indent(t){if(!t||!this.text.includes(`
71
+ `)},l;if(a){let n={};t.forEach((t,i)=>n[t]=e.nullable(r[i].json())),l={...e.object(n,t),description:`Fill only the field named by "${o}"; set the others to null.`}}else l=r.length===1?r[0].json():{anyOf:r.map(e=>e.json())};return e.object({[o]:n,[s]:l},[o,s])},run:(e,i)=>{let c=Yf(e,i,`object`);if(!Mf(c))return If(i,c,`Expected an object with "${o}" and "${s}".`);let l=c,u=l[o],d=typeof u==`string`?n.get(u):void 0;if(d===void 0)return i.enter(o),i.fail(`Expected one of: ${Lf(t)}.`,`tool`,u,()=>t),i.leave(),c;let f=l[s];if(a){let e=Yf(f,i,`object`);f=Mf(e)?e[u]:void 0,i.enter(s),i.enter(u,null)}else i.enter(s);let p=f===void 0?If(i,f,`Required.`,`required`,r[d]):r[d].run(f,i);return a&&i.leave(!1),i.leave(),p!==l[s]&&!i.dry?Zf(l,l,s,p,i):l},encode:(e,i)=>{let c=e,l=c[o],u=n.get(l);if(u===void 0)return e;let d=r[u].encode(c[s],i);return i.objects++,a?(i.objects++,{[o]:l,[s]:Object.fromEntries(t.map(e=>[e,e===l?d:null]))}):{[o]:l,[s]:d}}})}},wf=class extends $d{kind=`never`;children(){return[]}print(){return`never`}compile(e){return Ef(e,()=>this.ruleHint())}};function Tf(e,t){let n=Kf(e,t);return n?n.kind===`never`?!0:n instanceof lf?n.values.length===0:n instanceof vf&&n.options.every(e=>Tf(e,t)):!1}function Ef(e,t){return e.node({hint:()=>[`No value is allowed here.`,t()].filter(Boolean).join(` `),emit:()=>e.profile.conditionals?{not:{}}:{type:`null`},run:(e,t)=>If(t,e,`No value is allowed here.`,`not-allowed`),encode:e=>e})}var Df=class extends $d{constructor(e,t){super(),this.inner=e,this.value=t}inner;value;kind=`default`;children(){return[this.inner]}print(e){return e.print(this.inner)}fresh(e){let t=this.value;return typeof t!=`object`||!t?t:(e&&(Array.isArray(t)?e.arrays++:e.objects++),structuredClone(t))}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`,r=this.inner instanceof kf;return e.node({own:!0,deps:[t],hint:()=>this.hintOf([`Default when left out: ${JSON.stringify(t.encode(this.value))}.`]),emit:()=>n&&!r?e.nullable(t.json()):t.json(),run:(e,i)=>e===void 0||e===null&&n&&!r?this.fresh(i.dry?void 0:i.stats):t.run(e,i),encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},Of=class extends $d{constructor(e){super(),this.inner=e}inner;kind=`optional`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | undefined`}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`;return e.node({own:n,deps:[t],emit:()=>n?e.nullable(t.json()):t.json(),run:(e,r)=>e===void 0?e:e===null&&n&&!(this.inner instanceof kf)?void 0:t.run(e,r),encode:(e,r)=>e===void 0?n?null:void 0:t.encode(e,r),child:e=>t.child(e)})}},kf=class extends $d{constructor(e){super(),this.inner=e}inner;kind=`nullable`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | null`}compile(e){let t=e.guarded(this.inner);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>e.nullable(t.json()),run:(e,n)=>e===null?e:t.run(e,n),encode:(e,n)=>e===null?null:t.encode(e,n),child:e=>t.child(e)})}},Af=class extends $d{constructor(e){super(),this.name=e}name;kind=`ref`;children(){return[]}print(e){return e.ref(this.name)}compile(e){return e.ref(this.name)}},jf=class extends $d{constructor(e,t){super(),this.wire=e,this.codec=t}wire;codec;kind=`codec`;children(){return[this.wire]}print(e){return e.print(this.wire)}compile(e){let t=e.compile(this.wire);return e.node({own:!0,deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>{let r=n.errors.length,i=t.run(e,n);if(n.errors.length!==r)return e;let a=this.codec.decode(i);if(a instanceof Error)return If(n,e,a.message,`other`);if(a instanceof md){if(!a.issues.length)return If(n,e,`Rejected.`,`rule`);for(let e of a.issues)n.failAt(e.path,e.message,`rule`);return e}return a},encode:(e,n)=>t.encode(this.codec.encode(e),n)})}};function Mf(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Nf(e){return typeof e==`string`?Pf(e)??`string`:e===null?`null`:Array.isArray(e)?`a list`:typeof e==`object`?`an object`:typeof e}function Pf(e){let t=e.trimStart()[0];if(t===`{`||t===`[`)try{JSON.parse(e);return}catch(e){return`a string of JSON text that doesn't parse (${e.message}); send the value itself, not as a string`}}function Ff(e){return typeof e==`string`?`string`:typeof e==`number`?`number`:typeof e==`boolean`?`boolean`:`null`}function If(e,t,n,r=`type`,i){return typeof i==`function`?e.fail(n,r,t,i):e.fail(n,r,t,void 0,i),t}function Lf(e,t=30){return e.length<=t?e.join(`, `):`${e.slice(0,t).join(`, `)}, \u2026 (${e.length-t} more)`}function Rf(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function zf(e,t,n,r=0){let i=Kf(e,n);if(i instanceof hf){let e=Kf(i.shape[t],n);return e instanceof cf?[e.value]:e instanceof lf?[...e.values]:void 0}if(i instanceof vf&&r<8){let e=[];for(let a of i.options){let i=zf(a,t,n,r+1);if(!i)return;e.push(...i)}return e}}function Bf(e,t,n=0){let r=[];for(let i of e){let e=Kf(i,t);e instanceof lf?r.push(...e.values):e instanceof cf&&typeof e.value==`string`?r.push(e.value):e instanceof vf&&n<8&&r.push(...Bf(e.options,t,n+1))}return r}function Vf(e,t,n=0){let r=Kf(e,t);return r instanceof hf?Object.keys(r.shape):r instanceof vf&&n<8?Vf(r.options[0],t,n+1):[]}var Hf=new WeakMap;function Uf(e,t){let n=Hf.get(e);n||Hf.set(e,n=new WeakMap);let r=n.get(t);if(r===void 0){if(r=null,e.length>1)for(let n of Vf(e[0],t)){let i=new Set,a=!0;for(let r of e){let e=zf(r,n,t);if(!e||e.some(e=>i.has(e))){a=!1;break}for(let t of e)i.add(t)}if(a){r=n;break}}n.set(t,r)}return r??void 0}function Wf(e,t,n){if(!Mf(t))return-1;let r=t,i=-1,a=0,o=!1;if(e.forEach((e,t)=>{let s=0;for(let t of Vf(e,n)){let i=zf(e,t,n);i&&t in r&&(s+=i.includes(r[t])?1:-1)}s>a?(i=t,a=s,o=!1):s===a&&s>0&&(o=!0)}),!o&&i>=0)return i;let s=Object.keys(r);return s.length?(i=-1,a=0,o=!1,e.forEach((e,t)=>{let r=new Set(Vf(e,n));if(!r.size||s.some(e=>!r.has(e)))return;let c=s.length;c>a?(i=t,a=c,o=!1):c===a&&(o=!0)}),o?-1:i):-1}function Gf(e,t,n=`json`){let r=e.node({own:!0,deps:[t],emit:()=>e.object({[n]:t.json()},[n]),run:(e,r)=>{if(!Mf(e)||!(n in e))return If(r,e,n===`json`?`Expected {"json": "<JSON text>"}.`:`Expected {"${n}": [...]}.`);r.enter(n,null);let i=t.run(e[n],r);return r.leave(!1),i},encode:(e,r)=>(r.objects++,{[n]:t.encode(e,r)})});return e.nodes.push(r),r}function Kf(e,t){for(let n=0;e instanceof Af&&n<16;n++)e=t.get(e.name);return e}function qf(e,t,n){let r=new Sd(!1,!0,hd(),!1,!0);return e.lenient().nodeFor(t).run(n,r),r.errors.length===0}function Jf(e,t,n,r,i,a){r!==void 0&&(i?e[n]=r:t.includes(a)||t.push(a))}function Yf(e,t,n){if(!t.repair||typeof e!=`string`)return e;let r=e;for(let t=0;t<2&&typeof r==`string`;t++){let t=r.trim();if(!/^[[{"]/.test(t))return e;try{r=JSON.parse(t)}catch{return e}}return(n===`array`?Array.isArray(r):Mf(r))?(t.dry||t.stats.repaired++,r):e}function Xf(e,t,n){let r=e;for(let i=0;i<e.length;i++){let a=t(e[i],i);a!==e[i]&&(r===e&&(r=e.slice(),n.arrays++),r[i]=a)}return r}function Zf(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e={...t},i.stats.objects++),e[n]=r,e)}function Qf(e,t,n,r){return r.inPlace?(r.saving(t,n,!0),delete t[n],r.stats.edits++,t):(e===t&&(e={...t},r.stats.objects++),delete e[n],e)}function $f(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e=t.slice(),i.stats.arrays++),e[n]=r,e)}function ep(e,t={unsupported:[]}){let n=typeof e==`object`?e:{},r={...n.definitions??{},...n.$defs??{}},i={},a=!1,o=e=>{if(e===`#`)return a=!0,`__root`;let n=/^#\/(?:\$defs|definitions)\/(.+)$/.exec(e);return n?n[1].replace(/~1/g,`/`).replace(/~0/g,`~`):(t.unsupported.push(`$ref ${e}`),`__any`)},s=e=>{if(e===!0||e===void 0)return new uf;if(e===!1)return new vf([new sf]).refine(()=>!1,`No value is allowed here.`);let{allOf:n,not:r,if:i,then:a,else:o,...l}=e,u=Object.keys(l).every(e=>[`description`,`title`,`examples`,`$comment`,`default`].includes(e)),d=c(l);if(Array.isArray(n)&&n.length){let e=n.map(s),t=u?e:[d,...e];d=t.length===1?t[0]:new yf(t)}r!==void 0&&(d=new bf(s(r),d)),i!==void 0&&(d=new xf(d,s(i),a===void 0?void 0:s(a),o===void 0?void 0:s(o)));for(let n of[`dependentSchemas`,`dependentRequired`])n in e&&t.unsupported.push(n);return typeof e.description==`string`&&(d=d.describe(e.description)),typeof e.title==`string`&&(d=d.title(e.title)),Array.isArray(e.examples)&&(d=d.example(...e.examples)),d},c=e=>{if(typeof e.$ref==`string`)return new Af(o(e.$ref));if(`const`in e)return new cf(e.const);if(Array.isArray(e.enum)){let t=e.enum,n=t.filter(e=>typeof e==`string`),r=t.includes(null),i=n.length===t.length-+!!r&&n.length?new lf(n):new vf(t.filter(e=>e!==null).map(e=>new cf(e)));return r?new kf(i):i}let t=e.anyOf??e.oneOf;if(Array.isArray(t)){let e=t.map(s),n=e.filter(e=>!(e instanceof sf)),r=n.length===1?n[0]:new vf(n);return n.length<e.length?new kf(r):r}if(Array.isArray(e.type)){let t=e.type,n=t.filter(e=>e!==`null`).map(t=>c({...e,type:t})),r=n.length===1?n[0]:n.length?new vf(n):new sf;return t.includes(`null`)&&n.length?new kf(r):r}let n=e.type??tp(e);switch(n){case`string`:{let t=new rf;return typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),typeof e.pattern==`string`&&(t=t.pattern(e.pattern)),typeof e.format==`string`&&(t=t.format(e.format)),t}case`number`:case`integer`:{let t=new af({int:e.type===`integer`});return typeof e.minimum==`number`&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&(t=t.max(e.maximum)),t}case`boolean`:return new of;case`null`:return new sf;case`array`:{if(Array.isArray(e.prefixItems)&&e.prefixItems.length)return new mf(e.prefixItems.map(s));let t=new pf(s(e.items??!0));return typeof e.minItems==`number`&&(t=t.min(e.minItems)),typeof e.maxItems==`number`&&(t=t.max(e.maxItems)),t}default:{if(n===void 0&&!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new uf;if(!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new gf(new uf);let t=e.properties??{},r=new Set(e.required??[]),i=e.additionalProperties,a=e.patternProperties;if(!Object.keys(t).length&&!a&&i!==void 0&&i!==!1)return new gf(i===!0?new uf:s(i));let o={};for(let[e,n]of Object.entries(t))o[e]=r.has(e)?s(n):new Of(s(n));for(let e of r)e in o||(o[e]=new uf);let c=new hf(o);return a&&(c=c.patterns(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,s(t)])))),i===!0?c=c.rest(new uf):i!==void 0&&typeof i==`object`&&(c=c.rest(s(i))),i===!1?c.strict():c}}};for(let[e,t]of Object.entries(r))i[e]=s(t);let{$defs:l,definitions:u,...d}=n,f=s(d);a&&(i.__root=f),(t.unsupported.includes(`$ref`)||Object.values(i).some(()=>!1))&&(i.__any=new uf);for(let e of[f,...Object.values(i)].flatMap(e=>[...e.refNames()]))e in i||(e.startsWith(`__`)||t.unsupported.push(`$ref to a missing definition "${e}" (any JSON instead)`),i[e]=new uf().describe(`Unknown reference ${e}.`));return new qd(i,a?new Af(`__root`):f)}function tp(e){if([`minLength`,`maxLength`,`pattern`,`format`].some(t=>t in e))return`string`;if([`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`].some(t=>t in e))return`number`;if([`items`,`prefixItems`,`minItems`,`maxItems`].some(t=>t in e))return`array`;if([`properties`,`required`,`patternProperties`,`additionalProperties`].some(t=>t in e))return`object`}var np=()=>new rf,rp=()=>new af,ip=()=>new af({int:!0}),ap=()=>new of,op=()=>new sf,sp=e=>new cf(e);function cp(e){return new lf([...e])}var lp=()=>new wf,up=()=>new uf,dp=()=>new uf,fp=e=>new hf(e),pp=e=>new pf(e),mp=e=>new mf(e);function hp(e,t){return t?new gf(t,e):new gf(e)}function gp(e){return new vf([...e])}function _p(e,t){return new vf([...t],e)}var vp=e=>new yf(e);function yp(e,t){return new bf(e,t??new uf)}function bp(e,t){return new xf(e,t.if,t.then,t.else)}function xp(e,t,n){return new Sf(e,t,n)}var Sp=e=>new Of(e),Cp=(e,t)=>new Df(e,t),wp=e=>new kf(e),Tp=e=>new Af(e),Ep=e=>new Af(e),Dp=(e,t)=>new jf(e,t),Op=(e,t={})=>new Cf(e,t.tag??`tool`,t.args??`args`),kp=e=>new Wd(e),Ap=()=>new Wd,jp=()=>new Wd;function Mp(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function Np(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function Pp(e,t,n){let r=e.toLowerCase(),i=t.map((t,n)=>({candidate:t,index:n,ci:Mp(r,t.toLowerCase()),exact:Mp(e,t)})).filter(e=>e.ci<=n);return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function Fp(e,t,n=Np(e.length)){return Pp(e,t,n)[0]}function Ip(e,t,n={}){let r=Math.max(1,n.max??1),i=Pp(e,t,Np(e.length)).slice(0,r);return i.length===0?``:` \u2014 did you mean ${Lp(i.map(e=>`\`${e}\``))}?`}function Lp(e){return e.length===2?`${e[0]} or ${e[1]}`:e.length>2?`${e.slice(0,-1).join(`, `)}, or ${e[e.length-1]}`:e.join(`, `)}function Rp(e,t,n=2){let r=e.length,i=t.length,a=[];for(let e=0;e<=i;e++)a[e]=e*n;for(let o=1;o<=r;o++){let r=a[0];a[0]=o*n;let s=e[o-1].toLowerCase();for(let e=1;e<=i;e++){let i=a[e],o=r+Mp(s,t[e-1].toLowerCase());a[e]=Math.min(a[e]+n,a[e-1]+n,o),r=i}}return a[i]}function zp(e,t,n,r,i={}){if(r.length===0)return;let a=i.maxDepth??Math.min(6,r.length+1),o=r[r.length-1].toLowerCase(),s=Np(o.length),c=r.reduce((e,t)=>e+Np(t.length),0)+2,l=i.nodeBudget??2e3,u,d=new Set,f=(e,i)=>{if(!(l<=0)){for(let n of t(e)){if(l<=0)return;if(l--,Mp(n.toLowerCase(),o)>s)continue;let e=[...i,n],t=Rp(e,r);t>c||(!u||t<u.score||t===u.score&&e.length<u.path.length)&&(u={score:t,path:e})}if(!(i.length>=a||d.has(e))){d.add(e);for(let[t,r]of n(e)){if(l<=0)break;f(r,[...i,t])}d.delete(e)}}};return f(e,[]),u?.path}var Bp=[`name`,`docs`,`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`],Vp=[`docs`,`type`,`get`,`default`,`set`],Hp=[`docs`,`key`,`value`,`get`,`set`,`loop`,`loopDynamic`],Up=[`docs`,`types`,`args`,`returns`,`throws`,`get`,`set`],Wp=[`docs`,`args`,`run`];function Gp(e,t,n,r){let i=e;for(let n of Xp(i))if(!Bp.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown key '${n}'`+em(n,i[n],Bp,t,`top`,r));let a=Zp(e.options)?e.options:void 0;if(t?.optionKeys&&a){for(let n of Xp(a))if(!t.optionKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown options key '${n}'`+em(n,a[n],t.optionKeys,t,`options`,r))}let o=Zp(e.generic)?e.generic:void 0;if(n&&t?.genericKeys&&o){for(let n of Xp(o))if(!t.genericKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown generic parameter '${n}'`+em(n,o[n],t.genericKeys,t,`generic`,r))}}function Kp(e,t,n,r,i){if(Zp(t))for(let a of Xp(t)){if(n.includes(a))continue;let o=r?.[a],s=typeof o==`function`?o(t[a],i):o,c=Fp(a,n);throw Error(`gin.parse: ${e} has unknown key '${a}'`+(s?` \u2014 ${s}`:c?` \u2014 did you mean \`${c}\`?`:` \u2014 valid keys: ${n.join(`, `)}`))}}var qp={generic:`a fn declares its type parameters on the TYPE, not the call: {"name":"fn","generic":{"T":{"name":"any"}},"call":{"args":…,"returns":…}}`},Jp=[{by:`prop`,keys:[`prop`],example:`{"prop":"name"}`},{by:`args`,keys:[`args`,`generic`,`catch`],example:`{"args":{…}}`},{by:`key`,keys:[`key`],example:`{"key":<expr>}`}];function Yp(e){if(!Zp(e))return;let t=Jp.filter(t=>e[t.by]!==void 0);if(t.length===0){let t=Xp(e),n=Jp.map(e=>e.by),r=t.map(e=>Fp(e,n)).find(e=>e!==void 0);throw Error(`gin.parse: path step selects no form (keys: ${t.join(`, `)||`none`})`+(r?` \u2014 did you mean \`${r}\`?`:``)+` \u2014 a step is one of ${Jp.map(e=>e.example).join(`, `)}`)}if(t.length>1){let n=t.map(e=>`'${e.by}'`).join(` and `),r=t.map(t=>t.by===`prop`?JSON.stringify({prop:e.prop}):t.example).join(`, `);throw Error(`gin.parse: path step names ${t.length} forms (${n}) \u2014 each is its own step: [${r}]`)}Kp(`path step`,e,t[0].keys)}function Xp(e){return Object.keys(e).filter(t=>e[t]!==void 0)}function Zp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qp(e){return Array.isArray(e)?e.length>0&&Qp(e[0]):Zp(e)&&typeof e.name==`string`}function $p(e){return Zp(e)&&`type`in e}function em(e,t,n,r,i,a){let o=[],s=Fp(e,n);if(s)return` \u2014 did you mean \`${s}\`?`;let c=r?.genericKeys??[],l=i===`options`?nm(t,r,a):void 0;return l?o.push(l):r&&i!==`generic`&&c.length>0&&Qp(t)?o.push(`that value is a TypeDef, and '${r.NAME}' takes its type argument${c.length>1?`s`:``} in \`generic\` (${c.join(`, `)})`):i===`top`&&$p(t)&&(r?.consumes??[]).includes(`props`)&&o.push("that value is a PropDef — declare it under `props`"),o.push(am(n,r,i)),` \u2014 ${o.join(`; `)}`}var tm=12;function nm(e,t,n){if(!(!t||t.NAME===`enum`||(t.genericKeys?.length??0)>0))return im(e,n,"an `enum` in gin, not an option")}var rm={values:(e,t)=>t?im(e,t,`the prop's TYPE in gin, not a key beside it`,e=>`{"type":${e}}`):"a closed set of constants is the prop's TYPE in gin, not a key beside it: declare `type` as an `enum`"};function im(e,t,n,r=e=>e){let i=!Array.isArray(e)&&Zp(e),a=Array.isArray(e)?e:i?Object.values(e):void 0;if(!a||a.length===0)return;let o=typeof a[0];if(!a.every(e=>typeof e===o)||o!==`number`&&o!==`boolean`&&o!==`string`)return;let s=`a closed set of constants is ${n}`;if(a.length>tm)return s;let c=i?e:Object.fromEntries(a.map(e=>[String(e),e])),l=o===`number`?t.enum(c,t.num()):o===`boolean`?t.enum(c,t.bool()):o===`string`?t.enum(c,t.text()):void 0;if(l)return`${s}: ${r(JSON.stringify(l.toJSON()))}`}function am(e,t,n){let r=t?`'${t.NAME}'`:`this type`;return n===`top`?`valid keys: ${e.join(`, `)}`:n===`options`?e.length===0?`${r} takes no options`:`valid options for ${r}: ${e.join(`, `)}`:e.length===0?`${r} is not generic`:`valid generic parameters for ${r}: ${e.join(`, `)}`}var om=/^(?:\w[\w-]*\/)*\w+$/;function sm(e){return typeof e==`string`&&om.test(e)}var cm={any:`Type_any`,void:`Type_void`,null:`Type_null`,bool:`Type_bool`,num:`Type_num`,text:`Type_text`,list:`Type_list`,map:`Type_map`,tuple:`Type_tuple`,obj:`Type_object`,optional:`Type_optional`,nullable:`Type_nullable`,not:`Type_not`,or:`Type_or`,and:`Type_and`,enum:`Type_enum`,literal:`Type_literal`,fn:`Type_function`,interface:`Type_interface`,typ:`Type_typ`,date:`Type_date`,timestamp:`Type_timestamp`,duration:`Type_duration`,color:`Type_color`},lm=()=>R.string().pattern(om.source).describe(`A type name: an identifier, optionally namespaced as ns/Name.`);function um(e,t){let n=cm[t],r=e.typeClass(t);return r!==void 0&&n!==void 0&&e.namedTypeList().every(e=>e.name!==t)?R.ref(n):r===void 0?R.object({name:R.literal(t)}):r.toA?.()??R.object({name:R.literal(t)})}function dm(){return R.object({name:lm()}).strict().describe(`A named type, by its name.`)}function fm(e){return R.object({name:lm(),extends:e.length>0?R.enum([...new Set(e)]):R.never(),docs:R.string().optional(),satisfies:R.array(lm()).optional(),generic:R.ref(`Generic`).optional(),options:R.record(R.unknown()).optional(),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional(),init:R.ref(`InitDef`).optional(),constraint:R.ref(`Expr`).optional()}).describe(`A NEW named type declared inline: a name, the type it extends, and what it adds.`)}var pm=R.ref(`TypeDef`),z=R.ref(`Expr`),mm=R.string().optional().describe("Optional one-line note explaining why this expression exists. Travels with the node, surfaces in `toCode` as a `/* … */` annotation, and shows up in error paths. Use for non-obvious steps; skip for trivial reads."),hm={Generic:R.record(pm).describe(`Generic-parameter bindings: parameter name → TypeDef.`),PathStep:R.union([R.object({prop:R.string().describe("Named-property access. First step looks up a scope variable by name; subsequent steps read the previous value's prop / method. Reject if the name isn't on the type's `props()`.")}).describe("PROP step — `.<name>` access (scope var on first step, prop/method on later steps)."),R.object({args:R.record(z).describe("Map of arg-name → ExprDef. Calls the previous step (a method or any callable). Each arg expression is evaluated in the caller scope before the call; the result obj is bound as `args` inside the call body."),generic:R.ref(`Generic`).optional().describe("Optional generic-parameter map for parameterized callables (e.g. `list.map<R>` binds `R` to the element type of the result list). Usually unnecessary — most callables infer generics."),catch:z.optional().describe("Optional handler expression evaluated if this call throws. The thrown value is bound under `error` in the handler scope.")}).describe("CALL step — invoke the previous step, as its OWN step. Comes after a method (e.g. `list.push`) or any callable value; never fused into the prop step as `{prop, args}`."),R.object({key:z.describe("Indexed-access key expression. Evaluated at run time and passed to the previous value's `[key]` get/set surface.")}).describe("INDEX step — `[<key>]` access for types with index signatures (lists by `num`, maps by their key type).")]),PropDef:R.object({docs:R.string().optional(),type:pm,get:z.optional(),default:z.optional(),set:z.optional()}),GetSetDef:R.object({docs:R.string().optional(),key:pm,value:pm,get:z.optional(),set:z.optional(),loop:z.optional(),loopDynamic:R.boolean().optional().describe("When true, `loop over: <this-typed value>` re-evaluates the expression each iteration and exits when the result's raw is falsy. Bool uses this for while-loop semantics. The type may have either `loop` (for static iterables) OR `loopDynamic` set; with loopDynamic, no `loop` ExprDef is required.")}),CallDef:R.object({docs:R.string().optional(),types:R.record(pm).optional().describe('Call-local type aliases. Declare reusable named types here ONCE and reference them inside `args` / `returns` / `throws` / `get` / `set` as a bare `{name: "<alias>"}`. Aliases process AFTER any enclosing generics (so they may reference generic placeholders) and BEFORE the call slots — the call slots resolve them at parse time. Sequential: later aliases may reference earlier ones. Use this whenever the same composite type appears more than once in a signature — instead of writing `num{whole:true, min:1}` four times, declare `{ counter: { name:"num", options:{whole:true,min:1} } }` once and reference `{name:"counter"}`.'),args:pm,returns:pm.optional(),throws:pm.optional(),get:z.optional(),set:z.optional()}),InitDef:R.object({docs:R.string().optional(),args:pm,run:z})},gm=[`any`,`void`,`null`,`bool`,`num`,`text`,`list`,`map`,`tuple`,`obj`,`optional`,`nullable`,`not`,`or`,`and`,`enum`,`literal`,`fn`,`interface`,`typ`,`date`,`timestamp`,`duration`,`color`],_m={Type_any:R.object({name:R.literal(`any`)}),Type_void:R.object({name:R.literal(`void`)}),Type_null:R.object({name:R.literal(`null`)}),Type_bool:R.object({name:R.literal(`bool`),options:R.object({trueText:R.string().optional(),falseText:R.string().optional()}).optional()}),Type_num:R.object({name:R.literal(`num`),options:R.object({min:R.number().optional().describe('Only set when a real lower bound is part of the spec — e.g. "positive count" → min: 1, "age" → min: 0. Do NOT add `min: 0` to every num just because most numbers happen to be non-negative.'),max:R.number().optional().describe(`Only set when there is an actual upper bound — a percentage capped at 100, a year capped at 9999. Do NOT pick a generic ceiling like 1000/9999 to fill the field.`),whole:R.boolean().optional().describe(`Only set to true when the value is genuinely integral (counts, indices, ids). Leave unset (allow fractions) for measurements, ratios, etc.`),minPrecision:R.number().optional().describe(`Decimal-place floor. Almost never needed; omit unless the spec explicitly requires N decimal places.`),maxPrecision:R.number().optional().describe(`Decimal-place ceiling. Same rule as minPrecision — omit unless explicitly required.`),prefix:R.string().optional().describe(`Display-only prefix (e.g. "$"). Has no effect on validation. Omit unless rendering needs it.`),suffix:R.string().optional().describe(`Display-only suffix (e.g. "%"). Same as prefix — omit unless rendering needs it.`)}).optional().describe(`Omit entirely for ordinary numbers. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_text:R.object({name:R.literal(`text`),options:R.object({minLength:R.number().optional().describe(`Only set when a real lower bound is part of the spec — e.g. "non-empty input" → minLength: 1. Do NOT default to 0.`),maxLength:R.number().optional().describe(`Only set when there is an actual upper bound — a database column width, an API limit, an explicit "no longer than X chars" rule. Do NOT pick a generic ceiling like 100/200/1000 just to fill the field.`),pattern:R.string().optional().describe(`Only set for actual format constraints (UUID, ISO date, slug, etc.). Do NOT use ".*" or other accept-anything patterns — they add zero validation and clutter the schema.`),flags:R.string().optional().describe('Regex flags (e.g. "i"). Omit unless `pattern` is set AND requires flags.')}).optional().describe(`Omit entirely for ordinary strings. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_list:R.object({name:R.literal(`list`),generic:R.object({V:pm}).optional(),options:R.object({minLength:R.number().optional(),maxLength:R.number().optional()}).optional()}),Type_map:R.object({name:R.literal(`map`),generic:R.object({K:pm,V:pm}).optional()}),Type_tuple:R.object({name:R.literal(`tuple`),options:R.object({elements:R.array(pm)})}),Type_object:R.object({name:R.literal(`obj`),props:R.record(R.ref(`PropDef`)).optional()}),Type_optional:R.object({name:R.literal(`optional`),generic:R.object({T:pm}).optional()}),Type_nullable:R.object({name:R.literal(`nullable`),generic:R.object({T:pm}).optional()}),Type_not:R.object({name:R.literal(`not`),options:R.object({excluded:pm})}),Type_or:R.object({name:R.literal(`or`),options:R.object({types:R.array(pm)})}),Type_and:R.object({name:R.literal(`and`),options:R.object({types:R.array(pm)})}),Type_enum:R.object({name:R.literal(`enum`),generic:R.object({V:pm}).optional(),options:R.object({values:R.record(R.unknown())})}),Type_literal:R.object({name:R.literal(`literal`),generic:R.object({T:pm}).optional(),options:R.object({value:R.unknown()})}),Type_function:R.object({name:R.literal(`fn`),call:R.ref(`CallDef`).optional()}),Type_interface:R.object({name:R.literal(`interface`),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional()}),Type_typ:R.object({name:R.literal(`typ`),generic:R.object({T:pm}).optional()}),Type_date:R.object({name:R.literal(`date`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional()}).optional()}),Type_timestamp:R.object({name:R.literal(`timestamp`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional(),precision:R.enum([`ms`,`s`,`us`]).optional()}).optional()}),Type_duration:R.object({name:R.literal(`duration`)}),Type_color:R.object({name:R.literal(`color`),options:R.object({hasAlpha:R.boolean().optional()}).optional()})},vm={Expr_block:R.object({kind:R.literal(`block`),comment:mm,lines:R.array(z).describe(`Sequence of expressions evaluated in order. The block's value is the LAST line's value (an empty block returns void). Earlier lines run for their side effects (set, fns.fetch, etc.).`)}),Expr_define:R.object({kind:R.literal(`define`),comment:mm,vars:R.array(R.object({name:R.string().describe(`Variable name. Must NOT be a reserved name (args, recurse, this, super, key, value, yield, error) and must NOT shadow anything already in scope.`),type:pm.optional().describe("Optional declared type. OMIT this field when the value already determines the type — every value Expr (`new`, `get`, `if`, ...) is typed, and the var inherits that type. Set this only when you need to widen / narrow / annotate beyond what the value alone produces; a mismatch with the value's inferred type is reported as `define.var.type-mismatch`."),value:z.describe("The expression whose result is bound under `name`. May reference any earlier var in this define — each var is added to scope before the next var's value is evaluated.")})).describe("Bindings introduced before `body`. Evaluated sequentially, so `vars[i].value` may reference any of `vars[0..i-1]`."),body:z}),Expr_flow:R.object({kind:R.literal(`flow`),action:R.enum([`break`,`continue`,`return`,`exit`,`throw`]).describe("Which control-flow signal to raise. `break`/`continue` only valid inside a loop. `return` only valid inside a fn body / lambda; unwinds to the enclosing call with `value`. `exit` unwinds all the way to `engine.run`, returning `value` as the program result. `throw` raises `error` (caught by a path step's `catch:` handler)."),value:z.optional().describe("Required for `return` and `exit` (the value being returned). Ignored by `break` / `continue` / `throw`."),error:z.optional().describe("Required for `throw` — the value to raise. Ignored otherwise.")}),Expr_get:R.object({kind:R.literal(`get`),path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right starting from a scope variable. Step shapes: `{prop:"name"}` for prop/method access, `{args:{…}}` to call the previous step, `{key:Expr}` for index access. The first step MUST be a prop step (the scope-var name). A step names exactly ONE shape — a call is its own step, so a method with arguments is `[{"prop":"m"},{"args":{…}}]` and never `{"prop":"m","args":{…}}`. Result is the final step\'s value.')}),Expr_if:R.object({kind:R.literal(`if`),comment:mm,ifs:R.array(R.object({condition:z.describe("Bool-typed expression. First branch whose condition is `true` wins; the rest are skipped."),body:z.describe(`Evaluated when this branch's condition is true. The if-expression's value is this body's value.`)})).describe("Ordered list of `{condition, body}` branches — first true condition wins. Each `condition` must be bool-typed (warned otherwise). With multiple branches this is the gin equivalent of `if / else if / else if`."),else:z.optional().describe("Optional fallback evaluated when every `ifs[i].condition` is false. Without an else, a no-match if-expression evaluates to void.")}),Expr_lambda:R.object({kind:R.literal(`lambda`),comment:mm,type:pm.describe('The lambda\'s function type — `{ name: "fn", call: { args, returns } }` (or a registered named fn type). The `args` obj defines what the body sees under the `args` scope variable; `returns` is what the body must produce.'),body:z.describe('The lambda body. At runtime, scope contains the lexical scope at definition site PLUS `args` (the call arguments) and `recurse` (this same lambda, for self-calls). Read params via `[{prop:"args"},{prop:"<name>"}]`.'),constraint:z.optional().describe("Optional bool-typed precondition evaluated before the body on every call (with `args` in scope). If it returns false, the call throws. Use for input invariants you want enforced regardless of caller.")}),Expr_loop:R.object({kind:R.literal(`loop`),comment:mm,over:z.describe("The iterable expression. Two evaluation modes: (1) iterable types (list, map, etc. — anything whose `get().loop` is defined) iterate once; the expression is evaluated ONCE at the start. (2) bool — while-loop semantics: the expression is RE-EVALUATED each iteration; the loop continues while the value is `true` and exits the moment it becomes `false`. Use `flow:break` / `flow:continue` inside the body to control iteration regardless of mode."),body:z.describe("Evaluated once per iteration with the current `key` and `value` bound in scope. Use `{kind:'flow', action:'break'}` or `'continue'` for early-exit. The loop expression itself returns void."),key:R.string().optional().describe("Override the scope-variable name the iteration index/key is bound under (default: `key`). Must NOT be reserved or shadow an outer scope var. Use to disambiguate when looping inside another loop."),value:R.string().optional().describe("Override the scope-variable name the iteration value is bound under (default: `value`). Same rules as `key`."),parallel:R.object({concurrent:z.optional().describe(`Max in-flight iterations as a num (omit / 1 → strictly sequential). Use when iterations are independent I/O — e.g. fetching N URLs concurrently.`),rate:z.optional().describe(`Minimum interval between iteration starts. Accepts a num (milliseconds) or a duration. Use to rate-limit fan-out (e.g. avoid hammering an API).`)}).optional().describe("Opt-in parallelism. Both fields are optional and independent: `concurrent` caps fan-out width, `rate` paces start times. Iterations may finish out of order; the body should not assume sequential ordering. Composes with dynamic (bool while-loop) iteration: the body fans out up to `concurrent`, and `over` is re-evaluated against the outer scope each time a task completes — so accumulating side effects of earlier tasks decide whether more tasks spawn.")}),Expr_native:R.object({kind:R.literal(`native`),comment:mm,id:R.string().describe("Identifier of a native impl registered via `registry.setNative(id, fn)` (e.g. `list.push`, `num.add`). The model should NOT generate `native` expressions directly — methods on built-in types are reached via `get` paths, which gin resolves to natives internally."),type:pm.optional().describe("Optional type to wrap the native's raw return value with when the impl returns a non-Value. Defaults to `any` if omitted.")}),Expr_set:R.object({kind:R.literal(`set`),comment:mm,path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right to a writable target. Single-step `[{prop:"x"}]` re-assigns scope variable `x`. Multi-step targets need the type to support set on the final step (a prop with a `set` ExprDef, an indexed slot, or a method whose call has `set:`).'),value:z.describe("The expression evaluated and assigned to the path target. Its type must be compatible with the target's declared type — checked statically as `set.type-mismatch`.")}),Expr_switch:R.object({kind:R.literal(`switch`),comment:mm,value:z.describe("Expression whose result is compared against each case's `equals` candidates. Evaluated once."),cases:R.array(R.object({equals:R.array(z).describe("Candidate values for this case. The case wins if `value` equals ANY one of them (logical OR). Each candidate's type must be compatible with `value`'s type — checked as `switch.case.type`."),body:z.describe(`Evaluated when this case wins. The switch expression's value is this body's value.`)})).describe(`Ordered list of cases — first match wins. Cases are NOT fall-through; only the matching case's body runs.`),else:z.optional().describe(`Optional fallback evaluated when no case matches. Without an else, a no-match switch evaluates to void.`)}),Expr_template:R.object({kind:R.literal(`template`),template:R.union([z,R.string()]).describe("The template string — either a literal string (auto-wrapped as `new text`) or an Expr that evaluates to text. Placeholders use `{name}` syntax; each `name` is looked up first in `params` (when supplied) and then in the surrounding scope."),params:z.optional().describe("Optional obj-typed expression supplying placeholder values. When omitted or when a key is missing, `{name}` falls back to a scope lookup of the same name — so a `${baseUrl}` placeholder resolves to a surrounding `define baseUrl = ...`. Provide `params` only when placeholders need values not already in scope (or to override scope values).")})},ym=[`new`,`get`,`set`,`define`,`block`,`if`,`switch`,`loop`,`lambda`,`template`,`flow`,`native`],bm={any:R.unknown(),void:R.null(),null:R.null(),bool:R.boolean(),num:R.number(),text:R.string(),list:R.array(z),map:R.array(R.object({key:z,value:z})),tuple:R.array(z),obj:R.record(z),optional:z,nullable:R.nullable(z),not:R.unknown(),or:z,and:z,enum:R.union([R.string(),R.number()]),literal:R.unknown(),fn:R.union([R.string(),R.object({kind:R.string()})]),interface:R.record(z),typ:pm,date:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`),timestamp:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`),duration:R.object({days:R.number().optional(),hours:R.number().optional(),minutes:R.number().optional(),seconds:R.number().optional(),ms:R.number().optional()}),color:R.object({r:R.int().min(0).max(255),g:R.int().min(0).max(255),b:R.int().min(0).max(255),a:R.number().min(0).max(1).optional()})},xm=(e,t,n)=>R.object({kind:R.literal(`new`),type:t.describe(`Full TypeDef for a \`${e}\` instance (name + options + per-class fields).`),value:R.optional(n).describe(`Initial value matching this \`${e}\` instance. Composites accept Expr slots; primitives accept their raw form.`)}),Sm=Object.fromEntries(gm.map(e=>[`New_${e}`,xm(e,R.ref(cm[e]),bm[e])])),Cm=R.object({kind:R.literal(`new`),type:pm.describe("TypeDef of the value being constructed. The `value` field is interpreted relative to this type — primitives take their raw form (`new num` → number), composites take Expr slots (`new list` → Expr[])."),value:R.unknown().optional().describe("Initial value matching `type`. Optional when the type has a defined `init` constructor or a sensible default (empty list, zero num with no constraints, etc.).")}),wm=new Set([...Object.keys(hm),...Object.keys(_m),...Object.keys(vm),...Object.keys(Sm),`TypeDef`,`Type_Extension`,`Expr_new`,`Expr`]),Tm=(e,t)=>t.length===0?R.never():t.length===1?t[0]:R.discriminatedUnion(e,t);function Em(e,t){let n=new Map;for(let e of t?.types??[])n.set(e.name,e);for(let t of e.namedTypeList())n.has(t.name)||n.set(t.name,t);return n}function Dm(e,t){let n=Em(e,t),r=[...n.keys()],i=e.typeClasses(),a=[...r.map(e=>R.object({name:R.literal(e)}).describe(`The registered named type \`${e}\`, by name.`)),...i.map(t=>um(e,t.NAME)),R.ref(`Type_Extension`)];t?.namedRefs&&a.push(dm());let o=fm([...i.map(e=>e.NAME),...r]),s=e.exprClassList().map(e=>ym.includes(e.KIND)&&e.KIND!==`new`?R.ref(`Expr_${e.KIND}`):e.KIND===`new`?R.ref(`Expr_new`):e.toA?.()??R.object({kind:R.literal(e.KIND)}).describe(`A \`${e.KIND}\` expression.`)),c=Cm,l={};if(t?.newStrict){let t=[...n].map(([e,t])=>{let r=R.object({kind:R.literal(`new`),type:R.object({name:R.literal(e)}).describe(`Reference to the registered named type \`${e}\` \u2014 name-only, the registry resolves it to its full definition.`),value:R.optional(t.toNewA()).describe(`Initial value for the new \`${e}\` instance. Each composite slot accepts an Expr (Get, NewExpr, etc.); per-slot type correctness is enforced at runtime.`)});return wm.has(`New_${e}`)||n.has(`New_${e}`)?r:(l[`New_${e}`]=r,R.ref(`New_${e}`))}),r=i.map(t=>cm[t.NAME]!==void 0&&gm.includes(t.NAME)?R.ref(`New_${t.NAME}`):xm(t.NAME,um(e,t.NAME),t.toNewA?.()??R.unknown()));c=R.union([...t,...r])}let u={};for(let[e,t]of n)wm.has(e)||(u[e]=t.defineA({includeDocs:`all`}));return{...u,...l,TypeDef:Tm(`name`,a),Type_Extension:o,Expr_new:c,Expr:Tm(`kind`,s)}}var Om=new WeakMap,km=0,Am=e=>{let t=Om.get(e);return t===void 0&&Om.set(e,t=++km),t},jm=(e,t)=>`${Am(e)}:${e.version}|${t?.newStrict?`s`:``}${t?.namedRefs?`r`:``}|${(t?.types??[]).map(e=>e.name).join(`,`)}`,Mm=R.define(hm).define(_m).define(vm).define(Sm).declare(),Nm=Mm.dynamic((e,t)=>Dm(e,t),{key:jm,cacheSize:8});Nm.result(`TypeDef`),Nm.result(`Expr`);var Pm=class{list=[];stack=[];enter(e){return Array.isArray(e)?this.stack.push(...e):this.stack.push(e),this}leave(e=1){return this.stack.length=Math.max(0,this.stack.length-e),this}at(e,t){let n=Array.isArray(e)?e.length:1;this.enter(e);try{return t()}finally{this.leave(n)}}push(e,t,n=`error`,r){this.list.push({path:this.stack.slice(),code:e,message:t,severity:n,source:r})}error(e,t,n){this.push(e,t,`error`,n)}warn(e,t,n){this.push(e,t,`warning`,n)}info(e,t,n){this.push(e,t,`info`,n)}get hasErrors(){return this.list.some(e=>e.severity===`error`)}},Fm=class extends Error{constructor(e){super(`${e.code}: ${e.message} at ${e.path.join(`.`)}`),this.problem=e,this.name=`TypeError`}problem},B={NONE:0,STATE:1,SYSTEM:2,EXTERNAL:4};function Im(...e){let t=B.NONE;for(let n of e)t|=n;return t}var V=class e{constructor(e,t=[]){this.text=e,this.spans=t}text;spans;toString(){return this.text}concat(t){if(typeof t==`string`)return new e(this.text+t,this.spans);let n=this.text.length,r=t.spans.map(e=>({...e,start:e.start+n,end:e.end+n}));return new e(this.text+t.text,[...this.spans,...r])}indent(t){if(!t||!this.text.includes(`
72
72
  `))return this;let n=this.text.length,r=new Int32Array(n+1),i=0;for(let e=0;e<n;e++)r[e]=i,this.text[e]===`
73
73
  `&&(i+=t.length);r[n]=i;let a=this.text.replace(/\n/g,`
74
- ${t}`),o=this.spans.map(e=>({...e,start:e.start+r[e.start],end:e.end+r[e.end]}));return new e(a,o)}static jsonObject(t,n,r=0,i=2){let a=t.filter(e=>e.value!==void 0);if(a.length===0)return Fm(`{}`,n);let o=` `.repeat((r+1)*i),s=` `.repeat(r*i);return Fm(H`{\n${Im(a.map(({key:t,value:n})=>{let r=typeof n==`string`?new e(n):n;return H`${o}${JSON.stringify(t)}: ${r}`}),`,
75
- `)}\n${s}}`,n)}static jsonArray(t,n,r=0,i=2){if(t.length===0)return Fm(`[]`,n);let a=` `.repeat((r+1)*i),o=` `.repeat(r*i);return Fm(H`[\n${Im(t.map(t=>{let n=typeof t==`string`?new e(t):t;return H`${a}${n}`}),`,
76
- `)}\n${o}]`,n)}static jsonString(e){return JSON.stringify(e)}formatProblems(e,t={}){return Vm(this,e.list,t)}formatProblem(e,t={}){return Vm(this,[e],{...t,sectionHeaders:!1,lineNumbers:!1,contextLines:0})}spanFor(e){let t,n=-1,r=1/0;for(let i of this.spans){if(!Gm(i.path,e))continue;let a=i.end-i.start;(i.path.length>n||i.path.length===n&&a<r)&&(t=i,n=i.path.length,r=a)}return t}toLines(){let e=[],t=this.text.split(`
77
- `),n=0;for(let r=0;r<t.length;r++){let i=t[r],a=n,o=n+i.length,s=[];for(let e of this.spans){if(e.end<=a||e.start>=o)continue;let t=Math.max(e.start,a)-a,n=Math.min(e.end,o)-a;s.push({...e,start:t,end:n})}e.push({text:i,spans:s,lineNum:r+1}),n=o+1}return e}};function Fm(e,t){let n=typeof e==`string`?new V(e):e,r={start:0,end:n.text.length,path:t.path,expr:t.expr,type:t.type};return new V(n.text,[r,...n.spans])}function H(e,...t){let n=``,r=[];for(let i=0;i<e.length;i++)if(n+=e[i],i<t.length){let e=t[i];if(typeof e==`string`)n+=e;else{let t=n.length;n+=e.text;for(let n of e.spans)r.push({...n,start:n.start+t,end:n.end+t})}}return new V(n,r)}function Im(e,t=``){if(e.length===0)return new V(``);let n=typeof t==`string`?new V(t):t,r=typeof e[0]==`string`?new V(e[0]):e[0];for(let t=1;t<e.length;t++)r=r.concat(n).concat(e[t]);return r}function Lm(e){return Im(e,`
78
- `)}var Rm={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,cyan:`\x1B[36m`},zm={error:`error`,warning:`warning`,info:`info`},Bm={error:Rm.red,warning:Rm.yellow,info:Rm.blue};function Vm(e,t,n){if(t.length===0)return``;let r=n.color??!1,i=n.contextLines??2,a=n.sectionHeaders??!0,o=n.lineNumbers??!0,s=n.maxProblems??1/0,c=(e,t)=>r?`${e}${t}${Rm.reset}`:t,l=e.toLines(),u=[],d=[],f=0;for(let n=0;n<t.length;n++){if(n>=s){f=t.length-n;break}let r=t[n],i=Hm(e,l,r);if(i)u.push(i);else{let e=Bm[r.severity],t=`${zm[r.severity]}:`,n=r.path.length>0?` @ ${r.path.join(`.`)}`:``;d.push(`${c(e,t)} ${r.message}${n}`)}}let p=Um(u,l.length,i),m=l.length,h=o?String(m).length:0,ee=p.map(e=>Wm(e,l,{color:r,sectionHeaders:a,lineNumbers:o,gutterWidth:h,c}));return d.length>0&&ee.push(d.join(`
74
+ ${t}`),o=this.spans.map(e=>({...e,start:e.start+r[e.start],end:e.end+r[e.end]}));return new e(a,o)}static jsonObject(t,n,r=0,i=2){let a=t.filter(e=>e.value!==void 0);if(a.length===0)return Lm(`{}`,n);let o=` `.repeat((r+1)*i),s=` `.repeat(r*i);return Lm(H`{\n${Rm(a.map(({key:t,value:n})=>{let r=typeof n==`string`?new e(n):n;return H`${o}${JSON.stringify(t)}: ${r}`}),`,
75
+ `)}\n${s}}`,n)}static jsonArray(t,n,r=0,i=2){if(t.length===0)return Lm(`[]`,n);let a=` `.repeat((r+1)*i),o=` `.repeat(r*i);return Lm(H`[\n${Rm(t.map(t=>{let n=typeof t==`string`?new e(t):t;return H`${a}${n}`}),`,
76
+ `)}\n${o}]`,n)}static jsonString(e){return JSON.stringify(e)}formatProblems(e,t={}){return Um(this,e.list,t)}formatProblem(e,t={}){return Um(this,[e],{...t,sectionHeaders:!1,lineNumbers:!1,contextLines:0})}spanFor(e){let t,n=-1,r=1/0;for(let i of this.spans){if(!qm(i.path,e))continue;let a=i.end-i.start;(i.path.length>n||i.path.length===n&&a<r)&&(t=i,n=i.path.length,r=a)}return t}toLines(){let e=[],t=this.text.split(`
77
+ `),n=0;for(let r=0;r<t.length;r++){let i=t[r],a=n,o=n+i.length,s=[];for(let e of this.spans){if(e.end<=a||e.start>=o)continue;let t=Math.max(e.start,a)-a,n=Math.min(e.end,o)-a;s.push({...e,start:t,end:n})}e.push({text:i,spans:s,lineNum:r+1}),n=o+1}return e}};function Lm(e,t){let n=typeof e==`string`?new V(e):e,r={start:0,end:n.text.length,path:t.path,expr:t.expr,type:t.type};return new V(n.text,[r,...n.spans])}function H(e,...t){let n=``,r=[];for(let i=0;i<e.length;i++)if(n+=e[i],i<t.length){let e=t[i];if(typeof e==`string`)n+=e;else{let t=n.length;n+=e.text;for(let n of e.spans)r.push({...n,start:n.start+t,end:n.end+t})}}return new V(n,r)}function Rm(e,t=``){if(e.length===0)return new V(``);let n=typeof t==`string`?new V(t):t,r=typeof e[0]==`string`?new V(e[0]):e[0];for(let t=1;t<e.length;t++)r=r.concat(n).concat(e[t]);return r}function zm(e){return Rm(e,`
78
+ `)}var Bm={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,cyan:`\x1B[36m`},Vm={error:`error`,warning:`warning`,info:`info`},Hm={error:Bm.red,warning:Bm.yellow,info:Bm.blue};function Um(e,t,n){if(t.length===0)return``;let r=n.color??!1,i=n.contextLines??2,a=n.sectionHeaders??!0,o=n.lineNumbers??!0,s=n.maxProblems??1/0,c=(e,t)=>r?`${e}${t}${Bm.reset}`:t,l=e.toLines(),u=[],d=[],f=0;for(let n=0;n<t.length;n++){if(n>=s){f=t.length-n;break}let r=t[n],i=Wm(e,l,r);if(i)u.push(i);else{let e=Hm[r.severity],t=`${Vm[r.severity]}:`,n=r.path.length>0?` @ ${r.path.join(`.`)}`:``;d.push(`${c(e,t)} ${r.message}${n}`)}}let p=Gm(u,l.length,i),m=l.length,h=o?String(m).length:0,ee=p.map(e=>Km(e,l,{color:r,sectionHeaders:a,lineNumbers:o,gutterWidth:h,c}));return d.length>0&&ee.push(d.join(`
79
79
  `)),f>0&&ee.push(`\u2026 (${f} more problem${f===1?``:`s`} suppressed)`),ee.join(`
80
80
 
81
- `)}function Hm(e,t,n){let r=e.spanFor(n.path);if(!r)return null;let i=new Map,a=0,o=-1,s=-1;for(let e=0;e<t.length;e++){let n=t[e].text,c=a,l=a+n.length;if(r.end>c&&r.start<=l){let t=Math.max(r.start,c)-c,n=Math.min(r.end,l)-c;i.set(e,{startCol:t,endCol:n}),o<0&&(o=e),s=e}a=l+1}return o<0?null:{problem:n,firstLine:o,lastLine:s,hits:i}}function Um(e,t,n){if(e.length===0)return[];let r=[...e].sort((e,t)=>e.firstLine-t.firstLine),i=[];for(let e of r){let r=Math.max(0,e.firstLine-n),a=Math.min(t-1,e.lastLine+n),o=i[i.length-1];o&&r<=o.lastLine+1?(o.lastLine=Math.max(o.lastLine,a),o.problems.push(e)):i.push({firstLine:r,lastLine:a,problems:[e]})}return i}function Wm(e,t,n){let{color:r,sectionHeaders:i,lineNumbers:a,gutterWidth:o,c:s}=n,c=[],l=e=>a?s(Rm.dim,`${String(e).padStart(o)} \u2502 `):``,u=()=>a?s(Rm.dim,`${` `.repeat(o)} \u2502 `):``;if(i){let t=e.firstLine===e.lastLine?`line ${e.firstLine+1}`:`lines ${e.firstLine+1}-${e.lastLine+1}`,n=`─`.repeat(Math.max(3,60-t.length-4));c.push(s(Rm.dim,`\u2500\u2500 ${t} ${n}`))}let d={error:0,warning:1,info:2};for(let n=e.firstLine;n<=e.lastLine;n++){c.push(l(n+1)+t[n].text);let r=new Map;for(let t of e.problems){let e=t.hits.get(n);if(!e)continue;let i=`${e.startCol}:${e.endCol}`,a=r.get(i);(!a||d[t.problem.severity]<d[a])&&r.set(i,t.problem.severity)}for(let[e,t]of r){let[n,r]=e.split(`:`),i=Number(n),a=Number(r),o=` `.repeat(i)+`^`.repeat(Math.max(1,a-i));c.push(u()+s(Bm[t],o))}for(let t of e.problems){if(t.lastLine!==n)continue;let e=t.problem.severity,r=s(Bm[e],`${zm[e]}:`);c.push(u()+`${r} ${t.problem.message}`)}}return c.join(`
82
- `)}function Gm(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Km(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}var qm=new WeakMap,Jm=0,Ym=e=>{let t=qm.get(e);return t===void 0&&qm.set(e,t=++Jm),t},Xm=new WeakMap;function Zm(e){let t=Xm.get(e);return t===void 0&&(t=e instanceof Qm?`${Zm(e.parent)}/${Ym(e.bindingsRecord)}`:String(Ym(e)),Xm.set(e,t)),t}var Qm=class{parent;registry;local;constructor(e,t={}){this.parent=e,this.registry=e.registry,this.local=t}lookup(e){return this.local[e]??this.parent.lookup(e)}localLookup(e){return this.local[e]}get bindingsRecord(){return this.local}parse(e){return this.registry.parse(e,this)}parseExpr(e){return this.registry.parseExpr(e,this)}bind(e,t){this.local[e]=t}ownNames(){return Object.keys(this.local)}},$m=class e{comment;withComment(e){return e&&(this.comment=e),this}useLineComment(e={}){return e.expectsValue===!1}commentPrefix(e={}){return!this.comment||e.includeComments===!1?``:this.useLineComment(e)?`// ${this.comment}
83
- `:`/* ${this.comment} */ `}withCommentOn(e){return this.comment?{...e,comment:this.comment}:e}validate(e,t){let n=new Mm,r=t??e.globalTypeScope();return this.validateWalk(e,r,n,{inLoop:!1,inLambda:!1}),n}toCode(e,t){return this.toGinCode(e,t).toString()}toGinCode(e,t,n=[]){return Fm(this._toCodeFallback(e,t),{path:n,expr:this})}renderStatementBody(e,t={},n=!1){let r=this.kind;if(r===`flow`)return`${this.toCode(e,{...t,expectsValue:!1})};`;if(n&&r===`if`)return this.toCode(e,{...t,expectsValue:!1});if(r===`block`){let n=this.toCode(e,{...t,expectsValue:!1});return n.startsWith(`{`)?n:`{
84
- ${eh(n)}
81
+ `)}function Wm(e,t,n){let r=e.spanFor(n.path);if(!r)return null;let i=new Map,a=0,o=-1,s=-1;for(let e=0;e<t.length;e++){let n=t[e].text,c=a,l=a+n.length;if(r.end>c&&r.start<=l){let t=Math.max(r.start,c)-c,n=Math.min(r.end,l)-c;i.set(e,{startCol:t,endCol:n}),o<0&&(o=e),s=e}a=l+1}return o<0?null:{problem:n,firstLine:o,lastLine:s,hits:i}}function Gm(e,t,n){if(e.length===0)return[];let r=[...e].sort((e,t)=>e.firstLine-t.firstLine),i=[];for(let e of r){let r=Math.max(0,e.firstLine-n),a=Math.min(t-1,e.lastLine+n),o=i[i.length-1];o&&r<=o.lastLine+1?(o.lastLine=Math.max(o.lastLine,a),o.problems.push(e)):i.push({firstLine:r,lastLine:a,problems:[e]})}return i}function Km(e,t,n){let{color:r,sectionHeaders:i,lineNumbers:a,gutterWidth:o,c:s}=n,c=[],l=e=>a?s(Bm.dim,`${String(e).padStart(o)} \u2502 `):``,u=()=>a?s(Bm.dim,`${` `.repeat(o)} \u2502 `):``;if(i){let t=e.firstLine===e.lastLine?`line ${e.firstLine+1}`:`lines ${e.firstLine+1}-${e.lastLine+1}`,n=`─`.repeat(Math.max(3,60-t.length-4));c.push(s(Bm.dim,`\u2500\u2500 ${t} ${n}`))}let d={error:0,warning:1,info:2};for(let n=e.firstLine;n<=e.lastLine;n++){c.push(l(n+1)+t[n].text);let r=new Map;for(let t of e.problems){let e=t.hits.get(n);if(!e)continue;let i=`${e.startCol}:${e.endCol}`,a=r.get(i);(!a||d[t.problem.severity]<d[a])&&r.set(i,t.problem.severity)}for(let[e,t]of r){let[n,r]=e.split(`:`),i=Number(n),a=Number(r),o=` `.repeat(i)+`^`.repeat(Math.max(1,a-i));c.push(u()+s(Hm[t],o))}for(let t of e.problems){if(t.lastLine!==n)continue;let e=t.problem.severity,r=s(Hm[e],`${Vm[e]}:`);c.push(u()+`${r} ${t.problem.message}`)}}return c.join(`
82
+ `)}function qm(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Jm(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}var Ym=new WeakMap,Xm=0,Zm=e=>{let t=Ym.get(e);return t===void 0&&Ym.set(e,t=++Xm),t},Qm=new WeakMap;function $m(e){let t=Qm.get(e);return t===void 0&&(t=e instanceof eh?`${$m(e.parent)}/${Zm(e.bindingsRecord)}`:String(Zm(e)),Qm.set(e,t)),t}var eh=class{parent;registry;local;constructor(e,t={}){this.parent=e,this.registry=e.registry,this.local=t}lookup(e){return this.local[e]??this.parent.lookup(e)}localLookup(e){return this.local[e]}get bindingsRecord(){return this.local}parse(e){return this.registry.parse(e,this)}parseExpr(e){return this.registry.parseExpr(e,this)}bind(e,t){this.local[e]=t}ownNames(){return Object.keys(this.local)}},th=class e{comment;withComment(e){return e&&(this.comment=e),this}useLineComment(e={}){return e.expectsValue===!1}commentPrefix(e={}){return!this.comment||e.includeComments===!1?``:this.useLineComment(e)?`// ${this.comment}
83
+ `:`/* ${this.comment} */ `}withCommentOn(e){return this.comment?{...e,comment:this.comment}:e}validate(e,t){let n=new Pm,r=t??e.globalTypeScope();return this.validateWalk(e,r,n,{inLoop:!1,inLambda:!1}),n}toCode(e,t){return this.toGinCode(e,t).toString()}toGinCode(e,t,n=[]){return Lm(this._toCodeFallback(e,t),{path:n,expr:this})}renderStatementBody(e,t={},n=!1){let r=this.kind;if(r===`flow`)return`${this.toCode(e,{...t,expectsValue:!1})};`;if(n&&r===`if`)return this.toCode(e,{...t,expectsValue:!1});if(r===`block`){let n=this.toCode(e,{...t,expectsValue:!1});return n.startsWith(`{`)?n:`{
84
+ ${nh(n)}
85
85
  }`}return r===`if`||r===`switch`||r===`loop`?`{
86
- ${eh(this.toCode(e,{...t,expectsValue:!1}))}
86
+ ${nh(this.toCode(e,{...t,expectsValue:!1}))}
87
87
  }`:`{
88
- ${eh(this.toCode(e,{...t,expectsValue:!0}))};
88
+ ${nh(this.toCode(e,{...t,expectsValue:!0}))};
89
89
  }`}renderStatementBodyRich(e,t={},n=[],r=!1){let i=this.kind;if(i===`flow`)return H`${this.toGinCode(e,{...t,expectsValue:!1},n)};`;if(r&&i===`if`)return this.toGinCode(e,{...t,expectsValue:!1},n);if(i===`block`){let r=this.toGinCode(e,{...t,expectsValue:!1},n);return r.text.startsWith(`{`)?r:H`{\n ${r.indent(` `)}\n}`}return i===`if`||i===`switch`||i===`loop`?H`{\n ${this.toGinCode(e,{...t,expectsValue:!1},n).indent(` `)}\n}`:H`{\n ${this.toGinCode(e,{...t,expectsValue:!0},n).indent(` `)};\n}`}toJSONCode(e=[],t=2,n=0){let r=JSON.stringify(this.toJSON(),null,t);if(n>0){let e=` `.repeat(n*t);r=r.replace(/\n/g,`
90
- `+e)}return Fm(r,{path:e,expr:this})}_toCodeFallback(t,n){let r=Object.getPrototypeOf(this).toCode;return r&&r!==e.prototype.toCode?r.call(this,t,n):`<unrendered:${this.kind??`?`}>`}forEachChild(e){}};function eh(e){return e.replace(/\n/g,`
91
- `)}var th=new Set([`args`,`recurse`,`this`,`super`,`key`,`value`,`yield`,`error`]),nh=class e{parent;vars;control;constructor(e=null,t,n){this.parent=e,this.vars=new Map(t?Object.entries(t):[]),this.control=n??e?.control}async checkpoint(){this.control&&await this.control.checkpoint()}get(e){let t=this.vars.get(e);return t===void 0?this.parent?.get(e):t}set(e,t){this.vars.has(e)?this.vars.set(e,t):this.parent&&this.parent.has(e)?this.parent.set(e,t):this.vars.set(e,t)}has(e){return this.vars.has(e)?!0:this.parent?.has(e)??!1}child(t){return new e(this,t)}names(){let e=new Set;for(let t=this;t;t=t.parent)for(let n of t.vars.keys())e.add(n);return[...e]}};function rh(e,t,n){let r=t instanceof $m?t:ih(e,t);return r?r.typeOf(e,n):e.registry.any()}function ih(e,t){try{return e.registry.parseExpr(t)}catch{return}}function ah(e,t,n,r={inLoop:!1,inLambda:!1}){let i=new Mm;return oh(e,t,n,i,r),i}function oh(e,t,n,r,i){let a;if(t instanceof $m)a=t;else try{a=e.registry.parseExpr(t)}catch{return r.warn(`expr.unknown-kind`,`unknown expr kind '${t.kind}'`),e.registry.any()}return a.validateWalk(e,n,r,i)}function sh(e,t,n){th.has(e)?n.error(`binding.reserved`,`'${e}' is a reserved name (gin binds it automatically in fn/loop/path contexts) \u2014 pick a different name`):t.has(e)&&n.error(`binding.shadow`,`'${e}' is already in scope \u2014 pick a different name to avoid shadowing`)}var ch=class{constructor(e){this.action=e}action},lh=class extends ch{constructor(){super(`break`)}},uh=class extends ch{constructor(){super(`continue`)}},dh=class extends ch{constructor(e){super(`return`),this.value=e}value},fh=class extends ch{constructor(e){super(`exit`),this.value=e}value},ph=class extends ch{constructor(e){super(`throw`),this.error=e}error};function mh(e,t){let n=new vh(t);n.type(e,_h);let r=new Set(n.defines);return{refs:n.refs.filter(e=>!r.has(e)),defines:n.defines}}function hh(e,t,n){let r=new Map,i=[],a=[],o=new Map,s=new Set;for(let n of e)for(let e of mh(n,t).defines)s.add(e);let c=e=>{if(o.has(e)||s.has(e))return;let l=n(e);if(!l)o.set(e,`done`),i.push(e);else{o.set(e,`visiting`),r.set(e,l);for(let e of mh(l,t).refs)c(e);o.set(e,`done`),a.push(e)}};for(let n of e)for(let e of mh(n,t).refs)c(e);return{order:a,defs:r,missing:i}}var gh=new Set([`enum`,`literal`]),_h=new Set,vh=class{constructor(e){this.registry=e}registry;refs=[];defines=[];seenRefs=new Set;seenDefines=new Set;type(e,t){let n=this.registry.typeClass(e.name),r=e.extends!==void 0||n?.declaresGenerics===!0;e.extends===void 0?n||this.name(e.name,t):(this.define(e.name),this.name(e.extends,t));for(let n of e.satisfies??[])this.name(n,t);let i=r&&e.generic?xh(t,Object.keys(e.generic)):t;for(let t of Object.values(e.generic??{}))this.type(t,i);n&&gh.has(n.NAME)||this.options(e.options,i);for(let t of Object.values(e.props??{}))this.prop(t,i);e.get&&this.getSet(e.get,i),e.call&&this.call(e.call,i),e.init&&(this.type(e.init.args,i),this.expr(e.init.run,i)),e.constraint&&this.expr(e.constraint,i)}name(e,t){t.has(e)||this.registry.typeClass(e)||this.seenRefs.has(e)||(this.seenRefs.add(e),this.refs.push(e))}define(e){this.seenDefines.has(e)||(this.seenDefines.add(e),this.defines.push(e))}options(e,t){if(yh(e))for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)bh(e)&&this.type(e,t);else bh(n)&&this.type(n,t)}prop(e,t){this.type(e.type,t),this.expr(e.get,t),this.expr(e.set,t),this.expr(e.default,t)}getSet(e,t){this.type(e.key,t),this.type(e.value,t),this.expr(e.get,t),this.expr(e.set,t),this.expr(e.loop,t)}call(e,t){let n=t;for(let[t,r]of Object.entries(e.types??{}))this.type(r,n),n=xh(n,[t]);this.type(e.args,n),e.returns&&this.type(e.returns,n),e.throws&&this.type(e.throws,n),this.expr(e.get,n),this.expr(e.set,n)}expr(e,t){if(Array.isArray(e)){for(let n of e)this.expr(n,t);return}if(!yh(e))return;let n=bh(e.type)&&this.registry.typeClass(e.type.name)?.valuesAreTypes===!0;for(let[r,i]of Object.entries(e))if(r===`type`&&bh(i))this.type(i,t);else if(r===`generic`&&yh(i))for(let e of Object.values(i))bh(e)&&this.type(e,t);else r===`value`?n&&bh(i)?this.type(i,t):this.data(i,t):this.expr(i,t)}data(e,t){if(Array.isArray(e))for(let n of e)this.data(n,t);else if(yh(e)){if(this.isExpr(e))this.expr(e,t);else for(let n of Object.values(e))this.data(n,t)}}isExpr(e){return typeof e.kind==`string`&&this.registry.exprClass(e.kind)!==void 0}};function yh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bh(e){return yh(e)&&typeof e.name==`string`}function xh(e,t){return t.length===0?e:new Set([...e,...t])}function Sh(e,t,n){if(e===t||e.compatible(t,void 0,n))return!0;for(let r=Ch(t);r;r=Ch(r))if(e.compatible(r,void 0,n))return!0;return!1}function Ch(e){let t=e.base;return t instanceof U&&t!==e?t:void 0}function wh(e){if(e.name!==`or`)return;let t=e.variants;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function Th(e){if(e.name!==`and`)return;let t=e.parts;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function Eh(e,t,n){let r=e.type.encodeAs(e.raw,t,n);return t.form===`logical`?r:{type:e.type.toJSONRef(t),value:r}}function Dh(e,t,n,r,i){n instanceof W&&n.raw!==void 0&&(e[t]=Eh(n,r,i))}var Oh={form:`envelope`,typeRefs:`definition`};function kh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&!(e instanceof W)}function Ah(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return;let n=e.kind;if(typeof n==`string`&&t.registry.exprClass(n))try{return t.registry.parseExpr(e,t)}catch{return}}var jh=class e{type;get;set;default;docs;constructor(e){this.type=e.type,this.get=e.get,this.set=e.set,this.default=e.default,this.docs=e.docs}static from(t,n,r){if(t instanceof U)return new e({type:t});t instanceof e||Wp(r?`prop '${r}'`:`prop`,t,zp,tm,n?.registry);let i=t.type,a=i instanceof U?i:(()=>{if(!n)throw Error(`Prop.from: type is TypeDef but no scope provided to parse it`);return n.parse(i)})(),o=e=>e instanceof $m?e:n?.parseExpr(e),s=o(t.get),c=o(t.set),l=o(t.default);return t instanceof e&&t.type===a&&t.get===s&&t.set===c&&t.default===l?t:new e({type:a,get:s,set:c,default:l,docs:t.docs})}static fromMap(t,n){let r={};for(let[i,a]of Object.entries(t))r[i]=e.from(a,n,i);return r}static toJSONMap(t){let n={};for(let[r,i]of Object.entries(t))n[r]=e.from(i).toJSON();return n}toJSON(){return Km({docs:this.docs,type:this.type.toJSON(),get:this.get?.toJSON(),default:this.default?.toJSON(),set:this.set?.toJSON()})}async read(e,t,n,r,i=this.type){if(this.get){let i={this:e},a=e.type.propSuperFor(e,t,`get`,n,r);return a&&(i.super=a),this.get.evaluate(r,n.child(i))}return e.type.propGet(e,t,i)}async write(e,t,n,r,i){if(this.set){let a={this:e,value:n},o=e.type.propSuperFor(e,t,`set`,r,i);o&&(a.super=o),await this.set.evaluate(i,r.child(a))}else{if(this.get&&!this.type.call())throw Error(`path: prop '${t}' is computed (has 'get', no 'set') \u2014 cannot assign to it`);e.type.propSet(e,t,n)}}async invokeMethod(e,t,n,r,i,a){let o=a??this.type;if(!this.get){let a=e.raw?.[t],o=a instanceof W?a.raw:a;if(typeof o==`function`)return await o(n);if(o&&typeof o==`object`&&`kind`in o){let e=await i.evaluate(o,r);if(typeof e.raw==`function`)return await e.raw(n)}throw Error(`path: callable prop '${t}' has no get expression and raw is not a callable`)}let s=this.get,c=async n=>{let a={this:e,args:n,recurse:new W(o,c)},l=e.type.propSuperFor(e,t,`get`,r,i);l&&(a.super=l);try{return await s.evaluate(i,r.child(a))}catch(e){if(e instanceof dh)return e.value??new W(i.registry.void(),void 0);throw e}};return c(n)}async invokeMethodSet(e,t,n,r,i,a,o){let s=o??this.type,c=s.call?.();if(!c?.set)throw Error(`path: method '${t}' has no call.set`);let l=async n=>{let o={this:e,args:n,value:r,recurse:new W(s,l)},u=e.type.propSuperFor(e,t,`callSet`,i,a);return u&&(o.super=u),await c.set.evaluate(a,i.child(o)),G(a.registry.void(),void 0)};await l(n)}},Mh=class e{key;value;get;set;loop;loopDynamic;docs;constructor(e){this.key=e.key,this.value=e.value,this.get=e.get,this.set=e.set,this.loop=e.loop,this.loopDynamic=e.loopDynamic,this.docs=e.docs}static from(t,n){t instanceof e||Wp(`get/set surface`,t,Bp);let r=t.key,i=t.value,a=r instanceof U?r:(()=>{if(!n)throw Error(`GetSet.from: key is TypeDef but no scope provided`);return n.parse(r)})(),o=i instanceof U?i:(()=>{if(!n)throw Error(`GetSet.from: value is TypeDef but no scope provided`);return n.parse(i)})(),s=e=>e instanceof $m?e:n?.parseExpr(e),c=s(t.get),l=s(t.set),u=s(t.loop);return t instanceof e&&t.key===a&&t.value===o&&t.get===c&&t.set===l&&t.loop===u?t:new e({key:a,value:o,get:c,set:l,loop:u,loopDynamic:t.loopDynamic,docs:t.docs})}toJSON(){return Km({docs:this.docs,key:this.key.toJSON(),value:this.value.toJSON(),get:this.get?.toJSON(),set:this.set?.toJSON(),loop:this.loop?.toJSON(),loopDynamic:this.loopDynamic})}async indexRead(e,t,n,r){if(!this.get)throw Error(`path: type '${e.type.name}' has no index get`);let i={this:e,key:t},a=e.type.indexSuperFor(e,`get`,n,r);return a&&(i.super=a),this.get.evaluate(r,n.child(i))}async indexWrite(e,t,n,r,i){if(!this.set)throw Error(`path: type '${e.type.name}' has no index set`);let a={this:e,key:t,value:n},o=e.type.indexSuperFor(e,`set`,r,i);o&&(a.super=o),await this.set.evaluate(i,r.child(a))}},Nh=class e{args;returns;throws;get;set;docs;types;constructor(e){this.args=e.args,this.returns=e.returns,this.throws=e.throws,this.get=e.get,this.set=e.set,this.docs=e.docs,this.types=e.types}static from(t,n){t instanceof e||Wp(`call signature`,t,Vp,Gp);let r=t.types,i=n,a;if(r&&Object.keys(r).length>0){if(Object.values(r).every(e=>e instanceof U))a=r;else{if(!n)throw Error(`Call.from: types contain TypeDef but no scope provided`);let e=new Qm(n);i=e,a={};for(let[t,n]of Object.entries(r)){let r=n instanceof U?n:e.parse(n);e.bind(t,r),a[t]=r}}}let o=t.args,s=t.returns,c=t.throws,l=o instanceof U?o:(()=>{if(!i)throw Error(`Call.from: args is TypeDef but no scope provided`);return i.parse(o)})(),u=s===void 0?void 0:s instanceof U?s:(()=>{if(!i)throw Error(`Call.from: returns is TypeDef but no scope provided`);return i.parse(s)})(),d=c===void 0?void 0:c instanceof U?c:(()=>{if(!i)throw Error(`Call.from: throws is TypeDef but no scope provided`);return i.parse(c)})(),f=e=>e instanceof $m?e:i?.parseExpr(e),p=f(t.get),m=f(t.set),h=t.docs;return t instanceof e&&t.args===l&&t.returns===u&&t.throws===d&&t.get===p&&t.set===m&&t.types===a?t:new e({args:l,returns:u,throws:d,get:p,set:m,docs:h,types:a})}toJSON(){let e=this.types&&Object.keys(this.types).length>0?Object.fromEntries(Object.entries(this.types).map(([e,t])=>[e,t.toJSON()])):void 0;return Km({docs:this.docs,types:e,args:this.args.toJSON(),returns:this.returns?.toJSON(),throws:this.throws?.toJSON(),get:this.get?.toJSON(),set:this.set?.toJSON()})}renderTypes(e){if(!this.types)return``;let t=Object.keys(this.types);return t.length===0?``:`{${Bh(t.map(t=>`${t}: ${this.types[t].toCode(void 0,e)}`),{sep:`; `})}}`}effects(){let e=0;return this.get&&(e|=this.get.effects()),this.set&&(e|=this.set.effects()),e}},Ph=class e{args;run;docs;constructor(e){this.args=e.args,this.run=e.run,this.docs=e.docs}static from(t,n){t instanceof e||Wp(`init constructor`,t,Hp);let r=t.args,i=r instanceof U?r:(()=>{if(!n)throw Error(`Init.from: args is TypeDef but no scope provided`);return n.parse(r)})(),a=t.run,o=a instanceof $m?a:(()=>{if(!n)throw Error(`Init.from: run is ExprDef but no scope provided`);return n.parseExpr(a)})();return t instanceof e&&t.args===i&&t.run===o?t:new e({args:i,run:o,docs:t.docs})}toJSON(){return Km({docs:this.docs,args:this.args.toJSON(),run:this.run.toJSON()})}},U=class e{constructor(e,t,n={}){this.scope=e,this.options=t,this.generic=n}scope;options;generic;get registry(){return this.scope.registry}priority=0;docs;parsesExprValue(e){return!1}encodeAs(e,t,n){return this.encode(e,n)}toJSONRef(e){if(e?.typeRefs!==`name`)return this.toJSON();if(this.registry.lookup(this.name)===this)return{name:this.name};let t=this.toJSON(),n=Object.keys(this.generic);if(n.length===0)return t;let r={...t.generic??{}};for(let t of n)r[t]=this.generic[t].toJSONRef(e);return{...t,generic:r}}toDefinitionJSON(){let e=Lh.depth;Lh.active++,Lh.depth=this.registry.lookup(this.name)===this?0:1;try{return this.toJSON()}finally{Lh.active--,Lh.depth=e}}references(){return mh(this.toDefinitionJSON(),this.registry)}closure(e=this.scope){return hh([this.toDefinitionJSON()],this.registry,t=>e.lookup(t)?.toDefinitionJSON())}compatibleWithParts(e,t,n){let r=Th(e);if(!r)return!1;if(r.some(e=>this.compatible(e,t,n)))return!0;let i=e.simplify(n);return i!==e&&this.compatible(i,t,n)}compatible(e,t,n){for(let t=0;e.name===`alias`&&t<8;t++){let t=e.simplify(n);if(t===e)break;e=t}if(e===this)return!0;let r=Fh,i=Ih(t,n),a=r.active.get(this)?.get(e);if(a!==void 0&&a.key===i)return r.lowWater=Math.min(r.lowWater,a.depth),!0;let o=r.memo.get(this)?.get(e)?.get(i);if(o!==void 0)return o;let s=r.depth++,c=r.active.get(this);c||r.active.set(this,c=new Map),c.set(e,{depth:s,key:i});let l=r.lowWater;r.lowWater=1/0;let u=!1;try{let a=wh(e);if(u=a?a.every(e=>this.compatible(e,t,n)):this.compatibleType(e,t,n)||this.compatibleWithParts(e,t,n)||this.compatibleWithBase(e,t,n),!u||r.lowWater>=s){let t=r.memo.get(this);t||r.memo.set(this,t=new Map);let n=t.get(e);n||t.set(e,n=new Map),n.set(i,u)}return u}finally{c.delete(e),r.lowWater=Math.min(l,r.lowWater),--r.depth===0&&(r.memo=new Map,r.active=new Map,r.lowWater=1/0)}}compatibleWithBase(t,n,r){if(n?.strict||n?.exact)return!1;let i=t.base;return i instanceof e&&i!==t&&this.compatible(i,n,r)}accepts(e,t){return this.compatible(e,{strict:!0},t)}exact(e,t){return this.compatible(e,{strict:!0,exact:!0},t)}flexible(){return!1}like(e,t){return this}isUniversal(){return!1}simplify(e){return this}required(){return this}isOptional(){return!1}props(e){let t={toAny:this.registry.method({},this.registry.any(),`type.toAny`)},n=this.registry.augmentation(this.name);return n?.props?{...t,...n.props}:t}static UNIVERSAL_PROP_NAMES=new Set([`toAny`]);constraints(){return[]}get(e){return this.registry.augmentation(this.name)?.get}call(e){return this.registry.augmentation(this.name)?.call}init(e){return this.registry.augmentation(this.name)?.init}prop(e,t){let n=this.props(t)[e];return n?jh.from(n):void 0}follow(e,t){if(`prop`in e)return this.prop(e.prop,t)?.type;if(`args`in e)return this.call(t)?.returns;if(`key`in e)return this.get(t)?.value}at(e,t){let n=this;for(let r of e){if(!n)return;n=n.follow(r,t)}return n}toA(e){return e?.override?.(this)||(this.isRegisteredNamed()?R.ref(this.name):this.defineA(e))}defineA(e){return this.describeA(this.valueA(e),e)}valueA(e){return R.unknown()}toNewA(e){let t=this.init(e?.scope);return t?this.describeA(t.args.toA(e),e):this.toA(e)}isRegisteredNamed(){let e=this.registry;return e.typeClass(this.name)===void 0&&e.namedTypeList().includes(this)}objectA(e,t){let n=R.object(e);return t?.unknownKeys===`refuse`?n.strict():n}describeA(e,t){let n=t?.includeDocs??`none`,r=[];n!==`none`&&this.docs&&r.push(this.docs);let i=this.constraints();return i.length>0&&r.push(i.map(e=>`must satisfy ${e.toCode(this.registry,{expectsValue:!0})}`).join(`; `)),r.length>0?e.describe(r.join(` — `)):e}newEffects(e){let t=this.initEffects();return this.forEachNewSlot(e,{slot:(e,n)=>{t|=e.newEffects(n)},missing:e=>{t|=e.effects()}})?t:t|this.exprValueEffects(e)}exprValueEffects(e){if(!e||typeof e!=`object`||Array.isArray(e))return B.NONE;let t=e.kind;if(typeof t!=`string`||!this.registry.exprClass(t))return B.NONE;try{return this.registry.parseExpr(e,this.scope).effects()}catch{return B.NONE}}initEffects(){let e=this.init();if(!e)return B.NONE;try{return this.registry.parseExpr(e.run,this.scope).effects()}catch{return B.NONE}}newComplexity(e){let t=1+this.initComplexity();return this.forEachNewSlot(e,{slot:(e,n)=>{t+=e.elementComplexity(n)},missing:e=>{t+=e.complexity()}})?t:t+this.exprValueComplexity(e)}exprValueComplexity(e){if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e.kind;if(typeof t!=`string`||!this.registry.exprClass(t))return 0;try{return this.registry.parseExpr(e,this.scope).complexity()}catch{return 0}}initComplexity(){let e=this.init();if(!e)return 0;try{return this.registry.parseExpr(e.run,this.scope).complexity()}catch{return 0}}elementComplexity(e){let t=this.exprValueComplexity(e);return t>0?t:1}forEachNewSlot(e,t){return!1}validateNewValue(e,t,n,r,i){if(this.forEachNewSlot(e,{slot:(e,a,o)=>{r.at([o],()=>e.validateNewValue(a,t,n,r,i))}}))return;let a=Ah(e,this.scope);if(!a)return;let o=a.validateWalk(t,n,r,i);o.name!==`any`&&(Sh(this,o)||r.error(`new.slot.type`,`this slot is declared \`${this.toCode()}\` but the expression here produces \`${o.toCode()}\``))}async newFill(e,t,n){let r=Ah(e,this.scope);return r?r.evaluate(t,n):e}toGinCode(e,t,n=[]){return Fm(this.toCode(e,t),{path:n,type:this})}toJSONCode(e=[],t=2,n=0){return Jh(this.toJSON(),this.registry,e,t,n,this)}docsPrefix(e){return``}extendsClause(e){return``}toCodeRef(e,t){return this.toCode(e,t)}refProps(){return{}}refGet(){}refCall(){}static renderGenerics(e,t){let n=Object.keys(e);return n.length===0?``:`<${Bh(n.map(n=>{let r=e[n],i=r.name===`alias`&&r.options?.name===n;return r.name===`any`||i?n:`${n}: ${r.toCode(void 0,t)}`}),{indent:Vh(t)})}>`}static renderGenericArgs(t,n){let r=Object.keys(t);return r.length===0||!r.some(n=>!e.isGenericPlaceholder(n,t[n]))?``:`<${Bh(r.map(e=>t[e].toCode(void 0,n)),{indent:Vh(n)})}>`}static isGenericPlaceholder(e,t){return t.name===`any`||t.name===`alias`&&t.options?.name===e}static formatParams(e,t,n=`auto`){let r=e.fields;if(!r)return e.name===`void`||e.name===`any`?``:`args: ${e.toCode(void 0,t)}`;let i=Object.entries(r).map(([e,n])=>{let r=n.type.isOptional(),i=r?n.type.required():n.type;return`${n.docs&&t?.includeComments!==!1?`/* ${n.docs} */ `:``}${e}${r?`?`:``}: ${i.toCode(void 0,t)}`}),a=Vh(t);return n===`auto`?Bh(i,{indent:a}):i.length<=1?i.join(``):`
92
- ${i.map(e=>Hh(e,a)).join(`
90
+ `+e)}return Lm(r,{path:e,expr:this})}_toCodeFallback(t,n){let r=Object.getPrototypeOf(this).toCode;return r&&r!==e.prototype.toCode?r.call(this,t,n):`<unrendered:${this.kind??`?`}>`}forEachChild(e){}};function nh(e){return e.replace(/\n/g,`
91
+ `)}var rh=new Set([`args`,`recurse`,`this`,`super`,`key`,`value`,`yield`,`error`]),ih=class e{parent;vars;control;constructor(e=null,t,n){this.parent=e,this.vars=new Map(t?Object.entries(t):[]),this.control=n??e?.control}async checkpoint(){this.control&&await this.control.checkpoint()}get(e){let t=this.vars.get(e);return t===void 0?this.parent?.get(e):t}set(e,t){this.vars.has(e)?this.vars.set(e,t):this.parent&&this.parent.has(e)?this.parent.set(e,t):this.vars.set(e,t)}has(e){return this.vars.has(e)?!0:this.parent?.has(e)??!1}child(t){return new e(this,t)}names(){let e=new Set;for(let t=this;t;t=t.parent)for(let n of t.vars.keys())e.add(n);return[...e]}};function ah(e,t,n){let r=t instanceof th?t:oh(e,t);return r?r.typeOf(e,n):e.registry.any()}function oh(e,t){try{return e.registry.parseExpr(t)}catch{return}}function sh(e,t,n,r={inLoop:!1,inLambda:!1}){let i=new Pm;return ch(e,t,n,i,r),i}function ch(e,t,n,r,i){let a;if(t instanceof th)a=t;else try{a=e.registry.parseExpr(t)}catch{return r.warn(`expr.unknown-kind`,`unknown expr kind '${t.kind}'`),e.registry.any()}return a.validateWalk(e,n,r,i)}function lh(e,t,n){rh.has(e)?n.error(`binding.reserved`,`'${e}' is a reserved name (gin binds it automatically in fn/loop/path contexts) \u2014 pick a different name`):t.has(e)&&n.error(`binding.shadow`,`'${e}' is already in scope \u2014 pick a different name to avoid shadowing`)}var uh=class{constructor(e){this.action=e}action},dh=class extends uh{constructor(){super(`break`)}},fh=class extends uh{constructor(){super(`continue`)}},ph=class extends uh{constructor(e){super(`return`),this.value=e}value},mh=class extends uh{constructor(e){super(`exit`),this.value=e}value},hh=class extends uh{constructor(e){super(`throw`),this.error=e}error};function gh(e,t){let n=new bh(t);n.type(e,yh);let r=new Set(n.defines);return{refs:n.refs.filter(e=>!r.has(e)),defines:n.defines}}function _h(e,t,n){let r=new Map,i=[],a=[],o=new Map,s=new Set;for(let n of e)for(let e of gh(n,t).defines)s.add(e);let c=e=>{if(o.has(e)||s.has(e))return;let l=n(e);if(!l)o.set(e,`done`),i.push(e);else{o.set(e,`visiting`),r.set(e,l);for(let e of gh(l,t).refs)c(e);o.set(e,`done`),a.push(e)}};for(let n of e)for(let e of gh(n,t).refs)c(e);return{order:a,defs:r,missing:i}}var vh=new Set([`enum`,`literal`]),yh=new Set,bh=class{constructor(e){this.registry=e}registry;refs=[];defines=[];seenRefs=new Set;seenDefines=new Set;type(e,t){let n=this.registry.typeClass(e.name),r=e.extends!==void 0||n?.declaresGenerics===!0;e.extends===void 0?n||this.name(e.name,t):(this.define(e.name),this.name(e.extends,t));for(let n of e.satisfies??[])this.name(n,t);let i=r&&e.generic?Ch(t,Object.keys(e.generic)):t;for(let t of Object.values(e.generic??{}))this.type(t,i);n&&vh.has(n.NAME)||this.options(e.options,i);for(let t of Object.values(e.props??{}))this.prop(t,i);e.get&&this.getSet(e.get,i),e.call&&this.call(e.call,i),e.init&&(this.type(e.init.args,i),this.expr(e.init.run,i)),e.constraint&&this.expr(e.constraint,i)}name(e,t){t.has(e)||this.registry.typeClass(e)||this.seenRefs.has(e)||(this.seenRefs.add(e),this.refs.push(e))}define(e){this.seenDefines.has(e)||(this.seenDefines.add(e),this.defines.push(e))}options(e,t){if(xh(e))for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)Sh(e)&&this.type(e,t);else Sh(n)&&this.type(n,t)}prop(e,t){this.type(e.type,t),this.expr(e.get,t),this.expr(e.set,t),this.expr(e.default,t)}getSet(e,t){this.type(e.key,t),this.type(e.value,t),this.expr(e.get,t),this.expr(e.set,t),this.expr(e.loop,t)}call(e,t){let n=t;for(let[t,r]of Object.entries(e.types??{}))this.type(r,n),n=Ch(n,[t]);this.type(e.args,n),e.returns&&this.type(e.returns,n),e.throws&&this.type(e.throws,n),this.expr(e.get,n),this.expr(e.set,n)}expr(e,t){if(Array.isArray(e)){for(let n of e)this.expr(n,t);return}if(!xh(e))return;let n=Sh(e.type)&&this.registry.typeClass(e.type.name)?.valuesAreTypes===!0;for(let[r,i]of Object.entries(e))if(r===`type`&&Sh(i))this.type(i,t);else if(r===`generic`&&xh(i))for(let e of Object.values(i))Sh(e)&&this.type(e,t);else r===`value`?n&&Sh(i)?this.type(i,t):this.data(i,t):this.expr(i,t)}data(e,t){if(Array.isArray(e))for(let n of e)this.data(n,t);else if(xh(e)){if(this.isExpr(e))this.expr(e,t);else for(let n of Object.values(e))this.data(n,t)}}isExpr(e){return typeof e.kind==`string`&&this.registry.exprClass(e.kind)!==void 0}};function xh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sh(e){return xh(e)&&typeof e.name==`string`}function Ch(e,t){return t.length===0?e:new Set([...e,...t])}function wh(e,t,n){if(e===t||e.compatible(t,void 0,n))return!0;for(let r=Th(t);r;r=Th(r))if(e.compatible(r,void 0,n))return!0;return!1}function Th(e){let t=e.base;return t instanceof U&&t!==e?t:void 0}function Eh(e){if(e.name!==`or`)return;let t=e.variants;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function Dh(e){if(e.name!==`and`)return;let t=e.parts;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function Oh(e,t,n){let r=e.type.encodeAs(e.raw,t,n);return t.form===`logical`?r:{type:e.type.toJSONRef(t),value:r}}function kh(e,t,n,r,i){n instanceof W&&n.raw!==void 0&&(e[t]=Oh(n,r,i))}var Ah={form:`envelope`,typeRefs:`definition`};function jh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&!(e instanceof W)}function Mh(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return;let n=e.kind;if(typeof n==`string`&&t.registry.exprClass(n))try{return t.registry.parseExpr(e,t)}catch{return}}var Nh=class e{type;get;set;default;docs;constructor(e){this.type=e.type,this.get=e.get,this.set=e.set,this.default=e.default,this.docs=e.docs}static from(t,n,r){if(t instanceof U)return new e({type:t});t instanceof e||Kp(r?`prop '${r}'`:`prop`,t,Vp,rm,n?.registry);let i=t.type,a=i instanceof U?i:(()=>{if(!n)throw Error(`Prop.from: type is TypeDef but no scope provided to parse it`);return n.parse(i)})(),o=e=>e instanceof th?e:n?.parseExpr(e),s=o(t.get),c=o(t.set),l=o(t.default);return t instanceof e&&t.type===a&&t.get===s&&t.set===c&&t.default===l?t:new e({type:a,get:s,set:c,default:l,docs:t.docs})}static fromMap(t,n){let r={};for(let[i,a]of Object.entries(t))r[i]=e.from(a,n,i);return r}static toJSONMap(t){let n={};for(let[r,i]of Object.entries(t))n[r]=e.from(i).toJSON();return n}toJSON(){return Jm({docs:this.docs,type:this.type.toJSON(),get:this.get?.toJSON(),default:this.default?.toJSON(),set:this.set?.toJSON()})}async read(e,t,n,r,i=this.type){if(this.get){let i={this:e},a=e.type.propSuperFor(e,t,`get`,n,r);return a&&(i.super=a),this.get.evaluate(r,n.child(i))}return e.type.propGet(e,t,i)}async write(e,t,n,r,i){if(this.set){let a={this:e,value:n},o=e.type.propSuperFor(e,t,`set`,r,i);o&&(a.super=o),await this.set.evaluate(i,r.child(a))}else{if(this.get&&!this.type.call())throw Error(`path: prop '${t}' is computed (has 'get', no 'set') \u2014 cannot assign to it`);e.type.propSet(e,t,n)}}async invokeMethod(e,t,n,r,i,a){let o=a??this.type;if(!this.get){let a=e.raw?.[t],o=a instanceof W?a.raw:a;if(typeof o==`function`)return await o(n);if(o&&typeof o==`object`&&`kind`in o){let e=await i.evaluate(o,r);if(typeof e.raw==`function`)return await e.raw(n)}throw Error(`path: callable prop '${t}' has no get expression and raw is not a callable`)}let s=this.get,c=async n=>{let a={this:e,args:n,recurse:new W(o,c)},l=e.type.propSuperFor(e,t,`get`,r,i);l&&(a.super=l);try{return await s.evaluate(i,r.child(a))}catch(e){if(e instanceof ph)return e.value??new W(i.registry.void(),void 0);throw e}};return c(n)}async invokeMethodSet(e,t,n,r,i,a,o){let s=o??this.type,c=s.call?.();if(!c?.set)throw Error(`path: method '${t}' has no call.set`);let l=async n=>{let o={this:e,args:n,value:r,recurse:new W(s,l)},u=e.type.propSuperFor(e,t,`callSet`,i,a);return u&&(o.super=u),await c.set.evaluate(a,i.child(o)),G(a.registry.void(),void 0)};await l(n)}},Ph=class e{key;value;get;set;loop;loopDynamic;docs;constructor(e){this.key=e.key,this.value=e.value,this.get=e.get,this.set=e.set,this.loop=e.loop,this.loopDynamic=e.loopDynamic,this.docs=e.docs}static from(t,n){t instanceof e||Kp(`get/set surface`,t,Hp);let r=t.key,i=t.value,a=r instanceof U?r:(()=>{if(!n)throw Error(`GetSet.from: key is TypeDef but no scope provided`);return n.parse(r)})(),o=i instanceof U?i:(()=>{if(!n)throw Error(`GetSet.from: value is TypeDef but no scope provided`);return n.parse(i)})(),s=e=>e instanceof th?e:n?.parseExpr(e),c=s(t.get),l=s(t.set),u=s(t.loop);return t instanceof e&&t.key===a&&t.value===o&&t.get===c&&t.set===l&&t.loop===u?t:new e({key:a,value:o,get:c,set:l,loop:u,loopDynamic:t.loopDynamic,docs:t.docs})}toJSON(){return Jm({docs:this.docs,key:this.key.toJSON(),value:this.value.toJSON(),get:this.get?.toJSON(),set:this.set?.toJSON(),loop:this.loop?.toJSON(),loopDynamic:this.loopDynamic})}async indexRead(e,t,n,r){if(!this.get)throw Error(`path: type '${e.type.name}' has no index get`);let i={this:e,key:t},a=e.type.indexSuperFor(e,`get`,n,r);return a&&(i.super=a),this.get.evaluate(r,n.child(i))}async indexWrite(e,t,n,r,i){if(!this.set)throw Error(`path: type '${e.type.name}' has no index set`);let a={this:e,key:t,value:n},o=e.type.indexSuperFor(e,`set`,r,i);o&&(a.super=o),await this.set.evaluate(i,r.child(a))}},Fh=class e{args;returns;throws;get;set;docs;types;constructor(e){this.args=e.args,this.returns=e.returns,this.throws=e.throws,this.get=e.get,this.set=e.set,this.docs=e.docs,this.types=e.types}static from(t,n){t instanceof e||Kp(`call signature`,t,Up,qp);let r=t.types,i=n,a;if(r&&Object.keys(r).length>0){if(Object.values(r).every(e=>e instanceof U))a=r;else{if(!n)throw Error(`Call.from: types contain TypeDef but no scope provided`);let e=new eh(n);i=e,a={};for(let[t,n]of Object.entries(r)){let r=n instanceof U?n:e.parse(n);e.bind(t,r),a[t]=r}}}let o=t.args,s=t.returns,c=t.throws,l=o instanceof U?o:(()=>{if(!i)throw Error(`Call.from: args is TypeDef but no scope provided`);return i.parse(o)})(),u=s===void 0?void 0:s instanceof U?s:(()=>{if(!i)throw Error(`Call.from: returns is TypeDef but no scope provided`);return i.parse(s)})(),d=c===void 0?void 0:c instanceof U?c:(()=>{if(!i)throw Error(`Call.from: throws is TypeDef but no scope provided`);return i.parse(c)})(),f=e=>e instanceof th?e:i?.parseExpr(e),p=f(t.get),m=f(t.set),h=t.docs;return t instanceof e&&t.args===l&&t.returns===u&&t.throws===d&&t.get===p&&t.set===m&&t.types===a?t:new e({args:l,returns:u,throws:d,get:p,set:m,docs:h,types:a})}toJSON(){let e=this.types&&Object.keys(this.types).length>0?Object.fromEntries(Object.entries(this.types).map(([e,t])=>[e,t.toJSON()])):void 0;return Jm({docs:this.docs,types:e,args:this.args.toJSON(),returns:this.returns?.toJSON(),throws:this.throws?.toJSON(),get:this.get?.toJSON(),set:this.set?.toJSON()})}renderTypes(e){if(!this.types)return``;let t=Object.keys(this.types);return t.length===0?``:`{${Hh(t.map(t=>`${t}: ${this.types[t].toCode(void 0,e)}`),{sep:`; `})}}`}effects(){let e=0;return this.get&&(e|=this.get.effects()),this.set&&(e|=this.set.effects()),e}},Ih=class e{args;run;docs;constructor(e){this.args=e.args,this.run=e.run,this.docs=e.docs}static from(t,n){t instanceof e||Kp(`init constructor`,t,Wp);let r=t.args,i=r instanceof U?r:(()=>{if(!n)throw Error(`Init.from: args is TypeDef but no scope provided`);return n.parse(r)})(),a=t.run,o=a instanceof th?a:(()=>{if(!n)throw Error(`Init.from: run is ExprDef but no scope provided`);return n.parseExpr(a)})();return t instanceof e&&t.args===i&&t.run===o?t:new e({args:i,run:o,docs:t.docs})}toJSON(){return Jm({docs:this.docs,args:this.args.toJSON(),run:this.run.toJSON()})}},U=class e{constructor(e,t,n={}){this.scope=e,this.options=t,this.generic=n}scope;options;generic;get registry(){return this.scope.registry}priority=0;docs;parsesExprValue(e){return!1}encodeAs(e,t,n){return this.encode(e,n)}toJSONRef(e){if(e?.typeRefs!==`name`)return this.toJSON();if(this.registry.lookup(this.name)===this)return{name:this.name};let t=this.toJSON(),n=Object.keys(this.generic);if(n.length===0)return t;let r={...t.generic??{}};for(let t of n)r[t]=this.generic[t].toJSONRef(e);return{...t,generic:r}}toDefinitionJSON(){let e=zh.depth;zh.active++,zh.depth=this.registry.lookup(this.name)===this?0:1;try{return this.toJSON()}finally{zh.active--,zh.depth=e}}references(){return gh(this.toDefinitionJSON(),this.registry)}closure(e=this.scope){return _h([this.toDefinitionJSON()],this.registry,t=>e.lookup(t)?.toDefinitionJSON())}compatibleWithParts(e,t,n){let r=Dh(e);if(!r)return!1;if(r.some(e=>this.compatible(e,t,n)))return!0;let i=e.simplify(n);return i!==e&&this.compatible(i,t,n)}compatible(e,t,n){for(let t=0;e.name===`alias`&&t<8;t++){let t=e.simplify(n);if(t===e)break;e=t}if(e===this)return!0;let r=Lh,i=Rh(t,n),a=r.active.get(this)?.get(e);if(a!==void 0&&a.key===i)return r.lowWater=Math.min(r.lowWater,a.depth),!0;let o=r.memo.get(this)?.get(e)?.get(i);if(o!==void 0)return o;let s=r.depth++,c=r.active.get(this);c||r.active.set(this,c=new Map),c.set(e,{depth:s,key:i});let l=r.lowWater;r.lowWater=1/0;let u=!1;try{let a=Eh(e);if(u=a?a.every(e=>this.compatible(e,t,n)):this.compatibleType(e,t,n)||this.compatibleWithParts(e,t,n)||this.compatibleWithBase(e,t,n),!u||r.lowWater>=s){let t=r.memo.get(this);t||r.memo.set(this,t=new Map);let n=t.get(e);n||t.set(e,n=new Map),n.set(i,u)}return u}finally{c.delete(e),r.lowWater=Math.min(l,r.lowWater),--r.depth===0&&(r.memo=new Map,r.active=new Map,r.lowWater=1/0)}}compatibleWithBase(t,n,r){if(n?.strict||n?.exact)return!1;let i=t.base;return i instanceof e&&i!==t&&this.compatible(i,n,r)}accepts(e,t){return this.compatible(e,{strict:!0},t)}exact(e,t){return this.compatible(e,{strict:!0,exact:!0},t)}flexible(){return!1}like(e,t){return this}isUniversal(){return!1}simplify(e){return this}required(){return this}isOptional(){return!1}props(e){let t={toAny:this.registry.method({},this.registry.any(),`type.toAny`)},n=this.registry.augmentation(this.name);return n?.props?{...t,...n.props}:t}static UNIVERSAL_PROP_NAMES=new Set([`toAny`]);constraints(){return[]}get(e){return this.registry.augmentation(this.name)?.get}call(e){return this.registry.augmentation(this.name)?.call}init(e){return this.registry.augmentation(this.name)?.init}prop(e,t){let n=this.props(t)[e];return n?Nh.from(n):void 0}follow(e,t){if(`prop`in e)return this.prop(e.prop,t)?.type;if(`args`in e)return this.call(t)?.returns;if(`key`in e)return this.get(t)?.value}at(e,t){let n=this;for(let r of e){if(!n)return;n=n.follow(r,t)}return n}toA(e){return e?.override?.(this)||(this.isRegisteredNamed()?R.ref(this.name):this.defineA(e))}defineA(e){return this.describeA(this.valueA(e),e)}valueA(e){return R.unknown()}toNewA(e){let t=this.init(e?.scope);return t?this.describeA(t.args.toA(e),e):this.toA(e)}isRegisteredNamed(){let e=this.registry;return e.typeClass(this.name)===void 0&&e.namedTypeList().includes(this)}objectA(e,t){let n=R.object(e);return t?.unknownKeys===`refuse`?n.strict():n}describeA(e,t){let n=t?.includeDocs??`none`,r=[];n!==`none`&&this.docs&&r.push(this.docs);let i=this.constraints();return i.length>0&&r.push(i.map(e=>`must satisfy ${e.toCode(this.registry,{expectsValue:!0})}`).join(`; `)),r.length>0?e.describe(r.join(` — `)):e}newEffects(e){let t=this.initEffects();return this.forEachNewSlot(e,{slot:(e,n)=>{t|=e.newEffects(n)},missing:e=>{t|=e.effects()}})?t:t|this.exprValueEffects(e)}exprValueEffects(e){if(!e||typeof e!=`object`||Array.isArray(e))return B.NONE;let t=e.kind;if(typeof t!=`string`||!this.registry.exprClass(t))return B.NONE;try{return this.registry.parseExpr(e,this.scope).effects()}catch{return B.NONE}}initEffects(){let e=this.init();if(!e)return B.NONE;try{return this.registry.parseExpr(e.run,this.scope).effects()}catch{return B.NONE}}newComplexity(e){let t=1+this.initComplexity();return this.forEachNewSlot(e,{slot:(e,n)=>{t+=e.elementComplexity(n)},missing:e=>{t+=e.complexity()}})?t:t+this.exprValueComplexity(e)}exprValueComplexity(e){if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e.kind;if(typeof t!=`string`||!this.registry.exprClass(t))return 0;try{return this.registry.parseExpr(e,this.scope).complexity()}catch{return 0}}initComplexity(){let e=this.init();if(!e)return 0;try{return this.registry.parseExpr(e.run,this.scope).complexity()}catch{return 0}}elementComplexity(e){let t=this.exprValueComplexity(e);return t>0?t:1}forEachNewSlot(e,t){return!1}validateNewValue(e,t,n,r,i){if(this.forEachNewSlot(e,{slot:(e,a,o)=>{r.at([o],()=>e.validateNewValue(a,t,n,r,i))}}))return;let a=Mh(e,this.scope);if(!a)return;let o=a.validateWalk(t,n,r,i);o.name!==`any`&&(wh(this,o)||r.error(`new.slot.type`,`this slot is declared \`${this.toCode()}\` but the expression here produces \`${o.toCode()}\``))}async newFill(e,t,n){let r=Mh(e,this.scope);return r?r.evaluate(t,n):e}toGinCode(e,t,n=[]){return Lm(this.toCode(e,t),{path:n,type:this})}toJSONCode(e=[],t=2,n=0){return Xh(this.toJSON(),this.registry,e,t,n,this)}docsPrefix(e){return``}extendsClause(e){return``}toCodeRef(e,t){return this.toCode(e,t)}refProps(){return{}}refGet(){}refCall(){}static renderGenerics(e,t){let n=Object.keys(e);return n.length===0?``:`<${Hh(n.map(n=>{let r=e[n],i=r.name===`alias`&&r.options?.name===n;return r.name===`any`||i?n:`${n}: ${r.toCode(void 0,t)}`}),{indent:Uh(t)})}>`}static renderGenericArgs(t,n){let r=Object.keys(t);return r.length===0||!r.some(n=>!e.isGenericPlaceholder(n,t[n]))?``:`<${Hh(r.map(e=>t[e].toCode(void 0,n)),{indent:Uh(n)})}>`}static isGenericPlaceholder(e,t){return t.name===`any`||t.name===`alias`&&t.options?.name===e}static formatParams(e,t,n=`auto`){let r=e.fields;if(!r)return e.name===`void`||e.name===`any`?``:`args: ${e.toCode(void 0,t)}`;let i=Object.entries(r).map(([e,n])=>{let r=n.type.isOptional(),i=r?n.type.required():n.type;return`${n.docs&&t?.includeComments!==!1?`/* ${n.docs} */ `:``}${e}${r?`?`:``}: ${i.toCode(void 0,t)}`}),a=Uh(t);return n===`auto`?Hh(i,{indent:a}):i.length<=1?i.join(``):`
92
+ ${i.map(e=>Wh(e,a)).join(`
93
93
  `)}
94
- `}definitionInit(){return this.init()}definitionCall(){return this.call()}definitionGet(){return this.get()}definitionProps(){return this.props()}toCodeDefinition(t){let n=[],r=t?.includeComments!==!1,i=Vh(t),a=e=>`/// ${e}`,o=this.definitionCall();if(o?.types)for(let[e,r]of Object.entries(o.types))n.push(`type ${e} = ${r.toCode(void 0,t)};`);let s=this.definitionInit();if(s&&(s.docs&&r&&n.push(a(s.docs)),n.push(`new(${e.formatParams(s.args,t,`lines`)})`)),o){let r=o.returns?.toCode(void 0,t)??`void`;n.push(`(${e.formatParams(o.args,t,`lines`)}): ${r}`)}let c=this.definitionGet();c&&n.push(`[key: ${c.key.toCode(void 0,t)}]: ${c.value.toCode(void 0,t)}`);let l=new Set(Object.keys(this.generic));for(let[i,o]of Object.entries(this.definitionProps())){let s=o instanceof jh?o:jh.from(o);s.docs&&r&&n.push(a(s.docs));let c=s.type.isOptional(),u=c?s.type.required():s.type,d=c?`?`:``,f=u.call(),p=Object.keys(u.props()).filter(t=>!e.UNIVERSAL_PROP_NAMES.has(t));if(f&&!u.get()&&p.length===0){let r=f.returns?.toCode(void 0,t)??`void`,a=Object.fromEntries(Object.entries(u.generic).filter(([e])=>!l.has(e))),o=e.renderGenerics(a,t);n.push(`${i}${d}${o}(${e.formatParams(f.args,t,`lines`)}): ${r}`)}else n.push(`${i}${d}: ${u.toCode(void 0,t)}`)}let u=`${this.docs&&r?`${a(this.docs)}
94
+ `}definitionInit(){return this.init()}definitionCall(){return this.call()}definitionGet(){return this.get()}definitionProps(){return this.props()}toCodeDefinition(t){let n=[],r=t?.includeComments!==!1,i=Uh(t),a=e=>`/// ${e}`,o=this.definitionCall();if(o?.types)for(let[e,r]of Object.entries(o.types))n.push(`type ${e} = ${r.toCode(void 0,t)};`);let s=this.definitionInit();if(s&&(s.docs&&r&&n.push(a(s.docs)),n.push(`new(${e.formatParams(s.args,t,`lines`)})`)),o){let r=o.returns?.toCode(void 0,t)??`void`;n.push(`(${e.formatParams(o.args,t,`lines`)}): ${r}`)}let c=this.definitionGet();c&&n.push(`[key: ${c.key.toCode(void 0,t)}]: ${c.value.toCode(void 0,t)}`);let l=new Set(Object.keys(this.generic));for(let[i,o]of Object.entries(this.definitionProps())){let s=o instanceof Nh?o:Nh.from(o);s.docs&&r&&n.push(a(s.docs));let c=s.type.isOptional(),u=c?s.type.required():s.type,d=c?`?`:``,f=u.call(),p=Object.keys(u.props()).filter(t=>!e.UNIVERSAL_PROP_NAMES.has(t));if(f&&!u.get()&&p.length===0){let r=f.returns?.toCode(void 0,t)??`void`,a=Object.fromEntries(Object.entries(u.generic).filter(([e])=>!l.has(e))),o=e.renderGenerics(a,t);n.push(`${i}${d}${o}(${e.formatParams(f.args,t,`lines`)}): ${r}`)}else n.push(`${i}${d}: ${u.toCode(void 0,t)}`)}let u=`${this.docs&&r?`${a(this.docs)}
95
95
  `:``}type ${this.name}${e.renderGenerics(this.generic,t)}${this.extendsClause(t)}`;return n.length===0?`${u} {}`:`${u} {
96
- ${n.map(e=>Hh(e,i)).join(`
96
+ ${n.map(e=>Wh(e,i)).join(`
97
97
  `)}
98
- }`}propSuperFor(e,t,n,r,i){}indexSuperFor(e,t,n,r){}propGet(e,t,n){let r=e.raw&&typeof e.raw==`object`?e.raw[t]:void 0;return r instanceof W?r:G(n,r)}propSet(e,t,n){if(e.raw&&typeof e.raw==`object`)e.raw[t]=n;else throw Error(`type '${this.name}': cannot set prop '${t}' \u2014 value's raw is not an object`)}validate(e){let t=new Mm;try{this.registry.parse(this.toDefinitionJSON())}catch(e){t.error(`type.invalid`,e.message)}return Uh(this,e,t),t}},Fh={depth:0,lowWater:1/0,active:new Map,memo:new Map};function Ih(e,t){return`${+!!e?.strict}${+!!e?.value}${+!!e?.exact}:${t?Zm(t):``}`}var Lh={active:0,depth:0};function Rh(e,t){if(!e)return``;let n=Object.entries(e).filter(([e,n])=>!(n===void 0||n===``||t&&e in t&&zh(t[e],n)));return n.length===0?``:`{${Bh(n.map(([e,t])=>`${e}=${typeof t==`string`?JSON.stringify(t):typeof t==`number`||typeof t==`boolean`?String(t):t===null?`null`:JSON.stringify(t)}`))}}`}function zh(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function Bh(e,t={}){if(e.length===0)return``;let n=t.sep??`, `,r=t.threshold??32,i=t.totalThreshold??80,a=e.join(n);if(!(a.length>i||e.some(e=>e.length>r||e.includes(`
98
+ }`}propSuperFor(e,t,n,r,i){}indexSuperFor(e,t,n,r){}propGet(e,t,n){let r=e.raw&&typeof e.raw==`object`?e.raw[t]:void 0;return r instanceof W?r:G(n,r)}propSet(e,t,n){if(e.raw&&typeof e.raw==`object`)e.raw[t]=n;else throw Error(`type '${this.name}': cannot set prop '${t}' \u2014 value's raw is not an object`)}validate(e){let t=new Pm;try{this.registry.parse(this.toDefinitionJSON())}catch(e){t.error(`type.invalid`,e.message)}return Gh(this,e,t),t}},Lh={depth:0,lowWater:1/0,active:new Map,memo:new Map};function Rh(e,t){return`${+!!e?.strict}${+!!e?.value}${+!!e?.exact}:${t?$m(t):``}`}var zh={active:0,depth:0};function Bh(e,t){if(!e)return``;let n=Object.entries(e).filter(([e,n])=>!(n===void 0||n===``||t&&e in t&&Vh(t[e],n)));return n.length===0?``:`{${Hh(n.map(([e,t])=>`${e}=${typeof t==`string`?JSON.stringify(t):typeof t==`number`||typeof t==`boolean`?String(t):t===null?`null`:JSON.stringify(t)}`))}}`}function Vh(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function Hh(e,t={}){if(e.length===0)return``;let n=t.sep??`, `,r=t.threshold??32,i=t.totalThreshold??80,a=e.join(n);if(!(a.length>i||e.some(e=>e.length>r||e.includes(`
99
99
  `))))return a;let o=n.replace(/\s+$/,``),s=t.indent??` `;return`
100
- ${e.map(e=>Hh(e,s)).join(`${o}
100
+ ${e.map(e=>Wh(e,s)).join(`${o}
101
101
  `)}
102
- `}function Vh(e){return e?.indent??` `}function Hh(e,t){return t+e.replace(/\n/g,`
103
- ${t}`)}function Uh(e,t,n){let r=e.registry,i={inLoop:!1,inLambda:!1},a=e.props();for(let[o,s]of Object.entries(a)){let a=s instanceof jh?s:jh.from(s);n.at([`props`,o],()=>{qh(a.get,Wh(a,e,r),Kh(a),`get`,t,n,i),qh(a.set,Gh(a,e,r),r.void(),`set`,t,n,i),qh(a.default,new Map,a.type,`default`,t,n,i)})}let o=e.get();o&&n.at(`get`,()=>{let a=new Map([[`this`,e],[`key`,o.key]]),s=new Map([[`this`,e],[`key`,o.key],[`value`,o.value]]);qh(o.get,a,o.value,`get`,t,n,i),qh(o.set,s,r.void(),`set`,t,n,i),qh(o.loop,a,void 0,`loop`,t,n,i)});let s=e.call();s&&n.at(`call`,()=>{let a=new Map([[`this`,e],[`args`,s.args],[`recurse`,r.fn({args:s.args,returns:s.returns??r.any()})]]);qh(s.get,a,s.returns,`get`,t,n,{...i,inLambda:!0});let o=new Map([[`this`,e],[`args`,s.args],[`value`,s.returns??r.any()],[`recurse`,r.fn({args:s.args,returns:s.returns??r.any()})]]);qh(s.set,o,r.void(),`set`,t,n,{...i,inLambda:!0})});let c=e.init();c&&n.at(`init`,()=>{let r=new Map([[`this`,e],[`args`,c.args]]);qh(c.run,r,void 0,`run`,t,n,i)});for(let a of e.constraints())n.at(`constraint`,()=>{let o=oh(t,a,new Map([[`this`,e]]),n,i),s=r.bool();o.name!==`any`&&!s.compatible(o)&&n.warn(`type.surface.return-type`,`constraint must return bool, got '${o.name}'`)})}function Wh(e,t,n){let r=new Map([[`this`,t]]),i=e.type.call?.();return i&&(r.set(`args`,i.args),r.set(`recurse`,n.fn({args:i.args,returns:i.returns??n.any()}))),r}function Gh(e,t,n){return new Map([[`this`,t],[`value`,e.type]])}function Kh(e){let t=e.type.call?.();return t?t.returns:e.type}function qh(e,t,n,r,i,a,o){e&&a.at(r,()=>{let s=oh(i,e,t,a,o);n&&s.name!==`any`&&!n.compatible(s)&&a.warn(`type.surface.return-type`,`${r} body returns '${s.name}', not compatible with declared '${n.name}'`)})}function Jh(e,t,n,r,i,a){let o=i+1,s=[];return e.name!==void 0&&s.push({key:`name`,value:V.jsonString(e.name)}),e.extends!==void 0&&s.push({key:`extends`,value:V.jsonString(e.extends)}),e.satisfies!==void 0&&e.satisfies.length>0&&s.push({key:`satisfies`,value:ng(e.satisfies,[...n,`satisfies`],r,o)}),e.docs!==void 0&&s.push({key:`docs`,value:V.jsonString(e.docs)}),e.options!==void 0&&Object.keys(e.options).length>0&&s.push({key:`options`,value:ng(e.options,[...n,`options`],r,o)}),e.generic!==void 0&&Object.keys(e.generic).length>0&&s.push({key:`generic`,value:Yh(e.generic,t,[...n,`generic`],r,o)}),e.props!==void 0&&Object.keys(e.props).length>0&&s.push({key:`props`,value:Xh(e.props,t,[...n,`props`],r,o)}),e.get!==void 0&&s.push({key:`get`,value:Qh(e.get,t,[...n,`get`],r,o)}),e.call!==void 0&&s.push({key:`call`,value:$h(e.call,t,[...n,`call`],r,o)}),e.init!==void 0&&s.push({key:`init`,value:eg(e.init,t,[...n,`init`],r,o)}),e.constraint!==void 0&&s.push({key:`constraint`,value:tg(e.constraint,t,[...n,`constraint`],r,o)}),V.jsonObject(s,{path:n,type:a},i,r)}function Yh(e,t,n,r,i){let a=Object.entries(e).map(([e,a])=>({key:e,value:Jh(a,t,[...n,e],r,i+1,void 0)}));return V.jsonObject(a,{path:n},i,r)}function Xh(e,t,n,r,i){let a=Object.entries(e).map(([e,a])=>({key:e,value:Zh(a,t,[...n,e],r,i+1)}));return V.jsonObject(a,{path:n},i,r)}function Zh(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`type`,value:Jh(e.type,t,[...n,`type`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:tg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:tg(e.set,t,[...n,`set`],r,a)}),e.default!==void 0&&o.push({key:`default`,value:tg(e.default,t,[...n,`default`],r,a)}),V.jsonObject(o,{path:n},i,r)}function Qh(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`key`,value:Jh(e.key,t,[...n,`key`],r,a,void 0)}),o.push({key:`value`,value:Jh(e.value,t,[...n,`value`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:tg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:tg(e.set,t,[...n,`set`],r,a)}),e.loop!==void 0&&o.push({key:`loop`,value:tg(e.loop,t,[...n,`loop`],r,a)}),e.loopDynamic!==void 0&&o.push({key:`loopDynamic`,value:String(e.loopDynamic)}),V.jsonObject(o,{path:n},i,r)}function $h(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),e.types!==void 0&&Object.keys(e.types).length>0&&o.push({key:`types`,value:Yh(e.types,t,[...n,`types`],r,a)}),o.push({key:`args`,value:Jh(e.args,t,[...n,`args`],r,a,void 0)}),e.returns!==void 0&&o.push({key:`returns`,value:Jh(e.returns,t,[...n,`returns`],r,a,void 0)}),e.throws!==void 0&&o.push({key:`throws`,value:Jh(e.throws,t,[...n,`throws`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:tg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:tg(e.set,t,[...n,`set`],r,a)}),V.jsonObject(o,{path:n},i,r)}function eg(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`args`,value:Jh(e.args,t,[...n,`args`],r,a,void 0)}),o.push({key:`run`,value:tg(e.run,t,[...n,`run`],r,a)}),V.jsonObject(o,{path:n},i,r)}function tg(e,t,n,r,i){try{return t.parseExpr(e).toJSONCode(n,r,i)}catch{return ng(e,n,r,i)}}function ng(e,t,n,r){let i=JSON.stringify(e,null,n);if(r>0){let e=` `.repeat(r*n);i=i.replace(/\n/g,`
104
- `+e)}return Fm(i,{path:t})}var W=class{type;raw;constructor(e,t){this.type=e,this.raw=t}toLogical(){return rg(this.raw)}encode(){return this.type.encode(this.raw)}toJSON(e=Oh){return{type:this.type.toJSONRef(e),value:this.type.encodeAs(this.raw,e)}}encodeLogical(){return this.type.encodeAs(this.raw,og)}toJSONRefs(){return this.toJSON({form:`envelope`,typeRefs:`name`})}toJSONLogical(){return this.toJSON(og)}};function rg(e){if(e instanceof W)return e.toLogical();if(Array.isArray(e))return e.map(rg);if(e instanceof Map){let t=new Map;for(let n of e.values())ig(n)&&t.set(n[0].toLogical(),n[1].toLogical());return t}if(ag(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=rg(r);return t}return e}function ig(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function ag(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var og={form:`logical`,typeRefs:`name`};function G(e,t){return new W(e,t)}var sg=class extends Error{constructor(){super(`The run was stopped.`),this.name=`RunStoppedError`}},cg=class{signal;slice;#e=Date.now();constructor(e={}){this.signal=e.signal,this.slice=e.slice??10}check(){let e=this.signal;if(e?.aborted!==!0)return;let t=e.reason;throw t instanceof Error?t:new sg}async checkpoint(){this.check(),Date.now()-this.#e<this.slice||(await new Promise(e=>{setTimeout(e,0)}),this.#e=Date.now(),this.check())}},lg=new Set([`text`,`num`,`bool`,`enum`,`literal`,`date`,`timestamp`,`duration`,`color`,`null`]);function ug(e){let t=e;for(let e=0;e<16;e+=1){let e=t.inner??t.base;if(e===void 0||e===t)return t;t=e}return t}function dg(e){return lg.has(ug(e).name)}function fg(e,t){let n=e.isOptional()?e.inner??e:e;return dg(n)?R.union([n.toA(t),R.ref(`Expr`)]):R.ref(`Expr`)}function pg(e,t){if(e===t)return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;let n=e,r=t,i=Object.keys(n);return i.length===Object.keys(r).length&&i.every(e=>n[e]===r[e])}function mg(e,t,n){let r=Object.keys(e);return r.length===0?t?jh.toJSONMap(t):void 0:{...n&&Object.keys(n).length===r.length&&r.every(e=>e in n)?n:jh.toJSONMap(e),...t?jh.toJSONMap(t):{}}}function hg(e,t){return{...e,props:e.props?jh.fromMap(e.props,t):void 0,get:e.get?Mh.from(e.get,t):void 0,call:e.call?Nh.from(e.call,t):void 0,init:e.init?Ph.from(e.init,t):void 0}}var gg=class e extends U{name;docs;base;original;local;bindings;constructor(e,t,n,r,i){let a=n.options?t.narrow(n.options):t.options,o=n.options&&!pg(a,t.options)?e.parse({...t.toJSON(),options:a},i):t;super(r??e,a,n.generic??{}),this.original=t,this.base=o,this.local=hg(n,e),this.name=n.name,this.docs=n.docs;let s=Object.entries(n.generic??{}).filter(([e,t])=>!U.isGenericPlaceholder(e,t));this.bindings=s.length>0?Object.fromEntries(s):void 0}storedLocalProps(){let e=[];for(let[t,n]of Object.entries(this.local.props??{})){let r=n instanceof jh?n:jh.from(n);r.get||r.type.call()||e.push([t,r])}return e}valid(e,t){let n=this.bindScope(t);if(!this.base.valid(e,n))return!1;let r=this.storedLocalProps();if(r.length===0||!kh(e))return!0;let i=e;for(let[e,t]of r){let r=i[e];if(!(r instanceof W))return t.type.isOptional();if(!r.type.valid(r.raw,n)||!Sh(t.type,r.type,n))return!1}return!0}parse(e,t){let n=this.bindScope(t),r=this.base.parse(e,n),i=this.storedLocalProps();if(i.length===0||!kh(r.raw))return new W(this,r.raw);let a=kh(e)?e:{},o={...r.raw};for(let[e,t]of i)o[e]=this.registry.parseValue(a[e],t.type,n);return new W(this,o)}parsesExprValue(e){return this.base.parsesExprValue(this.bindScope(e))}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){let r=this.bindScope(n),i=this.base.encodeAs(e,t,r),a=this.storedLocalProps();if(a.length===0||!kh(i)||!kh(e))return i;let o=e,s={...i};for(let[e]of a)Dh(s,e,o[e],t,r);return s}create(){return this.withLocalSlots(this.base.create(),e=>e.create())}random(e){return this.withLocalSlots(this.base.random(e),t=>t.random(e))}withLocalSlots(e,t){let n=this.storedLocalProps();if(n.length===0||!kh(e))return e;let r={...e};for(let[e,i]of n)r[e]=new W(i.type,t(i.type));return r}forEachNewSlot(e,t){let n=this.base.forEachNewSlot(e,t),r=this.storedLocalProps();if(r.length===0||!kh(e))return n;let i=e;for(let[e,n]of r)e in i?t.slot(n.type,i[e],e):n.default!==void 0&&t.missing?.(n.default,e);return!0}async newFill(e,t,n){let r=await this.base.newFill(e,t,n),i=this.storedLocalProps();if(i.length===0||!kh(r))return r;let a=r,o;for(let[e,r]of i)if(e in a){let i=await r.type.newFill(a[e],t,n);i!==a[e]&&(o??={...a},o[e]=i)}else r.default!==void 0&&(o??={...a},o[e]=await r.default.evaluate(t,n));return o??a}compatibleType(t,n,r){return n?.exact?t instanceof e&&t.name===this.name&&this.base.compatible(t.base,n,r):t instanceof e?this.base.compatible(t.base,n,r):this.base.compatible(t,n,r)}or(t){if(t instanceof e&&t.name===this.name){let n={name:this.name,docs:this.docs??t.docs,options:{...this.local.options??{},...t.local.options??{}},props:{...this.local.props??{},...t.local.props??{}},get:this.local.get??t.local.get,call:this.local.call??t.local.call,init:this.local.init??t.local.init};return new e(this.registry,this.original,n)}return this.base.or(t)}simplify(){return this}required(){return this.base.required()}isOptional(){return this.base.isOptional()}narrow(e){return this.base.narrow(e)}props(e){let t=this.registry.augmentation(this.name);return{...this.base.props(this.bindScope(e)),...t?.props??{},...this.local.props??{}}}get(e){return this.local.get??this.registry.augmentation(this.name)?.get??this.base.get(this.bindScope(e))}call(e){return this.local.call??this.registry.augmentation(this.name)?.call??this.base.call(this.bindScope(e))}init(e){return this.local.init??this.registry.augmentation(this.name)?.init??this.base.init(this.bindScope(e))}toJSON(){if(Lh.active>0&&Lh.depth>0&&!this.local.useSite&&this.registry.lookup(this.name)!==void 0&&(this.registry.lookup(this.name)===this||this.bindings)){let e=Object.entries(this.bindings??{});return e.length>0?{name:this.name,generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{name:this.name}}Lh.depth++;try{return this.toJSONInner()}finally{Lh.depth--}}toJSONInner(){if(this.local.useSite){let e=Object.entries(this.bindings??{});return{name:this.name,...e.length>0?{generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{},options:{...this.local.options}}}let e=this.original.toJSON(),t=this.original.name!==this.name,n={...e.options,...this.local.options},r={...e.generic??{}};if(this.local.generic)for(let[e,t]of Object.entries(this.local.generic))r[e]=t.toJSON();return Km({name:this.name,extends:t?this.original.name:void 0,docs:this.docs,generic:Object.keys(r).length>0?r:void 0,options:n&&Object.keys(n).length>0?n:void 0,props:mg(t?this.original.refProps():{},this.local.props,e.props),get:(this.local.get??(t?this.original.refGet():void 0))?.toJSON(),call:(this.local.call??(t?this.original.refCall():void 0))?.toJSON(),init:this.local.init?.toJSON(),constraint:this.local.constraint?this.local.constraint.toJSON():void 0})}clone(){let t=this.local.generic?Object.fromEntries(Object.entries(this.local.generic).map(([e,t])=>[e,t.clone()])):void 0;return new e(this.registry,this.original.clone(),{name:this.local.name,docs:this.local.docs,options:this.local.options?{...this.local.options}:void 0,generic:t,props:this.local.props?{...this.local.props}:void 0,get:this.local.get,call:this.local.call,init:this.local.init,constraint:this.local.constraint?.clone(),useSite:this.local.useSite},this.bindings?this.scope:void 0)}toCode(e,t){return this.docsPrefix(t)+this.name+U.renderGenericArgs(this.generic,t)+(this.local.useSite?Rh(this.local.options):``)}extendsClause(e){return` extends ${this.base.toCodeRef(void 0,e)}`}baseMembersElided(e){return this.base.toCodeRef(void 0,e)!==this.base.toCode(void 0,e)}ownAugmentation(){return this.registry.augmentation(this.name)}definitionInit(){return this.local.init??this.ownAugmentation()?.init}definitionCall(){return this.local.call??this.ownAugmentation()?.call??(this.baseMembersElided()?this.base.refCall():void 0)}definitionGet(){return this.local.get??this.ownAugmentation()?.get??(this.baseMembersElided()?this.base.refGet():void 0)}definitionProps(){return{...this.baseMembersElided()?this.base.refProps():{},...this.ownAugmentation()?.props??{},...this.local.props??{}}}specialize(t){let n={...this.local.generic??{}},r={};for(let e of Object.keys(this.local.generic??{})){let i=t[e];i&&(n[e]=i,r[e]=i)}return Object.keys(r).length===0?this:new e(this.registry,this.original,{...this.local,generic:n},new Qm(this.scope,r))}bindScope(e){return this.bindings?e?new Qm(e,this.bindings):this.scope:e}constraints(){let e=this.base.constraints();return this.local.constraint?[this.local.constraint,...e]:e}valueA(e){return this.mergeLocalPropsA(this.base.defineA(e),e,t=>t.type.toA(e))}toNewA(e){return this.describeA(this.mergeLocalPropsA(this.base.toNewA(e),e,t=>fg(t.type,e)),e)}mergeLocalPropsA(e,t,n){if(!(e instanceof pf))return e;let r=t?.includeDocs??`none`,i={};for(let[e,t]of this.storedLocalProps()){let a=n(t);r===`all`&&t.docs&&(a=a.describe(t.docs)),i[e]=t.type.isOptional()&&a.kind!==`optional`?R.optional(a):a}return Object.keys(i).length===0?e:e.extend(i)}propSuperFor(e,t,n,r,i){let a=this.local.props;if(!(a&&Object.hasOwn(a,t)))return;let o=this.base.prop(t);if(!o)return;let s=new W(this.base,e.raw);if(n===`get`){if(o.type.call()&&o.get){let e=o.type;return new W(e,async e=>{let n={this:s,args:e},a=s.type.propSuperFor(s,t,`get`,r,i);return a&&(n.super=a),i.evaluate(o.get,r.child(n))})}return new W(i.registry.fn({args:i.registry.obj({}),returns:o.type}),async e=>{if(!o.get)return G(o.type,s.raw?.[t]);let n={this:s},a=s.type.propSuperFor(s,t,`get`,r,i);return a&&(n.super=a),i.evaluate(o.get,r.child(n))})}if(n===`set`)return o.set?new W(i.registry.fn({args:i.registry.obj({value:{type:o.type}}),returns:i.registry.void()}),async e=>{let n=e.raw.value,a={this:s,value:n},c=s.type.propSuperFor(s,t,`set`,r,i);return c&&(a.super=c),await i.evaluate(o.set,r.child(a)),G(i.registry.void(),void 0)}):void 0;let c=o.type.call();return c?.set?new W(i.registry.fn({args:i.registry.obj({args:{type:c.args},value:{type:c.returns??i.registry.any()}}),returns:i.registry.void()}),async e=>{let n=e.raw,a={this:s,args:n.args,value:n.value},o=s.type.propSuperFor(s,t,`callSet`,r,i);return o&&(a.super=o),await i.evaluate(c.set,r.child(a)),G(i.registry.void(),void 0)}):void 0}indexSuperFor(e,t,n,r){let i=this.local.get;if(!i)return;let a=this.base.get();if(!a)return;let o=new W(this.base,e.raw);return t===`get`?!i.get||!a.get?void 0:new W(r.registry.fn({args:r.registry.obj({key:{type:a.key}}),returns:a.value}),async e=>{let t=e.raw.key,n=r.createRootScope();return n.vars.set(`this`,o),n.vars.set(`key`,t),r.evaluate(a.get,n)}):!i.set||!a.set?void 0:new W(r.registry.fn({args:r.registry.obj({key:{type:a.key},value:{type:a.value}}),returns:r.registry.void()}),async e=>{let t=e.raw,n=r.createRootScope();return n.vars.set(`this`,o),n.vars.set(`key`,t.key),n.vars.set(`value`,t.value),await r.evaluate(a.set,n),G(r.registry.void(),void 0)})}},_g=class e extends U{static NAME=`any`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return!0}parse(e){return new W(this,e)}encode(e){return e}create(){return null}random(e){return null}compatibleType(e,t){return!0}flexible(){return!0}isUniversal(){return!0}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new Nm({path:[],code:`any.no-options`,message:`any has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),typeOf:e.method({},e.text(),`any.typeOf`),is:e.method({},e.bool(),`any.is`,{generic:{T:e.any()}}),as:e.method({},e.optional(e.alias(`T`)),`any.as`,{generic:{T:e.any()}}),toText:e.method({},e.text(),`any.toText`),toBool:e.method({},e.bool(),`any.toBool`),eq:e.method({other:e.any()},e.bool(),`any.eq`),neq:e.method({other:e.any()},e.bool(),`any.neq`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`any`}valueA(){return R.unknown()}},vg=class e extends U{static NAME=`obj`;static consumes=[`props`];name=e.NAME;static optionKeys=[];static genericKeys=[];fields;static from(t,n){let r=jh.fromMap(t.props??{},n);return new e(n,r)}constructor(e,t){super(e,{});let n={};for(let[e,r]of Object.entries(t))n[e]=jh.from(r);this.fields=n}valid(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let[n,r]of Object.entries(this.fields)){let i=e[n];if(!(i instanceof W)||!i.type.valid(i.raw,t)||!Sh(r.type,i.type,t))return!1}return!0}parse(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new Nm({path:[],code:`object.invalid`,message:`object.parse: expected object, got ${typeof e}`,severity:`error`});let n={};for(let[r,i]of Object.entries(this.fields)){let a=e[r];n[r]=this.registry.parseValue(a,i.type,t)}return new W(this,n)}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){let r=e,i={};for(let[e]of Object.entries(this.fields))Dh(i,e,r[e],t,n);return i}create(){let e={};for(let[t,n]of Object.entries(this.fields))e[t]=new W(n.type,n.type.create());return e}random(e){let t={};for(let[n,r]of Object.entries(this.fields))t[n]=new W(r.type,r.type.random(e));return t}forEachNewSlot(e,t){if(!yg(e)||Ah(e,this.scope))return!1;let n=e;for(let[e,r]of Object.entries(this.fields))e in n?t.slot(r.type,n[e],e):r.default!==void 0&&t.missing?.(r.default,e);return!0}async newFill(e,t,n){if(!yg(e)||Ah(e,this.scope))return super.newFill(e,t,n);let r=e,i;for(let[e,a]of Object.entries(this.fields))if(e in r){let o=await a.type.newFill(r[e],t,n);o!==r[e]&&(i??={...r},i[e]=o)}else a.default!==void 0&&(i??={...r},i[e]=await a.default.evaluate(t,n));return i??r}like(t){if(!(t instanceof e))return this;let n={};for(let[e,r]of Object.entries(t.fields)){let t=this.registry.like(r.type);if(t.name===`null`)return this.registry.null();n[e]={type:t}}return this.registry.obj(n)}compatibleType(t,n,r){if(!(t instanceof e))return!1;for(let[e,i]of Object.entries(this.fields)){let a=t.fields[e];if(!a){if(n?.exact)return!1;if(i.type.isOptional())continue;return!1}if(!i.type.compatible(a.type,n,r))return!1}if(n?.exact){let e=new Set(Object.keys(this.fields));for(let n of Object.keys(t.fields))if(!e.has(n))return!1}return!0}or(t){if(!(t instanceof e))return this;let n={};for(let[e,r]of Object.entries(this.fields)){let i=t.fields[e];i&&(n[e]={type:r.type.or(i.type)})}return new e(this.registry,n)}narrow(e){return{}}props(){let e=this.registry,t=Object.values(this.fields).map(e=>e.type),n=t.length===0?e.any():t.length===1?t[0]:e.or(t),r={keys:e.method({},e.list(e.text()),`object.keys`),values:e.method({},e.list(n),`object.values`),entries:e.method({},e.list(e.tuple([e.text(),n])),`object.entries`),has:e.method({key:e.text()},e.bool(),`object.has`),eq:e.method({other:e.any()},e.bool(),`object.eq`),neq:e.method({other:e.any()},e.bool(),`object.neq`),toText:e.method({},e.text(),`object.toText`)};return{...super.props(),...r,...this.fields}}get(){let e=Object.keys(this.fields);if(e.length===0)return;let t=this.registry.text(),n=e.map(e=>this.registry.literal(t,e)),r=n.length===1?n[0]:this.registry.or(n),i=Object.values(this.fields).map(e=>e.type),a=i.length===1?i[0]:this.registry.or(i),o=this.registry;return new Mh({key:r,value:a,get:o.nativeExpr(`object.indexGet`),set:o.nativeExpr(`object.indexSet`),loop:o.nativeExpr(`object.iterate`)})}toJSON(){return{name:e.NAME,props:jh.toJSONMap(this.fields)}}clone(){let t={};for(let[e,n]of Object.entries(this.fields))t[e]={...n,type:n.type.clone()};return new e(this.registry,t)}toCode(e,t){let n=Object.entries(this.fields);if(n.length===0)return this.docsPrefix(t)+`obj`;let r=t?.includeComments!==!1,i=n.map(([e,n])=>{let i=n.type.isOptional(),a=i?n.type.required():n.type,o=i?`${e}?`:e;return`${n.docs&&r?`/* ${n.docs} */ `:``}${o}: ${a.toCode(void 0,t)}`});return this.docsPrefix(t)+`obj{${Bh(i,{indent:Vh(t)})}}`}toCodeRef(e,t){return this.docsPrefix(t)+`obj`}refProps(){return this.fields}valueA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this.fields)){let a=i.type.toA(e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=a}return this.objectA(n,e)}toNewA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this.fields)){let a=fg(i.type,e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=i.type.isOptional()?R.optional(a):a}return this.describeA(R.object(n),e)}describe(t){if(typeof t!=`object`||!t||Array.isArray(t))return;let n={};for(let[e,r]of Object.entries(t))n[e]={type:this.registry.any().describe?.(r)??this.registry.any()};return new e(this.registry,n)}};function yg(e){return kh(e)}var bg=class e extends U{static NAME=`and`;name=e.NAME;static optionKeys=[`types`];static genericKeys=[];static from(t,n){n.registry;let r=(t.options?.types??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,{parts:t})}get parts(){return this.options.parts}valid(e,t){return this.parts.every(n=>n.valid(e,t))}effective(){let e=this.parts;if(e.length===0)return;if(e.length===1)return e[0];let t=this.mergedObjFields();return t?this.registry.obj(t):e[0]}mergedObjFields(){let e=[];for(let t of this.parts){if(!(t instanceof vg))return;e.push(t)}let t={};for(let n of e)for(let[e,r]of Object.entries(n.fields)){let n=t[e];t[e]=n?{type:this.registry.and([n.type,r.type])}:r}return t}parse(e,t){let n=this.effective();if(!n)return new W(this,e);let r=n.parse(e,t).raw;for(let e of this.parts)if(!e.valid(r,t))throw new Nm({path:[],code:`and.constraint`,message:`and: value fails part ${e.name}`,severity:`error`});return new W(this,r)}encode(e,t){return this.effective()?.encode(e,t)??e}parsesExprValue(e){return this.effective()?.parsesExprValue(e)??!1}encodeAs(e,t,n){return this.effective()?.encodeAs(e,t,n)??e}forEachNewSlot(e,t){return this.effective()?.forEachNewSlot(e,t)??!1}async newFill(e,t,n){let r=this.effective();return r?r.newFill(e,t,n):super.newFill(e,t,n)}create(){let e=this.effective();if(!e)return null;for(let t of[e,...this.parts]){let e=t.create();if(this.valid(e))return e}return e.create()}random(e){let t=this.effective();if(!t)return null;for(let n of[t,...this.parts]){let t=n.random(e);if(this.valid(t))return t}return t.random(e)}like(t){if(!(t instanceof e))return this;let n=t.parts.map(e=>this.registry.like(e)).filter(e=>e.name!==`null`);return n.length===0?this.registry.null():n.length===1?n[0]:this.registry.and(n)}compatibleType(e,t,n){return this.parts.every(r=>r.compatible(e,t,n))}isUniversal(){return this.parts.length===0||this.parts.every(e=>e.isUniversal())}or(t){return t instanceof e?new e(this.registry,[...this.parts,...t.parts]):this}simplify(){if(this.parts.length===1)return this.parts[0];if(this.parts.length===0)return this;let e=this.mergedObjFields();return e?this.registry.obj(e):this}narrow(e){return this.options}props(){let e={};for(let t of this.parts)for(let[n,r]of Object.entries(t.props()))e[n]=n in e?{type:this.registry.and([e[n].type,r.type])}:r;return e}get(){let e=this.parts.map(e=>e.get()).filter(e=>!!e);if(e.length!==0)return new Mh({key:this.registry.or(e.map(e=>e.key)),value:this.registry.and(e.map(e=>e.value))})}call(){let e=this.parts.map(e=>e.call()).filter(e=>!!e);if(e.length===0)return;let t=e.map(e=>e.returns).filter(e=>!!e);return new Nh({args:this.registry.or(e.map(e=>e.args)),returns:t.length>0?this.registry.and(t):void 0})}toJSON(){return{name:e.NAME,options:{types:this.parts.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.parts.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`and<${this.parts.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){return this.parts.length===0?R.unknown():this.parts.length===1?this.parts[0].toA(e):R.intersection(this.parts.map(t=>t.toA(e)))}toNewA(e){return this.parts.length===0?this.describeA(R.unknown(),e):this.parts.length===1?this.describeA(this.parts[0].toNewA(e),e):this.describeA(R.intersection(this.parts.map(t=>t.toNewA(e))),e)}},xg=new Set,Sg=class e extends U{static NAME=`alias`;name=e.NAME;constructor(e,t,n={}){super(e,t,n)}get hasUse(){return Object.keys(this.generic).length>0||this.options.options!==void 0}applied;static from(t,n){return new e(n,{name:t.name})}resolve(e){let t=(e?e.lookup(this.options.name):void 0)??this.scope.lookup(this.options.name);if(!t||!this.hasUse)return t;this.applied??=new WeakMap;let n=this.applied.get(t);return n||(n=this.registry.applyUse(t,this.generic,this.options.options),this.applied.set(t,n)),n}valid(e,t){let n=this.resolve(t);return!n||n.valid(e,t)}parse(e,t){let n=this.resolve(t);if(!n)return new W(this,e);let r=n.parse(e,t);return new W(this,r.raw)}encode(e,t){let n=this.resolve(t);return n?n.encode(e,t):e}parsesExprValue(e){return this.resolve(e)?.parsesExprValue(e)??!1}encodeAs(e,t,n){let r=this.resolve(n);return r?r.encodeAs(e,t,n):e}create(){let e=this.resolve();return e?e.create():null}random(e){let t=this.resolve();return t?t.random(e):null}compatibleType(e,t,n){let r=this.resolve(n);return!r||r.compatible(e,t,n)}flexible(){return!0}isUniversal(){let e=this.resolve();return!e||e.isUniversal()}or(e){let t=this.resolve();return t?t.or(e):this}simplify(e){return this.resolve(e)??this}narrow(e){return{...this.options,name:e.name??this.options.name}}props(e){let t=this.resolve(e);return t?t.props(e):super.props(e)}get(e){return this.resolve(e)?.get(e)}call(e){return this.resolve(e)?.call(e)}init(e){return this.resolve(e)?.init(e)}follow(e,t){return this.resolve(t)?.follow(e,t)}forEachNewSlot(e,t){return this.resolve()?.forEachNewSlot(e,t)??!1}async newFill(e,t,n){let r=this.resolve();return r?r.newFill(e,t,n):super.newFill(e,t,n)}toJSON(){if(!this.hasUse)return{name:this.options.name};let e=Object.entries(this.generic);return{name:this.options.name,...e.length>0?{generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{},...this.options.options===void 0?{}:{options:{...this.options.options}}}}clone(){return new e(this.scope,{...this.options},{...this.generic})}toCode(e,t){return this.docsPrefix(t)+this.options.name+U.renderGenericArgs(this.generic,t)+Rh(this.options.options)}valueA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(xg.has(this.options.name))return R.json().describe(`A value of the named type ${this.options.name}.`);xg.add(this.options.name);try{return t.toA(e)}finally{xg.delete(this.options.name)}}toNewA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(xg.has(this.options.name))return R.ref(`Expr`);xg.add(this.options.name);try{return t.toNewA(e)}finally{xg.delete(this.options.name)}}},Cg=class e extends U{static NAME=`bool`;name=e.NAME;static optionKeys=[`trueText`,`falseText`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return typeof e==`boolean`}parse(e){if(typeof e==`boolean`)return new W(this,e);if(e===this.options.trueText)return new W(this,!0);if(e===this.options.falseText)return new W(this,!1);throw Error(`bool.parse: expected boolean, got ${typeof e}`)}encode(e){return e}create(){return!1}random(e){return e(0,1,!0)===1}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e?new e(this.registry,{trueText:this.options.trueText??t.options.trueText,falseText:this.options.falseText??t.options.falseText}):this}narrow(e){return{...this.options,...e}}props(){let e=this.registry;return{...super.props(),eq:e.method({other:e.bool()},e.bool(),`bool.eq`),neq:e.method({other:e.bool()},e.bool(),`bool.neq`),and:e.method({other:e.bool()},e.bool(),`bool.and`),or:e.method({other:e.bool()},e.bool(),`bool.or`),xor:e.method({other:e.bool()},e.bool(),`bool.xor`),not:e.method({},e.bool(),`bool.not`),toText:e.method({},e.text(),`bool.toText`),toNum:e.method({},e.num(),`bool.toNum`)}}get(){let e=this.registry;return new Mh({key:e.num({whole:!0,min:0}),value:e.bool(),loopDynamic:!0})}toJSON(){return Km({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`bool`+Rh(this.options)}valueA(){return R.boolean()}describe(e){return typeof e==`boolean`?this:void 0}},wg=class e extends U{static NAME=`color`;name=e.NAME;static optionKeys=[`hasAlpha`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=4294967295}parse(e){let t=typeof e==`number`?e:Number(e);if(!this.valid(t))throw new Nm({path:[],code:`color.invalid`,message:`color.parse: not a valid 32-bit color int: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e}create(){return 255}random(e){return e(0,4294967295,!0)}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e?new e(this.registry,{hasAlpha:this.options.hasAlpha===t.options.hasAlpha?this.options.hasAlpha:void 0}):this}narrow(e){return{...this.options,...e}}init(){let e=this.registry,t=e.num({whole:!0,min:0,max:255}),n=e.optional(e.num({min:0,max:1}));return new Ph({args:e.obj({r:{type:t},g:{type:t},b:{type:t},a:{type:n}}),run:e.nativeExpr(`color.init`)})}props(){let e=this.registry,t=e.num(),n=e.bool(),r=e.text(),i=e.color();return{...super.props(),r:e.prop(t,`color.r`),g:e.prop(t,`color.g`),b:e.prop(t,`color.b`),a:e.prop(t,`color.a`),hue:e.prop(t,`color.hue`),saturation:e.prop(t,`color.saturation`),lightness:e.prop(t,`color.lightness`),eq:e.method({other:i},n,`color.eq`),neq:e.method({other:i},n,`color.neq`),lighten:e.method({amount:t},i,`color.lighten`),darken:e.method({amount:t},i,`color.darken`),saturate:e.method({amount:t},i,`color.saturate`),desaturate:e.method({amount:t},i,`color.desaturate`),opacity:e.method({alpha:t},i,`color.opacity`),invert:e.method({},i,`color.invert`),mix:e.method({other:i,weight:e.optional(t)},i,`color.mix`),complement:e.method({},i,`color.complement`),toHex:e.method({},r,`color.toHex`),toRgb:e.method({},r,`color.toRgb`),toHsl:e.method({},r,`color.toHsl`),toText:e.method({},r,`color.toText`)}}toJSON(){return Km({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`color`+Rh(this.options)}valueA(){return R.int().min(0).max(4294967295).describe(this.options.hasAlpha?`A color as a 32-bit integer 0xRRGGBBAA.`:`A color as an integer 0xRRGGBB.`)}},Tg=class e extends U{static NAME=`date`;name=e.NAME;static optionKeys=[`min`,`max`,`utc`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}boundDate(e){return e?new Date(e):void 0}valid(e){if(!(e instanceof Date)||Number.isNaN(e.getTime()))return!1;let t=this.boundDate(this.options.min),n=this.boundDate(this.options.max);return!(t&&e<t||n&&e>n)}parse(e){let t=e instanceof Date?e:typeof e==`string`?new Date(e):new Date(NaN);if(!this.valid(t))throw new Nm({path:[],code:`date.invalid`,message:`date.parse: invalid or out-of-range: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e.toISOString().slice(0,10)}create(){return new Date}random(e){let t=this.boundDate(this.options.min)?.getTime()??Date.UTC(2e3,0,1),n=this.boundDate(this.options.max)?.getTime()??Date.UTC(2050,11,31);return new Date(e(t,n,!0))}compatibleType(t,n){return t instanceof e}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{min:n.min&&r.min?n.min<r.min?n.min:r.min:void 0,max:n.max&&r.max?n.max>r.max?n.max:r.max:void 0,utc:n.utc===r.utc?n.utc:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Nm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.min!==void 0&&(t.min&&e.min<t.min&&n(`date.widen.min`,`cannot move min earlier`),r.min=e.min),e.max!==void 0&&(t.max&&e.max>t.max&&n(`date.widen.max`,`cannot move max later`),r.max=e.max),e.utc!==void 0&&(r.utc=e.utc),r}props(){let e=this.registry,t=e.num({whole:!0}),n=e.bool(),r=e.text(),i=e.date();return{...super.props(),year:e.prop(t,`date.year`),month:e.prop(t,`date.month`),day:e.prop(t,`date.day`),dayOfWeek:e.prop(t,`date.dayOfWeek`),dayOfYear:e.prop(t,`date.dayOfYear`),eq:e.method({other:i},n,`date.eq`),neq:e.method({other:i},n,`date.neq`),before:e.method({other:i},n,`date.before`),after:e.method({other:i},n,`date.after`),addDays:e.method({days:t},i,`date.addDays`),addMonths:e.method({months:t},i,`date.addMonths`),addYears:e.method({years:t},i,`date.addYears`),diffDays:e.method({other:i},t,`date.diffDays`),diffMonths:e.method({other:i},t,`date.diffMonths`),diffYears:e.method({other:i},t,`date.diffYears`),toText:e.method({format:e.optional(r)},r,`date.toText`)}}toJSON(){return Km({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`date`+Rh(this.options)}valueA(){return R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`).describe(`An ISO 8601 date (YYYY-MM-DD).`)}describe(e){return e instanceof Date?this:void 0}},Eg=class e extends U{static NAME=`duration`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return typeof e==`number`&&!Number.isNaN(e)}parse(e){let t=typeof e==`number`?e:Number(e);return new W(this,t)}encode(e){return e}create(){return 0}random(e){return e(0,864e5,!0)}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){return{}}init(){let e=this.registry,t=e.num();return new Ph({args:e.obj({days:{type:e.optional(t)},hours:{type:e.optional(t)},minutes:{type:e.optional(t)},seconds:{type:e.optional(t)},ms:{type:e.optional(t)}}),run:e.nativeExpr(`duration.init`)})}props(){let e=this.registry,t=e.num({whole:!0}),n=e.text();return{...super.props(),totalSeconds:e.prop(e.num(),`duration.totalSeconds`),totalMinutes:e.prop(e.num(),`duration.totalMinutes`),totalHours:e.prop(e.num(),`duration.totalHours`),totalDays:e.prop(e.num(),`duration.totalDays`),days:e.prop(t,`duration.days`),hours:e.prop(t,`duration.hours`),minutes:e.prop(t,`duration.minutes`),seconds:e.prop(t,`duration.seconds`),ms:e.prop(t,`duration.ms`),toText:e.method({format:e.optional(n)},n,`duration.toText`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`duration`}valueA(){return R.number().describe(`A duration in milliseconds.`)}},Dg=class e extends U{static NAME=`enum`;name=e.NAME;static optionKeys=[`values`];static genericKeys=[`V`];static from(t,n){let r=n.registry,i=t.generic?.V?n.parse(t.generic.V):r.text(),a=t.options?.values??{};return new e(n,i,{values:a})}constructor(e,t,n){super(e,n,{V:t})}get value(){return this.generic.V}valid(e,t){return this.value.valid(e,t)?Object.values(this.options.values).some(t=>t===e):!1}parse(e,t){let n=this.value.parse(e,t);if(!this.valid(n.raw,t))throw new Nm({path:[],code:`enum.not-a-member`,message:`enum.parse: ${String(n.raw)} is not one of ${Object.values(this.options.values).join(`, `)}`,severity:`error`});return new W(this,n.raw)}encode(e,t){return this.value.encode(e,t)}encodeAs(e,t,n){return this.value.encodeAs(e,t,n)}create(){let e=Object.values(this.options.values)[0];return e===void 0?this.value.create():e}random(e){let t=Object.values(this.options.values);return t.length===0?this.value.random(e):t[e(0,t.length-1,!0)]}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.value);return n.name===`null`?this.registry.null():this.registry.enum(t.options.values,n)}compatibleType(t,n,r){return!(t instanceof e)||!this.value.compatible(t.value,n,r)?!1:!n?.value||Object.values(t.options.values).every(e=>Object.values(this.options.values).some(t=>t===e))}or(t){return t instanceof e?new e(this.registry,this.value.or(t.value),{values:{...t.options.values,...this.options.values}}):this}narrow(e){let t=this.options.values;if(e.values===void 0)return this.options;for(let[n,r]of Object.entries(e.values))if(!Object.values(t).some(e=>e===r))throw new Nm({path:[],code:`enum.widen`,message:`enum.narrow: ${n}=${String(r)} not in base values`,severity:`error`});return{values:e.values}}props(){let e=this.registry,t=this.value;return{...super.props(),name:e.prop(e.text(),`enum.name`),value:e.prop(t,`enum.value`),eq:e.method({other:t},e.bool(),`enum.eq`),neq:e.method({other:t},e.bool(),`enum.neq`),toText:e.method({},e.text(),`enum.toText`)}}toJSON(){return{name:e.NAME,generic:{V:this.value.toJSON()},options:{values:this.options.values}}}clone(){return new e(this.registry,this.value.clone(),{values:{...this.options.values}})}toCode(e,t){let n=`enum<${this.value.toCode(void 0,t)}>`+kg(this.options.values,t);return this.docsPrefix(t)+n}valueA(){let e=Object.values(this.options.values);return e.length>0&&e.every(e=>typeof e==`string`)?R.enum(e):R.union(e.map(e=>R.literal(e)))}},Og=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function kg(e,t){let n=Object.entries(e);return n.length===0?``:`{${Bh(n.map(([e,t])=>{let n=Og.test(e)?e:JSON.stringify(e);return t===e?n:`${n}=${typeof t==`number`||typeof t==`boolean`?String(t):JSON.stringify(t??null)}`}),{indent:Vh(t)})}}`}var Ag=class e extends U{static NAME=`fn`;static consumes=[`call`];name=e.NAME;static optionKeys=[];static declaresGenerics=!0;_call;static from(t,n){let r=n.registry,i={},a=new Qm(n);if(t.generic)for(let[e,n]of Object.entries(t.generic))i[e]=a.parse(n);return t.call?new e(a,Nh.from(t.call,a),i):new e(a,new Nh({args:r.any(),returns:r.any()}),i)}constructor(e,t,n={}){super(e,{},n),this._call=t instanceof Nh?t:new Nh(t)}parsesExprValue(e){return!0}valid(e,t){return!!(typeof e==`function`||typeof e==`string`||e&&typeof e==`object`&&`kind`in e)}parse(e,t){return typeof e==`string`||e&&typeof e==`object`&&`kind`in e||typeof e==`function`?new W(this,e):new W(this,null)}encode(e,t){return typeof e==`function`?null:e}create(){return{kind:`new`,type:(this._call.returns??this.registry.void()).toJSON()}}random(e){return this.create()}like(t){if(!(t instanceof e))return this;let n=this.registry,r=n.like(t._call.args);if(r.name===`null`)return n.null();let i=t._call.returns?n.like(t._call.returns):void 0;if(i&&i.name===`null`)return n.null();let a=t._call.throws?n.like(t._call.throws):void 0;return a&&a.name===`null`?n.null():n.fn({args:r,returns:i,throws:a,generic:this.generic})}compatibleType(t,n,r){return!(!(t instanceof e)||!this._call.args.compatible(t._call.args,n,r)||this._call.returns&&t._call.returns&&!this._call.returns.compatible(t._call.returns,n,r))}or(t){return t instanceof e?new e(this.registry,{args:this._call.args.or(t._call.args),returns:this._call.returns&&t._call.returns?this._call.returns.or(t._call.returns):this._call.returns??t._call.returns,throws:this._call.throws&&t._call.throws?this._call.throws.or(t._call.throws):this._call.throws??t._call.throws}):this}narrow(e){return{}}call(e){return this._call}props(e){return super.props(e)}toJSON(){let t=Object.keys(this.generic),n=t.length===0?void 0:Object.fromEntries(t.map(e=>[e,this.generic[e].toJSON()]));return Km({name:e.NAME,call:this._call.toJSON(),generic:n})}clone(){let t={};for(let[e,n]of Object.entries(this.generic))t[e]=n.clone();return new e(this.registry,{args:this._call.args.clone(),returns:this._call.returns?.clone(),throws:this._call.throws?.clone(),get:this._call.get,set:this._call.set},t)}toCode(e,t){let n=this._call.returns?.toCode(void 0,t)??`void`;return this.docsPrefix(t)+`${U.renderGenerics(this.generic,t)}${this._call.renderTypes(t)}(${U.formatParams(this._call.args,t)}): ${n}`}valueA(){return R.union([R.string(),R.ref(`Expr`)])}},jg=class e extends U{static NAME=`interface`;static consumes=[`props`,`get`,`call`];name=e.NAME;static optionKeys=[];static genericKeys=[];_props;_get;_call;static from(t,n){return n.registry,new e(n,{props:t.props?jh.fromMap(t.props,n):{},get:t.get?Mh.from(t.get,n):void 0,call:t.call?Nh.from(t.call,n):void 0})}constructor(e,t){super(e,{});let n={};if(t.props)for(let[e,r]of Object.entries(t.props))n[e]=jh.from(r);this._props=n,this._get=t.get,this._call=t.call}valid(e,t){return!0}parse(e,t){return new W(this,e)}encode(e,t){return e}create(){return null}random(e){return null}like(t){if(!(t instanceof e))return this;let n=this.registry,r={};for(let[e,i]of Object.entries(t._props)){let t=n.like(i.type);if(t.name===`null`)return n.null();r[e]={type:t}}let i;if(t._get){let e=n.like(t._get.key),r=n.like(t._get.value);if(e.name===`null`||r.name===`null`)return n.null();i=new Mh({key:e,value:r})}let a;if(t._call){let e=n.like(t._call.args);if(e.name===`null`)return n.null();let r=t._call.returns?n.like(t._call.returns):void 0;if(r&&r.name===`null`)return n.null();a=new Nh({args:e,returns:r})}return new e(n,{props:r,get:i,call:a})}compatibleType(e,t,n){let r=e.props(n);for(let[e,i]of Object.entries(this._props)){let a=r[e];if(!a||!i.type.compatible(a.type,t,n))return!1}if(this._get){let r=e.get(n);if(!r||!this._get.key.compatible(r.key,t,n)||!this._get.value.compatible(r.value,t,n))return!1}if(this._call){let r=e.call(n);if(!r||!this._call.args.compatible(r.args,t,n)||this._call.returns&&r.returns&&!this._call.returns.compatible(r.returns,t,n))return!1}return!0}flexible(){return!0}isUniversal(){return Object.keys(this._props).length===0&&!this._get&&!this._call}or(t){if(!(t instanceof e))return this;let n={};for(let e of Object.keys(this._props))e in t._props&&(n[e]={type:this._props[e].type.or(t._props[e].type)});return new e(this.registry,{props:n})}narrow(e){return{}}props(e){return{...super.props(e),...this._props}}get(e){return this._get}call(e){return this._call}toJSON(){return Km({name:e.NAME,props:Object.keys(this._props).length>0?jh.toJSONMap(this._props):void 0,get:this._get?.toJSON(),call:this._call?.toJSON()})}clone(){let t={};for(let[e,n]of Object.entries(this._props))t[e]={...n,type:n.type.clone()};return new e(this.registry,{props:t,get:this._get,call:this._call})}toCode(e,t){let n=t?.includeComments!==!1,r=[];for(let[e,i]of Object.entries(this._props)){let a=i.type.isOptional(),o=a?i.type.required():i.type,s=a?`${e}?`:e,c=i.docs&&n?`/* ${i.docs} */ `:``;r.push(`${c}${s}: ${o.toCode(void 0,t)}`)}if(this._get&&r.push(`[key: ${this._get.key.toCode(void 0,t)}]: ${this._get.value.toCode(void 0,t)}`),this._call){let e=this._call.returns?.toCode(void 0,t)??`void`;r.push(`(${this._call.args.toCode(void 0,t)}): ${e}`)}let i=r.length===0?`iface`:`iface{${Bh(r,{indent:Vh(t)})}}`;return this.docsPrefix(t)+i}toCodeRef(e,t){return this.docsPrefix(t)+`iface`}refProps(){return this._props}refGet(){return this._get}refCall(){return this._call}valueA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this._props)){let a=i.type.toA(e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=a}return this.objectA(n,e)}toNewA(e){let t=e?.includeDocs??`none`,n={};for(let[e,r]of Object.entries(this._props)){let i=R.ref(`Expr`);t===`all`&&r.docs&&(i=i.describe(r.docs)),n[e]=i}return this.describeA(R.object(n),e)}},Mg=class e extends U{static NAME=`literal`;name=e.NAME;static optionKeys=[`value`];static genericKeys=[`T`];inner;static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any(),a=t.options?.value;return new e(n,i,a)}constructor(e,t,n){super(e,{value:n},{T:t}),this.inner=t}get literal(){return this.options.value}valid(e,t){return this.inner.valid(e,t)&&e===this.literal}parse(e,t){let n=this.inner.parse(e,t);if(n.raw!==this.literal)throw new Nm({path:[],code:`literal.not-match`,message:`literal: expected ${String(this.literal)}, got ${String(n.raw)}`,severity:`error`});return new W(this,n.raw)}encode(e,t){return this.inner.encode(e,t)}encodeAs(e,t,n){return this.inner.encodeAs(e,t,n)}create(){return this.literal}random(e){return this.literal}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r)&&this.literal===t.literal:!n?.exact&&this.inner.compatible(t,n,r)}isUniversal(){return this.inner.isUniversal()}or(t){return t instanceof e&&(t.literal,this.literal),this}narrow(e){if(e.value!==void 0&&e.value!==this.literal)throw new Nm({path:[],code:`literal.narrow`,message:`literal value cannot change via narrow`,severity:`error`});return this.options}props(){return this.inner.props()}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()},options:{value:this.literal}}}clone(){return new e(this.registry,this.inner.clone(),this.literal)}toCode(e,t){return this.docsPrefix(t)+`literal<${this.inner.toCode(void 0,t)}>`+Rh({value:this.literal})}valueA(){return R.literal(this.literal)}},Ng=class e extends U{static NAME=`list`;name=e.NAME;static optionKeys=[`minLength`,`maxLength`];static genericKeys=[`V`];static from(t,n){let r=n.registry,i=t.generic?.V?n.parse(t.generic.V):r.any();return new e(n,i,t.options??{})}constructor(e,t,n={}){super(e,n,{V:t})}get item(){return this.generic.V}valid(e,t){if(!Array.isArray(e))return!1;let{minLength:n,maxLength:r}=this.options;return n!==void 0&&e.length<n||r!==void 0&&e.length>r?!1:e.every(e=>e instanceof W&&e.type.valid(e.raw,t)&&Sh(this.item,e.type,t))}parse(e,t){if(!Array.isArray(e))throw new Nm({path:[],code:`list.invalid`,message:`list.parse: expected array, got ${typeof e}`,severity:`error`});let n=e.map(e=>this.registry.parseValue(e,this.item,t));if(!this.valid(n,t))throw new Nm({path:[],code:`list.constraint`,message:`list.parse: length constraints violated`,severity:`error`});return new W(this,n)}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){return e.map(e=>Eh(e,t,n))}create(){let e=this.options.minLength??0;return Array.from({length:e},()=>new W(this.item,this.item.create()))}random(e){let t=this.options.minLength??0,n=e(t,this.options.maxLength??Math.max(t,5),!0);return Array.from({length:n},()=>new W(this.item,this.item.random(e)))}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<e.length;n++)t.slot(this.item,e[n],n);return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i of e)r.push(await this.item.newFill(i,t,n));return r}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.item);return n.name===`null`?n:this.registry.list(n)}compatibleType(t,n,r){if(!(t instanceof e)||!this.item.compatible(t.item,n,r))return!1;if(!n?.value)return!0;let i=this.options,a=t.options;return!(i.minLength!==void 0&&(a.minLength===void 0||a.minLength<i.minLength)||i.maxLength!==void 0&&(a.maxLength===void 0||a.maxLength>i.maxLength))}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,this.item.or(t.item),{minLength:n.minLength!==void 0&&r.minLength!==void 0?Math.min(n.minLength,r.minLength):void 0,maxLength:n.maxLength!==void 0&&r.maxLength!==void 0?Math.max(n.maxLength,r.maxLength):void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Nm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.minLength!==void 0&&(t.minLength!==void 0&&e.minLength<t.minLength&&n(`list.widen.minLength`,`local ${e.minLength} < base ${t.minLength}`),r.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength!==void 0&&e.maxLength>t.maxLength&&n(`list.widen.maxLength`,`local ${e.maxLength} > base ${t.maxLength}`),r.maxLength=e.maxLength),r}get(){let e=this.registry;return new Mh({key:e.num({whole:!0,min:0}),value:this.item,get:e.nativeExpr(`list.indexGet`),set:e.nativeExpr(`list.indexSet`),loop:e.nativeExpr(`list.iterate`)})}props(){let e=this.registry,t=this.item,n=e.num(),r=e.bool(),i=e.text(),a=e.void(),o=e.optional(t),s=e.list(t),c=r=>e.fn({args:e.obj({value:{type:t},index:{type:n}}),returns:r});return{...super.props(),length:e.prop(n,`list.length`),at:e.method({index:n},o,`list.at`),push:e.method({value:t},a,`list.push`),pop:e.method({},o,`list.pop`),shift:e.method({},o,`list.shift`),unshift:e.method({value:t},a,`list.unshift`),insert:e.method({index:n,value:t},a,`list.insert`),remove:e.method({index:n},t,`list.remove`),clear:e.method({},a,`list.clear`),slice:e.method({start:e.optional(n),end:e.optional(n)},s,`list.slice`),concat:e.method({other:s},s,`list.concat`),reverse:e.method({},s,`list.reverse`),join:e.method({separator:e.optional(i)},i,`list.join`),indexOf:e.method({value:t},n,`list.indexOf`),contains:e.method({value:t},r,`list.contains`),unique:e.method({},s,`list.unique`),duplicates:e.method({},s,`list.duplicates`),map:e.method({fn:c(e.alias(`R`))},e.list(e.alias(`R`)),`list.map`,{generic:{R:e.any()}}),filter:e.method({fn:c(r)},s,`list.filter`),find:e.method({fn:c(r)},o,`list.find`),reduce:e.method({fn:e.fn({args:e.obj({acc:{type:e.alias(`R`)},value:{type:t},index:{type:n}}),returns:e.alias(`R`)}),initial:e.alias(`R`)},e.alias(`R`),`list.reduce`,{generic:{R:e.any()}}),some:e.method({fn:c(r)},r,`list.some`),every:e.method({fn:c(r)},r,`list.every`),sort:e.method({fn:e.optional(e.fn({args:e.obj({a:{type:t},b:{type:t}}),returns:n}))},s,`list.sort`),isEmpty:e.method({},r,`list.isEmpty`),isNotEmpty:e.method({},r,`list.isNotEmpty`),first:e.prop(o,`list.first`),last:e.prop(o,`list.last`)}}toJSON(){return Km({name:e.NAME,generic:{V:this.item.toJSON()},options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,this.item.clone(),{...this.options})}toCode(e,t){return this.docsPrefix(t)+`list<${this.item.toCode(void 0,t)}>`+Rh(this.options,{minLength:0})}valueA(e){let t=R.array(this.item.toA(e));return this.options.minLength!==void 0&&(t=t.min(this.options.minLength)),this.options.maxLength!==void 0&&(t=t.max(this.options.maxLength)),t}toNewA(e){let t=R.array(R.ref(`Expr`));return this.options.minLength!==void 0&&(t=t.min(this.options.minLength)),this.options.maxLength!==void 0&&(t=t.max(this.options.maxLength)),this.describeA(t,e)}describe(t){if(Array.isArray(t))return new e(this.registry,this.registry.any(),{})}};function Pg(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function Fg(e){if(Array.isArray(e))return[e[0],e[1]];let t=e;return[t?.key,t?.value]}function Ig(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var Lg=class e extends U{static NAME=`map`;name=e.NAME;static optionKeys=[];static genericKeys=[`K`,`V`];static from(t,n){let r=n.registry,i=t.generic?.K?n.parse(t.generic.K):r.text(),a=t.generic?.V?n.parse(t.generic.V):r.any();return new e(n,i,a)}constructor(e,t,n){super(e,{},{K:t,V:n})}get key(){return this.generic.K}get value(){return this.generic.V}valid(e,t){if(!(e instanceof Map))return!1;for(let[,n]of e){if(!Array.isArray(n)||n.length!==2)return!1;let[e,r]=n;if(!(e instanceof W)||!(r instanceof W)||!e.type.valid(e.raw,t)||!r.type.valid(r.raw,t)||!Sh(this.key,e.type,t)||!Sh(this.value,r.type,t))return!1}return!0}parse(e,t){let n=e instanceof Map?Array.from(e,([e,t])=>Pg(t)?t:[e,t]):this.textKeyed()&&Ig(e)?Object.entries(e):e;if(!Array.isArray(n))throw new Nm({path:[],code:`map.invalid`,message:`map.parse: expected array of [key, value] pairs`,severity:`error`});let r=new Map;for(let e of n){let[n,i]=Array.isArray(e)?e:[e.key,e.value],a=this.registry.parseValue(n,this.key,t),o=this.registry.parseValue(i,this.value,t);r.set(a.raw,[a,o])}return new W(this,r)}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){return t.form===`logical`&&this.textKeyed()?Object.fromEntries(Array.from(e,([,[e,r]])=>[String(Eh(e,t,n)),Eh(r,t,n)])):Array.from(e,([,[e,r]])=>({key:Eh(e,t,n),value:Eh(r,t,n)}))}textKeyed(){return this.key.name===`text`}create(){return new Map}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<e.length;n++){let[r,i]=Fg(e[n]);t.slot(this.key,r,`${n}.key`),t.slot(this.value,i,`${n}.value`)}return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i of e){let[e,a]=Fg(i);r.push({key:await this.key.newFill(e,t,n),value:await this.value.newFill(a,t,n)})}return r}random(e){let t=e(0,5,!0),n=new Map;for(let r=0;r<t;r++){let t=this.key.random(e),r=this.value.random(e);n.set(t,[new W(this.key,t),new W(this.value,r)])}return n}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.key),r=this.registry.like(t.value);return n.name===`null`||r.name===`null`?this.registry.null():this.registry.map(n,r)}compatibleType(t,n,r){return t instanceof e&&this.key.compatible(t.key,n,r)&&this.value.compatible(t.value,n,r)}or(t){return t instanceof e?new e(this.registry,this.key.or(t.key),this.value.or(t.value)):this}narrow(e){return{}}get(){let e=this.registry;return new Mh({key:this.key,value:this.value,get:e.nativeExpr(`map.indexGet`),set:e.nativeExpr(`map.indexSet`),loop:e.nativeExpr(`map.iterate`)})}props(){let e=this.registry,t=this.key,n=this.value,r=e.num(),i=e.bool(),a=e.void(),o=e.optional(n);return{...super.props(),size:e.prop(r,`map.size`),at:e.method({key:t},o,`map.at`),has:e.method({key:t},i,`map.has`),delete:e.method({key:t},i,`map.delete`),clear:e.method({},a,`map.clear`),keys:e.method({},e.list(t),`map.keys`),values:e.method({},e.list(n),`map.values`),isEmpty:e.method({},i,`map.isEmpty`),isNotEmpty:e.method({},i,`map.isNotEmpty`)}}toJSON(){return{name:e.NAME,generic:{K:this.key.toJSON(),V:this.value.toJSON()}}}clone(){return new e(this.registry,this.key.clone(),this.value.clone())}toCode(e,t){return this.docsPrefix(t)+`map<${this.key.toCode(void 0,t)}, ${this.value.toCode(void 0,t)}>`}valueA(e){return this.key.name===`text`?R.record(this.value.toA(e)):R.array(this.objectA({key:this.key.toA(e),value:this.value.toA(e)},e))}toNewA(e){return this.describeA(R.array(R.object({key:R.ref(`Expr`),value:R.ref(`Expr`)})),e)}describe(t){return t instanceof Map?new e(this.registry,this.registry.any(),this.registry.any()):void 0}},Rg=class e extends U{constructor(e,t){super(e,{excluded:t.toJSON()}),this.excluded=t}excluded;static NAME=`not`;name=e.NAME;static optionKeys=[`excluded`];static genericKeys=[];static from(t,n){let r=n.registry,i=t.options?.excluded?n.parse(t.options.excluded):r.any();return new e(n,i)}valid(e,t){return!this.excluded.valid(e,t)}parse(e,t){if(this.excluded.valid(e,t))throw new Nm({path:[],code:`not.excluded`,message:`not: value matches excluded type ${this.excluded.name}`,severity:`error`});return new W(this,e)}encode(e,t){return e}create(){return null}random(e){return null}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.excluded);return n.name===`null`?n:this.registry.not(n)}compatibleType(t,n,r){return n?.exact?t instanceof e&&this.excluded.exact(t.excluded,r):!this.excluded.compatible(t,n,r)}flexible(){return!0}or(t){return t instanceof e?new e(this.registry,this.registry.or([this.excluded,t.excluded])):this}narrow(e){return{excluded:e.excluded??this.options.excluded}}props(){let e=this.registry;return{...super.props(),typeOf:e.method({},e.text(),`not.typeOf`),toText:e.method({},e.text(),`not.toText`)}}toJSON(){return{name:e.NAME,options:{excluded:this.excluded.toJSON()}}}clone(){return new e(this.registry,this.excluded.clone())}toCode(e,t){return this.docsPrefix(t)+`not<${this.excluded.toCode(void 0,t)}>`}valueA(e){return R.not(this.excluded.toA(e))}},zg=class e extends U{static NAME=`null`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return e===null}parse(e){if(e!==null)throw new Nm({path:[],code:`null.invalid`,message:`null expects null, got ${typeof e}`,severity:`error`});return new W(this,null)}encode(e){return null}create(){return null}random(e){return null}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new Nm({path:[],code:`null.no-options`,message:`null has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),toText:e.method({},e.text(),`null.toText`),toBool:e.method({},e.bool(),`null.toBool`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`null`}valueA(){return R.null()}},Bg=class e extends U{constructor(e,t){super(e,{},{T:t}),this.inner=t}inner;static NAME=`nullable`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e===null||this.inner.valid(e,t)}parse(e,t){if(e===null)return new W(this,null);let n=this.inner.parse(e,t);return new W(this,n.raw)}parsesExprValue(e){return this.inner.parsesExprValue(e)}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){return e===null?null:this.inner.encodeAs(e,t,n)}forEachNewSlot(e,t){return e!=null&&this.inner.forEachNewSlot(e,t)}async newFill(e,t,n){return e==null?e:this.inner.newFill(e,t,n)}create(){return null}random(e){return e(0,9,!0)<3?null:this.inner.random(e)}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.inner);return n.name===`null`?n:this.registry.nullable(n)}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r):!n?.exact&&this.inner.compatible(t,n,r)}or(t){return t instanceof e?new e(this.registry,this.inner.or(t.inner)):this}required(){return this.inner}isUniversal(){return this.inner.isUniversal()}narrow(e){if(e&&Object.keys(e).length>0)throw new Nm({path:[],code:`nullable.no-options`,message:`nullable has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry,t=this.inner;return{...super.props(),value:e.prop(t,`nullable.value`),isNull:e.method({},e.bool(),`nullable.isNull`),or:e.method({fallback:t},t,`nullable.or`),map:e.method({fn:e.fn({args:e.obj({value:{type:t}}),returns:e.alias(`R`)})},e.nullable(e.alias(`R`)),`nullable.map`,{generic:{R:e.any()}})}}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()}}}clone(){return new e(this.registry,this.inner.clone())}toCode(e,t){return this.docsPrefix(t)+`nullable<${this.inner.toCode(void 0,t)}>`}valueA(e){return R.nullable(this.inner.toA(e))}toNewA(e){return this.describeA(R.nullable(this.inner.toNewA(e)),e)}},Vg=class e extends U{static NAME=`num`;name=e.NAME;static optionKeys=[`min`,`max`,`whole`,`minPrecision`,`maxPrecision`,`prefix`,`suffix`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){if(typeof e!=`number`||Number.isNaN(e))return!1;let{min:t,max:n,whole:r}=this.options;return!(t!==void 0&&e<t||n!==void 0&&e>n||r&&!Number.isInteger(e))}parse(e){let t=typeof e==`string`?Number(e):e;if(typeof t!=`number`||Number.isNaN(t))throw new Nm({path:[],code:`num.invalid`,message:`num.parse: not a number \u2014 ${String(e)}`,severity:`error`});if(!this.valid(t))throw new Nm({path:[],code:`num.out-of-range`,message:`num.parse: ${t} violates options ${JSON.stringify(this.options)}`,severity:`error`});return new W(this,t)}encode(e){return e}create(){let{min:e,max:t,whole:n}=this.options,r=0;if(e!==void 0&&r<e&&(r=e),t!==void 0&&r>t&&(r=t),n&&!Number.isInteger(r)){let e=Math.ceil(r);r=t!==void 0&&e>t?Math.floor(r):e}return r}random(e){return e(this.options.min??0,this.options.max??100,this.options.whole??!1)}compatibleType(t,n){if(!(t instanceof e))return!1;if(!n?.value)return!0;let r=this.options,i=t.options;return!(r.min!==void 0&&(i.min===void 0||i.min<r.min)||r.max!==void 0&&(i.max===void 0||i.max>r.max)||r.whole&&!i.whole)}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{min:n.min!==void 0&&r.min!==void 0?Math.min(n.min,r.min):void 0,max:n.max!==void 0&&r.max!==void 0?Math.max(n.max,r.max):void 0,whole:n.whole&&r.whole,minPrecision:n.minPrecision!==void 0&&r.minPrecision!==void 0?Math.min(n.minPrecision,r.minPrecision):void 0,maxPrecision:n.maxPrecision!==void 0&&r.maxPrecision!==void 0?Math.max(n.maxPrecision,r.maxPrecision):void 0,prefix:n.prefix===r.prefix?n.prefix:void 0,suffix:n.suffix===r.suffix?n.suffix:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Nm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.min!==void 0&&(t.min!==void 0&&e.min<t.min&&n(`num.widen.min`,`local.min ${e.min} < base.min ${t.min}`),r.min=e.min),e.max!==void 0&&(t.max!==void 0&&e.max>t.max&&n(`num.widen.max`,`local.max ${e.max} > base.max ${t.max}`),r.max=e.max),e.whole!==void 0&&(t.whole===!0&&!e.whole&&n(`num.widen.whole`,`base requires whole; local cannot remove`),r.whole=e.whole),e.minPrecision!==void 0&&(t.minPrecision!==void 0&&e.minPrecision<t.minPrecision&&n(`num.widen.minPrecision`,`minPrecision cannot decrease`),r.minPrecision=e.minPrecision),e.maxPrecision!==void 0&&(t.maxPrecision!==void 0&&e.maxPrecision>t.maxPrecision&&n(`num.widen.maxPrecision`,`maxPrecision cannot increase`),r.maxPrecision=e.maxPrecision),e.prefix!==void 0&&(r.prefix=e.prefix),e.suffix!==void 0&&(r.suffix=e.suffix),r}get(){let e=this.registry;return new Mh({key:e.num({whole:!0,min:0}),value:e.num(),loop:e.nativeExpr(`num.loop`)})}props(){let e=this.registry,t=e.num(),n=e.bool(),r=e.text(),i=e.optional(t);return{...super.props(),eq:e.method({other:t,epsilon:i},n,`num.eq`),neq:e.method({other:t,epsilon:i},n,`num.neq`),lt:e.method({other:t},n,`num.lt`),lte:e.method({other:t},n,`num.lte`),gt:e.method({other:t},n,`num.gt`),gte:e.method({other:t},n,`num.gte`),add:e.method({other:t},t,`num.add`),sub:e.method({other:t},t,`num.sub`),mul:e.method({other:t},t,`num.mul`),div:e.method({other:t},t,`num.div`),mod:e.method({other:t},t,`num.mod`),pow:e.method({other:t},t,`num.pow`),abs:e.method({},t,`num.abs`),neg:e.method({},t,`num.neg`),sign:e.method({},t,`num.sign`),sqrt:e.method({},t,`num.sqrt`),min:e.method({other:t},t,`num.min`),max:e.method({other:t},t,`num.max`),clamp:e.method({min:t,max:t},t,`num.clamp`),floor:e.method({},t,`num.floor`),ceil:e.method({},t,`num.ceil`),round:e.method({},t,`num.round`),isZero:e.method({},n,`num.isZero`),isPositive:e.method({},n,`num.isPositive`),isNegative:e.method({},n,`num.isNegative`),isInteger:e.method({},n,`num.isInteger`),isEven:e.method({},n,`num.isEven`),isOdd:e.method({},n,`num.isOdd`),toText:e.method({precision:i},r,`num.toText`),toBool:e.method({},n,`num.toBool`)}}toJSON(){return Km({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`num`+Rh(this.options,{minPrecision:1,maxPrecision:7,prefix:``,suffix:``})}valueA(){let e=this.options.whole?R.int():R.number();return this.options.min!==void 0&&(e=e.min(this.options.min)),this.options.max!==void 0&&(e=e.max(this.options.max)),e}describe(t){if(!(typeof t!=`number`||Number.isNaN(t)))return new e(this.registry,{whole:Number.isInteger(t)})}},Hg=class e extends U{constructor(e,t){super(e,{},{T:t}),this.inner=t}inner;static NAME=`optional`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e===void 0||this.inner.valid(e,t)}parse(e,t){if(e==null)return new W(this,void 0);let n=this.inner.parse(e,t);return new W(this,n.raw)}parsesExprValue(e){return this.inner.parsesExprValue(e)}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){return e===void 0?null:this.inner.encodeAs(e,t,n)}forEachNewSlot(e,t){return e!=null&&this.inner.forEachNewSlot(e,t)}async newFill(e,t,n){return e==null?e:this.inner.newFill(e,t,n)}create(){}random(e){if(!(e(0,9,!0)<3))return this.inner.random(e)}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.inner);return n.name===`null`?n:this.registry.optional(n)}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r):!n?.exact&&this.inner.compatible(t,n,r)}or(t){return t instanceof e?new e(this.registry,this.inner.or(t.inner)):this}required(){return this.inner}isOptional(){return!0}isUniversal(){return this.inner.isUniversal()}narrow(e){if(e&&Object.keys(e).length>0)throw new Nm({path:[],code:`optional.no-options`,message:`optional has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry,t=this.inner;return{...super.props(),value:e.prop(t,`optional.value`),has:e.method({},e.bool(),`optional.has`),or:e.method({fallback:t},t,`optional.or`),map:e.method({fn:e.fn({args:e.obj({value:{type:t}}),returns:e.alias(`R`)})},e.optional(e.alias(`R`)),`optional.map`,{generic:{R:e.any()}})}}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()}}}clone(){return new e(this.registry,this.inner.clone())}toCode(e,t){return this.docsPrefix(t)+`optional<${this.inner.toCode(void 0,t)}>`}valueA(e){return R.optional(this.inner.toA(e))}toNewA(e){return this.describeA(R.optional(this.inner.toNewA(e)),e)}},Ug=class e extends U{static NAME=`or`;name=e.NAME;static optionKeys=[`types`];static genericKeys=[];static from(t,n){n.registry;let r=(t.options?.types??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,{variants:t})}get variants(){return this.options.variants}valid(e,t){return this.variants.some(n=>n.valid(e,t))}parse(e,t){for(let n of this.variants)try{let r=n.parse(e,t);return new W(this,r.raw)}catch{continue}throw new Nm({path:[],code:`or.no-match`,message:`or: no variant matched (${this.variants.map(e=>e.name).join(` | `)})`,severity:`error`})}encode(e,t){let n=this.variants.find(n=>n.valid(e,t));if(!n)throw new Nm({path:[],code:`or.dump.no-match`,message:`or.dump: value does not satisfy any variant`,severity:`error`});return n.encode(e,t)}parsesExprValue(e){return this.variants.some(t=>t.parsesExprValue(e))}encodeAs(e,t,n){let r=this.variants.find(t=>t.valid(e,n));if(!r)throw new Nm({path:[],code:`or.dump.no-match`,message:`or.dump: value does not satisfy any variant`,severity:`error`});return r.encodeAs(e,t,n)}create(){return this.variants[0]?.create()??null}random(e){let t=e(0,this.variants.length-1,!0);return this.variants[t]?.random(e)??null}like(t){if(!(t instanceof e))return this;let n=t.variants.map(e=>this.registry.like(e)).filter(e=>e.name!==`null`);return n.length===0?this.registry.null():n.length===1?n[0]:this.registry.or(n)}compatibleType(e,t,n){return this.variants.some(r=>r.compatible(e,t,n))}or(t){return t instanceof e?new e(this.registry,[...this.variants,...t.variants]):new e(this.registry,[...this.variants,t])}simplify(){return this.variants.length===1?this.variants[0]:this}narrow(e){return this.options}props(){let e=super.props();if(this.variants.length===0)return e;let t=this.variants.map(e=>e.props()),n=Object.keys(t[0]).filter(e=>t.every(t=>e in t)),r={...e};for(let e of n){let n=t.map(t=>t[e].type);r[e]={type:this.registry.or(n)}}return r}get(){let e=this.variants.map(e=>e.get());if(e.some(e=>!e))return;let t=e;return new Mh({key:this.registry.and(t.map(e=>e.key)),value:this.registry.or(t.map(e=>e.value))})}call(){let e=this.variants.map(e=>e.call());if(e.some(e=>!e))return;let t=e,n=t.map(e=>e.returns).filter(e=>!!e),r=t.map(e=>e.throws).filter(e=>!!e);return new Nh({args:this.registry.and(t.map(e=>e.args)),returns:n.length===t.length?this.registry.or(n):void 0,throws:r.length>0?this.registry.or(r):void 0})}toJSON(){return{name:e.NAME,options:{types:this.variants.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.variants.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`or<${this.variants.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){return this.variants.length===0?R.never():this.variants.length===1?this.variants[0].toA(e):R.union(this.variants.map(t=>t.toA(e)))}toNewA(e){return this.variants.length===0?this.describeA(R.never(),e):this.variants.length===1?this.describeA(this.variants[0].toNewA(e),e):this.describeA(R.union(this.variants.map(t=>t.toNewA(e))),e)}},Wg=class e extends U{static NAME=`text`;name=e.NAME;static optionKeys=[`minLength`,`maxLength`,`pattern`,`flags`];static genericKeys=[];_regex;static from(t,n){return n.registry,new e(n,t.options??{})}regex(){if(this._regex)return this._regex;if(this.options.pattern)return this._regex=new RegExp(this.options.pattern,this.options.flags),this._regex}valid(e){if(typeof e!=`string`)return!1;let{minLength:t,maxLength:n}=this.options;if(t!==void 0&&e.length<t||n!==void 0&&e.length>n)return!1;let r=this.regex();return!(r&&!r.test(e))}parse(e){if(typeof e!=`string`)throw new Nm({path:[],code:`text.invalid`,message:`text.parse: expected string, got ${typeof e}`,severity:`error`});if(!this.valid(e))throw new Nm({path:[],code:`text.constraint`,message:`text.parse: value violates constraints`,severity:`error`});return new W(this,e)}encode(e){return e}create(){let e=this.options.minLength??0;return e>0?`a`.repeat(e):``}random(e){let t=e(this.options.minLength??0,this.options.maxLength??16,!0),n=``;for(let r=0;r<t;r++)n+=`abcdefghijklmnopqrstuvwxyz0123456789`[e(0,35,!0)];return n}compatibleType(t,n){if(!(t instanceof e))return!1;if(!n?.value)return!0;let r=this.options,i=t.options;return!(r.minLength!==void 0&&(i.minLength===void 0||i.minLength<r.minLength)||r.maxLength!==void 0&&(i.maxLength===void 0||i.maxLength>r.maxLength)||r.pattern&&r.pattern!==i.pattern)}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{minLength:n.minLength!==void 0&&r.minLength!==void 0?Math.min(n.minLength,r.minLength):void 0,maxLength:n.maxLength!==void 0&&r.maxLength!==void 0?Math.max(n.maxLength,r.maxLength):void 0,pattern:n.pattern===r.pattern?n.pattern:void 0,flags:n.pattern===r.pattern?n.flags:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Nm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.minLength!==void 0&&(t.minLength!==void 0&&e.minLength<t.minLength&&n(`text.widen.minLength`,`local ${e.minLength} < base ${t.minLength}`),r.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength!==void 0&&e.maxLength>t.maxLength&&n(`text.widen.maxLength`,`local ${e.maxLength} > base ${t.maxLength}`),r.maxLength=e.maxLength),e.pattern!==void 0&&(t.pattern!==void 0&&(e.pattern!==t.pattern||e.flags!==t.flags)&&n(`text.widen.pattern`,`pattern narrowing is only allowed when base has no pattern or matches exactly`),r.pattern=e.pattern,r.flags=e.flags),r}get(){let e=this.registry;return new Mh({key:e.num(),value:e.text({minLength:1,maxLength:1}),get:e.nativeExpr(`text.charAt`),loop:e.nativeExpr(`text.chars`)})}props(){let e=this.registry,t=e.text(),n=e.num(),r=e.bool(),i=e.optional(n);return{...super.props(),length:e.prop(n,`text.length`),eq:e.method({other:t},r,`text.eq`),neq:e.method({other:t},r,`text.neq`),contains:e.method({search:t},r,`text.contains`),startsWith:e.method({prefix:t},r,`text.startsWith`),endsWith:e.method({suffix:t},r,`text.endsWith`),trim:e.method({},t,`text.trim`),trimStart:e.method({},t,`text.trimStart`),trimEnd:e.method({},t,`text.trimEnd`),upper:e.method({},t,`text.upper`),lower:e.method({},t,`text.lower`),slice:e.method({start:n,end:i},t,`text.slice`),replace:e.method({search:t,replacement:t},t,`text.replace`),split:e.method({separator:t},e.list(t),`text.split`),concat:e.method({other:t},t,`text.concat`),repeat:e.method({count:n},t,`text.repeat`),indexOf:e.method({search:t,from:i},n,`text.indexOf`),lastIndexOf:e.method({search:t,from:i},n,`text.lastIndexOf`),match:e.method({pattern:t},e.list(t),`text.match`),test:e.method({pattern:t},r,`text.test`),isEmpty:e.method({},r,`text.isEmpty`),isNotEmpty:e.method({},r,`text.isNotEmpty`),toNum:e.method({},n,`text.toNum`),toBool:e.method({},r,`text.toBool`)}}toJSON(){return Km({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`text`+Rh(this.options)}valueA(){let e=R.string();return this.options.minLength!==void 0&&(e=e.min(this.options.minLength)),this.options.maxLength!==void 0&&(e=e.max(this.options.maxLength)),this.options.pattern&&(e=e.pattern(this.options.pattern,this.options.flags)),e}describe(e){return typeof e==`string`?this:void 0}},Gg=class e extends U{static NAME=`timestamp`;name=e.NAME;static optionKeys=[`min`,`max`,`utc`,`precision`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return e instanceof Date&&!Number.isNaN(e.getTime())}parse(e){let t=e instanceof Date?e:typeof e==`string`?new Date(e):new Date(NaN);if(!this.valid(t))throw new Nm({path:[],code:`timestamp.invalid`,message:`timestamp.parse: invalid: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e.toISOString()}create(){return new Date}random(e){return new Date(e(Date.UTC(2e3,0,1),Date.UTC(2050,11,31),!0))}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e,this}narrow(e){return this.options}props(){let e=this.registry,t=e.num({whole:!0}),n=e.bool(),r=e.text(),i=e.timestamp(),a=e.duration();return{...super.props(),year:e.prop(t,`timestamp.year`),month:e.prop(t,`timestamp.month`),day:e.prop(t,`timestamp.day`),hour:e.prop(t,`timestamp.hour`),minute:e.prop(t,`timestamp.minute`),second:e.prop(t,`timestamp.second`),millisecond:e.prop(t,`timestamp.millisecond`),eq:e.method({other:i},n,`timestamp.eq`),before:e.method({other:i},n,`timestamp.before`),after:e.method({other:i},n,`timestamp.after`),addDuration:e.method({duration:a},i,`timestamp.addDuration`),subDuration:e.method({duration:a},i,`timestamp.subDuration`),diff:e.method({other:i},a,`timestamp.diff`),toDate:e.method({},e.date(),`timestamp.toDate`),toEpoch:e.method({},t,`timestamp.toEpoch`),toText:e.method({format:e.optional(r)},r,`timestamp.toText`)}}toJSON(){return Km({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`timestamp`+Rh(this.options)}valueA(){return R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`).describe(`An ISO 8601 timestamp (YYYY-MM-DD HH:MM[:SS][Z]).`)}describe(e){return e instanceof Date?this:void 0}};function Kg(e){let t,n={};return Object.defineProperty(n,"elements",{enumerable:!0,get:()=>t??=e.map(e=>e.toJSON())}),n}var qg=class e extends U{static NAME=`tuple`;name=e.NAME;static optionKeys=[`elements`];static genericKeys=[];elements;static from(t,n){n.registry;let r=(t.options?.elements??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,Kg(t)),this.elements=t}valid(e,t){return!Array.isArray(e)||e.length!==this.elements.length?!1:e.every((e,n)=>e instanceof W&&e.type.valid(e.raw,t)&&Sh(this.elements[n],e.type,t))}parse(e,t){if(!Array.isArray(e)||e.length!==this.elements.length)throw new Nm({path:[],code:`tuple.invalid`,message:`tuple.parse: expected array of length ${this.elements.length}`,severity:`error`});let n=this.elements.map((n,r)=>this.registry.parseValue(e[r],n,t));return new W(this,n)}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){if(!Array.isArray(e))throw new Nm({path:[],code:`tuple.invalid`,message:`tuple.encode: expected an array of cells`,severity:`error`});return e.map(e=>Eh(e,t,n))}create(){return this.elements.map(e=>new W(e,e.create()))}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<this.elements.length&&n<e.length;n++)t.slot(this.elements[n],e[n],n);return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i=0;i<e.length;i++){let a=this.elements[i];r.push(a?await a.newFill(e[i],t,n):e[i])}return r}random(e){return this.elements.map(t=>new W(t,t.random(e)))}like(t){if(!(t instanceof e)||t.elements.length!==this.elements.length)return this;let n=t.elements.map(e=>this.registry.like(e));return n.some(e=>e.name===`null`)?this.registry.null():this.registry.tuple(n)}compatibleType(t,n,r){return!(t instanceof e)||t.elements.length!==this.elements.length?!1:this.elements.every((e,i)=>e.compatible(t.elements[i],n,r))}or(t){return!(t instanceof e)||t.elements.length!==this.elements.length?this:new e(this.registry,this.elements.map((e,n)=>e.or(t.elements[n])))}narrow(e){return e.elements===void 0?this.options:{elements:e.elements}}get(){let e=this.elements.length===1?this.elements[0]:this.registry.or(this.elements),t=this.registry;return new Mh({key:t.num({whole:!0,min:0,max:this.elements.length-1}),value:e,get:t.nativeExpr(`tuple.at`),set:t.nativeExpr(`tuple.setAt`),loop:t.nativeExpr(`tuple.iterate`)})}follow(e,t){if(`key`in e&&!(`args`in e)){let t=e.key,n=t?.kind===`new`?t.value:void 0;if(typeof n==`number`&&Number.isInteger(n))return this.elements[n]}return super.follow(e,t)}props(){let e=this.registry;e.num();let t=this.elements[0]??e.any(),n=this.elements[this.elements.length-1]??e.any();return{...super.props(),length:e.prop(e.num({whole:!0,min:this.elements.length,max:this.elements.length}),`tuple.length`),first:e.prop(t,`tuple.first`),last:e.prop(n,`tuple.last`),toList:e.method({},e.list(this.elements.length===0?e.any():e.or(this.elements)),`tuple.toList`)}}toJSON(){return{name:e.NAME,options:{elements:this.elements.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.elements.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`tuple<${this.elements.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){let t=this.elements.map(t=>t.toA(e));return t.length>0?R.tuple(t):R.array(R.unknown()).max(0)}toNewA(e){let t=this.elements.map(()=>R.ref(`Expr`));return this.describeA(t.length>0?R.tuple(t):R.array(R.ref(`Expr`)).max(0),e)}},Jg=class e extends U{constructor(e,t){super(e,{},{T:t}),this.constraint=t}constraint;static NAME=`typ`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static valuesAreTypes=!0;static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e instanceof U?e.compatible(this.constraint,void 0,t)||this.constraint.compatible(e,void 0,t):!1}parse(t,n){if(t instanceof W&&t.type instanceof e)return t;if(t instanceof U){if(!this.valid(t,n))throw Error(`typ.parse: Type '${t.name}' is not compatible with ${this.constraint.toCode()}`);return new W(this,t)}if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`typ.parse: expected TypeDef or Type, got ${typeof t}`);if(!(`name`in t)||typeof t.name!=`string`)throw Error(`typ.parse: TypeDef missing 'name' field`);let r;try{r=this.registry.parse(t,n)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`typ.parse: ${t}`)}if(!this.valid(r,n))throw Error(`typ.parse: Type '${r.name}' is not compatible with ${this.constraint.toCode()}`);let i=n??this.registry,a=r.references().refs.filter(e=>i.lookup(e)===void 0);if(a.length>0)throw Error(`typ.parse: no type named ${a.join(`, `)}`);return new W(this,r)}encode(e,t){return e.toJSON()}create(){return this.constraint}random(e){return this.constraint}compatibleType(t,n,r){return t instanceof e&&this.constraint.compatible(t.constraint,n,r)}or(t){return t instanceof e?new e(this.registry,this.registry.or([this.constraint,t.constraint])):this}narrow(e){return{}}props(){return{...super.props()}}toJSON(){return{name:e.NAME,generic:{T:this.constraint.toJSON()}}}clone(){return new e(this.registry,this.constraint.clone())}toCode(e,t){return this.docsPrefix(t)+`typ<${this.constraint.toCode(void 0,t)}>`}valueA(e){let t=this.registry.compatible(this.constraint);if(t.length===0&&this.constraint.name!==`any`)return R.never();let n;if(this.constraint.name===`any`)n=R.ref(`TypeDef`);else{let e=t.map(e=>cm(this.registry,e.name));e.push(lm()),e.push(um(t.map(e=>e.name))),n=R.union(e).describe(`A gin type definition ({ "name": ..., ... }) whose type fits ${this.constraint.toCode()}.`)}return n.refine(t=>{try{return this.parse(t,e?.scope),!0}catch(e){return e instanceof Error?e.message:String(e)}})}toNewA(e){return this.describeA(this.toA(e),e)}},Yg=class e extends U{static NAME=`void`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return e===void 0}parse(e){if(e!=null)throw new Nm({path:[],code:`void.invalid`,message:`void expects undefined/null, got ${typeof e}`,severity:`error`});return new W(this,void 0)}encode(e){return null}create(){}random(e){}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new Nm({path:[],code:`void.no-options`,message:`void has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),toText:e.method({},e.text(),`void.toText`),toBool:e.method({},e.bool(),`void.toBool`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`void`}valueA(){return R.null()}};function K(e){return e.get(`this`).raw}function Xg(e){return e.get(`this`)}function q(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];return r==null?r:$g(r)?r.raw:r}function Zg(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];if($g(r))return r}function Qg(e){let t=q(e,`epsilon`);return typeof t==`number`?t:0}function $g(e){return!!e&&typeof e==`object`&&`type`in e&&`raw`in e}function e_(e,t,n,r){let i=e.get(`yield`).raw,a=t.obj({key:{type:n},value:{type:r}});return(e,t)=>i(new W(a,{key:e,value:t}))}var t_={"type.toAny":(e,t)=>G(t.any(),K(e)),"any.typeOf":(e,t)=>G(t.text(),Xg(e).type.name),"any.is":(e,t)=>G(t.bool(),!0),"any.as":(e,t)=>{let n=Xg(e);return G(t.optional(n.type),n.raw)},"any.toText":(e,t)=>G(t.text(),String(K(e))),"any.toBool":(e,t)=>G(t.bool(),!!K(e)),"any.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"any.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`))},n_={"void.toText":(e,t)=>G(t.text(),`void`),"void.toBool":(e,t)=>G(t.bool(),!1)},r_={"null.toText":(e,t)=>G(t.text(),`null`),"null.toBool":(e,t)=>G(t.bool(),!1)},i_={"bool.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"bool.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"bool.and":(e,t)=>G(t.bool(),K(e)&&q(e,`other`)),"bool.or":(e,t)=>G(t.bool(),K(e)||q(e,`other`)),"bool.xor":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"bool.not":(e,t)=>G(t.bool(),!K(e)),"bool.toText":(e,t)=>{let n=K(e),r=q(e,`trueText`),i=q(e,`falseText`);return G(t.text(),n?r??`true`:i??`false`)},"bool.toNum":(e,t)=>{let n=K(e),r=q(e,`trueValue`),i=q(e,`falseValue`);return G(t.num(),n?r??1:i??0)}},a_={"num.eq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))<=Qg(e)),"num.neq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))>Qg(e)),"num.lt":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"num.lte":(e,t)=>G(t.bool(),K(e)<=q(e,`other`)),"num.gt":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"num.gte":(e,t)=>G(t.bool(),K(e)>=q(e,`other`)),"num.add":(e,t)=>G(t.num(),K(e)+q(e,`other`)),"num.sub":(e,t)=>G(t.num(),K(e)-q(e,`other`)),"num.mul":(e,t)=>G(t.num(),K(e)*q(e,`other`)),"num.div":(e,t)=>G(t.num(),K(e)/q(e,`other`)),"num.mod":(e,t)=>G(t.num(),K(e)%q(e,`other`)),"num.pow":(e,t)=>G(t.num(),K(e)**q(e,`other`)),"num.abs":(e,t)=>G(t.num(),Math.abs(K(e))),"num.neg":(e,t)=>G(t.num(),-K(e)),"num.sign":(e,t)=>G(t.num(),Math.sign(K(e))),"num.sqrt":(e,t)=>G(t.num(),Math.sqrt(K(e))),"num.min":(e,t)=>G(t.num(),Math.min(K(e),q(e,`other`))),"num.max":(e,t)=>G(t.num(),Math.max(K(e),q(e,`other`))),"num.clamp":(e,t)=>G(t.num(),Math.min(Math.max(K(e),q(e,`min`)),q(e,`max`))),"num.floor":(e,t)=>G(t.num(),Math.floor(K(e))),"num.ceil":(e,t)=>G(t.num(),Math.ceil(K(e))),"num.round":(e,t)=>G(t.num(),Math.round(K(e))),"num.isZero":(e,t)=>G(t.bool(),Math.abs(K(e))<=Qg(e)),"num.isPositive":(e,t)=>G(t.bool(),K(e)>Qg(e)),"num.isNegative":(e,t)=>G(t.bool(),K(e)<-Qg(e)),"num.isInteger":(e,t)=>G(t.bool(),Number.isInteger(K(e))),"num.isEven":(e,t)=>G(t.bool(),K(e)%2==0),"num.isOdd":(e,t)=>G(t.bool(),Math.abs(K(e))%2==1),"num.toText":(e,t)=>{let n=q(e,`precision`),r=n==null?String(K(e)):K(e).toFixed(n);return G(t.text(),r)},"num.toBool":(e,t)=>G(t.bool(),K(e)!==0),"num.loop":async(e,t)=>{let n=K(e),r=t.num(),i=e_(e,t,r,r),a=Math.abs(Math.trunc(n)),o=n<0?-1:1;for(let e=0;e<a;e++){let t=e*o,n=Object.is(t,-0)?0:t;await i(G(r,e),G(r,n))}return G(t.void(),void 0)}},o_={"text.length":(e,t)=>G(t.num({whole:!0,min:0}),K(e).length),"text.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"text.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"text.contains":(e,t)=>G(t.bool(),K(e).includes(q(e,`search`))),"text.startsWith":(e,t)=>G(t.bool(),K(e).startsWith(q(e,`prefix`))),"text.endsWith":(e,t)=>G(t.bool(),K(e).endsWith(q(e,`suffix`))),"text.trim":(e,t)=>G(t.text(),K(e).trim()),"text.trimStart":(e,t)=>G(t.text(),K(e).trimStart()),"text.trimEnd":(e,t)=>G(t.text(),K(e).trimEnd()),"text.upper":(e,t)=>G(t.text(),K(e).toUpperCase()),"text.lower":(e,t)=>G(t.text(),K(e).toLowerCase()),"text.slice":(e,t)=>{let n=q(e,`start`),r=q(e,`end`);return G(t.text(),K(e).slice(n,r))},"text.replace":(e,t)=>{let n=q(e,`search`),r=q(e,`replacement`);return G(t.text(),K(e).split(n).join(r))},"text.split":(e,t)=>{let n=K(e).split(q(e,`separator`));return G(t.list(t.text()),n.map(e=>G(t.text(),e)))},"text.concat":(e,t)=>G(t.text(),K(e)+q(e,`other`)),"text.repeat":(e,t)=>G(t.text(),K(e).repeat(q(e,`count`))),"text.indexOf":(e,t)=>{let n=q(e,`from`);return G(t.num(),K(e).indexOf(q(e,`search`),n))},"text.lastIndexOf":(e,t)=>{let n=q(e,`from`);return G(t.num(),K(e).lastIndexOf(q(e,`search`),n))},"text.match":(e,t)=>{let n=q(e,`pattern`),r=K(e).match(new RegExp(n,`g`))??[];return G(t.list(t.text()),r.map(e=>G(t.text(),e)))},"text.test":(e,t)=>{let n=q(e,`pattern`);return G(t.bool(),new RegExp(n).test(K(e)))},"text.isEmpty":(e,t)=>G(t.bool(),K(e).length===0),"text.isNotEmpty":(e,t)=>G(t.bool(),K(e).length>0),"text.toNum":(e,t)=>G(t.num(),Number(K(e))),"text.toBool":(e,t)=>G(t.bool(),K(e).length>0),"text.charAt":(e,t)=>{let n=e.get(`key`).raw,r=K(e)[n];if(r===void 0)throw Error(`text[${n}]: index out of range`);return G(t.text({minLength:1,maxLength:1}),r)},"text.chars":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=t.text({minLength:1,maxLength:1}),a=e_(e,t,r,i);for(let e=0;e<n.length;e++)await a(G(r,e),G(i,n[e]));return G(t.void(),void 0)}},s_=e=>Xg(e).type.item,c_={"list.length":(e,t)=>G(t.num({whole:!0,min:0}),K(e).length),"list.indexGet":e=>{let t=e.get(`key`).raw,n=K(e);if(t<0||t>=n.length)throw Error(`list[${t}]: index out of range`);return n[t]},"list.indexSet":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`),i=K(e);if(n<0||n>=i.length)throw Error(`list[${n}] =: index out of range`);return i[n]=r,G(t.void(),void 0)},"list.iterate":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=e_(e,t,r,s_(e)),a=G(t.void(),void 0);for(let e=0;e<n.length;e++)await i(G(r,e),n[e]);return a},"list.at":(e,t)=>{let n=q(e,`index`),r=K(e);return n<0||n>=r.length?G(t.optional(s_(e)),void 0):G(t.optional(s_(e)),r[n].raw)},"list.push":(e,t)=>(K(e).push(Zg(e,`value`)),G(t.void(),void 0)),"list.pop":(e,t)=>{let n=K(e).pop();return G(t.optional(s_(e)),n?n.raw:void 0)},"list.shift":(e,t)=>{let n=K(e).shift();return G(t.optional(s_(e)),n?n.raw:void 0)},"list.unshift":(e,t)=>(K(e).unshift(Zg(e,`value`)),G(t.void(),void 0)),"list.insert":(e,t)=>(K(e).splice(q(e,`index`),0,Zg(e,`value`)),G(t.void(),void 0)),"list.remove":e=>K(e).splice(q(e,`index`),1)[0],"list.clear":(e,t)=>(K(e).length=0,G(t.void(),void 0)),"list.slice":e=>{let t=Xg(e).type,n=q(e,`start`),r=q(e,`end`);return G(t,K(e).slice(n,r))},"list.concat":e=>{let t=Xg(e).type,n=q(e,`other`);return G(t,K(e).concat(n))},"list.reverse":e=>{let t=Xg(e).type;return G(t,[...K(e)].reverse())},"list.join":(e,t)=>{let n=q(e,`separator`)??`,`;return G(t.text(),K(e).map(e=>String(e.raw)).join(n))},"list.indexOf":(e,t)=>{let n=Zg(e,`value`).raw,r=K(e).findIndex(e=>e.raw===n);return G(t.num(),r)},"list.contains":(e,t)=>{let n=Zg(e,`value`).raw,r=K(e);return G(t.bool(),r.some(e=>e.raw===n))},"list.unique":e=>{let t=Xg(e).type,n=new Set,r=[];for(let t of K(e))n.has(t.raw)||(n.add(t.raw),r.push(t));return G(t,r)},"list.duplicates":e=>{let t=Xg(e).type,n=new Set,r=new Set,i=[];for(let t of K(e))n.has(t.raw)?r.has(t.raw)||(r.add(t.raw),i.push(t)):n.add(t.raw);return G(t,i)},"list.map":async(e,t)=>{let n=K(e),r=Zg(e,`fn`).raw,i=s_(e),a=[],o=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++){let i=new W(o,{value:n[e],index:G(t.num(),e)});a.push(await r(i))}return G(t.list(t.any()),a)},"list.filter":async e=>{let t=Xg(e).type,n=K(e),r=Zg(e,`fn`).raw,i=[],a=t.registry.obj({value:{type:t.item},index:{type:t.registry.num()}});for(let e=0;e<n.length;e++)(await r(new W(a,{value:n[e],index:G(t.registry.num(),e)}))).raw&&i.push(n[e]);return G(t,i)},"list.find":async(e,t)=>{let n=K(e),r=Zg(e,`fn`).raw,i=s_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if((await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.optional(i),n[e].raw);return G(t.optional(i),void 0)},"list.reduce":async(e,t)=>{let n=K(e),r=Zg(e,`fn`),i=Zg(e,`initial`),a=r.raw,o=s_(e),s=i,c=t.obj({acc:{type:t.any()},value:{type:o},index:{type:t.num()}});for(let e=0;e<n.length;e++)s=await a(new W(c,{acc:s,value:n[e],index:G(t.num(),e)}));return s},"list.some":async(e,t)=>{let n=K(e),r=Zg(e,`fn`).raw,i=s_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if((await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.bool(),!0);return G(t.bool(),!1)},"list.every":async(e,t)=>{let n=K(e),r=Zg(e,`fn`).raw,i=s_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if(!(await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.bool(),!1);return G(t.bool(),!0)},"list.sort":async e=>{let t=Xg(e).type,n=[...K(e)],r=Zg(e,`fn`);if(r&&typeof r.raw==`function`){let e=r.raw,i=t.registry.obj({a:{type:t.item},b:{type:t.item}}),a=[];for(let t=0;t<n.length;t++){let r=0;for(let a=0;a<n.length;a++)t!==a&&(await e(new W(i,{a:n[t],b:n[a]}))).raw>0&&r++;a.push({index:t,key:r})}return a.sort((e,t)=>e.key-t.key),G(t,a.map(e=>n[e.index]))}return G(t,n.sort((e,t)=>{let n=e.raw,r=t.raw;return n<r?-1:+(n>r)}))},"list.isEmpty":(e,t)=>G(t.bool(),K(e).length===0),"list.isNotEmpty":(e,t)=>G(t.bool(),K(e).length>0),"list.first":(e,t)=>{let n=K(e);return G(t.optional(s_(e)),n.length>0?n[0].raw:void 0)},"list.last":(e,t)=>{let n=K(e);return G(t.optional(s_(e)),n.length>0?n[n.length-1].raw:void 0)}},l_={"list.indexSet":B.STATE,"list.push":B.STATE,"list.pop":B.STATE,"list.shift":B.STATE,"list.unshift":B.STATE,"list.insert":B.STATE,"list.remove":B.STATE,"list.clear":B.STATE},u_=e=>Xg(e).type.value,d_={"map.size":(e,t)=>G(t.num({whole:!0,min:0}),K(e).size),"map.indexGet":e=>{let t=e.get(`key`).raw,n=K(e).get(t);if(!n)throw Error(`map[${String(t)}]: key not found`);return n[1]},"map.indexSet":(e,t)=>{let n=e.get(`key`),r=e.get(`value`);return K(e).set(n.raw,[n,r]),G(t.void(),void 0)},"map.iterate":async(e,t)=>{let n=K(e),r=n.values().next().value,i=e_(e,t,r?r[0].type:t.any(),r?r[1].type:t.any());for(let[,[e,t]]of n)await i(e,t);return G(t.void(),void 0)},"map.at":(e,t)=>{let n=q(e,`key`),r=K(e).get(n);return G(t.optional(u_(e)),r?r[1].raw:void 0)},"map.has":(e,t)=>G(t.bool(),K(e).has(q(e,`key`))),"map.delete":(e,t)=>G(t.bool(),K(e).delete(q(e,`key`))),"map.clear":(e,t)=>(K(e).clear(),G(t.void(),void 0)),"map.keys":(e,t)=>{let n=K(e),r=Xg(e).type.key,i=[];for(let[,[e]]of n)i.push(e);return G(t.list(r),i)},"map.values":(e,t)=>{let n=K(e),r=Xg(e).type.value,i=[];for(let[,[,e]]of n)i.push(e);return G(t.list(r),i)},"map.isEmpty":(e,t)=>G(t.bool(),K(e).size===0),"map.isNotEmpty":(e,t)=>G(t.bool(),K(e).size>0)},f_={"map.indexSet":B.STATE,"map.delete":B.STATE,"map.clear":B.STATE},p_=e=>Xg(e).type.elements,m_={"tuple.at":e=>{let t=e.get(`key`).raw,n=K(e)[t];return n instanceof W?n:G(p_(e)[t]??G.prototype,n)},"tuple.setAt":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`);return K(e)[n]=r,G(t.void(),void 0)},"tuple.iterate":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=n.map(e=>e.type),a=e_(e,t,r,i.length===0?t.any():i.length===1?i[0]:t.or(i));for(let e=0;e<n.length;e++)await a(G(r,e),n[e]);return G(t.void(),void 0)},"tuple.length":(e,t)=>G(t.num({whole:!0}),K(e).length),"tuple.first":e=>{let t=K(e),n=p_(e),r=t[0];return r instanceof W?r:G(n[0],r)},"tuple.last":e=>{let t=K(e),n=p_(e),r=t[t.length-1];return r instanceof W?r:G(n[n.length-1],r)},"tuple.toList":(e,t)=>G(t.list(t.any()),[...K(e)])},h_={"tuple.setAt":B.STATE},g_=e=>Xg(e).type.fields,__={"object.indexGet":e=>{let t=e.get(`key`).raw,n=g_(e)[t];if(!n)throw Error(`object[${t}]: no such field`);let r=K(e)[t];return r instanceof W?r:G(n.type,r)},"object.indexSet":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`);return K(e)[n]=r,G(t.void(),void 0)},"object.iterate":async(e,t)=>{let n=K(e),r=g_(e),i=t.text(),a=Object.values(r).map(e=>e.type),o=e_(e,t,i,a.length===0?t.any():a.length===1?a[0]:t.or(a));for(let[e]of Object.entries(r)){let t=n[e];t instanceof W&&await o(G(i,e),t)}return G(t.void(),void 0)},"object.keys":(e,t)=>{let n=Object.keys(g_(e));return G(t.list(t.text()),n.map(e=>G(t.text(),e)))},"object.values":(e,t)=>{let n=K(e),r=Object.keys(g_(e)).map(e=>n[e]??G(t.any(),void 0));return G(t.list(t.any()),r)},"object.entries":(e,t)=>{let n=K(e),r=Object.keys(g_(e)).map(e=>G(t.any(),[e,n[e]?.raw]));return G(t.list(t.any()),r)},"object.has":(e,t)=>G(t.bool(),Object.hasOwn(g_(e),q(e,`key`))),"object.eq":(e,t)=>G(t.bool(),y_(Xg(e),e.get(`args`).raw)),"object.neq":(e,t)=>G(t.bool(),!y_(Xg(e),e.get(`args`).raw)),"object.toText":(e,t)=>{let n=K(e),r=g_(e),i={};for(let[e]of Object.entries(r)){let t=n[e];i[e]=t?t.type.encode(t.raw):void 0}return G(t.text(),JSON.stringify(i))}},v_={"object.indexSet":B.STATE};function y_(e,t){let n=t.other,r=n instanceof W?n.raw:n;return b_(e.raw,r)}function b_(e,t){if(e instanceof W&&(e=e.raw),t instanceof W&&(t=t.raw),e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!b_(e[n],t[n]))return!1;return!0}let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!b_(e[r],t[r]))return!1;return!0}var x_={"optional.value":e=>{let t=K(e);if(t===void 0)throw Error(`optional.value: value is undefined`);return G(Xg(e).type.inner,t)},"optional.has":(e,t)=>G(t.bool(),K(e)!==void 0),"optional.or":e=>{let t=K(e),n=Xg(e).type.inner;return t===void 0?Zg(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"optional.map":async(e,t)=>{let n=K(e),r=Xg(e).type.inner;if(n===void 0)return G(t.optional(t.any()),void 0);let i=Zg(e,`fn`).raw,a=await i(new W(t.obj({value:{type:r}}),{value:G(r,n)}));return G(t.optional(t.any()),a.raw)}},S_={"nullable.value":e=>{let t=K(e);if(t===null)throw Error(`nullable.value: value is null`);return G(Xg(e).type.inner,t)},"nullable.isNull":(e,t)=>G(t.bool(),K(e)===null),"nullable.or":e=>{let t=K(e),n=Xg(e).type.inner;return t===null?Zg(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"nullable.map":async(e,t)=>{let n=K(e),r=Xg(e).type.inner;if(n===null)return G(t.nullable(t.any()),null);let i=Zg(e,`fn`).raw,a=await i(new W(t.obj({value:{type:r}}),{value:G(r,n)}));return G(t.nullable(t.any()),a.raw)}},C_={"not.typeOf":(e,t)=>G(t.text(),Xg(e).type.name),"not.toText":(e,t)=>G(t.text(),String(K(e)))},w_={"enum.name":(e,t)=>{let n=K(e),r=Xg(e).type,i=Object.entries(r.options.values).find(([,e])=>e===n);return G(t.text(),i?i[0]:``)},"enum.value":e=>{let t=Xg(e).type;return G(t.value,K(e))},"enum.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"enum.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"enum.toText":(e,t)=>G(t.text(),String(K(e)))},T_={"date.year":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()),"date.month":(e,t)=>G(t.num({whole:!0,min:1,max:12}),K(e).getUTCMonth()+1),"date.day":(e,t)=>G(t.num({whole:!0,min:1,max:31}),K(e).getUTCDate()),"date.dayOfWeek":(e,t)=>G(t.num({whole:!0,min:0,max:6}),K(e).getUTCDay()),"date.dayOfYear":(e,t)=>{let n=K(e),r=Date.UTC(n.getUTCFullYear(),0,0);return G(t.num({whole:!0,min:1,max:366}),Math.floor((n.getTime()-r)/864e5))},"date.eq":(e,t)=>G(t.bool(),K(e).getTime()===q(e,`other`).getTime()),"date.neq":(e,t)=>G(t.bool(),K(e).getTime()!==q(e,`other`).getTime()),"date.before":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"date.after":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"date.addDays":(e,t)=>{let n=new Date(K(e));return n.setUTCDate(n.getUTCDate()+q(e,`days`)),G(t.date(),n)},"date.addMonths":(e,t)=>{let n=new Date(K(e));return n.setUTCMonth(n.getUTCMonth()+q(e,`months`)),G(t.date(),n)},"date.addYears":(e,t)=>{let n=new Date(K(e));return n.setUTCFullYear(n.getUTCFullYear()+q(e,`years`)),G(t.date(),n)},"date.diffDays":(e,t)=>G(t.num({whole:!0}),Math.round((K(e).getTime()-q(e,`other`).getTime())/864e5)),"date.diffMonths":(e,t)=>{let n=K(e),r=q(e,`other`);return G(t.num({whole:!0}),(n.getUTCFullYear()-r.getUTCFullYear())*12+(n.getUTCMonth()-r.getUTCMonth()))},"date.diffYears":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()-q(e,`other`).getUTCFullYear()),"date.toText":(e,t)=>G(t.text(),K(e).toISOString().slice(0,10))},E_={"timestamp.year":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()),"timestamp.month":(e,t)=>G(t.num({whole:!0}),K(e).getUTCMonth()+1),"timestamp.day":(e,t)=>G(t.num({whole:!0}),K(e).getUTCDate()),"timestamp.hour":(e,t)=>G(t.num({whole:!0,min:0,max:23}),K(e).getUTCHours()),"timestamp.minute":(e,t)=>G(t.num({whole:!0,min:0,max:59}),K(e).getUTCMinutes()),"timestamp.second":(e,t)=>G(t.num({whole:!0,min:0,max:59}),K(e).getUTCSeconds()),"timestamp.millisecond":(e,t)=>G(t.num({whole:!0,min:0,max:999}),K(e).getUTCMilliseconds()),"timestamp.eq":(e,t)=>G(t.bool(),K(e).getTime()===q(e,`other`).getTime()),"timestamp.before":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"timestamp.after":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"timestamp.addDuration":(e,t)=>G(t.timestamp(),new Date(K(e).getTime()+q(e,`duration`))),"timestamp.subDuration":(e,t)=>G(t.timestamp(),new Date(K(e).getTime()-q(e,`duration`))),"timestamp.diff":(e,t)=>G(t.duration(),K(e).getTime()-q(e,`other`).getTime()),"timestamp.toDate":(e,t)=>G(t.date(),new Date(K(e).toISOString().slice(0,10))),"timestamp.toEpoch":(e,t)=>G(t.num(),K(e).getTime()),"timestamp.toText":(e,t)=>G(t.text(),K(e).toISOString())},D_=864e5,O_=36e5,k_=6e4,A_=1e3,j_={"duration.init":(e,t)=>{let n=q(e,`days`)??0,r=q(e,`hours`)??0,i=q(e,`minutes`)??0,a=q(e,`seconds`)??0,o=q(e,`ms`)??0;return G(t.duration(),n*D_+r*O_+i*k_+a*A_+o)},"duration.totalSeconds":(e,t)=>G(t.num(),K(e)/1e3),"duration.totalMinutes":(e,t)=>G(t.num(),K(e)/6e4),"duration.totalHours":(e,t)=>G(t.num(),K(e)/36e5),"duration.totalDays":(e,t)=>G(t.num(),K(e)/864e5),"duration.days":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/D_)),"duration.hours":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/O_)%24),"duration.minutes":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/k_)%60),"duration.seconds":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/A_)%60),"duration.ms":(e,t)=>G(t.num({whole:!0}),K(e)%A_),"duration.toText":(e,t)=>{let n=K(e),r=Math.trunc(n/D_),i=Math.trunc(n%D_/O_),a=Math.trunc(n%O_/k_),o=Math.trunc(n%k_/A_),s=[];return r&&s.push(`${r}d`),i&&s.push(`${i}h`),a&&s.push(`${a}m`),(o||s.length===0)&&s.push(`${o}s`),G(t.text(),s.join(` `))}},M_=e=>e>>>24&255,N_=e=>e>>>16&255,P_=e=>e>>>8&255,F_=e=>(e&255)/255,I_=(e,t,n,r)=>(Math.round(e)&255)<<24|(Math.round(t)&255)<<16|(Math.round(n)&255)<<8|Math.round(r*255)&255,L_={"color.init":(e,t)=>{let n=q(e,`r`),r=q(e,`g`),i=q(e,`b`),a=q(e,`a`)??1;return G(t.color(),I_(n,r,i,a)>>>0)},"color.r":(e,t)=>G(t.num(),M_(K(e))),"color.g":(e,t)=>G(t.num(),N_(K(e))),"color.b":(e,t)=>G(t.num(),P_(K(e))),"color.a":(e,t)=>G(t.num(),F_(K(e))),"color.hue":(e,t)=>G(t.num(),R_(K(e)).h),"color.saturation":(e,t)=>G(t.num(),R_(K(e)).s),"color.lightness":(e,t)=>G(t.num(),R_(K(e)).l),"color.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"color.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"color.lighten":(e,t)=>G(t.color(),B_(K(e),q(e,`amount`))),"color.darken":(e,t)=>G(t.color(),B_(K(e),-q(e,`amount`))),"color.saturate":(e,t)=>G(t.color(),V_(K(e),q(e,`amount`))),"color.desaturate":(e,t)=>G(t.color(),V_(K(e),-q(e,`amount`))),"color.opacity":(e,t)=>G(t.color(),K(e)&4294967040|Math.round(q(e,`alpha`)*255)&255),"color.invert":(e,t)=>{let n=K(e);return G(t.color(),I_(255-M_(n),255-N_(n),255-P_(n),F_(n))>>>0)},"color.mix":(e,t)=>{let n=K(e),r=q(e,`other`),i=q(e,`weight`)??.5;return G(t.color(),I_(M_(n)*(1-i)+M_(r)*i,N_(n)*(1-i)+N_(r)*i,P_(n)*(1-i)+P_(r)*i,F_(n)*(1-i)+F_(r)*i)>>>0)},"color.complement":(e,t)=>G(t.color(),H_(K(e),180)),"color.toHex":(e,t)=>G(t.text(),`#`+K(e).toString(16).padStart(8,`0`)),"color.toRgb":(e,t)=>{let n=K(e);return G(t.text(),`rgb(${M_(n)},${N_(n)},${P_(n)})`)},"color.toHsl":(e,t)=>{let{h:n,s:r,l:i}=R_(K(e));return G(t.text(),`hsl(${Math.round(n)},${Math.round(r*100)}%,${Math.round(i*100)}%)`)},"color.toText":(e,t)=>G(t.text(),`#`+K(e).toString(16).padStart(8,`0`))};function R_(e){let t=M_(e)/255,n=N_(e)/255,r=P_(e)/255,i=Math.max(t,n,r),a=Math.min(t,n,r),o=(i+a)/2,s=0,c=0;if(i!==a){let e=i-a;switch(c=o>.5?e/(2-i-a):e/(i+a),i){case t:s=(n-r)/e+(n<r?6:0);break;case n:s=(r-t)/e+2;break;case r:s=(t-n)/e+4}s*=60}return{h:s,s:c,l:o}}function z_(e,t,n,r){let i=(1-Math.abs(2*n-1))*t,a=i*(1-Math.abs(e/60%2-1)),o=n-i/2,s=0,c=0,l=0;return e<60?[s,c,l]=[i,a,0]:e<120?[s,c,l]=[a,i,0]:e<180?[s,c,l]=[0,i,a]:e<240?[s,c,l]=[0,a,i]:e<300?[s,c,l]=[a,0,i]:[s,c,l]=[i,0,a],I_((s+o)*255,(c+o)*255,(l+o)*255,r)}function B_(e,t){let{h:n,s:r,l:i}=R_(e);return z_(n,r,Math.max(0,Math.min(1,i+t)),F_(e))>>>0}function V_(e,t){let{h:n,s:r,l:i}=R_(e);return z_(n,Math.max(0,Math.min(1,r+t)),i,F_(e))>>>0}function H_(e,t){let{h:n,s:r,l:i}=R_(e);return z_((n+t+360)%360,r,i,F_(e))>>>0}function U_(e){let t=[{impls:t_},{impls:n_},{impls:r_},{impls:i_},{impls:a_},{impls:o_},{impls:c_,effects:l_},{impls:d_,effects:f_},{impls:m_,effects:h_},{impls:__,effects:v_},{impls:x_},{impls:S_},{impls:C_},{impls:w_},{impls:T_},{impls:E_},{impls:j_},{impls:L_}];for(let n of t)for(let[t,r]of Object.entries(n.impls)){let i=n.effects?.[t]??B.NONE;e.setNative(t,r,i)}return e}var W_=class e extends $m{constructor(e,t){super(),this.type=e,this.value=t}type;value;static KIND=`new`;kind=e.KIND;static from(t,n){return new e(n.registry.parse(t.type,n),t.value).withComment(t.comment)}async evaluate(e,t){let n=this.type,r=n.init();if(this.value!==void 0){if(r){let i=r.args.parse(this.value),a=G(n,n.create()),o=t.child({this:a,args:i}),s=await r.run.evaluate(e,o);return s===void 0||s.raw===void 0?a:new W(n,s.raw)}let i=await n.newFill(this.value,e,t);if(i instanceof W)return e.registry.parseValue(i,n);let a=n.parse(i);return a.type===n?a:new W(n,a.raw)}return G(n,n.create())}typeOf(e,t){return this.type}validateWalk(e,t,n,r){return this.value===void 0&&J_(this.type)&&n.warn(`new.value.missing`,`\`new ${this.type.name}\` has no \`value\` \u2014 every field will fall to its type default (0 / "" / null). Provide a \`value\` matching the type's shape.`),this.value!==void 0&&n.at([`value`],()=>this.type.validateNewValue(this.value,e,t,n,r)),this.type}toCode(e,t={}){let n=this.type.toCode(void 0,t),r;return r=this.value===void 0?this.type.isOptional()?`undefined`:`new ${n}()`:typeof this.value==`number`||typeof this.value==`boolean`?String(this.value):typeof this.value==`string`?JSON.stringify(this.value):this.value===null?`null`:G_(this.value,e,this.type,t),this.commentPrefix(t)+r}toJSON(){return this.withCommentOn({kind:`new`,type:this.type.toJSON(),value:this.value})}toJSONCode(e=[],t=2,n=0){let r=this.type.toJSONCode([...e,`type`],t,n+1),i=this.value===void 0?void 0:(()=>{let e=JSON.stringify(this.value,null,t),r=n+1;return r>0?e.replace(/\n/g,`
105
- `+` `.repeat(r*t)):e})(),a=i===void 0?void 0:Fm(i,{path:[...e,`value`]});return V.jsonObject([{key:`kind`,value:V.jsonString(`new`)},{key:`type`,value:r},{key:`value`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.type.clone(),this.value).withComment(this.comment)}effects(){return this.type.newEffects(this.value)}complexity(){return this.type.newComplexity(this.value)}};function G_(e,t,n,r={}){if(t&&e&&typeof e==`object`&&!Array.isArray(e)&&`kind`in e&&typeof e.kind==`string`){let n=e.kind;if(t.exprClass(n))try{return t.parseExpr(e).toCode(t,{...r,expectsValue:!0})}catch{}}let i=n?n.toCode(void 0,r):`<inferred>`;if(Array.isArray(e)){let i=n?.item,a=Bh(e.map(e=>K_(e,t,i,r)));return a.startsWith(`
106
- `),`[${a}]`}if(e&&typeof e==`object`){let a=n?.fields,o=Object.entries(e);if(o.length===0)return`new ${i}()`;let s=Bh(o.map(([e,n])=>`${e}: ${K_(n,t,a?.[e]?.type,r)}`));return s.startsWith(`
107
- `)?`new ${i} {${s}}`:`new ${i} { ${s} }`}return JSON.stringify(e)}function K_(e,t,n,r={}){return e===null?`null`:e===void 0?`undefined`:typeof e==`string`?JSON.stringify(e):typeof e==`number`||typeof e==`boolean`?String(e):G_(e,t,n,r)}function q_(e){if(e instanceof vg)return e;let t=e.base;return t?q_(t):void 0}function J_(e){let t=q_(e);if(!t)return!1;for(let e of Object.values(t.fields))if(!e.type.isOptional())return!0;return!1}function Y_(e,t){let n=e.call(t);if(!n)return!1;let r=n.args;if(!(r instanceof vg))return!0;for(let e of Object.values(r.fields))if(!e.type.isOptional())return!1;return!0}function X_(e,t,n,r){if(!e)return;let i=e.args;if(i instanceof vg)for(let[e,a]of Object.entries(i.fields))a.type.isOptional()||e in t||n.at(r,()=>n.error(`call.missing-arg`,`missing required argument '${e}'`))}function Z_(e,t){return t.type instanceof Sg?t.type.simplify(e.scope):t.type}function Q_(e,t){let n=e.raw;if(!n||typeof n!=`object`)return;let r=n[t];return r instanceof W?r:void 0}function $_(e){return e instanceof vg||e instanceof jg||e instanceof gg&&$_(e.base)}function ev(e,t,n){let r=[];for(let e=n;e<t.length;e++){let n=t[e];if(n instanceof nv)r.push(n.prop);else break}if(r.length===0)return``;let i=Lp(e,e=>Object.keys(e.props()),e=>{let t=[];for(let n of Object.keys(e.props())){let r=e.prop(n)?.type;r&&$_(r)&&t.push([n,r])}return t},r);if(!i||i.length===0)return``;if(i.length===1)return` \u2014 did you mean \`${i[0]}\`?`;let a=[];for(let e=0;e<n;e++){let n=t[e];if(n instanceof nv)a.push(n.prop);else{a.length=0;break}}return` \u2014 did you mean \`${[...a,...i].join(`.`)}\`?`}var tv=class{static from(e,t){if(qp(e),`prop`in e)return new nv(e.prop);let n=t.registry;if(`args`in e){let r={};for(let[i,a]of Object.entries(e.args??{}))r[i]=n.parseExpr(a,t);return new rv(r,e.generic,e.catch?n.parseExpr(e.catch,t):void 0)}if(`key`in e)return new iv(n.parseExpr(e.key,t));throw Error(`PathStep.from: unknown step shape`)}},nv=class e extends tv{constructor(e){super(),this.prop=e}prop;toJSON(){return{prop:this.prop}}clone(){return new e(this.prop)}complexity(){return 1}},rv=class e extends tv{constructor(e,t,n){super(),this.args=e,this.generic=t,this.catch_=n}args;generic;catch_;resolvedEffects;toJSON(){let e={};for(let[t,n]of Object.entries(this.args))e[t]=n.toJSON();let t={args:e};return this.generic&&(t.generic=this.generic),this.catch_&&(t.catch=this.catch_.toJSON()),t}clone(){let t={};for(let[e,n]of Object.entries(this.args))t[e]=n.clone();return new e(t,this.generic,this.catch_?.clone())}callSiteScope(e){if(!this.generic||Object.keys(this.generic).length===0)return e.scope;let t={},n=e.generic??{};for(let[r,i]of Object.entries(this.generic)){let a=e.scope.parse(i),o=n[r];if(o&&(o.name!==`alias`||o.options?.name!==r)&&!o.compatible(a))throw Error(`path: generic '${r}' binding '${a.toCode()}' does not satisfy constraint '${o.toCode()}'`);t[r]=a}return new Qm(e.scope,t)}complexity(){let e=1;for(let t of Object.values(this.args))e+=t.complexity();return this.catch_&&(e+=this.catch_.complexity()),e}async buildArgsValue(e,t,n){let r=this.callSiteScope(e),i=e.call?.(r)?.args??n.registry.obj({}),a={};for(let[e,r]of Object.entries(this.args))a[e]=await r.evaluate(n,t);return new W(i,a)}},iv=class e extends tv{constructor(e){super(),this.key=e}key;toJSON(){return{key:this.key.toJSON()}}clone(){return new e(this.key.clone())}complexity(){return 1+this.key.complexity()}},av=class e{constructor(e){this.steps=e}steps;static from(t,n){return new e(t.map(e=>tv.from(e,n)))}toJSON(){return this.steps.map(e=>e.toJSON())}toJSONCode(e=[],t=2,n=0){let r=this.steps.map((r,i)=>sv(r,[...e,i],t,n+1));return V.jsonArray(r,{path:e},n,t)}clone(){return new e(this.steps.map(e=>e.clone()))}complexity(){let e=0;for(let t of this.steps)e+=t.complexity();return e}forEachExpr(e){for(let t of this.steps)if(t instanceof rv){for(let n of Object.values(t.args))e(n);t.catch_&&e(t.catch_)}else t instanceof iv&&e(t.key)}toCode(e,t={}){return this.toGinCode(e,t).toString()}toGinCode(e,t={},n=[]){if(this.steps.length===0)return new V(``);let r=new V(``);for(let i=0;i<this.steps.length;i++){let a=this.steps[i],o=[...n,`path`,i];if(a instanceof nv){let e=i===0?a.prop:`.${a.prop}`;r=i===0?Fm(e,{path:o}):H`${r}${Fm(e,{path:o})}`}else if(a instanceof rv){let n=Object.entries(a.args),i;if(n.length===0)i=new V(`()`);else{let r=n.map(([n,r])=>{let i=[...o,`args`,n];return H`${n}: ${r.toGinCode(e,{...t,expectsValue:!0},i)}`});i=Bh(r.map(e=>e.toString())).startsWith(`
108
- `)?H`({\n ${Im(r,`,
109
- `)}\n})`:H`({ ${Im(r,`, `)} })`}if(r=H`${r}${Fm(i,{path:o})}`,a.catch_){let n=a.catch_.toGinCode(e,{...t,expectsValue:!0},[...o,`catch`]);r=H`${r}.catch((error) => ${n})`}}else if(a instanceof iv){let n=a.key.toGinCode(e,{...t,expectsValue:!0},[...o,`key`]);r=H`${r}${Fm(H`[${n}]`,{path:o})}`}}return r}async walk(e,t,n={mode:`get`}){if(this.steps.length===0)throw Error(`Path.walk: empty path`);let r=()=>G(t.registry.bool(),!1),i=()=>G(t.registry.bool(),!0),a=null,o=0;for(;o<this.steps.length;){let s=this.steps[o],c=o===this.steps.length-1;if(n.mode===`set`&&a!==null&&ov(a)&&!(s instanceof rv))return r();if(s instanceof nv){if(a===null){let t=e.get(s.prop);if(t===void 0)throw Error(`path: unknown variable '${s.prop}'${Pp(s.prop,e.names())}`);a=t,o++;continue}let r=a.type.prop(s.prop);if(!r){let e=n.mode===`get`?Q_(a,s.prop):void 0;if(e){a=e,o++;continue}throw Error(`path: no prop '${s.prop}' on type '${a.type.name}'${ev(a.type,this.steps,o)}`)}let l=Z_(a.type,r),u=this.steps[o+1],d=u instanceof rv;if(d&&l.call()){let c=await u.buildArgsValue(l,e,t);if(o+1===this.steps.length-1&&n.mode===`set`)return await r.invokeMethodSet(a,s.prop,c,n.setValue,e,t,l),i();try{a=await r.invokeMethod(a,s.prop,c,e,t,l)}catch(n){if(n instanceof ph&&u.catch_){let r=e.child({error:n.error});a=await u.catch_.evaluate(t,r)}else throw n}o+=2;continue}if(!d&&Y_(l)){let u=await new rv({},void 0,void 0).buildArgsValue(l,e,t);if(c&&n.mode===`set`)return await r.invokeMethodSet(a,s.prop,u,n.setValue,e,t,l),i();a=await r.invokeMethod(a,s.prop,u,e,t,l),o++;continue}if(c&&n.mode===`set`)return await r.write(a,s.prop,n.setValue,e,t),i();a=await r.read(a,s.prop,e,t,l),o++}else if(s instanceof iv){if(a===null)throw Error(`path: [key] cannot be the first step`);let r=a.type.get();if(!r)throw Error(`path: type '${a.type.name}' has no indexed access`);let l=await s.key.evaluate(t,e);if(c&&n.mode===`set`)return await r.indexWrite(a,l,n.setValue,e,t),i();a=await r.indexRead(a,l,e,t),o++}else if(s instanceof rv){if(a===null)throw Error(`path: (args) cannot be the first step`);let r=a.raw,l=a.type,u=l.call(),d=await s.buildArgsValue(l,e,t);if(c&&n.mode===`set`){if(!u?.set)throw Error(`path: call on type '${l.name}' has no call.set`);let r=u.set,a=async i=>{let o=new W(l,a);return await r.evaluate(t,e.child({args:i,value:n.setValue,recurse:o})),G(t.registry.void(),void 0)};return await a(d),i()}try{if(typeof r==`function`)a=await r(d);else if(u?.get){let n=u.get,r=async i=>{let a=new W(l,r);try{return await n.evaluate(t,e.child({args:i,recurse:a}))}catch(e){if(e instanceof dh)return e.value??G(t.registry.void(),void 0);throw e}};a=await r(d)}else throw Error(`path: value of type '${l.name}' is not callable`)}catch(n){if(n instanceof ph&&s.catch_){let r=e.child({error:n.error});a=await s.catch_.evaluate(t,r)}else throw n}o++}else throw Error(`path: unknown step at index ${o}`)}return a}typeOf(e,t){if(this.steps.length===0)return e.registry.any();let n=null,r=0;for(;r<this.steps.length;){let i=this.steps[r];if(i instanceof nv){if(n===null){n=t.get(i.prop)??e.registry.any(),r++;continue}let a=n.prop(i.prop);if(!a)return e.registry.any();let o=Z_(n,a),s=this.steps[r+1];if(s instanceof rv&&o.call()){let t=s.callSiteScope(o),i=o.call(t)?.returns;n=i?.simplify(t)??i??e.registry.any(),r+=2;continue}if(!(s instanceof rv)&&Y_(o)){n=o.call()?.returns??e.registry.any(),r++;continue}n=o,r++}else if(i instanceof iv)n=n?.get()?.value??e.registry.any(),r++;else if(i instanceof rv){if(n){let t=i.callSiteScope(n),r=n.call(t)?.returns;n=r?.simplify(t)??r??e.registry.any()}else n=e.registry.any();r++}else r++}return n??e.registry.any()}validateWalk(e,t,n,r,i=`get`){if(this.steps.length===0)return n.error(`path.empty`,`path is empty`),e.registry.any();if(i===`set`&&this.steps.length===1&&this.steps[0]instanceof nv)return e.registry.any();let a=null,o=0;for(;o<this.steps.length;){let s=this.steps[o],c=o===this.steps.length-1;if(s instanceof nv){if(a===null){let r=t.get(s.prop);r?a=r:(n.at([`path`,o],()=>n.error(`var.unknown`,`unknown variable '${s.prop}'${Pp(s.prop,[...t.keys()])}`)),a=e.registry.any()),o++;continue}let l=a.prop(s.prop);if(!l){n.at([`path`,o],()=>n.error(`prop.unknown`,`no prop '${s.prop}' on type '${a.name}'${ev(a,this.steps,o)}`)),a=e.registry.any(),o++;continue}let u=Z_(a,l),d=this.steps[o+1];if(d instanceof rv&&u.call()){for(let[i,a]of Object.entries(d.args))n.at([`path`,o+1,`args`,i],()=>a.validateWalk(e,t,n,r));d.catch_&&n.at([`path`,o+1,`catch`],()=>d.catch_.validateWalk(e,t,n,r));let c=d.callSiteScope(u),l=u.call(c);X_(l,d.args,n,[`path`,o+1]),i===`set`&&o+1===this.steps.length-1&&(l?.set||n.at([`path`,o+1],()=>n.error(`set.call.no-set`,`method '${s.prop}' has no call.set`))),d.resolvedEffects=l?.effects()??0;let f=l?.returns;a=f?.simplify(c)??f??e.registry.any(),o+=2;continue}if(!(d instanceof rv)&&Y_(u)){a=u.call()?.returns??e.registry.any(),o++;continue}i===`set`&&c&&!l.set&&l.get&&!u.call()&&n.at([`path`,o],()=>n.error(`set.prop.computed`,`prop '${s.prop}' is computed (read-only); cannot assign to it`));let f=i===`get`?u.call():void 0;if(f&&!Y_(u)){n.at([`path`,o],()=>n.error(`call.uncalled`,`method '${s.prop}' needs arguments \u2014 add an {args:{\u2026}} step to call it`)),a=f.returns??e.registry.any(),o++;continue}a=u,o++}else if(s instanceof iv){n.at([`path`,o,`key`],()=>s.key.validateWalk(e,t,n,r));let l=a?.get();i===`set`&&c?l?.set||n.at([`path`,o],()=>n.error(`set.index.no-set`,`type '${a?.name??`?`}' has no index set`)):l?.get||n.at([`path`,o],()=>n.error(`index.unsupported`,`type '${a?.name??`?`}' has no indexed access`)),a=l?.value??e.registry.any(),o++}else if(s instanceof rv){for(let[i,a]of Object.entries(s.args))n.at([`path`,o,`args`,i],()=>a.validateWalk(e,t,n,r));if(a){let t=s.callSiteScope(a),r=a.call(t);X_(r,s.args,n,[`path`,o]),i===`set`&&c&&(r?.set||n.at([`path`,o],()=>n.error(`set.call.no-set`,`call on type '${a?.name??`?`}' has no call.set`))),s.resolvedEffects=r?.effects()??0;let l=r?.returns;a=l?.simplify(t)??l??e.registry.any()}else s.resolvedEffects=0,a=e.registry.any();o++}else o++}return a??e.registry.any()}};function ov(e){return e.raw===null||e.raw===void 0}function sv(e,t,n,r){if(e instanceof nv)return V.jsonObject([{key:`prop`,value:V.jsonString(e.prop)}],{path:t},r,n);if(e instanceof rv){let i=Object.entries(e.args).map(([e,i])=>({key:e,value:i.toJSONCode([...t,`args`,e],n,r+2)})),a=[{key:`args`,value:V.jsonObject(i,{path:[...t,`args`]},r+1,n)}];return e.generic&&a.push({key:`generic`,value:JSON.stringify(e.generic,null,n).replace(/\n/g,`
110
- `+` `.repeat(r*n))}),e.catch_&&a.push({key:`catch`,value:e.catch_.toJSONCode([...t,`catch`],n,r+1)}),V.jsonObject(a,{path:t},r,n)}return e instanceof iv?V.jsonObject([{key:`key`,value:e.key.toJSONCode([...t,`key`],n,r+1)}],{path:t},r,n):new V(JSON.stringify(e.toJSON(),null,n))}var cv=class e extends $m{constructor(e){super(),this.path=e}path;static KIND=`get`;kind=e.KIND;static from(t,n){return new e(av.from(t.path,n)).withComment(t.comment)}async evaluate(e,t){return this.path.walk(t,e,{mode:`get`})}typeOf(e,t){return this.path.typeOf(e,t)}validateWalk(e,t,n,r){return this.path.validateWalk(e,t,n,r,`get`)}toGinCode(e,t={},n=[]){let r=this.path.toGinCode(e,t,n);return Fm(H`${this.commentPrefix(t)}${r}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`get`,path:this.path.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.path.toJSONCode([...e,`path`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`get`)},{key:`path`,value:r},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.path.clone()).withComment(this.comment)}forEachChild(e){this.path.forEachExpr(t=>e(t,`inherit`))}effects(){let e=[];this.path.forEachExpr(t=>{e.push(t.effects())});for(let t of this.path.steps)t instanceof rv&&t.resolvedEffects!==void 0&&e.push(t.resolvedEffects);return Pm(...e)}complexity(){return this.path.complexity()}},lv=class e extends $m{constructor(e,t){super(),this.path=e,this.value=t}path;value;static KIND=`set`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){return new e(av.from(t.path,n),n.registry.parseExpr(t.value,n)).withComment(t.comment)}async evaluate(e,t){let n=await this.value.evaluate(e,t);return this.path.steps.length===1&&this.path.steps[0]instanceof nv?(t.set(this.path.steps[0].prop,n),G(e.registry.bool(),!0)):this.path.walk(t,e,{mode:`set`,setValue:n})}typeOf(e,t){return e.registry.bool()}validateWalk(e,t,n,r){let i=n.at(`value`,()=>this.value.validateWalk(e,t,n,r)),a=this.path.validateWalk(e,t,n,r,`set`);return a.name!==`any`&&!a.compatible(i)&&n.at(`value`,()=>n.warn(`set.type-mismatch`,`value type '${i.name}' not compatible with target '${a.name}'`)),e.registry.bool()}toGinCode(e,t={},n=[]){let r=this.path.toGinCode(e,t,n),i=this.value.toGinCode(e,{...t,expectsValue:!0},[...n,`value`]);return Fm(H`${this.commentPrefix(t)}${r} = ${i}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`set`,path:this.path.toJSON(),value:this.value.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.path.toJSONCode([...e,`path`],t,n+1),i=this.value.toJSONCode([...e,`value`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`set`)},{key:`path`,value:r},{key:`value`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.path.clone(),this.value.clone()).withComment(this.comment)}forEachChild(e){this.path.forEachExpr(t=>e(t,`inherit`)),e(this.value,`inherit`)}effects(){let e=B.STATE|this.value.effects();this.path.forEachExpr(t=>{e|=t.effects()});for(let t of this.path.steps)t instanceof rv&&t.resolvedEffects!==void 0&&(e|=t.resolvedEffects);return e}complexity(){return this.path.complexity()+this.value.complexity()}},uv=class e extends $m{constructor(e,t){super(),this.vars=e,this.body=t}vars;body;static KIND=`define`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.vars.map(e=>({name:e.name,type:e.type?r.parse(e.type,n):void 0,value:r.parseExpr(e.value,n)}));return new e(i,r.parseExpr(t.body,n)).withComment(t.comment)}async evaluate(e,t){let n=t.child();for(let t of this.vars){let r=await t.value.evaluate(e,n);n.vars.set(t.name,r)}return this.body.evaluate(e,n)}typeOf(e,t){let n=new Map(t);for(let t of this.vars){let r=t.type??rh(e,t.value,n);n.set(t.name,r)}return rh(e,this.body,n)}validateWalk(e,t,n,r){let i=new Map(t);for(let t=0;t<this.vars.length;t++){let a=this.vars[t];n.at([`vars`,t,`name`],()=>sh(a.name,i,n));let o=n.at([`vars`,t,`value`],()=>oh(e,a.value,i,n,r));if(a.type&&!o.isUniversal()&&!a.type.compatible(o)){let e=dv(a.type),r=dv(o),i=o.name===`alias`?` (hint: '${r}' is an unbound generic \u2014 either bind it via \`generic: {${r}: ...}\` on the call site, pass \`output: typ<...>\`, or omit the declared type so the alias flows through)`:``;n.at([`vars`,t,`value`],()=>n.error(`define.var.type-mismatch`,`var '${a.name}' value type '${r}' not compatible with declared '${e}'${i}`))}i.set(a.name,a.type??o)}return n.at(`body`,()=>oh(e,this.body,i,n,r))}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i={...t,expectsValue:!0},a={...t,expectsValue:!1},o=this.vars.map((r,a)=>{let o=r.type?H`: ${r.type.toGinCode(void 0,t,[...n,`vars`,a,`type`])}`:``,s=r.value.toGinCode(e,i,[...n,`vars`,a,`value`]),c=H`let ${r.name}${o} = ${s};`;return c.text.split(`
111
- `,1)[0].length<=80?c:H`let ${r.name}${o} =\n ${s.indent(` `)};`});if(r){let r=this.body.toGinCode(e,i,[...n,`body`]),a=o.map(e=>H` ${e}`),s=H` return ${r.indent(` `)};`,c=Lm([...a,s]);return Fm(H`${this.commentPrefix(t)}(() => {\n${c}\n})()`,{path:n,expr:this})}let s=this.body.kind,c=this.body.toGinCode(e,a,[...n,`body`]),l=s===`if`||s===`switch`||s===`loop`||s===`block`?c:H`${c};`;return Fm(H`${this.commentPrefix(t)}${Lm([...o,l])}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`define`,vars:this.vars.map(e=>{let t={name:e.name,value:e.value.toJSON()};return e.type&&(t.type=e.type.toJSON()),t}),body:this.body.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.vars.map((r,i)=>{let a=[...e,`vars`,i],o=r.value.toJSONCode([...a,`value`],t,n+3),s=r.type?r.type.toJSONCode([...a,`type`],t,n+3):void 0;return V.jsonObject([{key:`name`,value:V.jsonString(r.name)},{key:`value`,value:o},{key:`type`,value:s}],{path:a},n+2,t)}),i=this.body.toJSONCode([...e,`body`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`define`)},{key:`vars`,value:V.jsonArray(r,{path:[...e,`vars`]},n+1,t)},{key:`body`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.vars.map(e=>({name:e.name,type:e.type?.clone(),value:e.value.clone()})),this.body.clone()).withComment(this.comment)}forEachChild(e){for(let t of this.vars)e(t.value,`inherit`);e(this.body,`inherit`)}effects(){let e=this.body.effects();for(let t of this.vars)e|=t.value.effects();return e}complexity(){let e=1+this.body.complexity();for(let t of this.vars)e+=1+t.value.complexity();return e}};function dv(e){try{return e.toCode()}catch{return e.name}}var fv=class e extends $m{constructor(e){super(),this.lines=e}lines;static KIND=`block`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(t.lines.map(e=>r.parseExpr(e,n))).withComment(t.comment)}async evaluate(e,t){let n=G(e.registry.void(),void 0);for(let r of this.lines)n=await r.evaluate(e,t);return n}typeOf(e,t){return this.lines.length===0?e.registry.void():rh(e,this.lines[this.lines.length-1],t)}validateWalk(e,t,n,r){let i=e.registry.void();for(let a=0;a<this.lines.length;a++)i=n.at(a,()=>oh(e,this.lines[a],t,n,r));return i}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1;if(this.lines.length===0)return Fm(r?`undefined`:``,{path:n,expr:this});if(this.lines.length===1)return Fm(this.lines[0].toGinCode(e,t,[...n,0]),{path:n,expr:this});let i=this.commentPrefix(t);return Fm(r?H`${i}(() => {\n${Lm(this.lines.map((r,i)=>{let a=i===this.lines.length-1,o=r.toGinCode(e,{...t,expectsValue:a},[...n,i]).indent(` `);return a?H` return ${o};`:H` ${o};`}))}\n})()`:H`${i}${Lm(this.lines.map((r,i)=>{let a=r.kind,o=r.toGinCode(e,{...t,expectsValue:!1},[...n,i]);return a===`if`||a===`switch`||a===`loop`||a===`block`?o:H`${o};`}))}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`block`,lines:this.lines.map(e=>e.toJSON())})}toJSONCode(e=[],t=2,n=0){let r=this.lines.map((r,i)=>r.toJSONCode([...e,i],t,n+2));return V.jsonObject([{key:`kind`,value:V.jsonString(`block`)},{key:`lines`,value:V.jsonArray(r,{path:[...e,`lines`]},n+1,t)},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.lines.map(e=>e.clone())).withComment(this.comment)}forEachChild(e){for(let t of this.lines)e(t,`inherit`)}effects(){let e=B.NONE;for(let t of this.lines)e|=t.effects();return e}complexity(){let e=1;for(let t of this.lines)e+=t.complexity();return e}},pv=class e extends $m{constructor(e,t,n){super(),this.action=e,this.value=t,this.error=n}action;value;error;static KIND=`flow`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(t.action,t.value?r.parseExpr(t.value,n):void 0,t.error?r.parseExpr(t.error,n):void 0).withComment(t.comment)}async evaluate(e,t){switch(this.action){case`break`:throw new lh;case`continue`:throw new uh;case`return`:throw new dh(this.value?await this.value.evaluate(e,t):void 0);case`exit`:throw new fh(this.value?await this.value.evaluate(e,t):void 0);case`throw`:throw this.error?new ph(await this.error.evaluate(e,t)):Error("flow.throw requires `error`")}}typeOf(e,t){return e.registry.void()}validateWalk(e,t,n,r){return this.action!==`break`&&this.action!==`continue`||r.inLoop||n.error(`flow.outside-loop`,`${this.action} used outside a loop`),this.action===`return`&&!r.inLambda&&n.warn(`flow.outside-lambda`,`return used outside a lambda`),this.action===`throw`&&!this.error&&n.error(`flow.throw.no-error`,"throw requires an `error` expression"),this.value&&n.at(`value`,()=>oh(e,this.value,t,n,r)),this.error&&n.at(`error`,()=>oh(e,this.error,t,n,r)),e.registry.void()}toGinCode(e,t={},n=[]){let r=this.commentPrefix(t),i={...t,expectsValue:!0},a;switch(this.action){case`break`:a=new V(`break`);break;case`continue`:a=new V(`continue`);break;case`return`:a=this.value?H`return ${this.value.toGinCode(e,i,[...n,`value`])}`:new V(`return`);break;case`throw`:a=this.error?H`throw ${this.error.toGinCode(e,i,[...n,`error`])}`:new V(`throw`);break;case`exit`:a=this.value?H`exit ${this.value.toGinCode(e,i,[...n,`value`])}`:new V(`exit`);break;default:a=new V(``)}return Fm(H`${r}${a}`,{path:n,expr:this})}toJSONCode(e=[],t=2,n=0){let r=this.value?this.value.toJSONCode([...e,`value`],t,n+1):void 0,i=this.error?this.error.toJSONCode([...e,`error`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`flow`)},{key:`action`,value:V.jsonString(this.action)},{key:`value`,value:r},{key:`error`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}toJSON(){let e={kind:`flow`,action:this.action};return this.value&&(e.value=this.value.toJSON()),this.error&&(e.error=this.error.toJSON()),this.withCommentOn(e)}clone(){return new e(this.action,this.value?.clone(),this.error?.clone()).withComment(this.comment)}forEachChild(e){this.value&&e(this.value,`inherit`),this.error&&e(this.error,`inherit`)}effects(){return B.STATE|(this.value?.effects()??B.NONE)|(this.error?.effects()??B.NONE)}complexity(){return 1+(this.value?.complexity()??0)+(this.error?.complexity()??0)}};function mv(e){return e.replace(/\n/g,`
112
- `)}function hv(e,t=`inherit`){if(e instanceof pv)return e.action===`throw`||e.action===`exit`?e:e.action===`return`?t===`lambda`?void 0:e:e.action===`break`||e.action===`continue`?t===`loop`?void 0:e:void 0;let n;return e.forEachChild((e,r)=>{if(n)return;let i=hv(e,r===`inherit`?t:r);i&&(n=i)}),n}var gv=class e extends $m{constructor(e,t){super(),this.ifs=e,this.otherwise=t}ifs;otherwise;static KIND=`if`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.ifs.map(e=>({condition:r.parseExpr(e.condition,n),body:r.parseExpr(e.body,n)}));return new e(i,t.else?r.parseExpr(t.else,n):void 0).withComment(t.comment)}async evaluate(e,t){for(let n of this.ifs)if((await n.condition.evaluate(e,t)).raw)return n.body.evaluate(e,t);return this.otherwise?this.otherwise.evaluate(e,t):G(e.registry.void(),void 0)}typeOf(e,t){let n=this.ifs.map(n=>rh(e,n.body,t));return this.otherwise&&n.push(rh(e,this.otherwise,t)),n.length===1?n[0]:e.registry.or(n)}validateWalk(e,t,n,r){let i=e.registry.bool(),a=[];for(let o=0;o<this.ifs.length;o++){let s=this.ifs[o],c=n.at([`ifs`,o,`condition`],()=>oh(e,s.condition,t,n,r));if(!i.compatible(c)){let e;try{e=c.toCode()}catch{e=c.name}n.at([`ifs`,o,`condition`],()=>n.warn(`if.condition.type`,`if condition should be bool, got '${e}' (did you forget to call a method?)`))}a.push(n.at([`ifs`,o,`body`],()=>oh(e,s.body,t,n,r)))}for(let e=0;e<this.ifs.length;e++)this.ifs[e].body.effects()===B.NONE&&n.at([`ifs`,e,`body`],()=>n.warn(`if.branch.no-effect`,"if branch body has no observable effect — when this branch matches, nothing happens. Either give it a `set`/`flow`/native call, or drop the branch entirely"));return this.otherwise&&(a.push(n.at(`else`,()=>oh(e,this.otherwise,t,n,r))),this.otherwise.effects()===B.NONE&&n.at(`else`,()=>n.warn(`if.else.no-effect`,"else arm has no observable effect — `else` is optional; OMIT it entirely when its only purpose is producing a placeholder value"))),a.length===1?a[0]:e.registry.or(a)}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i=this.ifs.some(e=>!!hv(e.body))||(this.otherwise?!!hv(this.otherwise):!1),a=this.commentPrefix(t),o={...t,expectsValue:!0};if(r&&!i){if(this.ifs.length===1&&this.otherwise){let t=this.ifs[0];return Fm(H`${a}(${t.condition.toGinCode(e,o,[...n,`ifs`,0,`condition`])} ? ${t.body.toGinCode(e,o,[...n,`ifs`,0,`body`])} : ${this.otherwise.toGinCode(e,o,[...n,`else`])})`,{path:n,expr:this})}let t=H``;for(let r=0;r<this.ifs.length;r++){let i=this.ifs[r],a=r===0?`if`:`else if`,s=i.condition.toGinCode(e,o,[...n,`ifs`,r,`condition`]),c=i.body.toGinCode(e,o,[...n,`ifs`,r,`body`]);t=H`${t}${r===0?``:`
113
- `} ${a} (${s}) return ${c.indent(` `)};`}let r=``;return this.otherwise&&(r=H`\n return ${this.otherwise.toGinCode(e,o,[...n,`else`]).indent(` `)};`),Fm(H`${a}(() => {\n${t}${r}\n})()`,{path:n,expr:this})}let s=H``;for(let r=0;r<this.ifs.length;r++){let i=this.ifs[r],a=r===0?`if`:`else if`,c=r===0?``:` `,l=i.condition.toGinCode(e,o,[...n,`ifs`,r,`condition`]),u=i.body.renderStatementBodyRich(e,t,[...n,`ifs`,r,`body`]);s=H`${s}${c}${a} (${l}) ${u}`}if(this.otherwise){let r=this.otherwise.renderStatementBodyRich(e,t,[...n,`else`],!0);s=H`${s} else ${r}`}return Fm(H`${a}${s}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`if`,ifs:this.ifs.map(e=>({condition:e.condition.toJSON(),body:e.body.toJSON()})),else:this.otherwise?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.ifs.map((r,i)=>{let a=[...e,`ifs`,i];return V.jsonObject([{key:`condition`,value:r.condition.toJSONCode([...a,`condition`],t,n+3)},{key:`body`,value:r.body.toJSONCode([...a,`body`],t,n+3)}],{path:a},n+2,t)}),i=this.otherwise?this.otherwise.toJSONCode([...e,`else`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`if`)},{key:`ifs`,value:V.jsonArray(r,{path:[...e,`ifs`]},n+1,t)},{key:`else`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.ifs.map(e=>({condition:e.condition.clone(),body:e.body.clone()})),this.otherwise?.clone()).withComment(this.comment)}forEachChild(e){for(let t of this.ifs)e(t.condition,`inherit`),e(t.body,`inherit`);this.otherwise&&e(this.otherwise,`inherit`)}effects(){let e=B.NONE;for(let t of this.ifs)e|=t.condition.effects()|t.body.effects();return this.otherwise&&(e|=this.otherwise.effects()),e}complexity(){let e=1;for(let t of this.ifs)e+=t.condition.complexity()+t.body.complexity();return this.otherwise&&(e+=this.otherwise.complexity()),e}},_v=class e extends $m{constructor(e,t,n){super(),this.value=e,this.cases=t,this.otherwise=n}value;cases;otherwise;static KIND=`switch`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(r.parseExpr(t.value,n),t.cases.map(e=>({equals:e.equals.map(e=>r.parseExpr(e,n)),body:r.parseExpr(e.body,n)})),t.else?r.parseExpr(t.else,n):void 0).withComment(t.comment)}async evaluate(e,t){let n=await this.value.evaluate(e,t);for(let r of this.cases)for(let i of r.equals)if((await i.evaluate(e,t)).raw===n.raw)return r.body.evaluate(e,t);return this.otherwise?this.otherwise.evaluate(e,t):G(e.registry.void(),void 0)}typeOf(e,t){let n=this.cases.map(n=>rh(e,n.body,t));return this.otherwise&&n.push(rh(e,this.otherwise,t)),n.length===0?e.registry.void():n.length===1?n[0]:e.registry.or(n)}validateWalk(e,t,n,r){let i=n.at(`value`,()=>oh(e,this.value,t,n,r)),a=[];for(let o=0;o<this.cases.length;o++){let s=this.cases[o];for(let a=0;a<s.equals.length;a++){let c=n.at([`cases`,o,`equals`,a],()=>oh(e,s.equals[a],t,n,r));i.compatible(c)||n.at([`cases`,o,`equals`,a],()=>n.warn(`switch.case.type`,`case value type '${c.name}' not compatible with switch value '${i.name}'`))}a.push(n.at([`cases`,o,`body`],()=>oh(e,s.body,t,n,r))),s.body.effects()===B.NONE&&n.at([`cases`,o,`body`],()=>n.warn(`switch.case.no-effect`,"switch case body has no observable effect — when this case matches, nothing happens. Either give it a `set`/`flow`/native call, or drop the case"))}return this.otherwise&&(a.push(n.at(`else`,()=>oh(e,this.otherwise,t,n,r))),this.otherwise.effects()===B.NONE&&n.at(`else`,()=>n.warn(`switch.else.no-effect`,`switch default has no observable effect — OMIT it instead of carrying a placeholder fallback`))),a.length===0?e.registry.void():a.length===1?a[0]:e.registry.or(a)}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i=this.cases.some(e=>!!hv(e.body))||(this.otherwise?!!hv(this.otherwise):!1),a={...t,expectsValue:!0},o=this.value.toGinCode(e,a,[...n,`value`]),s=this.commentPrefix(t);if(r&&!i){let t=Lm(this.cases.map((t,r)=>H`${Lm(t.equals.map((t,i)=>H` case ${t.toGinCode(e,a,[...n,`cases`,r,`equals`,i])}:`))}\n return ${t.body.toGinCode(e,a,[...n,`cases`,r,`body`]).indent(` `)};`)),r=``;return this.otherwise&&(r=H`\n default:\n return ${this.otherwise.toGinCode(e,a,[...n,`else`]).indent(` `)};`),Fm(H`${s}(() => {\n switch (${o}) {\n${t}${r}\n }\n})()`,{path:n,expr:this})}let c=(n,r)=>{let i=n.kind;return n instanceof pv?H`${n.toGinCode(e,{...t,expectsValue:!1},r)};`:i===`block`||i===`if`||i===`switch`||i===`loop`?n.toGinCode(e,{...t,expectsValue:!1},r):H`${n.toGinCode(e,{...t,expectsValue:!0},r)};`},l=Lm(this.cases.map((t,r)=>{let i=Lm(t.equals.map((t,i)=>H` case ${t.toGinCode(e,a,[...n,`cases`,r,`equals`,i])}:`)),o=[...n,`cases`,r,`body`];return H`${i}\n ${c(t.body,o).indent(` `)}${t.body instanceof pv?``:`
114
- break;`}`})),u=``;return this.otherwise&&(u=H`\n default:\n ${c(this.otherwise,[...n,`else`]).indent(` `)}`),Fm(H`${s}switch (${o}) {\n${l}${u}\n}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`switch`,value:this.value.toJSON(),cases:this.cases.map(e=>({equals:e.equals.map(e=>e.toJSON()),body:e.body.toJSON()})),else:this.otherwise?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.value.toJSONCode([...e,`value`],t,n+1),i=this.cases.map((r,i)=>{let a=[...e,`cases`,i],o=r.equals.map((e,r)=>e.toJSONCode([...a,`equals`,r],t,n+4));return V.jsonObject([{key:`equals`,value:V.jsonArray(o,{path:[...a,`equals`]},n+3,t)},{key:`body`,value:r.body.toJSONCode([...a,`body`],t,n+3)}],{path:a},n+2,t)}),a=this.otherwise?this.otherwise.toJSONCode([...e,`else`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`switch`)},{key:`value`,value:r},{key:`cases`,value:V.jsonArray(i,{path:[...e,`cases`]},n+1,t)},{key:`else`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.value.clone(),this.cases.map(e=>({equals:e.equals.map(e=>e.clone()),body:e.body.clone()})),this.otherwise?.clone()).withComment(this.comment)}forEachChild(e){e(this.value,`inherit`);for(let t of this.cases){for(let n of t.equals)e(n,`inherit`);e(t.body,`inherit`)}this.otherwise&&e(this.otherwise,`inherit`)}effects(){let e=this.value.effects();for(let t of this.cases){for(let n of t.equals)e|=n.effects();e|=t.body.effects()}return this.otherwise&&(e|=this.otherwise.effects()),e}complexity(){let e=1+this.value.complexity();for(let t of this.cases){for(let n of t.equals)e+=n.complexity();e+=t.body.complexity()}return this.otherwise&&(e+=this.otherwise.complexity()),e}},vv=class e extends $m{constructor(e,t,n,r,i){super(),this.over=e,this.body=t,this.keyName=n,this.valueName=r,this.parallel=i}over;body;keyName;valueName;parallel;static KIND=`loop`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.parallel?{concurrent:t.parallel.concurrent?r.parseExpr(t.parallel.concurrent,n):void 0,rate:t.parallel.rate?r.parseExpr(t.parallel.rate,n):void 0}:void 0;return new e(r.parseExpr(t.over,n),r.parseExpr(t.body,n),t.key,t.value,i).withComment(t.comment)}async evaluate(e,t){let n=await this.over.evaluate(e,t),r=n.type.get();if(!(r?.loop||r?.loopDynamic))throw Error(`loop: type '${n.type.name}' has no loop or loopDynamic defined on its GetSet`);let i=this.keyName??`key`,a=this.valueName??`value`,o=this.parallel?.concurrent?Number((await this.parallel.concurrent.evaluate(e,t)).raw):void 0,s=this.parallel?.rate?Number((await this.parallel.rate.evaluate(e,t)).raw):void 0,c=o!==void 0||s!==void 0;if(r.loopDynamic){let r=e.registry.num({whole:!0,min:0});if(!c){let o=n,s=0;for(;o.raw;){await t.checkpoint();let n=t.child({[i]:G(r,s),[a]:o});try{await this.body.evaluate(e,n)}catch(e){if(e instanceof lh)break;if(!(e instanceof uh))throw e}s++,o=await this.over.evaluate(e,t)}return G(e.registry.void(),void 0)}let l=new Set,u=o??1/0,d=!1,f=0,p=0,m=async()=>{if(d)return!1;await t.checkpoint();let n=await this.over.evaluate(e,t);if(!n.raw)return!1;if(s&&s>0){let e=Date.now()-f;e<s&&await new Promise(t=>setTimeout(t,s-e)),f=Date.now()}let o=t.child({[i]:G(r,p),[a]:n}),c=(async()=>{try{await this.body.evaluate(e,o)}catch(e){if(e instanceof uh)return;if(e instanceof lh){d=!0;return}throw e}})().finally(()=>l.delete(c));return l.add(c),p++,!0},h=Number.isFinite(u)?u:1;for(;l.size<h&&await m(););for(;l.size>0;)for(await Promise.race(l);!d&&l.size<h&&await m(););return G(e.registry.void(),void 0)}let l=r.loop;if(!l)throw Error(`loop: type '${n.type.name}' has no loop ExprDef on its GetSet`);if(!c)return await yv(l,t,e,n,async(n,r)=>{let o=t.child({[i]:n,[a]:r});try{return await this.body.evaluate(e,o)}catch(t){if(t instanceof uh)return G(e.registry.void(),void 0);throw t}}),G(e.registry.void(),void 0);let u=new Set,d=o??1/0,f=!1,p=0;return await yv(r.loop,t,e,n,async(n,r)=>{if(f)return G(e.registry.void(),void 0);if(s&&s>0){let e=Date.now()-p;e<s&&await new Promise(t=>setTimeout(t,s-e)),p=Date.now()}for(;u.size>=d;)await Promise.race(u);let o=t.child({[i]:n,[a]:r}),c=(async()=>{try{await this.body.evaluate(e,o)}catch(e){if(e instanceof uh)return;if(e instanceof lh){f=!0;return}throw e}})().finally(()=>u.delete(c));return u.add(c),G(e.registry.void(),void 0)}),await Promise.all(u),G(e.registry.void(),void 0)}typeOf(e,t){return e.registry.void()}validateWalk(e,t,n,r){let i=n.at(`over`,()=>oh(e,this.over,t,n,r)),a=i.get();if(a?.loop||a?.loopDynamic||n.error(`loop.not-iterable`,`type '${i.name}' has no loop defined`),this.parallel?.concurrent){let i=n.at([`parallel`,`concurrent`],()=>oh(e,this.parallel.concurrent,t,n,r));e.registry.num().compatible(i)||n.at([`parallel`,`concurrent`],()=>n.error(`loop.parallel.concurrent.type`,`parallel.concurrent must be a number, got '${i.name}'`))}if(this.parallel?.rate){let i=n.at([`parallel`,`rate`],()=>oh(e,this.parallel.rate,t,n,r)),a=e.registry.num().compatible(i),o=e.registry.duration().compatible(i);!a&&!o&&n.at([`parallel`,`rate`],()=>n.error(`loop.parallel.rate.type`,`parallel.rate must be a number or duration, got '${i.name}'`))}this.keyName===void 0?t.has(`key`)&&n.error(`loop.key.shadow`,`loop's default 'key' is already in scope from an enclosing loop — set the \`key\` field on this loop to a distinct name (e.g. "i", "j", "outerKey") so the inner loop doesn't shadow the outer iteration index`):n.at(`key`,()=>sh(this.keyName,t,n)),this.valueName===void 0?t.has(`value`)&&n.error(`loop.value.shadow`,`loop's default 'value' is already in scope from an enclosing loop — set the \`value\` field on this loop to a distinct name (e.g. "v", "row", "outerValue") so the inner loop doesn't shadow the outer iteration value`):n.at(`value`,()=>sh(this.valueName,t,n));let o=a?.key??e.registry.any(),s=a?.value??e.registry.any(),c=new Map(t);return c.set(this.keyName??`key`,o),c.set(this.valueName??`value`,s),n.at(`body`,()=>oh(e,this.body,c,n,{...r,inLoop:!0})),this.body.effects()===B.NONE&&n.at(`body`,()=>n.warn(`loop.body.no-effect`,"loop body has no observable effect — the iteration's computed value is discarded. Add a `set` to accumulate into an outer var, a `flow` to control iteration, or invoke a side-effecting native (e.g. `fns.log`, `fns.fetch`)")),e.registry.void()}toCode(e,t={}){let n=t.expectsValue??!1,r={...t,expectsValue:!0},i={...t,expectsValue:!1},a=this.over.toCode(e,r),o=this.keyName??`key`,s=this.valueName??`value`,c=``;t.includeComments!==!1&&(this.parallel?.concurrent&&(c+=`/* parallel.concurrent: ${this.parallel.concurrent.toCode(e,r)} */ `),this.parallel?.rate&&(c+=`/* parallel.rate: ${this.parallel.rate.toCode(e,r)} */ `));let l=(()=>{let t=this.body.kind;if(t===`flow`)return`${this.body.toCode(e,i)};`;if(t===`block`){let t=this.body.toCode(e,i);return t.startsWith(`{`)?t.slice(1,-1).trim():t}return t===`if`||t===`switch`||t===`loop`?this.body.toCode(e,i):`${this.body.toCode(e,i)};`})(),u=`${c}for (const [${o}, ${s}] of ${a}) {
115
- ${mv(l)}
116
- }`,d=this.commentPrefix(t);return n?d+`(() => { ${u}; return undefined; })()`:d+u}toJSON(){let e={kind:`loop`,over:this.over.toJSON(),body:this.body.toJSON()};return this.keyName!==void 0&&(e.key=this.keyName),this.valueName!==void 0&&(e.value=this.valueName),this.parallel&&(e.parallel={concurrent:this.parallel.concurrent?.toJSON(),rate:this.parallel.rate?.toJSON()}),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.over.toJSONCode([...e,`over`],t,n+1),i=this.body.toJSONCode([...e,`body`],t,n+1),a=this.parallel?V.jsonObject([{key:`concurrent`,value:this.parallel.concurrent?.toJSONCode([...e,`parallel`,`concurrent`],t,n+2)},{key:`rate`,value:this.parallel.rate?.toJSONCode([...e,`parallel`,`rate`],t,n+2)}],{path:[...e,`parallel`]},n+1,t):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`loop`)},{key:`over`,value:r},{key:`body`,value:i},{key:`key`,value:this.keyName===void 0?void 0:V.jsonString(this.keyName)},{key:`value`,value:this.valueName===void 0?void 0:V.jsonString(this.valueName)},{key:`parallel`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.over.clone(),this.body.clone(),this.keyName,this.valueName,this.parallel?{concurrent:this.parallel.concurrent?.clone(),rate:this.parallel.rate?.clone()}:void 0).withComment(this.comment)}forEachChild(e){e(this.over,`inherit`),e(this.body,`loop`),this.parallel?.concurrent&&e(this.parallel.concurrent,`inherit`),this.parallel?.rate&&e(this.parallel.rate,`inherit`)}effects(){return this.over.effects()|this.body.effects()|(this.parallel?.concurrent?.effects()??B.NONE)|(this.parallel?.rate?.effects()??B.NONE)}complexity(){return 6+this.over.complexity()+this.body.complexity()+(this.parallel?.concurrent?.complexity()??0)+(this.parallel?.rate?.complexity()??0)}};async function yv(e,t,n,r,i){let a=n.registry,o=new W(a.fn({args:a.obj({key:{type:a.any()},value:{type:a.any()}}),returns:a.void()}),async e=>{let t=e.raw;if(!t)throw Error(`yield: missing args`);return await s.checkpoint(),i(t.key,t.value)}),s=t.child({this:r,yield:o});try{await e.evaluate(n,s)}catch(e){if(!(e instanceof lh))throw e}}var bv=class e extends $m{constructor(e,t,n){super(),this.fnType=e,this.body=t,this.constraint=n}fnType;body;constraint;static KIND=`lambda`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=r.parse(t.type,n),a=Cv(n,i),o=r.parseExpr(t.body,a),s=t.constraint?r.parseExpr(t.constraint,a):void 0;return new e(i,o,s).withComment(t.comment)}async evaluate(e,t){let n=this.fnType,r=this.body,i=t,a=this.constraint,o=async t=>{await i.checkpoint();let s=new W(n,o),c=i.child({args:t,recurse:s});if(a&&(await a.evaluate(e,c)).raw!==!0)throw Error(`lambda constraint failed: ${a.toCode(e.registry,{expectsValue:!0})}`);try{return await r.evaluate(e,c)}catch(t){if(t instanceof dh)return t.value??new W(e.registry.void(),void 0);throw t}};return new W(n,o)}typeOf(e,t){return this.fnType}validateWalk(e,t,n,r){let i=this.fnType.call(),a=new Map(t);a.set(`args`,i?.args??e.registry.any());let o=n.at(`body`,()=>oh(e,this.body,a,n,{...r,inLambda:!0}));if(i?.returns&&!i.returns.compatible(o)&&n.at(`body`,()=>n.warn(`lambda.returns.type`,`body type '${o.name}' not compatible with declared returns '${i.returns.name}'`)),this.constraint){let t=e.registry.bool(),i=n.at(`constraint`,()=>oh(e,this.constraint,a,n,{...r,inLambda:!0}));t.compatible(i)||n.at(`constraint`,()=>n.warn(`lambda.constraint.type`,`constraint must return bool, got '${i.name}'`))}return this.fnType}toGinCode(e,t={},n=[]){let r=this.fnType.call(),i={...t,expectsValue:!0},a=this.commentPrefix(t),o=`(${xv(r?.args,t)})${r?.returns?`: ${r.returns.toCode(void 0,t)}`:``}`,s=this.body.toGinCode(e,i,[...n,`body`]),c=s.text,l;return l=this.constraint?H`${o} => {\n if (!(${Sv(this.constraint.toGinCode(e,i,[...n,`constraint`]))})) throw new Error('constraint');\n return ${s.indent(` `)};\n}`:c.includes(`
117
- `)?H`${o} => {\n ${s.indent(` `)}\n}`:H`${o} => ${s}`,Fm(a?H`${a}${l}`:l,{path:n,expr:this})}toCode(e,t={}){return this.toGinCode(e,t).toString()}toJSON(){return this.withCommentOn({kind:`lambda`,type:this.fnType.toJSON(),body:this.body.toJSON(),constraint:this.constraint?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.fnType.toJSONCode([...e,`type`],t,n+1),i=this.body.toJSONCode([...e,`body`],t,n+1),a=this.constraint?this.constraint.toJSONCode([...e,`constraint`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`lambda`)},{key:`type`,value:r},{key:`body`,value:i},{key:`constraint`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.fnType.clone(),this.body.clone(),this.constraint?.clone()).withComment(this.comment)}forEachChild(e){e(this.body,`lambda`),this.constraint&&e(this.constraint,`lambda`)}effects(){return B.NONE}complexity(){return 10+this.body.complexity()+(this.constraint?.complexity()??0)}};function xv(e,t){if(!e||e.name===`void`||e.name===`any`)return``;let n=e.fields;if(!n)return`args: ${e.toCode(void 0,t)}`;let r=Object.entries(n);return r.length===0?``:r.map(([e,n])=>{let r=n.type.isOptional?.()??!1,i=r&&typeof n.type.required==`function`?n.type.required():n.type;return`${n.docs&&t.includeComments!==!1?`/* ${n.docs} */ `:``}${e}${r?`?`:``}: ${i.toCode(void 0,t)}`}).join(`, `)}function Sv(e){return e.text.includes(`
118
- `)?new V(e.text.replace(/\n\s*/g,` `),e.spans):e}function Cv(e,t){let n=new Qm(e),r=t.call();if(r?.types)for(let[e,t]of Object.entries(r.types))n.bind(e,t);return n}var wv=class e extends $m{constructor(e,t){super(),this.template=e,this.params=t}template;params;static KIND=`template`;kind=e.KIND;static from(t,n){let r=n.registry,i=t.template,a=i&&typeof i==`object`&&`kind`in i?r.parseExpr(i,n):r.parseExpr({kind:`new`,type:{name:`text`},value:String(i)},n),o=t.params?r.parseExpr(t.params,n):void 0;return new e(a,o).withComment(t.comment)}async evaluate(e,t){let n=await this.template.evaluate(e,t),r=String(n.raw),i;this.params&&(i=(await this.params.evaluate(e,t)).raw);let a=r.replace(/\{(\w+)\}/g,(e,n)=>{if(i&&Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];return e==null?``:e instanceof W?String(e.raw??``):String(e)}let r=t.get(n);return r===void 0?``:r instanceof W?String(r.raw??``):String(r)});return G(e.registry.text(),a)}typeOf(e,t){return e.registry.text()}validateWalk(e,t,n,r){let i=e.registry.text(),a=n.at(`template`,()=>oh(e,this.template,t,n,r));i.compatible(a)||n.at(`template`,()=>n.warn(`template.template.type`,`template should resolve to text, got '${a.name}'`));let o,s=!1;if(this.params){let i=n.at(`params`,()=>oh(e,this.params,t,n,r));if(i.name===`any`)s=!0;else if(i.name===`obj`||i.name===`iface`){let e=i.props(),t=Object.entries(e).filter(([,e])=>!e.type.call()).map(([e])=>e);o=new Set(t)}else n.at(`params`,()=>n.warn(`template.params.type`,`template params should be an object, got '${i.name}'`)),s=!0}let c=this.template instanceof W_&&typeof this.template.value==`string`?this.template.value:void 0;if(c!==void 0){let e=new Set,r=/\{(\w+)\}/g,i;for(;(i=r.exec(c))!==null;){let r=i[1];if(e.has(r))continue;e.add(r);let a=o?.has(r)??!1,c=t.has(r);s?c||n.error(`template.placeholder.unresolved`,`placeholder '{${r}}' isn't a scope variable; either define '${r}' in scope or pass a typed obj as \`params\` so it can be checked`):!a&&!c&&n.error(`template.placeholder.unresolved`,this.params?`placeholder '{${r}}' is not a key of \`params\` (keys: [${[...o??[]].join(`, `)||`none`}]) and not a scope variable`:`placeholder '{${r}}' does not match any scope variable; either \`define ${r} = ...\` first or pass it via \`params\``)}}return e.registry.text()}toCode(e,t={}){let n=this.commentPrefix(t),r=this.template instanceof W_&&typeof this.template.value==`string`?this.template.value:void 0;if(r===void 0){let r=e.toCode(this.template,{...t,expectsValue:!0});return this.params?`${n}template(${r}, ${e.toCode(this.params,{...t,expectsValue:!0})})`:`${n}template(${r})`}let i=this.params?Tv(this.params,e):void 0;return`${n}${`\`${r.replace(/\{(\w+)\}/g,(e,t)=>{if(i&&Object.prototype.hasOwnProperty.call(i,t)){let e=i[t];return e.length>64?`\${
102
+ `}function Uh(e){return e?.indent??` `}function Wh(e,t){return t+e.replace(/\n/g,`
103
+ ${t}`)}function Gh(e,t,n){let r=e.registry,i={inLoop:!1,inLambda:!1},a=e.props();for(let[o,s]of Object.entries(a)){let a=s instanceof Nh?s:Nh.from(s);n.at([`props`,o],()=>{Yh(a.get,Kh(a,e,r),Jh(a),`get`,t,n,i),Yh(a.set,qh(a,e,r),r.void(),`set`,t,n,i),Yh(a.default,new Map,a.type,`default`,t,n,i)})}let o=e.get();o&&n.at(`get`,()=>{let a=new Map([[`this`,e],[`key`,o.key]]),s=new Map([[`this`,e],[`key`,o.key],[`value`,o.value]]);Yh(o.get,a,o.value,`get`,t,n,i),Yh(o.set,s,r.void(),`set`,t,n,i),Yh(o.loop,a,void 0,`loop`,t,n,i)});let s=e.call();s&&n.at(`call`,()=>{let a=new Map([[`this`,e],[`args`,s.args],[`recurse`,r.fn({args:s.args,returns:s.returns??r.any()})]]);Yh(s.get,a,s.returns,`get`,t,n,{...i,inLambda:!0});let o=new Map([[`this`,e],[`args`,s.args],[`value`,s.returns??r.any()],[`recurse`,r.fn({args:s.args,returns:s.returns??r.any()})]]);Yh(s.set,o,r.void(),`set`,t,n,{...i,inLambda:!0})});let c=e.init();c&&n.at(`init`,()=>{let r=new Map([[`this`,e],[`args`,c.args]]);Yh(c.run,r,void 0,`run`,t,n,i)});for(let a of e.constraints())n.at(`constraint`,()=>{let o=ch(t,a,new Map([[`this`,e]]),n,i),s=r.bool();o.name!==`any`&&!s.compatible(o)&&n.warn(`type.surface.return-type`,`constraint must return bool, got '${o.name}'`)})}function Kh(e,t,n){let r=new Map([[`this`,t]]),i=e.type.call?.();return i&&(r.set(`args`,i.args),r.set(`recurse`,n.fn({args:i.args,returns:i.returns??n.any()}))),r}function qh(e,t,n){return new Map([[`this`,t],[`value`,e.type]])}function Jh(e){let t=e.type.call?.();return t?t.returns:e.type}function Yh(e,t,n,r,i,a,o){e&&a.at(r,()=>{let s=ch(i,e,t,a,o);n&&s.name!==`any`&&!n.compatible(s)&&a.warn(`type.surface.return-type`,`${r} body returns '${s.name}', not compatible with declared '${n.name}'`)})}function Xh(e,t,n,r,i,a){let o=i+1,s=[];return e.name!==void 0&&s.push({key:`name`,value:V.jsonString(e.name)}),e.extends!==void 0&&s.push({key:`extends`,value:V.jsonString(e.extends)}),e.satisfies!==void 0&&e.satisfies.length>0&&s.push({key:`satisfies`,value:ig(e.satisfies,[...n,`satisfies`],r,o)}),e.docs!==void 0&&s.push({key:`docs`,value:V.jsonString(e.docs)}),e.options!==void 0&&Object.keys(e.options).length>0&&s.push({key:`options`,value:ig(e.options,[...n,`options`],r,o)}),e.generic!==void 0&&Object.keys(e.generic).length>0&&s.push({key:`generic`,value:Zh(e.generic,t,[...n,`generic`],r,o)}),e.props!==void 0&&Object.keys(e.props).length>0&&s.push({key:`props`,value:Qh(e.props,t,[...n,`props`],r,o)}),e.get!==void 0&&s.push({key:`get`,value:eg(e.get,t,[...n,`get`],r,o)}),e.call!==void 0&&s.push({key:`call`,value:tg(e.call,t,[...n,`call`],r,o)}),e.init!==void 0&&s.push({key:`init`,value:ng(e.init,t,[...n,`init`],r,o)}),e.constraint!==void 0&&s.push({key:`constraint`,value:rg(e.constraint,t,[...n,`constraint`],r,o)}),V.jsonObject(s,{path:n,type:a},i,r)}function Zh(e,t,n,r,i){let a=Object.entries(e).map(([e,a])=>({key:e,value:Xh(a,t,[...n,e],r,i+1,void 0)}));return V.jsonObject(a,{path:n},i,r)}function Qh(e,t,n,r,i){let a=Object.entries(e).map(([e,a])=>({key:e,value:$h(a,t,[...n,e],r,i+1)}));return V.jsonObject(a,{path:n},i,r)}function $h(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`type`,value:Xh(e.type,t,[...n,`type`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:rg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:rg(e.set,t,[...n,`set`],r,a)}),e.default!==void 0&&o.push({key:`default`,value:rg(e.default,t,[...n,`default`],r,a)}),V.jsonObject(o,{path:n},i,r)}function eg(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`key`,value:Xh(e.key,t,[...n,`key`],r,a,void 0)}),o.push({key:`value`,value:Xh(e.value,t,[...n,`value`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:rg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:rg(e.set,t,[...n,`set`],r,a)}),e.loop!==void 0&&o.push({key:`loop`,value:rg(e.loop,t,[...n,`loop`],r,a)}),e.loopDynamic!==void 0&&o.push({key:`loopDynamic`,value:String(e.loopDynamic)}),V.jsonObject(o,{path:n},i,r)}function tg(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),e.types!==void 0&&Object.keys(e.types).length>0&&o.push({key:`types`,value:Zh(e.types,t,[...n,`types`],r,a)}),o.push({key:`args`,value:Xh(e.args,t,[...n,`args`],r,a,void 0)}),e.returns!==void 0&&o.push({key:`returns`,value:Xh(e.returns,t,[...n,`returns`],r,a,void 0)}),e.throws!==void 0&&o.push({key:`throws`,value:Xh(e.throws,t,[...n,`throws`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:rg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:rg(e.set,t,[...n,`set`],r,a)}),V.jsonObject(o,{path:n},i,r)}function ng(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`args`,value:Xh(e.args,t,[...n,`args`],r,a,void 0)}),o.push({key:`run`,value:rg(e.run,t,[...n,`run`],r,a)}),V.jsonObject(o,{path:n},i,r)}function rg(e,t,n,r,i){try{return t.parseExpr(e).toJSONCode(n,r,i)}catch{return ig(e,n,r,i)}}function ig(e,t,n,r){let i=JSON.stringify(e,null,n);if(r>0){let e=` `.repeat(r*n);i=i.replace(/\n/g,`
104
+ `+e)}return Lm(i,{path:t})}var W=class{type;raw;constructor(e,t){this.type=e,this.raw=t}toLogical(){return ag(this.raw)}encode(){return this.type.encode(this.raw)}toJSON(e=Ah){return{type:this.type.toJSONRef(e),value:this.type.encodeAs(this.raw,e)}}encodeLogical(){return this.type.encodeAs(this.raw,cg)}toJSONRefs(){return this.toJSON({form:`envelope`,typeRefs:`name`})}toJSONLogical(){return this.toJSON(cg)}};function ag(e){if(e instanceof W)return e.toLogical();if(Array.isArray(e))return e.map(ag);if(e instanceof Map){let t=new Map;for(let n of e.values())og(n)&&t.set(n[0].toLogical(),n[1].toLogical());return t}if(sg(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=ag(r);return t}return e}function og(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function sg(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var cg={form:`logical`,typeRefs:`name`};function G(e,t){return new W(e,t)}var lg=class extends Error{constructor(){super(`The run was stopped.`),this.name=`RunStoppedError`}},ug=class{signal;slice;#e=Date.now();constructor(e={}){this.signal=e.signal,this.slice=e.slice??10}check(){let e=this.signal;if(e?.aborted!==!0)return;let t=e.reason;throw t instanceof Error?t:new lg}async checkpoint(){this.check(),Date.now()-this.#e<this.slice||(await new Promise(e=>{setTimeout(e,0)}),this.#e=Date.now(),this.check())}},dg=new Set([`text`,`num`,`bool`,`enum`,`literal`,`date`,`timestamp`,`duration`,`color`,`null`]);function fg(e){let t=e;for(let e=0;e<16;e+=1){let e=t.inner??t.base;if(e===void 0||e===t)return t;t=e}return t}function pg(e){return dg.has(fg(e).name)}function mg(e,t){let n=e.isOptional()?e.inner??e:e;return pg(n)?R.union([n.toA(t),R.ref(`Expr`)]):R.ref(`Expr`)}function hg(e,t){if(e===t)return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;let n=e,r=t,i=Object.keys(n);return i.length===Object.keys(r).length&&i.every(e=>n[e]===r[e])}function gg(e,t,n){let r=Object.keys(e);return r.length===0?t?Nh.toJSONMap(t):void 0:{...n&&Object.keys(n).length===r.length&&r.every(e=>e in n)?n:Nh.toJSONMap(e),...t?Nh.toJSONMap(t):{}}}function _g(e,t){return{...e,props:e.props?Nh.fromMap(e.props,t):void 0,get:e.get?Ph.from(e.get,t):void 0,call:e.call?Fh.from(e.call,t):void 0,init:e.init?Ih.from(e.init,t):void 0}}var vg=class e extends U{name;docs;base;original;local;bindings;constructor(e,t,n,r,i){let a=n.options?t.narrow(n.options):t.options,o=n.options&&!hg(a,t.options)?e.parse({...t.toJSON(),options:a},i):t;super(r??e,a,n.generic??{}),this.original=t,this.base=o,this.local=_g(n,e),this.name=n.name,this.docs=n.docs;let s=Object.entries(n.generic??{}).filter(([e,t])=>!U.isGenericPlaceholder(e,t));this.bindings=s.length>0?Object.fromEntries(s):void 0}storedLocalProps(){let e=[];for(let[t,n]of Object.entries(this.local.props??{})){let r=n instanceof Nh?n:Nh.from(n);r.get||r.type.call()||e.push([t,r])}return e}valid(e,t){let n=this.bindScope(t);if(!this.base.valid(e,n))return!1;let r=this.storedLocalProps();if(r.length===0||!jh(e))return!0;let i=e;for(let[e,t]of r){let r=i[e];if(!(r instanceof W))return t.type.isOptional();if(!r.type.valid(r.raw,n)||!wh(t.type,r.type,n))return!1}return!0}parse(e,t){let n=this.bindScope(t),r=this.base.parse(e,n),i=this.storedLocalProps();if(i.length===0||!jh(r.raw))return new W(this,r.raw);let a=jh(e)?e:{},o={...r.raw};for(let[e,t]of i)o[e]=this.registry.parseValue(a[e],t.type,n);return new W(this,o)}parsesExprValue(e){return this.base.parsesExprValue(this.bindScope(e))}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){let r=this.bindScope(n),i=this.base.encodeAs(e,t,r),a=this.storedLocalProps();if(a.length===0||!jh(i)||!jh(e))return i;let o=e,s={...i};for(let[e]of a)kh(s,e,o[e],t,r);return s}create(){return this.withLocalSlots(this.base.create(),e=>e.create())}random(e){return this.withLocalSlots(this.base.random(e),t=>t.random(e))}withLocalSlots(e,t){let n=this.storedLocalProps();if(n.length===0||!jh(e))return e;let r={...e};for(let[e,i]of n)r[e]=new W(i.type,t(i.type));return r}forEachNewSlot(e,t){let n=this.base.forEachNewSlot(e,t),r=this.storedLocalProps();if(r.length===0||!jh(e))return n;let i=e;for(let[e,n]of r)e in i?t.slot(n.type,i[e],e):n.default!==void 0&&t.missing?.(n.default,e);return!0}async newFill(e,t,n){let r=await this.base.newFill(e,t,n),i=this.storedLocalProps();if(i.length===0||!jh(r))return r;let a=r,o;for(let[e,r]of i)if(e in a){let i=await r.type.newFill(a[e],t,n);i!==a[e]&&(o??={...a},o[e]=i)}else r.default!==void 0&&(o??={...a},o[e]=await r.default.evaluate(t,n));return o??a}compatibleType(t,n,r){return n?.exact?t instanceof e&&t.name===this.name&&this.base.compatible(t.base,n,r):t instanceof e?this.base.compatible(t.base,n,r):this.base.compatible(t,n,r)}or(t){if(t instanceof e&&t.name===this.name){let n={name:this.name,docs:this.docs??t.docs,options:{...this.local.options??{},...t.local.options??{}},props:{...this.local.props??{},...t.local.props??{}},get:this.local.get??t.local.get,call:this.local.call??t.local.call,init:this.local.init??t.local.init};return new e(this.registry,this.original,n)}return this.base.or(t)}simplify(){return this}required(){return this.base.required()}isOptional(){return this.base.isOptional()}narrow(e){return this.base.narrow(e)}props(e){let t=this.registry.augmentation(this.name);return{...this.base.props(this.bindScope(e)),...t?.props??{},...this.local.props??{}}}get(e){return this.local.get??this.registry.augmentation(this.name)?.get??this.base.get(this.bindScope(e))}call(e){return this.local.call??this.registry.augmentation(this.name)?.call??this.base.call(this.bindScope(e))}init(e){return this.local.init??this.registry.augmentation(this.name)?.init??this.base.init(this.bindScope(e))}toJSON(){if(zh.active>0&&zh.depth>0&&!this.local.useSite&&this.registry.lookup(this.name)!==void 0&&(this.registry.lookup(this.name)===this||this.bindings)){let e=Object.entries(this.bindings??{});return e.length>0?{name:this.name,generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{name:this.name}}zh.depth++;try{return this.toJSONInner()}finally{zh.depth--}}toJSONInner(){if(this.local.useSite){let e=Object.entries(this.bindings??{});return{name:this.name,...e.length>0?{generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{},options:{...this.local.options}}}let e=this.original.toJSON(),t=this.original.name!==this.name,n={...e.options,...this.local.options},r={...e.generic??{}};if(this.local.generic)for(let[e,t]of Object.entries(this.local.generic))r[e]=t.toJSON();return Jm({name:this.name,extends:t?this.original.name:void 0,docs:this.docs,generic:Object.keys(r).length>0?r:void 0,options:n&&Object.keys(n).length>0?n:void 0,props:gg(t?this.original.refProps():{},this.local.props,e.props),get:(this.local.get??(t?this.original.refGet():void 0))?.toJSON(),call:(this.local.call??(t?this.original.refCall():void 0))?.toJSON(),init:this.local.init?.toJSON(),constraint:this.local.constraint?this.local.constraint.toJSON():void 0})}clone(){let t=this.local.generic?Object.fromEntries(Object.entries(this.local.generic).map(([e,t])=>[e,t.clone()])):void 0;return new e(this.registry,this.original.clone(),{name:this.local.name,docs:this.local.docs,options:this.local.options?{...this.local.options}:void 0,generic:t,props:this.local.props?{...this.local.props}:void 0,get:this.local.get,call:this.local.call,init:this.local.init,constraint:this.local.constraint?.clone(),useSite:this.local.useSite},this.bindings?this.scope:void 0)}toCode(e,t){return this.docsPrefix(t)+this.name+U.renderGenericArgs(this.generic,t)+(this.local.useSite?Bh(this.local.options):``)}extendsClause(e){return` extends ${this.base.toCodeRef(void 0,e)}`}baseMembersElided(e){return this.base.toCodeRef(void 0,e)!==this.base.toCode(void 0,e)}ownAugmentation(){return this.registry.augmentation(this.name)}definitionInit(){return this.local.init??this.ownAugmentation()?.init}definitionCall(){return this.local.call??this.ownAugmentation()?.call??(this.baseMembersElided()?this.base.refCall():void 0)}definitionGet(){return this.local.get??this.ownAugmentation()?.get??(this.baseMembersElided()?this.base.refGet():void 0)}definitionProps(){return{...this.baseMembersElided()?this.base.refProps():{},...this.ownAugmentation()?.props??{},...this.local.props??{}}}specialize(t){let n={...this.local.generic??{}},r={};for(let e of Object.keys(this.local.generic??{})){let i=t[e];i&&(n[e]=i,r[e]=i)}return Object.keys(r).length===0?this:new e(this.registry,this.original,{...this.local,generic:n},new eh(this.scope,r))}bindScope(e){return this.bindings?e?new eh(e,this.bindings):this.scope:e}constraints(){let e=this.base.constraints();return this.local.constraint?[this.local.constraint,...e]:e}valueA(e){return this.mergeLocalPropsA(this.base.defineA(e),e,t=>t.type.toA(e))}toNewA(e){return this.describeA(this.mergeLocalPropsA(this.base.toNewA(e),e,t=>mg(t.type,e)),e)}mergeLocalPropsA(e,t,n){if(!(e instanceof hf))return e;let r=t?.includeDocs??`none`,i={};for(let[e,t]of this.storedLocalProps()){let a=n(t);r===`all`&&t.docs&&(a=a.describe(t.docs)),i[e]=t.type.isOptional()&&a.kind!==`optional`?R.optional(a):a}return Object.keys(i).length===0?e:e.extend(i)}propSuperFor(e,t,n,r,i){let a=this.local.props;if(!(a&&Object.hasOwn(a,t)))return;let o=this.base.prop(t);if(!o)return;let s=new W(this.base,e.raw);if(n===`get`){if(o.type.call()&&o.get){let e=o.type;return new W(e,async e=>{let n={this:s,args:e},a=s.type.propSuperFor(s,t,`get`,r,i);return a&&(n.super=a),i.evaluate(o.get,r.child(n))})}return new W(i.registry.fn({args:i.registry.obj({}),returns:o.type}),async e=>{if(!o.get)return G(o.type,s.raw?.[t]);let n={this:s},a=s.type.propSuperFor(s,t,`get`,r,i);return a&&(n.super=a),i.evaluate(o.get,r.child(n))})}if(n===`set`)return o.set?new W(i.registry.fn({args:i.registry.obj({value:{type:o.type}}),returns:i.registry.void()}),async e=>{let n=e.raw.value,a={this:s,value:n},c=s.type.propSuperFor(s,t,`set`,r,i);return c&&(a.super=c),await i.evaluate(o.set,r.child(a)),G(i.registry.void(),void 0)}):void 0;let c=o.type.call();return c?.set?new W(i.registry.fn({args:i.registry.obj({args:{type:c.args},value:{type:c.returns??i.registry.any()}}),returns:i.registry.void()}),async e=>{let n=e.raw,a={this:s,args:n.args,value:n.value},o=s.type.propSuperFor(s,t,`callSet`,r,i);return o&&(a.super=o),await i.evaluate(c.set,r.child(a)),G(i.registry.void(),void 0)}):void 0}indexSuperFor(e,t,n,r){let i=this.local.get;if(!i)return;let a=this.base.get();if(!a)return;let o=new W(this.base,e.raw);return t===`get`?!i.get||!a.get?void 0:new W(r.registry.fn({args:r.registry.obj({key:{type:a.key}}),returns:a.value}),async e=>{let t=e.raw.key,n=r.createRootScope();return n.vars.set(`this`,o),n.vars.set(`key`,t),r.evaluate(a.get,n)}):!i.set||!a.set?void 0:new W(r.registry.fn({args:r.registry.obj({key:{type:a.key},value:{type:a.value}}),returns:r.registry.void()}),async e=>{let t=e.raw,n=r.createRootScope();return n.vars.set(`this`,o),n.vars.set(`key`,t.key),n.vars.set(`value`,t.value),await r.evaluate(a.set,n),G(r.registry.void(),void 0)})}},yg=class e extends U{static NAME=`any`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return!0}parse(e){return new W(this,e)}encode(e){return e}create(){return null}random(e){return null}compatibleType(e,t){return!0}flexible(){return!0}isUniversal(){return!0}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new Fm({path:[],code:`any.no-options`,message:`any has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),typeOf:e.method({},e.text(),`any.typeOf`),is:e.method({},e.bool(),`any.is`,{generic:{T:e.any()}}),as:e.method({},e.optional(e.alias(`T`)),`any.as`,{generic:{T:e.any()}}),toText:e.method({},e.text(),`any.toText`),toBool:e.method({},e.bool(),`any.toBool`),eq:e.method({other:e.any()},e.bool(),`any.eq`),neq:e.method({other:e.any()},e.bool(),`any.neq`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`any`}valueA(){return R.unknown()}},bg=class e extends U{static NAME=`obj`;static consumes=[`props`];name=e.NAME;static optionKeys=[];static genericKeys=[];fields;static from(t,n){let r=Nh.fromMap(t.props??{},n);return new e(n,r)}constructor(e,t){super(e,{});let n={};for(let[e,r]of Object.entries(t))n[e]=Nh.from(r);this.fields=n}valid(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let[n,r]of Object.entries(this.fields)){let i=e[n];if(!(i instanceof W)||!i.type.valid(i.raw,t)||!wh(r.type,i.type,t))return!1}return!0}parse(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new Fm({path:[],code:`object.invalid`,message:`object.parse: expected object, got ${typeof e}`,severity:`error`});let n={};for(let[r,i]of Object.entries(this.fields)){let a=e[r];n[r]=this.registry.parseValue(a,i.type,t)}return new W(this,n)}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){let r=e,i={};for(let[e]of Object.entries(this.fields))kh(i,e,r[e],t,n);return i}create(){let e={};for(let[t,n]of Object.entries(this.fields))e[t]=new W(n.type,n.type.create());return e}random(e){let t={};for(let[n,r]of Object.entries(this.fields))t[n]=new W(r.type,r.type.random(e));return t}forEachNewSlot(e,t){if(!xg(e)||Mh(e,this.scope))return!1;let n=e;for(let[e,r]of Object.entries(this.fields))e in n?t.slot(r.type,n[e],e):r.default!==void 0&&t.missing?.(r.default,e);return!0}async newFill(e,t,n){if(!xg(e)||Mh(e,this.scope))return super.newFill(e,t,n);let r=e,i;for(let[e,a]of Object.entries(this.fields))if(e in r){let o=await a.type.newFill(r[e],t,n);o!==r[e]&&(i??={...r},i[e]=o)}else a.default!==void 0&&(i??={...r},i[e]=await a.default.evaluate(t,n));return i??r}like(t){if(!(t instanceof e))return this;let n={};for(let[e,r]of Object.entries(t.fields)){let t=this.registry.like(r.type);if(t.name===`null`)return this.registry.null();n[e]={type:t}}return this.registry.obj(n)}compatibleType(t,n,r){if(!(t instanceof e))return!1;for(let[e,i]of Object.entries(this.fields)){let a=t.fields[e];if(!a){if(n?.exact)return!1;if(i.type.isOptional())continue;return!1}if(!i.type.compatible(a.type,n,r))return!1}if(n?.exact){let e=new Set(Object.keys(this.fields));for(let n of Object.keys(t.fields))if(!e.has(n))return!1}return!0}or(t){if(!(t instanceof e))return this;let n={};for(let[e,r]of Object.entries(this.fields)){let i=t.fields[e];i&&(n[e]={type:r.type.or(i.type)})}return new e(this.registry,n)}narrow(e){return{}}props(){let e=this.registry,t=Object.values(this.fields).map(e=>e.type),n=t.length===0?e.any():t.length===1?t[0]:e.or(t),r={keys:e.method({},e.list(e.text()),`object.keys`),values:e.method({},e.list(n),`object.values`),entries:e.method({},e.list(e.tuple([e.text(),n])),`object.entries`),has:e.method({key:e.text()},e.bool(),`object.has`),eq:e.method({other:e.any()},e.bool(),`object.eq`),neq:e.method({other:e.any()},e.bool(),`object.neq`),toText:e.method({},e.text(),`object.toText`)};return{...super.props(),...r,...this.fields}}get(){let e=Object.keys(this.fields);if(e.length===0)return;let t=this.registry.text(),n=e.map(e=>this.registry.literal(t,e)),r=n.length===1?n[0]:this.registry.or(n),i=Object.values(this.fields).map(e=>e.type),a=i.length===1?i[0]:this.registry.or(i),o=this.registry;return new Ph({key:r,value:a,get:o.nativeExpr(`object.indexGet`),set:o.nativeExpr(`object.indexSet`),loop:o.nativeExpr(`object.iterate`)})}toJSON(){return{name:e.NAME,props:Nh.toJSONMap(this.fields)}}clone(){let t={};for(let[e,n]of Object.entries(this.fields))t[e]={...n,type:n.type.clone()};return new e(this.registry,t)}toCode(e,t){let n=Object.entries(this.fields);if(n.length===0)return this.docsPrefix(t)+`obj`;let r=t?.includeComments!==!1,i=n.map(([e,n])=>{let i=n.type.isOptional(),a=i?n.type.required():n.type,o=i?`${e}?`:e;return`${n.docs&&r?`/* ${n.docs} */ `:``}${o}: ${a.toCode(void 0,t)}`});return this.docsPrefix(t)+`obj{${Hh(i,{indent:Uh(t)})}}`}toCodeRef(e,t){return this.docsPrefix(t)+`obj`}refProps(){return this.fields}valueA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this.fields)){let a=i.type.toA(e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=a}return this.objectA(n,e)}toNewA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this.fields)){let a=mg(i.type,e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=i.type.isOptional()?R.optional(a):a}return this.describeA(R.object(n),e)}describe(t){if(typeof t!=`object`||!t||Array.isArray(t))return;let n={};for(let[e,r]of Object.entries(t))n[e]={type:this.registry.any().describe?.(r)??this.registry.any()};return new e(this.registry,n)}};function xg(e){return jh(e)}var Sg=class e extends U{static NAME=`and`;name=e.NAME;static optionKeys=[`types`];static genericKeys=[];static from(t,n){n.registry;let r=(t.options?.types??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,{parts:t})}get parts(){return this.options.parts}valid(e,t){return this.parts.every(n=>n.valid(e,t))}effective(){let e=this.parts;if(e.length===0)return;if(e.length===1)return e[0];let t=this.mergedObjFields();return t?this.registry.obj(t):e[0]}mergedObjFields(){let e=[];for(let t of this.parts){if(!(t instanceof bg))return;e.push(t)}let t={};for(let n of e)for(let[e,r]of Object.entries(n.fields)){let n=t[e];t[e]=n?{type:this.registry.and([n.type,r.type])}:r}return t}parse(e,t){let n=this.effective();if(!n)return new W(this,e);let r=n.parse(e,t).raw;for(let e of this.parts)if(!e.valid(r,t))throw new Fm({path:[],code:`and.constraint`,message:`and: value fails part ${e.name}`,severity:`error`});return new W(this,r)}encode(e,t){return this.effective()?.encode(e,t)??e}parsesExprValue(e){return this.effective()?.parsesExprValue(e)??!1}encodeAs(e,t,n){return this.effective()?.encodeAs(e,t,n)??e}forEachNewSlot(e,t){return this.effective()?.forEachNewSlot(e,t)??!1}async newFill(e,t,n){let r=this.effective();return r?r.newFill(e,t,n):super.newFill(e,t,n)}create(){let e=this.effective();if(!e)return null;for(let t of[e,...this.parts]){let e=t.create();if(this.valid(e))return e}return e.create()}random(e){let t=this.effective();if(!t)return null;for(let n of[t,...this.parts]){let t=n.random(e);if(this.valid(t))return t}return t.random(e)}like(t){if(!(t instanceof e))return this;let n=t.parts.map(e=>this.registry.like(e)).filter(e=>e.name!==`null`);return n.length===0?this.registry.null():n.length===1?n[0]:this.registry.and(n)}compatibleType(e,t,n){return this.parts.every(r=>r.compatible(e,t,n))}isUniversal(){return this.parts.length===0||this.parts.every(e=>e.isUniversal())}or(t){return t instanceof e?new e(this.registry,[...this.parts,...t.parts]):this}simplify(){if(this.parts.length===1)return this.parts[0];if(this.parts.length===0)return this;let e=this.mergedObjFields();return e?this.registry.obj(e):this}narrow(e){return this.options}props(){let e={};for(let t of this.parts)for(let[n,r]of Object.entries(t.props()))e[n]=n in e?{type:this.registry.and([e[n].type,r.type])}:r;return e}get(){let e=this.parts.map(e=>e.get()).filter(e=>!!e);if(e.length!==0)return new Ph({key:this.registry.or(e.map(e=>e.key)),value:this.registry.and(e.map(e=>e.value))})}call(){let e=this.parts.map(e=>e.call()).filter(e=>!!e);if(e.length===0)return;let t=e.map(e=>e.returns).filter(e=>!!e);return new Fh({args:this.registry.or(e.map(e=>e.args)),returns:t.length>0?this.registry.and(t):void 0})}toJSON(){return{name:e.NAME,options:{types:this.parts.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.parts.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`and<${this.parts.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){return this.parts.length===0?R.unknown():this.parts.length===1?this.parts[0].toA(e):R.intersection(this.parts.map(t=>t.toA(e)))}toNewA(e){return this.parts.length===0?this.describeA(R.unknown(),e):this.parts.length===1?this.describeA(this.parts[0].toNewA(e),e):this.describeA(R.intersection(this.parts.map(t=>t.toNewA(e))),e)}},Cg=new Set,wg=class e extends U{static NAME=`alias`;name=e.NAME;constructor(e,t,n={}){super(e,t,n)}get hasUse(){return Object.keys(this.generic).length>0||this.options.options!==void 0}applied;static from(t,n){return new e(n,{name:t.name})}resolve(e){let t=(e?e.lookup(this.options.name):void 0)??this.scope.lookup(this.options.name);if(!t||!this.hasUse)return t;this.applied??=new WeakMap;let n=this.applied.get(t);return n||(n=this.registry.applyUse(t,this.generic,this.options.options),this.applied.set(t,n)),n}valid(e,t){let n=this.resolve(t);return!n||n.valid(e,t)}parse(e,t){let n=this.resolve(t);if(!n)return new W(this,e);let r=n.parse(e,t);return new W(this,r.raw)}encode(e,t){let n=this.resolve(t);return n?n.encode(e,t):e}parsesExprValue(e){return this.resolve(e)?.parsesExprValue(e)??!1}encodeAs(e,t,n){let r=this.resolve(n);return r?r.encodeAs(e,t,n):e}create(){let e=this.resolve();return e?e.create():null}random(e){let t=this.resolve();return t?t.random(e):null}compatibleType(e,t,n){let r=this.resolve(n);return!r||r.compatible(e,t,n)}flexible(){return!0}isUniversal(){let e=this.resolve();return!e||e.isUniversal()}or(e){let t=this.resolve();return t?t.or(e):this}simplify(e){return this.resolve(e)??this}narrow(e){return{...this.options,name:e.name??this.options.name}}props(e){let t=this.resolve(e);return t?t.props(e):super.props(e)}get(e){return this.resolve(e)?.get(e)}call(e){return this.resolve(e)?.call(e)}init(e){return this.resolve(e)?.init(e)}follow(e,t){return this.resolve(t)?.follow(e,t)}forEachNewSlot(e,t){return this.resolve()?.forEachNewSlot(e,t)??!1}async newFill(e,t,n){let r=this.resolve();return r?r.newFill(e,t,n):super.newFill(e,t,n)}toJSON(){if(!this.hasUse)return{name:this.options.name};let e=Object.entries(this.generic);return{name:this.options.name,...e.length>0?{generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{},...this.options.options===void 0?{}:{options:{...this.options.options}}}}clone(){return new e(this.scope,{...this.options},{...this.generic})}toCode(e,t){return this.docsPrefix(t)+this.options.name+U.renderGenericArgs(this.generic,t)+Bh(this.options.options)}valueA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(Cg.has(this.options.name))return R.json().describe(`A value of the named type ${this.options.name}.`);Cg.add(this.options.name);try{return t.toA(e)}finally{Cg.delete(this.options.name)}}toNewA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(Cg.has(this.options.name))return R.ref(`Expr`);Cg.add(this.options.name);try{return t.toNewA(e)}finally{Cg.delete(this.options.name)}}},Tg=class e extends U{static NAME=`bool`;name=e.NAME;static optionKeys=[`trueText`,`falseText`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return typeof e==`boolean`}parse(e){if(typeof e==`boolean`)return new W(this,e);if(e===this.options.trueText)return new W(this,!0);if(e===this.options.falseText)return new W(this,!1);throw Error(`bool.parse: expected boolean, got ${typeof e}`)}encode(e){return e}create(){return!1}random(e){return e(0,1,!0)===1}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e?new e(this.registry,{trueText:this.options.trueText??t.options.trueText,falseText:this.options.falseText??t.options.falseText}):this}narrow(e){return{...this.options,...e}}props(){let e=this.registry;return{...super.props(),eq:e.method({other:e.bool()},e.bool(),`bool.eq`),neq:e.method({other:e.bool()},e.bool(),`bool.neq`),and:e.method({other:e.bool()},e.bool(),`bool.and`),or:e.method({other:e.bool()},e.bool(),`bool.or`),xor:e.method({other:e.bool()},e.bool(),`bool.xor`),not:e.method({},e.bool(),`bool.not`),toText:e.method({},e.text(),`bool.toText`),toNum:e.method({},e.num(),`bool.toNum`)}}get(){let e=this.registry;return new Ph({key:e.num({whole:!0,min:0}),value:e.bool(),loopDynamic:!0})}toJSON(){return Jm({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`bool`+Bh(this.options)}valueA(){return R.boolean()}describe(e){return typeof e==`boolean`?this:void 0}},Eg=class e extends U{static NAME=`color`;name=e.NAME;static optionKeys=[`hasAlpha`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=4294967295}parse(e){let t=typeof e==`number`?e:Number(e);if(!this.valid(t))throw new Fm({path:[],code:`color.invalid`,message:`color.parse: not a valid 32-bit color int: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e}create(){return 255}random(e){return e(0,4294967295,!0)}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e?new e(this.registry,{hasAlpha:this.options.hasAlpha===t.options.hasAlpha?this.options.hasAlpha:void 0}):this}narrow(e){return{...this.options,...e}}init(){let e=this.registry,t=e.num({whole:!0,min:0,max:255}),n=e.optional(e.num({min:0,max:1}));return new Ih({args:e.obj({r:{type:t},g:{type:t},b:{type:t},a:{type:n}}),run:e.nativeExpr(`color.init`)})}props(){let e=this.registry,t=e.num(),n=e.bool(),r=e.text(),i=e.color();return{...super.props(),r:e.prop(t,`color.r`),g:e.prop(t,`color.g`),b:e.prop(t,`color.b`),a:e.prop(t,`color.a`),hue:e.prop(t,`color.hue`),saturation:e.prop(t,`color.saturation`),lightness:e.prop(t,`color.lightness`),eq:e.method({other:i},n,`color.eq`),neq:e.method({other:i},n,`color.neq`),lighten:e.method({amount:t},i,`color.lighten`),darken:e.method({amount:t},i,`color.darken`),saturate:e.method({amount:t},i,`color.saturate`),desaturate:e.method({amount:t},i,`color.desaturate`),opacity:e.method({alpha:t},i,`color.opacity`),invert:e.method({},i,`color.invert`),mix:e.method({other:i,weight:e.optional(t)},i,`color.mix`),complement:e.method({},i,`color.complement`),toHex:e.method({},r,`color.toHex`),toRgb:e.method({},r,`color.toRgb`),toHsl:e.method({},r,`color.toHsl`),toText:e.method({},r,`color.toText`)}}toJSON(){return Jm({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`color`+Bh(this.options)}valueA(){return R.int().min(0).max(4294967295).describe(this.options.hasAlpha?`A color as a 32-bit integer 0xRRGGBBAA.`:`A color as an integer 0xRRGGBB.`)}},Dg=class e extends U{static NAME=`date`;name=e.NAME;static optionKeys=[`min`,`max`,`utc`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}boundDate(e){return e?new Date(e):void 0}valid(e){if(!(e instanceof Date)||Number.isNaN(e.getTime()))return!1;let t=this.boundDate(this.options.min),n=this.boundDate(this.options.max);return!(t&&e<t||n&&e>n)}parse(e){let t=e instanceof Date?e:typeof e==`string`?new Date(e):new Date(NaN);if(!this.valid(t))throw new Fm({path:[],code:`date.invalid`,message:`date.parse: invalid or out-of-range: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e.toISOString().slice(0,10)}create(){return new Date}random(e){let t=this.boundDate(this.options.min)?.getTime()??Date.UTC(2e3,0,1),n=this.boundDate(this.options.max)?.getTime()??Date.UTC(2050,11,31);return new Date(e(t,n,!0))}compatibleType(t,n){return t instanceof e}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{min:n.min&&r.min?n.min<r.min?n.min:r.min:void 0,max:n.max&&r.max?n.max>r.max?n.max:r.max:void 0,utc:n.utc===r.utc?n.utc:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Fm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.min!==void 0&&(t.min&&e.min<t.min&&n(`date.widen.min`,`cannot move min earlier`),r.min=e.min),e.max!==void 0&&(t.max&&e.max>t.max&&n(`date.widen.max`,`cannot move max later`),r.max=e.max),e.utc!==void 0&&(r.utc=e.utc),r}props(){let e=this.registry,t=e.num({whole:!0}),n=e.bool(),r=e.text(),i=e.date();return{...super.props(),year:e.prop(t,`date.year`),month:e.prop(t,`date.month`),day:e.prop(t,`date.day`),dayOfWeek:e.prop(t,`date.dayOfWeek`),dayOfYear:e.prop(t,`date.dayOfYear`),eq:e.method({other:i},n,`date.eq`),neq:e.method({other:i},n,`date.neq`),before:e.method({other:i},n,`date.before`),after:e.method({other:i},n,`date.after`),addDays:e.method({days:t},i,`date.addDays`),addMonths:e.method({months:t},i,`date.addMonths`),addYears:e.method({years:t},i,`date.addYears`),diffDays:e.method({other:i},t,`date.diffDays`),diffMonths:e.method({other:i},t,`date.diffMonths`),diffYears:e.method({other:i},t,`date.diffYears`),toText:e.method({format:e.optional(r)},r,`date.toText`)}}toJSON(){return Jm({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`date`+Bh(this.options)}valueA(){return R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`).describe(`An ISO 8601 date (YYYY-MM-DD).`)}describe(e){return e instanceof Date?this:void 0}},Og=class e extends U{static NAME=`duration`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return typeof e==`number`&&!Number.isNaN(e)}parse(e){let t=typeof e==`number`?e:Number(e);return new W(this,t)}encode(e){return e}create(){return 0}random(e){return e(0,864e5,!0)}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){return{}}init(){let e=this.registry,t=e.num();return new Ih({args:e.obj({days:{type:e.optional(t)},hours:{type:e.optional(t)},minutes:{type:e.optional(t)},seconds:{type:e.optional(t)},ms:{type:e.optional(t)}}),run:e.nativeExpr(`duration.init`)})}props(){let e=this.registry,t=e.num({whole:!0}),n=e.text();return{...super.props(),totalSeconds:e.prop(e.num(),`duration.totalSeconds`),totalMinutes:e.prop(e.num(),`duration.totalMinutes`),totalHours:e.prop(e.num(),`duration.totalHours`),totalDays:e.prop(e.num(),`duration.totalDays`),days:e.prop(t,`duration.days`),hours:e.prop(t,`duration.hours`),minutes:e.prop(t,`duration.minutes`),seconds:e.prop(t,`duration.seconds`),ms:e.prop(t,`duration.ms`),toText:e.method({format:e.optional(n)},n,`duration.toText`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`duration`}valueA(){return R.number().describe(`A duration in milliseconds.`)}},kg=class e extends U{static NAME=`enum`;name=e.NAME;static optionKeys=[`values`];static genericKeys=[`V`];static from(t,n){let r=n.registry,i=t.generic?.V?n.parse(t.generic.V):r.text(),a=t.options?.values??{};return new e(n,i,{values:a})}constructor(e,t,n){super(e,n,{V:t})}get value(){return this.generic.V}valid(e,t){return this.value.valid(e,t)?Object.values(this.options.values).some(t=>t===e):!1}parse(e,t){let n=this.value.parse(e,t);if(!this.valid(n.raw,t))throw new Fm({path:[],code:`enum.not-a-member`,message:`enum.parse: ${String(n.raw)} is not one of ${Object.values(this.options.values).join(`, `)}`,severity:`error`});return new W(this,n.raw)}encode(e,t){return this.value.encode(e,t)}encodeAs(e,t,n){return this.value.encodeAs(e,t,n)}create(){let e=Object.values(this.options.values)[0];return e===void 0?this.value.create():e}random(e){let t=Object.values(this.options.values);return t.length===0?this.value.random(e):t[e(0,t.length-1,!0)]}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.value);return n.name===`null`?this.registry.null():this.registry.enum(t.options.values,n)}compatibleType(t,n,r){return!(t instanceof e)||!this.value.compatible(t.value,n,r)?!1:!n?.value||Object.values(t.options.values).every(e=>Object.values(this.options.values).some(t=>t===e))}or(t){return t instanceof e?new e(this.registry,this.value.or(t.value),{values:{...t.options.values,...this.options.values}}):this}narrow(e){let t=this.options.values;if(e.values===void 0)return this.options;for(let[n,r]of Object.entries(e.values))if(!Object.values(t).some(e=>e===r))throw new Fm({path:[],code:`enum.widen`,message:`enum.narrow: ${n}=${String(r)} not in base values`,severity:`error`});return{values:e.values}}props(){let e=this.registry,t=this.value;return{...super.props(),name:e.prop(e.text(),`enum.name`),value:e.prop(t,`enum.value`),eq:e.method({other:t},e.bool(),`enum.eq`),neq:e.method({other:t},e.bool(),`enum.neq`),toText:e.method({},e.text(),`enum.toText`)}}toJSON(){return{name:e.NAME,generic:{V:this.value.toJSON()},options:{values:this.options.values}}}clone(){return new e(this.registry,this.value.clone(),{values:{...this.options.values}})}toCode(e,t){let n=`enum<${this.value.toCode(void 0,t)}>`+jg(this.options.values,t);return this.docsPrefix(t)+n}valueA(){let e=Object.values(this.options.values);return e.length>0&&e.every(e=>typeof e==`string`)?R.enum(e):R.union(e.map(e=>R.literal(e)))}},Ag=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function jg(e,t){let n=Object.entries(e);return n.length===0?``:`{${Hh(n.map(([e,t])=>{let n=Ag.test(e)?e:JSON.stringify(e);return t===e?n:`${n}=${typeof t==`number`||typeof t==`boolean`?String(t):JSON.stringify(t??null)}`}),{indent:Uh(t)})}}`}var Mg=class e extends U{static NAME=`fn`;static consumes=[`call`];name=e.NAME;static optionKeys=[];static declaresGenerics=!0;_call;static from(t,n){let r=n.registry,i={},a=new eh(n);if(t.generic)for(let[e,n]of Object.entries(t.generic))i[e]=a.parse(n);return t.call?new e(a,Fh.from(t.call,a),i):new e(a,new Fh({args:r.any(),returns:r.any()}),i)}constructor(e,t,n={}){super(e,{},n),this._call=t instanceof Fh?t:new Fh(t)}parsesExprValue(e){return!0}valid(e,t){return!!(typeof e==`function`||typeof e==`string`||e&&typeof e==`object`&&`kind`in e)}parse(e,t){return typeof e==`string`||e&&typeof e==`object`&&`kind`in e||typeof e==`function`?new W(this,e):new W(this,null)}encode(e,t){return typeof e==`function`?null:e}create(){return{kind:`new`,type:(this._call.returns??this.registry.void()).toJSON()}}random(e){return this.create()}like(t){if(!(t instanceof e))return this;let n=this.registry,r=n.like(t._call.args);if(r.name===`null`)return n.null();let i=t._call.returns?n.like(t._call.returns):void 0;if(i&&i.name===`null`)return n.null();let a=t._call.throws?n.like(t._call.throws):void 0;return a&&a.name===`null`?n.null():n.fn({args:r,returns:i,throws:a,generic:this.generic})}compatibleType(t,n,r){return!(!(t instanceof e)||!this._call.args.compatible(t._call.args,n,r)||this._call.returns&&t._call.returns&&!this._call.returns.compatible(t._call.returns,n,r))}or(t){return t instanceof e?new e(this.registry,{args:this._call.args.or(t._call.args),returns:this._call.returns&&t._call.returns?this._call.returns.or(t._call.returns):this._call.returns??t._call.returns,throws:this._call.throws&&t._call.throws?this._call.throws.or(t._call.throws):this._call.throws??t._call.throws}):this}narrow(e){return{}}call(e){return this._call}props(e){return super.props(e)}toJSON(){let t=Object.keys(this.generic),n=t.length===0?void 0:Object.fromEntries(t.map(e=>[e,this.generic[e].toJSON()]));return Jm({name:e.NAME,call:this._call.toJSON(),generic:n})}clone(){let t={};for(let[e,n]of Object.entries(this.generic))t[e]=n.clone();return new e(this.registry,{args:this._call.args.clone(),returns:this._call.returns?.clone(),throws:this._call.throws?.clone(),get:this._call.get,set:this._call.set},t)}toCode(e,t){let n=this._call.returns?.toCode(void 0,t)??`void`;return this.docsPrefix(t)+`${U.renderGenerics(this.generic,t)}${this._call.renderTypes(t)}(${U.formatParams(this._call.args,t)}): ${n}`}valueA(){return R.union([R.string(),R.ref(`Expr`)])}},Ng=class e extends U{static NAME=`interface`;static consumes=[`props`,`get`,`call`];name=e.NAME;static optionKeys=[];static genericKeys=[];_props;_get;_call;static from(t,n){return n.registry,new e(n,{props:t.props?Nh.fromMap(t.props,n):{},get:t.get?Ph.from(t.get,n):void 0,call:t.call?Fh.from(t.call,n):void 0})}constructor(e,t){super(e,{});let n={};if(t.props)for(let[e,r]of Object.entries(t.props))n[e]=Nh.from(r);this._props=n,this._get=t.get,this._call=t.call}valid(e,t){return!0}parse(e,t){return new W(this,e)}encode(e,t){return e}create(){return null}random(e){return null}like(t){if(!(t instanceof e))return this;let n=this.registry,r={};for(let[e,i]of Object.entries(t._props)){let t=n.like(i.type);if(t.name===`null`)return n.null();r[e]={type:t}}let i;if(t._get){let e=n.like(t._get.key),r=n.like(t._get.value);if(e.name===`null`||r.name===`null`)return n.null();i=new Ph({key:e,value:r})}let a;if(t._call){let e=n.like(t._call.args);if(e.name===`null`)return n.null();let r=t._call.returns?n.like(t._call.returns):void 0;if(r&&r.name===`null`)return n.null();a=new Fh({args:e,returns:r})}return new e(n,{props:r,get:i,call:a})}compatibleType(e,t,n){let r=e.props(n);for(let[e,i]of Object.entries(this._props)){let a=r[e];if(!a||!i.type.compatible(a.type,t,n))return!1}if(this._get){let r=e.get(n);if(!r||!this._get.key.compatible(r.key,t,n)||!this._get.value.compatible(r.value,t,n))return!1}if(this._call){let r=e.call(n);if(!r||!this._call.args.compatible(r.args,t,n)||this._call.returns&&r.returns&&!this._call.returns.compatible(r.returns,t,n))return!1}return!0}flexible(){return!0}isUniversal(){return Object.keys(this._props).length===0&&!this._get&&!this._call}or(t){if(!(t instanceof e))return this;let n={};for(let e of Object.keys(this._props))e in t._props&&(n[e]={type:this._props[e].type.or(t._props[e].type)});return new e(this.registry,{props:n})}narrow(e){return{}}props(e){return{...super.props(e),...this._props}}get(e){return this._get}call(e){return this._call}toJSON(){return Jm({name:e.NAME,props:Object.keys(this._props).length>0?Nh.toJSONMap(this._props):void 0,get:this._get?.toJSON(),call:this._call?.toJSON()})}clone(){let t={};for(let[e,n]of Object.entries(this._props))t[e]={...n,type:n.type.clone()};return new e(this.registry,{props:t,get:this._get,call:this._call})}toCode(e,t){let n=t?.includeComments!==!1,r=[];for(let[e,i]of Object.entries(this._props)){let a=i.type.isOptional(),o=a?i.type.required():i.type,s=a?`${e}?`:e,c=i.docs&&n?`/* ${i.docs} */ `:``;r.push(`${c}${s}: ${o.toCode(void 0,t)}`)}if(this._get&&r.push(`[key: ${this._get.key.toCode(void 0,t)}]: ${this._get.value.toCode(void 0,t)}`),this._call){let e=this._call.returns?.toCode(void 0,t)??`void`;r.push(`(${this._call.args.toCode(void 0,t)}): ${e}`)}let i=r.length===0?`iface`:`iface{${Hh(r,{indent:Uh(t)})}}`;return this.docsPrefix(t)+i}toCodeRef(e,t){return this.docsPrefix(t)+`iface`}refProps(){return this._props}refGet(){return this._get}refCall(){return this._call}valueA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this._props)){let a=i.type.toA(e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=a}return this.objectA(n,e)}toNewA(e){let t=e?.includeDocs??`none`,n={};for(let[e,r]of Object.entries(this._props)){let i=R.ref(`Expr`);t===`all`&&r.docs&&(i=i.describe(r.docs)),n[e]=i}return this.describeA(R.object(n),e)}},Pg=class e extends U{static NAME=`literal`;name=e.NAME;static optionKeys=[`value`];static genericKeys=[`T`];inner;static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any(),a=t.options?.value;return new e(n,i,a)}constructor(e,t,n){super(e,{value:n},{T:t}),this.inner=t}get literal(){return this.options.value}valid(e,t){return this.inner.valid(e,t)&&e===this.literal}parse(e,t){let n=this.inner.parse(e,t);if(n.raw!==this.literal)throw new Fm({path:[],code:`literal.not-match`,message:`literal: expected ${String(this.literal)}, got ${String(n.raw)}`,severity:`error`});return new W(this,n.raw)}encode(e,t){return this.inner.encode(e,t)}encodeAs(e,t,n){return this.inner.encodeAs(e,t,n)}create(){return this.literal}random(e){return this.literal}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r)&&this.literal===t.literal:!n?.exact&&this.inner.compatible(t,n,r)}isUniversal(){return this.inner.isUniversal()}or(t){return t instanceof e&&(t.literal,this.literal),this}narrow(e){if(e.value!==void 0&&e.value!==this.literal)throw new Fm({path:[],code:`literal.narrow`,message:`literal value cannot change via narrow`,severity:`error`});return this.options}props(){return this.inner.props()}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()},options:{value:this.literal}}}clone(){return new e(this.registry,this.inner.clone(),this.literal)}toCode(e,t){return this.docsPrefix(t)+`literal<${this.inner.toCode(void 0,t)}>`+Bh({value:this.literal})}valueA(){return R.literal(this.literal)}},Fg=class e extends U{static NAME=`list`;name=e.NAME;static optionKeys=[`minLength`,`maxLength`];static genericKeys=[`V`];static from(t,n){let r=n.registry,i=t.generic?.V?n.parse(t.generic.V):r.any();return new e(n,i,t.options??{})}constructor(e,t,n={}){super(e,n,{V:t})}get item(){return this.generic.V}valid(e,t){if(!Array.isArray(e))return!1;let{minLength:n,maxLength:r}=this.options;return n!==void 0&&e.length<n||r!==void 0&&e.length>r?!1:e.every(e=>e instanceof W&&e.type.valid(e.raw,t)&&wh(this.item,e.type,t))}parse(e,t){if(!Array.isArray(e))throw new Fm({path:[],code:`list.invalid`,message:`list.parse: expected array, got ${typeof e}`,severity:`error`});let n=e.map(e=>this.registry.parseValue(e,this.item,t));if(!this.valid(n,t))throw new Fm({path:[],code:`list.constraint`,message:`list.parse: length constraints violated`,severity:`error`});return new W(this,n)}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){return e.map(e=>Oh(e,t,n))}create(){let e=this.options.minLength??0;return Array.from({length:e},()=>new W(this.item,this.item.create()))}random(e){let t=this.options.minLength??0,n=e(t,this.options.maxLength??Math.max(t,5),!0);return Array.from({length:n},()=>new W(this.item,this.item.random(e)))}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<e.length;n++)t.slot(this.item,e[n],n);return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i of e)r.push(await this.item.newFill(i,t,n));return r}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.item);return n.name===`null`?n:this.registry.list(n)}compatibleType(t,n,r){if(!(t instanceof e)||!this.item.compatible(t.item,n,r))return!1;if(!n?.value)return!0;let i=this.options,a=t.options;return!(i.minLength!==void 0&&(a.minLength===void 0||a.minLength<i.minLength)||i.maxLength!==void 0&&(a.maxLength===void 0||a.maxLength>i.maxLength))}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,this.item.or(t.item),{minLength:n.minLength!==void 0&&r.minLength!==void 0?Math.min(n.minLength,r.minLength):void 0,maxLength:n.maxLength!==void 0&&r.maxLength!==void 0?Math.max(n.maxLength,r.maxLength):void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Fm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.minLength!==void 0&&(t.minLength!==void 0&&e.minLength<t.minLength&&n(`list.widen.minLength`,`local ${e.minLength} < base ${t.minLength}`),r.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength!==void 0&&e.maxLength>t.maxLength&&n(`list.widen.maxLength`,`local ${e.maxLength} > base ${t.maxLength}`),r.maxLength=e.maxLength),r}get(){let e=this.registry;return new Ph({key:e.num({whole:!0,min:0}),value:this.item,get:e.nativeExpr(`list.indexGet`),set:e.nativeExpr(`list.indexSet`),loop:e.nativeExpr(`list.iterate`)})}props(){let e=this.registry,t=this.item,n=e.num(),r=e.bool(),i=e.text(),a=e.void(),o=e.optional(t),s=e.list(t),c=r=>e.fn({args:e.obj({value:{type:t},index:{type:n}}),returns:r});return{...super.props(),length:e.prop(n,`list.length`),at:e.method({index:n},o,`list.at`),push:e.method({value:t},a,`list.push`),pop:e.method({},o,`list.pop`),shift:e.method({},o,`list.shift`),unshift:e.method({value:t},a,`list.unshift`),insert:e.method({index:n,value:t},a,`list.insert`),remove:e.method({index:n},t,`list.remove`),clear:e.method({},a,`list.clear`),slice:e.method({start:e.optional(n),end:e.optional(n)},s,`list.slice`),concat:e.method({other:s},s,`list.concat`),reverse:e.method({},s,`list.reverse`),join:e.method({separator:e.optional(i)},i,`list.join`),indexOf:e.method({value:t},n,`list.indexOf`),contains:e.method({value:t},r,`list.contains`),unique:e.method({},s,`list.unique`),duplicates:e.method({},s,`list.duplicates`),map:e.method({fn:c(e.alias(`R`))},e.list(e.alias(`R`)),`list.map`,{generic:{R:e.any()}}),filter:e.method({fn:c(r)},s,`list.filter`),find:e.method({fn:c(r)},o,`list.find`),reduce:e.method({fn:e.fn({args:e.obj({acc:{type:e.alias(`R`)},value:{type:t},index:{type:n}}),returns:e.alias(`R`)}),initial:e.alias(`R`)},e.alias(`R`),`list.reduce`,{generic:{R:e.any()}}),some:e.method({fn:c(r)},r,`list.some`),every:e.method({fn:c(r)},r,`list.every`),sort:e.method({fn:e.optional(e.fn({args:e.obj({a:{type:t},b:{type:t}}),returns:n}))},s,`list.sort`),isEmpty:e.method({},r,`list.isEmpty`),isNotEmpty:e.method({},r,`list.isNotEmpty`),first:e.prop(o,`list.first`),last:e.prop(o,`list.last`)}}toJSON(){return Jm({name:e.NAME,generic:{V:this.item.toJSON()},options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,this.item.clone(),{...this.options})}toCode(e,t){return this.docsPrefix(t)+`list<${this.item.toCode(void 0,t)}>`+Bh(this.options,{minLength:0})}valueA(e){let t=R.array(this.item.toA(e));return this.options.minLength!==void 0&&(t=t.min(this.options.minLength)),this.options.maxLength!==void 0&&(t=t.max(this.options.maxLength)),t}toNewA(e){let t=R.array(R.ref(`Expr`));return this.options.minLength!==void 0&&(t=t.min(this.options.minLength)),this.options.maxLength!==void 0&&(t=t.max(this.options.maxLength)),this.describeA(t,e)}describe(t){if(Array.isArray(t))return new e(this.registry,this.registry.any(),{})}};function Ig(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function Lg(e){if(Array.isArray(e))return[e[0],e[1]];let t=e;return[t?.key,t?.value]}function Rg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var zg=class e extends U{static NAME=`map`;name=e.NAME;static optionKeys=[];static genericKeys=[`K`,`V`];static from(t,n){let r=n.registry,i=t.generic?.K?n.parse(t.generic.K):r.text(),a=t.generic?.V?n.parse(t.generic.V):r.any();return new e(n,i,a)}constructor(e,t,n){super(e,{},{K:t,V:n})}get key(){return this.generic.K}get value(){return this.generic.V}valid(e,t){if(!(e instanceof Map))return!1;for(let[,n]of e){if(!Array.isArray(n)||n.length!==2)return!1;let[e,r]=n;if(!(e instanceof W)||!(r instanceof W)||!e.type.valid(e.raw,t)||!r.type.valid(r.raw,t)||!wh(this.key,e.type,t)||!wh(this.value,r.type,t))return!1}return!0}parse(e,t){let n=e instanceof Map?Array.from(e,([e,t])=>Ig(t)?t:[e,t]):this.textKeyed()&&Rg(e)?Object.entries(e):e;if(!Array.isArray(n))throw new Fm({path:[],code:`map.invalid`,message:`map.parse: expected array of [key, value] pairs`,severity:`error`});let r=new Map;for(let e of n){let[n,i]=Array.isArray(e)?e:[e.key,e.value],a=this.registry.parseValue(n,this.key,t),o=this.registry.parseValue(i,this.value,t);r.set(a.raw,[a,o])}return new W(this,r)}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){return t.form===`logical`&&this.textKeyed()?Object.fromEntries(Array.from(e,([,[e,r]])=>[String(Oh(e,t,n)),Oh(r,t,n)])):Array.from(e,([,[e,r]])=>({key:Oh(e,t,n),value:Oh(r,t,n)}))}textKeyed(){return this.key.name===`text`}create(){return new Map}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<e.length;n++){let[r,i]=Lg(e[n]);t.slot(this.key,r,`${n}.key`),t.slot(this.value,i,`${n}.value`)}return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i of e){let[e,a]=Lg(i);r.push({key:await this.key.newFill(e,t,n),value:await this.value.newFill(a,t,n)})}return r}random(e){let t=e(0,5,!0),n=new Map;for(let r=0;r<t;r++){let t=this.key.random(e),r=this.value.random(e);n.set(t,[new W(this.key,t),new W(this.value,r)])}return n}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.key),r=this.registry.like(t.value);return n.name===`null`||r.name===`null`?this.registry.null():this.registry.map(n,r)}compatibleType(t,n,r){return t instanceof e&&this.key.compatible(t.key,n,r)&&this.value.compatible(t.value,n,r)}or(t){return t instanceof e?new e(this.registry,this.key.or(t.key),this.value.or(t.value)):this}narrow(e){return{}}get(){let e=this.registry;return new Ph({key:this.key,value:this.value,get:e.nativeExpr(`map.indexGet`),set:e.nativeExpr(`map.indexSet`),loop:e.nativeExpr(`map.iterate`)})}props(){let e=this.registry,t=this.key,n=this.value,r=e.num(),i=e.bool(),a=e.void(),o=e.optional(n);return{...super.props(),size:e.prop(r,`map.size`),at:e.method({key:t},o,`map.at`),has:e.method({key:t},i,`map.has`),delete:e.method({key:t},i,`map.delete`),clear:e.method({},a,`map.clear`),keys:e.method({},e.list(t),`map.keys`),values:e.method({},e.list(n),`map.values`),isEmpty:e.method({},i,`map.isEmpty`),isNotEmpty:e.method({},i,`map.isNotEmpty`)}}toJSON(){return{name:e.NAME,generic:{K:this.key.toJSON(),V:this.value.toJSON()}}}clone(){return new e(this.registry,this.key.clone(),this.value.clone())}toCode(e,t){return this.docsPrefix(t)+`map<${this.key.toCode(void 0,t)}, ${this.value.toCode(void 0,t)}>`}valueA(e){return this.key.name===`text`?R.record(this.value.toA(e)):R.array(this.objectA({key:this.key.toA(e),value:this.value.toA(e)},e))}toNewA(e){return this.describeA(R.array(R.object({key:R.ref(`Expr`),value:R.ref(`Expr`)})),e)}describe(t){return t instanceof Map?new e(this.registry,this.registry.any(),this.registry.any()):void 0}},Bg=class e extends U{constructor(e,t){super(e,{excluded:t.toJSON()}),this.excluded=t}excluded;static NAME=`not`;name=e.NAME;static optionKeys=[`excluded`];static genericKeys=[];static from(t,n){let r=n.registry,i=t.options?.excluded?n.parse(t.options.excluded):r.any();return new e(n,i)}valid(e,t){return!this.excluded.valid(e,t)}parse(e,t){if(this.excluded.valid(e,t))throw new Fm({path:[],code:`not.excluded`,message:`not: value matches excluded type ${this.excluded.name}`,severity:`error`});return new W(this,e)}encode(e,t){return e}create(){return null}random(e){return null}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.excluded);return n.name===`null`?n:this.registry.not(n)}compatibleType(t,n,r){return n?.exact?t instanceof e&&this.excluded.exact(t.excluded,r):!this.excluded.compatible(t,n,r)}flexible(){return!0}or(t){return t instanceof e?new e(this.registry,this.registry.or([this.excluded,t.excluded])):this}narrow(e){return{excluded:e.excluded??this.options.excluded}}props(){let e=this.registry;return{...super.props(),typeOf:e.method({},e.text(),`not.typeOf`),toText:e.method({},e.text(),`not.toText`)}}toJSON(){return{name:e.NAME,options:{excluded:this.excluded.toJSON()}}}clone(){return new e(this.registry,this.excluded.clone())}toCode(e,t){return this.docsPrefix(t)+`not<${this.excluded.toCode(void 0,t)}>`}valueA(e){return R.not(this.excluded.toA(e))}},Vg=class e extends U{static NAME=`null`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return e===null}parse(e){if(e!==null)throw new Fm({path:[],code:`null.invalid`,message:`null expects null, got ${typeof e}`,severity:`error`});return new W(this,null)}encode(e){return null}create(){return null}random(e){return null}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new Fm({path:[],code:`null.no-options`,message:`null has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),toText:e.method({},e.text(),`null.toText`),toBool:e.method({},e.bool(),`null.toBool`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`null`}valueA(){return R.null()}},Hg=class e extends U{constructor(e,t){super(e,{},{T:t}),this.inner=t}inner;static NAME=`nullable`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e===null||this.inner.valid(e,t)}parse(e,t){if(e===null)return new W(this,null);let n=this.inner.parse(e,t);return new W(this,n.raw)}parsesExprValue(e){return this.inner.parsesExprValue(e)}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){return e===null?null:this.inner.encodeAs(e,t,n)}forEachNewSlot(e,t){return e!=null&&this.inner.forEachNewSlot(e,t)}async newFill(e,t,n){return e==null?e:this.inner.newFill(e,t,n)}create(){return null}random(e){return e(0,9,!0)<3?null:this.inner.random(e)}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.inner);return n.name===`null`?n:this.registry.nullable(n)}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r):!n?.exact&&this.inner.compatible(t,n,r)}or(t){return t instanceof e?new e(this.registry,this.inner.or(t.inner)):this}required(){return this.inner}isUniversal(){return this.inner.isUniversal()}narrow(e){if(e&&Object.keys(e).length>0)throw new Fm({path:[],code:`nullable.no-options`,message:`nullable has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry,t=this.inner;return{...super.props(),value:e.prop(t,`nullable.value`),isNull:e.method({},e.bool(),`nullable.isNull`),or:e.method({fallback:t},t,`nullable.or`),map:e.method({fn:e.fn({args:e.obj({value:{type:t}}),returns:e.alias(`R`)})},e.nullable(e.alias(`R`)),`nullable.map`,{generic:{R:e.any()}})}}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()}}}clone(){return new e(this.registry,this.inner.clone())}toCode(e,t){return this.docsPrefix(t)+`nullable<${this.inner.toCode(void 0,t)}>`}valueA(e){return R.nullable(this.inner.toA(e))}toNewA(e){return this.describeA(R.nullable(this.inner.toNewA(e)),e)}},Ug=class e extends U{static NAME=`num`;name=e.NAME;static optionKeys=[`min`,`max`,`whole`,`minPrecision`,`maxPrecision`,`prefix`,`suffix`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){if(typeof e!=`number`||Number.isNaN(e))return!1;let{min:t,max:n,whole:r}=this.options;return!(t!==void 0&&e<t||n!==void 0&&e>n||r&&!Number.isInteger(e))}parse(e){let t=typeof e==`string`?Number(e):e;if(typeof t!=`number`||Number.isNaN(t))throw new Fm({path:[],code:`num.invalid`,message:`num.parse: not a number \u2014 ${String(e)}`,severity:`error`});if(!this.valid(t))throw new Fm({path:[],code:`num.out-of-range`,message:`num.parse: ${t} violates options ${JSON.stringify(this.options)}`,severity:`error`});return new W(this,t)}encode(e){return e}create(){let{min:e,max:t,whole:n}=this.options,r=0;if(e!==void 0&&r<e&&(r=e),t!==void 0&&r>t&&(r=t),n&&!Number.isInteger(r)){let e=Math.ceil(r);r=t!==void 0&&e>t?Math.floor(r):e}return r}random(e){return e(this.options.min??0,this.options.max??100,this.options.whole??!1)}compatibleType(t,n){if(!(t instanceof e))return!1;if(!n?.value)return!0;let r=this.options,i=t.options;return!(r.min!==void 0&&(i.min===void 0||i.min<r.min)||r.max!==void 0&&(i.max===void 0||i.max>r.max)||r.whole&&!i.whole)}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{min:n.min!==void 0&&r.min!==void 0?Math.min(n.min,r.min):void 0,max:n.max!==void 0&&r.max!==void 0?Math.max(n.max,r.max):void 0,whole:n.whole&&r.whole,minPrecision:n.minPrecision!==void 0&&r.minPrecision!==void 0?Math.min(n.minPrecision,r.minPrecision):void 0,maxPrecision:n.maxPrecision!==void 0&&r.maxPrecision!==void 0?Math.max(n.maxPrecision,r.maxPrecision):void 0,prefix:n.prefix===r.prefix?n.prefix:void 0,suffix:n.suffix===r.suffix?n.suffix:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Fm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.min!==void 0&&(t.min!==void 0&&e.min<t.min&&n(`num.widen.min`,`local.min ${e.min} < base.min ${t.min}`),r.min=e.min),e.max!==void 0&&(t.max!==void 0&&e.max>t.max&&n(`num.widen.max`,`local.max ${e.max} > base.max ${t.max}`),r.max=e.max),e.whole!==void 0&&(t.whole===!0&&!e.whole&&n(`num.widen.whole`,`base requires whole; local cannot remove`),r.whole=e.whole),e.minPrecision!==void 0&&(t.minPrecision!==void 0&&e.minPrecision<t.minPrecision&&n(`num.widen.minPrecision`,`minPrecision cannot decrease`),r.minPrecision=e.minPrecision),e.maxPrecision!==void 0&&(t.maxPrecision!==void 0&&e.maxPrecision>t.maxPrecision&&n(`num.widen.maxPrecision`,`maxPrecision cannot increase`),r.maxPrecision=e.maxPrecision),e.prefix!==void 0&&(r.prefix=e.prefix),e.suffix!==void 0&&(r.suffix=e.suffix),r}get(){let e=this.registry;return new Ph({key:e.num({whole:!0,min:0}),value:e.num(),loop:e.nativeExpr(`num.loop`)})}props(){let e=this.registry,t=e.num(),n=e.bool(),r=e.text(),i=e.optional(t);return{...super.props(),eq:e.method({other:t,epsilon:i},n,`num.eq`),neq:e.method({other:t,epsilon:i},n,`num.neq`),lt:e.method({other:t},n,`num.lt`),lte:e.method({other:t},n,`num.lte`),gt:e.method({other:t},n,`num.gt`),gte:e.method({other:t},n,`num.gte`),add:e.method({other:t},t,`num.add`),sub:e.method({other:t},t,`num.sub`),mul:e.method({other:t},t,`num.mul`),div:e.method({other:t},t,`num.div`),mod:e.method({other:t},t,`num.mod`),pow:e.method({other:t},t,`num.pow`),abs:e.method({},t,`num.abs`),neg:e.method({},t,`num.neg`),sign:e.method({},t,`num.sign`),sqrt:e.method({},t,`num.sqrt`),min:e.method({other:t},t,`num.min`),max:e.method({other:t},t,`num.max`),clamp:e.method({min:t,max:t},t,`num.clamp`),floor:e.method({},t,`num.floor`),ceil:e.method({},t,`num.ceil`),round:e.method({},t,`num.round`),isZero:e.method({},n,`num.isZero`),isPositive:e.method({},n,`num.isPositive`),isNegative:e.method({},n,`num.isNegative`),isInteger:e.method({},n,`num.isInteger`),isEven:e.method({},n,`num.isEven`),isOdd:e.method({},n,`num.isOdd`),toText:e.method({precision:i},r,`num.toText`),toBool:e.method({},n,`num.toBool`)}}toJSON(){return Jm({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`num`+Bh(this.options,{minPrecision:1,maxPrecision:7,prefix:``,suffix:``})}valueA(){let e=this.options.whole?R.int():R.number();return this.options.min!==void 0&&(e=e.min(this.options.min)),this.options.max!==void 0&&(e=e.max(this.options.max)),e}describe(t){if(!(typeof t!=`number`||Number.isNaN(t)))return new e(this.registry,{whole:Number.isInteger(t)})}},Wg=class e extends U{constructor(e,t){super(e,{},{T:t}),this.inner=t}inner;static NAME=`optional`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e===void 0||this.inner.valid(e,t)}parse(e,t){if(e==null)return new W(this,void 0);let n=this.inner.parse(e,t);return new W(this,n.raw)}parsesExprValue(e){return this.inner.parsesExprValue(e)}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){return e===void 0?null:this.inner.encodeAs(e,t,n)}forEachNewSlot(e,t){return e!=null&&this.inner.forEachNewSlot(e,t)}async newFill(e,t,n){return e==null?e:this.inner.newFill(e,t,n)}create(){}random(e){if(!(e(0,9,!0)<3))return this.inner.random(e)}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.inner);return n.name===`null`?n:this.registry.optional(n)}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r):!n?.exact&&this.inner.compatible(t,n,r)}or(t){return t instanceof e?new e(this.registry,this.inner.or(t.inner)):this}required(){return this.inner}isOptional(){return!0}isUniversal(){return this.inner.isUniversal()}narrow(e){if(e&&Object.keys(e).length>0)throw new Fm({path:[],code:`optional.no-options`,message:`optional has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry,t=this.inner;return{...super.props(),value:e.prop(t,`optional.value`),has:e.method({},e.bool(),`optional.has`),or:e.method({fallback:t},t,`optional.or`),map:e.method({fn:e.fn({args:e.obj({value:{type:t}}),returns:e.alias(`R`)})},e.optional(e.alias(`R`)),`optional.map`,{generic:{R:e.any()}})}}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()}}}clone(){return new e(this.registry,this.inner.clone())}toCode(e,t){return this.docsPrefix(t)+`optional<${this.inner.toCode(void 0,t)}>`}valueA(e){return R.optional(this.inner.toA(e))}toNewA(e){return this.describeA(R.optional(this.inner.toNewA(e)),e)}},Gg=class e extends U{static NAME=`or`;name=e.NAME;static optionKeys=[`types`];static genericKeys=[];static from(t,n){n.registry;let r=(t.options?.types??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,{variants:t})}get variants(){return this.options.variants}valid(e,t){return this.variants.some(n=>n.valid(e,t))}parse(e,t){for(let n of this.variants)try{let r=n.parse(e,t);return new W(this,r.raw)}catch{continue}throw new Fm({path:[],code:`or.no-match`,message:`or: no variant matched (${this.variants.map(e=>e.name).join(` | `)})`,severity:`error`})}encode(e,t){let n=this.variants.find(n=>n.valid(e,t));if(!n)throw new Fm({path:[],code:`or.dump.no-match`,message:`or.dump: value does not satisfy any variant`,severity:`error`});return n.encode(e,t)}parsesExprValue(e){return this.variants.some(t=>t.parsesExprValue(e))}encodeAs(e,t,n){let r=this.variants.find(t=>t.valid(e,n));if(!r)throw new Fm({path:[],code:`or.dump.no-match`,message:`or.dump: value does not satisfy any variant`,severity:`error`});return r.encodeAs(e,t,n)}create(){return this.variants[0]?.create()??null}random(e){let t=e(0,this.variants.length-1,!0);return this.variants[t]?.random(e)??null}like(t){if(!(t instanceof e))return this;let n=t.variants.map(e=>this.registry.like(e)).filter(e=>e.name!==`null`);return n.length===0?this.registry.null():n.length===1?n[0]:this.registry.or(n)}compatibleType(e,t,n){return this.variants.some(r=>r.compatible(e,t,n))}or(t){return t instanceof e?new e(this.registry,[...this.variants,...t.variants]):new e(this.registry,[...this.variants,t])}simplify(){return this.variants.length===1?this.variants[0]:this}narrow(e){return this.options}props(){let e=super.props();if(this.variants.length===0)return e;let t=this.variants.map(e=>e.props()),n=Object.keys(t[0]).filter(e=>t.every(t=>e in t)),r={...e};for(let e of n){let n=t.map(t=>t[e].type);r[e]={type:this.registry.or(n)}}return r}get(){let e=this.variants.map(e=>e.get());if(e.some(e=>!e))return;let t=e;return new Ph({key:this.registry.and(t.map(e=>e.key)),value:this.registry.or(t.map(e=>e.value))})}call(){let e=this.variants.map(e=>e.call());if(e.some(e=>!e))return;let t=e,n=t.map(e=>e.returns).filter(e=>!!e),r=t.map(e=>e.throws).filter(e=>!!e);return new Fh({args:this.registry.and(t.map(e=>e.args)),returns:n.length===t.length?this.registry.or(n):void 0,throws:r.length>0?this.registry.or(r):void 0})}toJSON(){return{name:e.NAME,options:{types:this.variants.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.variants.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`or<${this.variants.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){return this.variants.length===0?R.never():this.variants.length===1?this.variants[0].toA(e):R.union(this.variants.map(t=>t.toA(e)))}toNewA(e){return this.variants.length===0?this.describeA(R.never(),e):this.variants.length===1?this.describeA(this.variants[0].toNewA(e),e):this.describeA(R.union(this.variants.map(t=>t.toNewA(e))),e)}},Kg=class e extends U{static NAME=`text`;name=e.NAME;static optionKeys=[`minLength`,`maxLength`,`pattern`,`flags`];static genericKeys=[];_regex;static from(t,n){return n.registry,new e(n,t.options??{})}regex(){if(this._regex)return this._regex;if(this.options.pattern)return this._regex=new RegExp(this.options.pattern,this.options.flags),this._regex}valid(e){if(typeof e!=`string`)return!1;let{minLength:t,maxLength:n}=this.options;if(t!==void 0&&e.length<t||n!==void 0&&e.length>n)return!1;let r=this.regex();return!(r&&!r.test(e))}parse(e){if(typeof e!=`string`)throw new Fm({path:[],code:`text.invalid`,message:`text.parse: expected string, got ${typeof e}`,severity:`error`});if(!this.valid(e))throw new Fm({path:[],code:`text.constraint`,message:`text.parse: value violates constraints`,severity:`error`});return new W(this,e)}encode(e){return e}create(){let e=this.options.minLength??0;return e>0?`a`.repeat(e):``}random(e){let t=e(this.options.minLength??0,this.options.maxLength??16,!0),n=``;for(let r=0;r<t;r++)n+=`abcdefghijklmnopqrstuvwxyz0123456789`[e(0,35,!0)];return n}compatibleType(t,n){if(!(t instanceof e))return!1;if(!n?.value)return!0;let r=this.options,i=t.options;return!(r.minLength!==void 0&&(i.minLength===void 0||i.minLength<r.minLength)||r.maxLength!==void 0&&(i.maxLength===void 0||i.maxLength>r.maxLength)||r.pattern&&r.pattern!==i.pattern)}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{minLength:n.minLength!==void 0&&r.minLength!==void 0?Math.min(n.minLength,r.minLength):void 0,maxLength:n.maxLength!==void 0&&r.maxLength!==void 0?Math.max(n.maxLength,r.maxLength):void 0,pattern:n.pattern===r.pattern?n.pattern:void 0,flags:n.pattern===r.pattern?n.flags:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Fm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.minLength!==void 0&&(t.minLength!==void 0&&e.minLength<t.minLength&&n(`text.widen.minLength`,`local ${e.minLength} < base ${t.minLength}`),r.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength!==void 0&&e.maxLength>t.maxLength&&n(`text.widen.maxLength`,`local ${e.maxLength} > base ${t.maxLength}`),r.maxLength=e.maxLength),e.pattern!==void 0&&(t.pattern!==void 0&&(e.pattern!==t.pattern||e.flags!==t.flags)&&n(`text.widen.pattern`,`pattern narrowing is only allowed when base has no pattern or matches exactly`),r.pattern=e.pattern,r.flags=e.flags),r}get(){let e=this.registry;return new Ph({key:e.num(),value:e.text({minLength:1,maxLength:1}),get:e.nativeExpr(`text.charAt`),loop:e.nativeExpr(`text.chars`)})}props(){let e=this.registry,t=e.text(),n=e.num(),r=e.bool(),i=e.optional(n);return{...super.props(),length:e.prop(n,`text.length`),eq:e.method({other:t},r,`text.eq`),neq:e.method({other:t},r,`text.neq`),contains:e.method({search:t},r,`text.contains`),startsWith:e.method({prefix:t},r,`text.startsWith`),endsWith:e.method({suffix:t},r,`text.endsWith`),trim:e.method({},t,`text.trim`),trimStart:e.method({},t,`text.trimStart`),trimEnd:e.method({},t,`text.trimEnd`),upper:e.method({},t,`text.upper`),lower:e.method({},t,`text.lower`),slice:e.method({start:n,end:i},t,`text.slice`),replace:e.method({search:t,replacement:t},t,`text.replace`),split:e.method({separator:t},e.list(t),`text.split`),concat:e.method({other:t},t,`text.concat`),repeat:e.method({count:n},t,`text.repeat`),indexOf:e.method({search:t,from:i},n,`text.indexOf`),lastIndexOf:e.method({search:t,from:i},n,`text.lastIndexOf`),match:e.method({pattern:t},e.list(t),`text.match`),test:e.method({pattern:t},r,`text.test`),isEmpty:e.method({},r,`text.isEmpty`),isNotEmpty:e.method({},r,`text.isNotEmpty`),toNum:e.method({},n,`text.toNum`),toBool:e.method({},r,`text.toBool`)}}toJSON(){return Jm({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`text`+Bh(this.options)}valueA(){let e=R.string();return this.options.minLength!==void 0&&(e=e.min(this.options.minLength)),this.options.maxLength!==void 0&&(e=e.max(this.options.maxLength)),this.options.pattern&&(e=e.pattern(this.options.pattern,this.options.flags)),e}describe(e){return typeof e==`string`?this:void 0}},qg=class e extends U{static NAME=`timestamp`;name=e.NAME;static optionKeys=[`min`,`max`,`utc`,`precision`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return e instanceof Date&&!Number.isNaN(e.getTime())}parse(e){let t=e instanceof Date?e:typeof e==`string`?new Date(e):new Date(NaN);if(!this.valid(t))throw new Fm({path:[],code:`timestamp.invalid`,message:`timestamp.parse: invalid: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e.toISOString()}create(){return new Date}random(e){return new Date(e(Date.UTC(2e3,0,1),Date.UTC(2050,11,31),!0))}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e,this}narrow(e){return this.options}props(){let e=this.registry,t=e.num({whole:!0}),n=e.bool(),r=e.text(),i=e.timestamp(),a=e.duration();return{...super.props(),year:e.prop(t,`timestamp.year`),month:e.prop(t,`timestamp.month`),day:e.prop(t,`timestamp.day`),hour:e.prop(t,`timestamp.hour`),minute:e.prop(t,`timestamp.minute`),second:e.prop(t,`timestamp.second`),millisecond:e.prop(t,`timestamp.millisecond`),eq:e.method({other:i},n,`timestamp.eq`),before:e.method({other:i},n,`timestamp.before`),after:e.method({other:i},n,`timestamp.after`),addDuration:e.method({duration:a},i,`timestamp.addDuration`),subDuration:e.method({duration:a},i,`timestamp.subDuration`),diff:e.method({other:i},a,`timestamp.diff`),toDate:e.method({},e.date(),`timestamp.toDate`),toEpoch:e.method({},t,`timestamp.toEpoch`),toText:e.method({format:e.optional(r)},r,`timestamp.toText`)}}toJSON(){return Jm({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`timestamp`+Bh(this.options)}valueA(){return R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`).describe(`An ISO 8601 timestamp (YYYY-MM-DD HH:MM[:SS][Z]).`)}describe(e){return e instanceof Date?this:void 0}};function Jg(e){let t,n={};return Object.defineProperty(n,"elements",{enumerable:!0,get:()=>t??=e.map(e=>e.toJSON())}),n}var Yg=class e extends U{static NAME=`tuple`;name=e.NAME;static optionKeys=[`elements`];static genericKeys=[];elements;static from(t,n){n.registry;let r=(t.options?.elements??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,Jg(t)),this.elements=t}valid(e,t){return!Array.isArray(e)||e.length!==this.elements.length?!1:e.every((e,n)=>e instanceof W&&e.type.valid(e.raw,t)&&wh(this.elements[n],e.type,t))}parse(e,t){if(!Array.isArray(e)||e.length!==this.elements.length)throw new Fm({path:[],code:`tuple.invalid`,message:`tuple.parse: expected array of length ${this.elements.length}`,severity:`error`});let n=this.elements.map((n,r)=>this.registry.parseValue(e[r],n,t));return new W(this,n)}encode(e,t){return this.encodeAs(e,Ah,t)}encodeAs(e,t,n){if(!Array.isArray(e))throw new Fm({path:[],code:`tuple.invalid`,message:`tuple.encode: expected an array of cells`,severity:`error`});return e.map(e=>Oh(e,t,n))}create(){return this.elements.map(e=>new W(e,e.create()))}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<this.elements.length&&n<e.length;n++)t.slot(this.elements[n],e[n],n);return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i=0;i<e.length;i++){let a=this.elements[i];r.push(a?await a.newFill(e[i],t,n):e[i])}return r}random(e){return this.elements.map(t=>new W(t,t.random(e)))}like(t){if(!(t instanceof e)||t.elements.length!==this.elements.length)return this;let n=t.elements.map(e=>this.registry.like(e));return n.some(e=>e.name===`null`)?this.registry.null():this.registry.tuple(n)}compatibleType(t,n,r){return!(t instanceof e)||t.elements.length!==this.elements.length?!1:this.elements.every((e,i)=>e.compatible(t.elements[i],n,r))}or(t){return!(t instanceof e)||t.elements.length!==this.elements.length?this:new e(this.registry,this.elements.map((e,n)=>e.or(t.elements[n])))}narrow(e){return e.elements===void 0?this.options:{elements:e.elements}}get(){let e=this.elements.length===1?this.elements[0]:this.registry.or(this.elements),t=this.registry;return new Ph({key:t.num({whole:!0,min:0,max:this.elements.length-1}),value:e,get:t.nativeExpr(`tuple.at`),set:t.nativeExpr(`tuple.setAt`),loop:t.nativeExpr(`tuple.iterate`)})}follow(e,t){if(`key`in e&&!(`args`in e)){let t=e.key,n=t?.kind===`new`?t.value:void 0;if(typeof n==`number`&&Number.isInteger(n))return this.elements[n]}return super.follow(e,t)}props(){let e=this.registry;e.num();let t=this.elements[0]??e.any(),n=this.elements[this.elements.length-1]??e.any();return{...super.props(),length:e.prop(e.num({whole:!0,min:this.elements.length,max:this.elements.length}),`tuple.length`),first:e.prop(t,`tuple.first`),last:e.prop(n,`tuple.last`),toList:e.method({},e.list(this.elements.length===0?e.any():e.or(this.elements)),`tuple.toList`)}}toJSON(){return{name:e.NAME,options:{elements:this.elements.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.elements.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`tuple<${this.elements.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){let t=this.elements.map(t=>t.toA(e));return t.length>0?R.tuple(t):R.array(R.unknown()).max(0)}toNewA(e){let t=this.elements.map(()=>R.ref(`Expr`));return this.describeA(t.length>0?R.tuple(t):R.array(R.ref(`Expr`)).max(0),e)}},Xg=class e extends U{constructor(e,t){super(e,{},{T:t}),this.constraint=t}constraint;static NAME=`typ`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static valuesAreTypes=!0;static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e instanceof U?e.compatible(this.constraint,void 0,t)||this.constraint.compatible(e,void 0,t):!1}parse(t,n){if(t instanceof W&&t.type instanceof e)return t;if(t instanceof U){if(!this.valid(t,n))throw Error(`typ.parse: Type '${t.name}' is not compatible with ${this.constraint.toCode()}`);return new W(this,t)}if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`typ.parse: expected TypeDef or Type, got ${typeof t}`);if(!(`name`in t)||typeof t.name!=`string`)throw Error(`typ.parse: TypeDef missing 'name' field`);let r;try{r=this.registry.parse(t,n)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`typ.parse: ${t}`)}if(!this.valid(r,n))throw Error(`typ.parse: Type '${r.name}' is not compatible with ${this.constraint.toCode()}`);let i=n??this.registry,a=r.references().refs.filter(e=>i.lookup(e)===void 0);if(a.length>0)throw Error(`typ.parse: no type named ${a.join(`, `)}`);return new W(this,r)}encode(e,t){return e.toJSON()}create(){return this.constraint}random(e){return this.constraint}compatibleType(t,n,r){return t instanceof e&&this.constraint.compatible(t.constraint,n,r)}or(t){return t instanceof e?new e(this.registry,this.registry.or([this.constraint,t.constraint])):this}narrow(e){return{}}props(){return{...super.props()}}toJSON(){return{name:e.NAME,generic:{T:this.constraint.toJSON()}}}clone(){return new e(this.registry,this.constraint.clone())}toCode(e,t){return this.docsPrefix(t)+`typ<${this.constraint.toCode(void 0,t)}>`}valueA(e){let t=this.registry.compatible(this.constraint);if(t.length===0&&this.constraint.name!==`any`)return R.never();let n;if(this.constraint.name===`any`)n=R.ref(`TypeDef`);else{let e=t.map(e=>um(this.registry,e.name));e.push(dm()),e.push(fm(t.map(e=>e.name))),n=R.union(e).describe(`A gin type definition ({ "name": ..., ... }) whose type fits ${this.constraint.toCode()}.`)}return n.refine(t=>{try{return this.parse(t,e?.scope),!0}catch(e){return e instanceof Error?e.message:String(e)}})}toNewA(e){return this.describeA(this.toA(e),e)}},Zg=class e extends U{static NAME=`void`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return e===void 0}parse(e){if(e!=null)throw new Fm({path:[],code:`void.invalid`,message:`void expects undefined/null, got ${typeof e}`,severity:`error`});return new W(this,void 0)}encode(e){return null}create(){}random(e){}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new Fm({path:[],code:`void.no-options`,message:`void has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),toText:e.method({},e.text(),`void.toText`),toBool:e.method({},e.bool(),`void.toBool`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`void`}valueA(){return R.null()}};function K(e){return e.get(`this`).raw}function Qg(e){return e.get(`this`)}function q(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];return r==null?r:t_(r)?r.raw:r}function $g(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];if(t_(r))return r}function e_(e){let t=q(e,`epsilon`);return typeof t==`number`?t:0}function t_(e){return!!e&&typeof e==`object`&&`type`in e&&`raw`in e}function n_(e,t,n,r){let i=e.get(`yield`).raw,a=t.obj({key:{type:n},value:{type:r}});return(e,t)=>i(new W(a,{key:e,value:t}))}var r_={"type.toAny":(e,t)=>G(t.any(),K(e)),"any.typeOf":(e,t)=>G(t.text(),Qg(e).type.name),"any.is":(e,t)=>G(t.bool(),!0),"any.as":(e,t)=>{let n=Qg(e);return G(t.optional(n.type),n.raw)},"any.toText":(e,t)=>G(t.text(),String(K(e))),"any.toBool":(e,t)=>G(t.bool(),!!K(e)),"any.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"any.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`))},i_={"void.toText":(e,t)=>G(t.text(),`void`),"void.toBool":(e,t)=>G(t.bool(),!1)},a_={"null.toText":(e,t)=>G(t.text(),`null`),"null.toBool":(e,t)=>G(t.bool(),!1)},o_={"bool.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"bool.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"bool.and":(e,t)=>G(t.bool(),K(e)&&q(e,`other`)),"bool.or":(e,t)=>G(t.bool(),K(e)||q(e,`other`)),"bool.xor":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"bool.not":(e,t)=>G(t.bool(),!K(e)),"bool.toText":(e,t)=>{let n=K(e),r=q(e,`trueText`),i=q(e,`falseText`);return G(t.text(),n?r??`true`:i??`false`)},"bool.toNum":(e,t)=>{let n=K(e),r=q(e,`trueValue`),i=q(e,`falseValue`);return G(t.num(),n?r??1:i??0)}},s_={"num.eq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))<=e_(e)),"num.neq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))>e_(e)),"num.lt":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"num.lte":(e,t)=>G(t.bool(),K(e)<=q(e,`other`)),"num.gt":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"num.gte":(e,t)=>G(t.bool(),K(e)>=q(e,`other`)),"num.add":(e,t)=>G(t.num(),K(e)+q(e,`other`)),"num.sub":(e,t)=>G(t.num(),K(e)-q(e,`other`)),"num.mul":(e,t)=>G(t.num(),K(e)*q(e,`other`)),"num.div":(e,t)=>G(t.num(),K(e)/q(e,`other`)),"num.mod":(e,t)=>G(t.num(),K(e)%q(e,`other`)),"num.pow":(e,t)=>G(t.num(),K(e)**q(e,`other`)),"num.abs":(e,t)=>G(t.num(),Math.abs(K(e))),"num.neg":(e,t)=>G(t.num(),-K(e)),"num.sign":(e,t)=>G(t.num(),Math.sign(K(e))),"num.sqrt":(e,t)=>G(t.num(),Math.sqrt(K(e))),"num.min":(e,t)=>G(t.num(),Math.min(K(e),q(e,`other`))),"num.max":(e,t)=>G(t.num(),Math.max(K(e),q(e,`other`))),"num.clamp":(e,t)=>G(t.num(),Math.min(Math.max(K(e),q(e,`min`)),q(e,`max`))),"num.floor":(e,t)=>G(t.num(),Math.floor(K(e))),"num.ceil":(e,t)=>G(t.num(),Math.ceil(K(e))),"num.round":(e,t)=>G(t.num(),Math.round(K(e))),"num.isZero":(e,t)=>G(t.bool(),Math.abs(K(e))<=e_(e)),"num.isPositive":(e,t)=>G(t.bool(),K(e)>e_(e)),"num.isNegative":(e,t)=>G(t.bool(),K(e)<-e_(e)),"num.isInteger":(e,t)=>G(t.bool(),Number.isInteger(K(e))),"num.isEven":(e,t)=>G(t.bool(),K(e)%2==0),"num.isOdd":(e,t)=>G(t.bool(),Math.abs(K(e))%2==1),"num.toText":(e,t)=>{let n=q(e,`precision`),r=n==null?String(K(e)):K(e).toFixed(n);return G(t.text(),r)},"num.toBool":(e,t)=>G(t.bool(),K(e)!==0),"num.loop":async(e,t)=>{let n=K(e),r=t.num(),i=n_(e,t,r,r),a=Math.abs(Math.trunc(n)),o=n<0?-1:1;for(let e=0;e<a;e++){let t=e*o,n=Object.is(t,-0)?0:t;await i(G(r,e),G(r,n))}return G(t.void(),void 0)}},c_={"text.length":(e,t)=>G(t.num({whole:!0,min:0}),K(e).length),"text.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"text.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"text.contains":(e,t)=>G(t.bool(),K(e).includes(q(e,`search`))),"text.startsWith":(e,t)=>G(t.bool(),K(e).startsWith(q(e,`prefix`))),"text.endsWith":(e,t)=>G(t.bool(),K(e).endsWith(q(e,`suffix`))),"text.trim":(e,t)=>G(t.text(),K(e).trim()),"text.trimStart":(e,t)=>G(t.text(),K(e).trimStart()),"text.trimEnd":(e,t)=>G(t.text(),K(e).trimEnd()),"text.upper":(e,t)=>G(t.text(),K(e).toUpperCase()),"text.lower":(e,t)=>G(t.text(),K(e).toLowerCase()),"text.slice":(e,t)=>{let n=q(e,`start`),r=q(e,`end`);return G(t.text(),K(e).slice(n,r))},"text.replace":(e,t)=>{let n=q(e,`search`),r=q(e,`replacement`);return G(t.text(),K(e).split(n).join(r))},"text.split":(e,t)=>{let n=K(e).split(q(e,`separator`));return G(t.list(t.text()),n.map(e=>G(t.text(),e)))},"text.concat":(e,t)=>G(t.text(),K(e)+q(e,`other`)),"text.repeat":(e,t)=>G(t.text(),K(e).repeat(q(e,`count`))),"text.indexOf":(e,t)=>{let n=q(e,`from`);return G(t.num(),K(e).indexOf(q(e,`search`),n))},"text.lastIndexOf":(e,t)=>{let n=q(e,`from`);return G(t.num(),K(e).lastIndexOf(q(e,`search`),n))},"text.match":(e,t)=>{let n=q(e,`pattern`),r=K(e).match(new RegExp(n,`g`))??[];return G(t.list(t.text()),r.map(e=>G(t.text(),e)))},"text.test":(e,t)=>{let n=q(e,`pattern`);return G(t.bool(),new RegExp(n).test(K(e)))},"text.isEmpty":(e,t)=>G(t.bool(),K(e).length===0),"text.isNotEmpty":(e,t)=>G(t.bool(),K(e).length>0),"text.toNum":(e,t)=>G(t.num(),Number(K(e))),"text.toBool":(e,t)=>G(t.bool(),K(e).length>0),"text.charAt":(e,t)=>{let n=e.get(`key`).raw,r=K(e)[n];if(r===void 0)throw Error(`text[${n}]: index out of range`);return G(t.text({minLength:1,maxLength:1}),r)},"text.chars":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=t.text({minLength:1,maxLength:1}),a=n_(e,t,r,i);for(let e=0;e<n.length;e++)await a(G(r,e),G(i,n[e]));return G(t.void(),void 0)}},l_=e=>Qg(e).type.item,u_={"list.length":(e,t)=>G(t.num({whole:!0,min:0}),K(e).length),"list.indexGet":e=>{let t=e.get(`key`).raw,n=K(e);if(t<0||t>=n.length)throw Error(`list[${t}]: index out of range`);return n[t]},"list.indexSet":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`),i=K(e);if(n<0||n>=i.length)throw Error(`list[${n}] =: index out of range`);return i[n]=r,G(t.void(),void 0)},"list.iterate":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=n_(e,t,r,l_(e)),a=G(t.void(),void 0);for(let e=0;e<n.length;e++)await i(G(r,e),n[e]);return a},"list.at":(e,t)=>{let n=q(e,`index`),r=K(e);return n<0||n>=r.length?G(t.optional(l_(e)),void 0):G(t.optional(l_(e)),r[n].raw)},"list.push":(e,t)=>(K(e).push($g(e,`value`)),G(t.void(),void 0)),"list.pop":(e,t)=>{let n=K(e).pop();return G(t.optional(l_(e)),n?n.raw:void 0)},"list.shift":(e,t)=>{let n=K(e).shift();return G(t.optional(l_(e)),n?n.raw:void 0)},"list.unshift":(e,t)=>(K(e).unshift($g(e,`value`)),G(t.void(),void 0)),"list.insert":(e,t)=>(K(e).splice(q(e,`index`),0,$g(e,`value`)),G(t.void(),void 0)),"list.remove":e=>K(e).splice(q(e,`index`),1)[0],"list.clear":(e,t)=>(K(e).length=0,G(t.void(),void 0)),"list.slice":e=>{let t=Qg(e).type,n=q(e,`start`),r=q(e,`end`);return G(t,K(e).slice(n,r))},"list.concat":e=>{let t=Qg(e).type,n=q(e,`other`);return G(t,K(e).concat(n))},"list.reverse":e=>{let t=Qg(e).type;return G(t,[...K(e)].reverse())},"list.join":(e,t)=>{let n=q(e,`separator`)??`,`;return G(t.text(),K(e).map(e=>String(e.raw)).join(n))},"list.indexOf":(e,t)=>{let n=$g(e,`value`).raw,r=K(e).findIndex(e=>e.raw===n);return G(t.num(),r)},"list.contains":(e,t)=>{let n=$g(e,`value`).raw,r=K(e);return G(t.bool(),r.some(e=>e.raw===n))},"list.unique":e=>{let t=Qg(e).type,n=new Set,r=[];for(let t of K(e))n.has(t.raw)||(n.add(t.raw),r.push(t));return G(t,r)},"list.duplicates":e=>{let t=Qg(e).type,n=new Set,r=new Set,i=[];for(let t of K(e))n.has(t.raw)?r.has(t.raw)||(r.add(t.raw),i.push(t)):n.add(t.raw);return G(t,i)},"list.map":async(e,t)=>{let n=K(e),r=$g(e,`fn`).raw,i=l_(e),a=[],o=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++){let i=new W(o,{value:n[e],index:G(t.num(),e)});a.push(await r(i))}return G(t.list(t.any()),a)},"list.filter":async e=>{let t=Qg(e).type,n=K(e),r=$g(e,`fn`).raw,i=[],a=t.registry.obj({value:{type:t.item},index:{type:t.registry.num()}});for(let e=0;e<n.length;e++)(await r(new W(a,{value:n[e],index:G(t.registry.num(),e)}))).raw&&i.push(n[e]);return G(t,i)},"list.find":async(e,t)=>{let n=K(e),r=$g(e,`fn`).raw,i=l_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if((await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.optional(i),n[e].raw);return G(t.optional(i),void 0)},"list.reduce":async(e,t)=>{let n=K(e),r=$g(e,`fn`),i=$g(e,`initial`),a=r.raw,o=l_(e),s=i,c=t.obj({acc:{type:t.any()},value:{type:o},index:{type:t.num()}});for(let e=0;e<n.length;e++)s=await a(new W(c,{acc:s,value:n[e],index:G(t.num(),e)}));return s},"list.some":async(e,t)=>{let n=K(e),r=$g(e,`fn`).raw,i=l_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if((await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.bool(),!0);return G(t.bool(),!1)},"list.every":async(e,t)=>{let n=K(e),r=$g(e,`fn`).raw,i=l_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if(!(await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.bool(),!1);return G(t.bool(),!0)},"list.sort":async e=>{let t=Qg(e).type,n=[...K(e)],r=$g(e,`fn`);if(r&&typeof r.raw==`function`){let e=r.raw,i=t.registry.obj({a:{type:t.item},b:{type:t.item}}),a=[];for(let t=0;t<n.length;t++){let r=0;for(let a=0;a<n.length;a++)t!==a&&(await e(new W(i,{a:n[t],b:n[a]}))).raw>0&&r++;a.push({index:t,key:r})}return a.sort((e,t)=>e.key-t.key),G(t,a.map(e=>n[e.index]))}return G(t,n.sort((e,t)=>{let n=e.raw,r=t.raw;return n<r?-1:+(n>r)}))},"list.isEmpty":(e,t)=>G(t.bool(),K(e).length===0),"list.isNotEmpty":(e,t)=>G(t.bool(),K(e).length>0),"list.first":(e,t)=>{let n=K(e);return G(t.optional(l_(e)),n.length>0?n[0].raw:void 0)},"list.last":(e,t)=>{let n=K(e);return G(t.optional(l_(e)),n.length>0?n[n.length-1].raw:void 0)}},d_={"list.indexSet":B.STATE,"list.push":B.STATE,"list.pop":B.STATE,"list.shift":B.STATE,"list.unshift":B.STATE,"list.insert":B.STATE,"list.remove":B.STATE,"list.clear":B.STATE},f_=e=>Qg(e).type.value,p_={"map.size":(e,t)=>G(t.num({whole:!0,min:0}),K(e).size),"map.indexGet":e=>{let t=e.get(`key`).raw,n=K(e).get(t);if(!n)throw Error(`map[${String(t)}]: key not found`);return n[1]},"map.indexSet":(e,t)=>{let n=e.get(`key`),r=e.get(`value`);return K(e).set(n.raw,[n,r]),G(t.void(),void 0)},"map.iterate":async(e,t)=>{let n=K(e),r=n.values().next().value,i=n_(e,t,r?r[0].type:t.any(),r?r[1].type:t.any());for(let[,[e,t]]of n)await i(e,t);return G(t.void(),void 0)},"map.at":(e,t)=>{let n=q(e,`key`),r=K(e).get(n);return G(t.optional(f_(e)),r?r[1].raw:void 0)},"map.has":(e,t)=>G(t.bool(),K(e).has(q(e,`key`))),"map.delete":(e,t)=>G(t.bool(),K(e).delete(q(e,`key`))),"map.clear":(e,t)=>(K(e).clear(),G(t.void(),void 0)),"map.keys":(e,t)=>{let n=K(e),r=Qg(e).type.key,i=[];for(let[,[e]]of n)i.push(e);return G(t.list(r),i)},"map.values":(e,t)=>{let n=K(e),r=Qg(e).type.value,i=[];for(let[,[,e]]of n)i.push(e);return G(t.list(r),i)},"map.isEmpty":(e,t)=>G(t.bool(),K(e).size===0),"map.isNotEmpty":(e,t)=>G(t.bool(),K(e).size>0)},m_={"map.indexSet":B.STATE,"map.delete":B.STATE,"map.clear":B.STATE},h_=e=>Qg(e).type.elements,g_={"tuple.at":e=>{let t=e.get(`key`).raw,n=K(e)[t];return n instanceof W?n:G(h_(e)[t]??G.prototype,n)},"tuple.setAt":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`);return K(e)[n]=r,G(t.void(),void 0)},"tuple.iterate":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=n.map(e=>e.type),a=n_(e,t,r,i.length===0?t.any():i.length===1?i[0]:t.or(i));for(let e=0;e<n.length;e++)await a(G(r,e),n[e]);return G(t.void(),void 0)},"tuple.length":(e,t)=>G(t.num({whole:!0}),K(e).length),"tuple.first":e=>{let t=K(e),n=h_(e),r=t[0];return r instanceof W?r:G(n[0],r)},"tuple.last":e=>{let t=K(e),n=h_(e),r=t[t.length-1];return r instanceof W?r:G(n[n.length-1],r)},"tuple.toList":(e,t)=>G(t.list(t.any()),[...K(e)])},__={"tuple.setAt":B.STATE},v_=e=>Qg(e).type.fields,y_={"object.indexGet":e=>{let t=e.get(`key`).raw,n=v_(e)[t];if(!n)throw Error(`object[${t}]: no such field`);let r=K(e)[t];return r instanceof W?r:G(n.type,r)},"object.indexSet":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`);return K(e)[n]=r,G(t.void(),void 0)},"object.iterate":async(e,t)=>{let n=K(e),r=v_(e),i=t.text(),a=Object.values(r).map(e=>e.type),o=n_(e,t,i,a.length===0?t.any():a.length===1?a[0]:t.or(a));for(let[e]of Object.entries(r)){let t=n[e];t instanceof W&&await o(G(i,e),t)}return G(t.void(),void 0)},"object.keys":(e,t)=>{let n=Object.keys(v_(e));return G(t.list(t.text()),n.map(e=>G(t.text(),e)))},"object.values":(e,t)=>{let n=K(e),r=Object.keys(v_(e)).map(e=>n[e]??G(t.any(),void 0));return G(t.list(t.any()),r)},"object.entries":(e,t)=>{let n=K(e),r=Object.keys(v_(e)).map(e=>G(t.any(),[e,n[e]?.raw]));return G(t.list(t.any()),r)},"object.has":(e,t)=>G(t.bool(),Object.hasOwn(v_(e),q(e,`key`))),"object.eq":(e,t)=>G(t.bool(),x_(Qg(e),e.get(`args`).raw)),"object.neq":(e,t)=>G(t.bool(),!x_(Qg(e),e.get(`args`).raw)),"object.toText":(e,t)=>{let n=K(e),r=v_(e),i={};for(let[e]of Object.entries(r)){let t=n[e];i[e]=t?t.type.encode(t.raw):void 0}return G(t.text(),JSON.stringify(i))}},b_={"object.indexSet":B.STATE};function x_(e,t){let n=t.other,r=n instanceof W?n.raw:n;return S_(e.raw,r)}function S_(e,t){if(e instanceof W&&(e=e.raw),t instanceof W&&(t=t.raw),e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!S_(e[n],t[n]))return!1;return!0}let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!S_(e[r],t[r]))return!1;return!0}var C_={"optional.value":e=>{let t=K(e);if(t===void 0)throw Error(`optional.value: value is undefined`);return G(Qg(e).type.inner,t)},"optional.has":(e,t)=>G(t.bool(),K(e)!==void 0),"optional.or":e=>{let t=K(e),n=Qg(e).type.inner;return t===void 0?$g(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"optional.map":async(e,t)=>{let n=K(e),r=Qg(e).type.inner;if(n===void 0)return G(t.optional(t.any()),void 0);let i=$g(e,`fn`).raw,a=await i(new W(t.obj({value:{type:r}}),{value:G(r,n)}));return G(t.optional(t.any()),a.raw)}},w_={"nullable.value":e=>{let t=K(e);if(t===null)throw Error(`nullable.value: value is null`);return G(Qg(e).type.inner,t)},"nullable.isNull":(e,t)=>G(t.bool(),K(e)===null),"nullable.or":e=>{let t=K(e),n=Qg(e).type.inner;return t===null?$g(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"nullable.map":async(e,t)=>{let n=K(e),r=Qg(e).type.inner;if(n===null)return G(t.nullable(t.any()),null);let i=$g(e,`fn`).raw,a=await i(new W(t.obj({value:{type:r}}),{value:G(r,n)}));return G(t.nullable(t.any()),a.raw)}},T_={"not.typeOf":(e,t)=>G(t.text(),Qg(e).type.name),"not.toText":(e,t)=>G(t.text(),String(K(e)))},E_={"enum.name":(e,t)=>{let n=K(e),r=Qg(e).type,i=Object.entries(r.options.values).find(([,e])=>e===n);return G(t.text(),i?i[0]:``)},"enum.value":e=>{let t=Qg(e).type;return G(t.value,K(e))},"enum.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"enum.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"enum.toText":(e,t)=>G(t.text(),String(K(e)))},D_={"date.year":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()),"date.month":(e,t)=>G(t.num({whole:!0,min:1,max:12}),K(e).getUTCMonth()+1),"date.day":(e,t)=>G(t.num({whole:!0,min:1,max:31}),K(e).getUTCDate()),"date.dayOfWeek":(e,t)=>G(t.num({whole:!0,min:0,max:6}),K(e).getUTCDay()),"date.dayOfYear":(e,t)=>{let n=K(e),r=Date.UTC(n.getUTCFullYear(),0,0);return G(t.num({whole:!0,min:1,max:366}),Math.floor((n.getTime()-r)/864e5))},"date.eq":(e,t)=>G(t.bool(),K(e).getTime()===q(e,`other`).getTime()),"date.neq":(e,t)=>G(t.bool(),K(e).getTime()!==q(e,`other`).getTime()),"date.before":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"date.after":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"date.addDays":(e,t)=>{let n=new Date(K(e));return n.setUTCDate(n.getUTCDate()+q(e,`days`)),G(t.date(),n)},"date.addMonths":(e,t)=>{let n=new Date(K(e));return n.setUTCMonth(n.getUTCMonth()+q(e,`months`)),G(t.date(),n)},"date.addYears":(e,t)=>{let n=new Date(K(e));return n.setUTCFullYear(n.getUTCFullYear()+q(e,`years`)),G(t.date(),n)},"date.diffDays":(e,t)=>G(t.num({whole:!0}),Math.round((K(e).getTime()-q(e,`other`).getTime())/864e5)),"date.diffMonths":(e,t)=>{let n=K(e),r=q(e,`other`);return G(t.num({whole:!0}),(n.getUTCFullYear()-r.getUTCFullYear())*12+(n.getUTCMonth()-r.getUTCMonth()))},"date.diffYears":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()-q(e,`other`).getUTCFullYear()),"date.toText":(e,t)=>G(t.text(),K(e).toISOString().slice(0,10))},O_={"timestamp.year":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()),"timestamp.month":(e,t)=>G(t.num({whole:!0}),K(e).getUTCMonth()+1),"timestamp.day":(e,t)=>G(t.num({whole:!0}),K(e).getUTCDate()),"timestamp.hour":(e,t)=>G(t.num({whole:!0,min:0,max:23}),K(e).getUTCHours()),"timestamp.minute":(e,t)=>G(t.num({whole:!0,min:0,max:59}),K(e).getUTCMinutes()),"timestamp.second":(e,t)=>G(t.num({whole:!0,min:0,max:59}),K(e).getUTCSeconds()),"timestamp.millisecond":(e,t)=>G(t.num({whole:!0,min:0,max:999}),K(e).getUTCMilliseconds()),"timestamp.eq":(e,t)=>G(t.bool(),K(e).getTime()===q(e,`other`).getTime()),"timestamp.before":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"timestamp.after":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"timestamp.addDuration":(e,t)=>G(t.timestamp(),new Date(K(e).getTime()+q(e,`duration`))),"timestamp.subDuration":(e,t)=>G(t.timestamp(),new Date(K(e).getTime()-q(e,`duration`))),"timestamp.diff":(e,t)=>G(t.duration(),K(e).getTime()-q(e,`other`).getTime()),"timestamp.toDate":(e,t)=>G(t.date(),new Date(K(e).toISOString().slice(0,10))),"timestamp.toEpoch":(e,t)=>G(t.num(),K(e).getTime()),"timestamp.toText":(e,t)=>G(t.text(),K(e).toISOString())},k_=864e5,A_=36e5,j_=6e4,M_=1e3,N_={"duration.init":(e,t)=>{let n=q(e,`days`)??0,r=q(e,`hours`)??0,i=q(e,`minutes`)??0,a=q(e,`seconds`)??0,o=q(e,`ms`)??0;return G(t.duration(),n*k_+r*A_+i*j_+a*M_+o)},"duration.totalSeconds":(e,t)=>G(t.num(),K(e)/1e3),"duration.totalMinutes":(e,t)=>G(t.num(),K(e)/6e4),"duration.totalHours":(e,t)=>G(t.num(),K(e)/36e5),"duration.totalDays":(e,t)=>G(t.num(),K(e)/864e5),"duration.days":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/k_)),"duration.hours":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/A_)%24),"duration.minutes":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/j_)%60),"duration.seconds":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/M_)%60),"duration.ms":(e,t)=>G(t.num({whole:!0}),K(e)%M_),"duration.toText":(e,t)=>{let n=K(e),r=Math.trunc(n/k_),i=Math.trunc(n%k_/A_),a=Math.trunc(n%A_/j_),o=Math.trunc(n%j_/M_),s=[];return r&&s.push(`${r}d`),i&&s.push(`${i}h`),a&&s.push(`${a}m`),(o||s.length===0)&&s.push(`${o}s`),G(t.text(),s.join(` `))}},P_=e=>e>>>24&255,F_=e=>e>>>16&255,I_=e=>e>>>8&255,L_=e=>(e&255)/255,R_=(e,t,n,r)=>(Math.round(e)&255)<<24|(Math.round(t)&255)<<16|(Math.round(n)&255)<<8|Math.round(r*255)&255,z_={"color.init":(e,t)=>{let n=q(e,`r`),r=q(e,`g`),i=q(e,`b`),a=q(e,`a`)??1;return G(t.color(),R_(n,r,i,a)>>>0)},"color.r":(e,t)=>G(t.num(),P_(K(e))),"color.g":(e,t)=>G(t.num(),F_(K(e))),"color.b":(e,t)=>G(t.num(),I_(K(e))),"color.a":(e,t)=>G(t.num(),L_(K(e))),"color.hue":(e,t)=>G(t.num(),B_(K(e)).h),"color.saturation":(e,t)=>G(t.num(),B_(K(e)).s),"color.lightness":(e,t)=>G(t.num(),B_(K(e)).l),"color.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"color.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"color.lighten":(e,t)=>G(t.color(),H_(K(e),q(e,`amount`))),"color.darken":(e,t)=>G(t.color(),H_(K(e),-q(e,`amount`))),"color.saturate":(e,t)=>G(t.color(),U_(K(e),q(e,`amount`))),"color.desaturate":(e,t)=>G(t.color(),U_(K(e),-q(e,`amount`))),"color.opacity":(e,t)=>G(t.color(),K(e)&4294967040|Math.round(q(e,`alpha`)*255)&255),"color.invert":(e,t)=>{let n=K(e);return G(t.color(),R_(255-P_(n),255-F_(n),255-I_(n),L_(n))>>>0)},"color.mix":(e,t)=>{let n=K(e),r=q(e,`other`),i=q(e,`weight`)??.5;return G(t.color(),R_(P_(n)*(1-i)+P_(r)*i,F_(n)*(1-i)+F_(r)*i,I_(n)*(1-i)+I_(r)*i,L_(n)*(1-i)+L_(r)*i)>>>0)},"color.complement":(e,t)=>G(t.color(),W_(K(e),180)),"color.toHex":(e,t)=>G(t.text(),`#`+K(e).toString(16).padStart(8,`0`)),"color.toRgb":(e,t)=>{let n=K(e);return G(t.text(),`rgb(${P_(n)},${F_(n)},${I_(n)})`)},"color.toHsl":(e,t)=>{let{h:n,s:r,l:i}=B_(K(e));return G(t.text(),`hsl(${Math.round(n)},${Math.round(r*100)}%,${Math.round(i*100)}%)`)},"color.toText":(e,t)=>G(t.text(),`#`+K(e).toString(16).padStart(8,`0`))};function B_(e){let t=P_(e)/255,n=F_(e)/255,r=I_(e)/255,i=Math.max(t,n,r),a=Math.min(t,n,r),o=(i+a)/2,s=0,c=0;if(i!==a){let e=i-a;switch(c=o>.5?e/(2-i-a):e/(i+a),i){case t:s=(n-r)/e+(n<r?6:0);break;case n:s=(r-t)/e+2;break;case r:s=(t-n)/e+4}s*=60}return{h:s,s:c,l:o}}function V_(e,t,n,r){let i=(1-Math.abs(2*n-1))*t,a=i*(1-Math.abs(e/60%2-1)),o=n-i/2,s=0,c=0,l=0;return e<60?[s,c,l]=[i,a,0]:e<120?[s,c,l]=[a,i,0]:e<180?[s,c,l]=[0,i,a]:e<240?[s,c,l]=[0,a,i]:e<300?[s,c,l]=[a,0,i]:[s,c,l]=[i,0,a],R_((s+o)*255,(c+o)*255,(l+o)*255,r)}function H_(e,t){let{h:n,s:r,l:i}=B_(e);return V_(n,r,Math.max(0,Math.min(1,i+t)),L_(e))>>>0}function U_(e,t){let{h:n,s:r,l:i}=B_(e);return V_(n,Math.max(0,Math.min(1,r+t)),i,L_(e))>>>0}function W_(e,t){let{h:n,s:r,l:i}=B_(e);return V_((n+t+360)%360,r,i,L_(e))>>>0}function G_(e){let t=[{impls:r_},{impls:i_},{impls:a_},{impls:o_},{impls:s_},{impls:c_},{impls:u_,effects:d_},{impls:p_,effects:m_},{impls:g_,effects:__},{impls:y_,effects:b_},{impls:C_},{impls:w_},{impls:T_},{impls:E_},{impls:D_},{impls:O_},{impls:N_},{impls:z_}];for(let n of t)for(let[t,r]of Object.entries(n.impls)){let i=n.effects?.[t]??B.NONE;e.setNative(t,r,i)}return e}var K_=class e extends th{constructor(e,t){super(),this.type=e,this.value=t}type;value;static KIND=`new`;kind=e.KIND;static from(t,n){return new e(n.registry.parse(t.type,n),t.value).withComment(t.comment)}async evaluate(e,t){let n=this.type,r=n.init();if(this.value!==void 0){if(r){let i=r.args.parse(this.value),a=G(n,n.create()),o=t.child({this:a,args:i}),s=await r.run.evaluate(e,o);return s===void 0||s.raw===void 0?a:new W(n,s.raw)}let i=await n.newFill(this.value,e,t);if(i instanceof W)return e.registry.parseValue(i,n);let a=n.parse(i);return a.type===n?a:new W(n,a.raw)}return G(n,n.create())}typeOf(e,t){return this.type}validateWalk(e,t,n,r){return this.value===void 0&&X_(this.type)&&n.warn(`new.value.missing`,`\`new ${this.type.name}\` has no \`value\` \u2014 every field will fall to its type default (0 / "" / null). Provide a \`value\` matching the type's shape.`),this.value!==void 0&&n.at([`value`],()=>this.type.validateNewValue(this.value,e,t,n,r)),this.type}toCode(e,t={}){let n=this.type.toCode(void 0,t),r;return r=this.value===void 0?this.type.isOptional()?`undefined`:`new ${n}()`:typeof this.value==`number`||typeof this.value==`boolean`?String(this.value):typeof this.value==`string`?JSON.stringify(this.value):this.value===null?`null`:q_(this.value,e,this.type,t),this.commentPrefix(t)+r}toJSON(){return this.withCommentOn({kind:`new`,type:this.type.toJSON(),value:this.value})}toJSONCode(e=[],t=2,n=0){let r=this.type.toJSONCode([...e,`type`],t,n+1),i=this.value===void 0?void 0:(()=>{let e=JSON.stringify(this.value,null,t),r=n+1;return r>0?e.replace(/\n/g,`
105
+ `+` `.repeat(r*t)):e})(),a=i===void 0?void 0:Lm(i,{path:[...e,`value`]});return V.jsonObject([{key:`kind`,value:V.jsonString(`new`)},{key:`type`,value:r},{key:`value`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.type.clone(),this.value).withComment(this.comment)}effects(){return this.type.newEffects(this.value)}complexity(){return this.type.newComplexity(this.value)}};function q_(e,t,n,r={}){if(t&&e&&typeof e==`object`&&!Array.isArray(e)&&`kind`in e&&typeof e.kind==`string`){let n=e.kind;if(t.exprClass(n))try{return t.parseExpr(e).toCode(t,{...r,expectsValue:!0})}catch{}}let i=n?n.toCode(void 0,r):`<inferred>`;if(Array.isArray(e)){let i=n?.item,a=Hh(e.map(e=>J_(e,t,i,r)));return a.startsWith(`
106
+ `),`[${a}]`}if(e&&typeof e==`object`){let a=n?.fields,o=Object.entries(e);if(o.length===0)return`new ${i}()`;let s=Hh(o.map(([e,n])=>`${e}: ${J_(n,t,a?.[e]?.type,r)}`));return s.startsWith(`
107
+ `)?`new ${i} {${s}}`:`new ${i} { ${s} }`}return JSON.stringify(e)}function J_(e,t,n,r={}){return e===null?`null`:e===void 0?`undefined`:typeof e==`string`?JSON.stringify(e):typeof e==`number`||typeof e==`boolean`?String(e):q_(e,t,n,r)}function Y_(e){if(e instanceof bg)return e;let t=e.base;return t?Y_(t):void 0}function X_(e){let t=Y_(e);if(!t)return!1;for(let e of Object.values(t.fields))if(!e.type.isOptional())return!0;return!1}function Z_(e,t){let n=e.call(t);if(!n)return!1;let r=n.args;if(!(r instanceof bg))return!0;for(let e of Object.values(r.fields))if(!e.type.isOptional())return!1;return!0}function Q_(e,t,n,r){if(!e)return;let i=e.args;if(i instanceof bg)for(let[e,a]of Object.entries(i.fields))a.type.isOptional()||e in t||n.at(r,()=>n.error(`call.missing-arg`,`missing required argument '${e}'`))}function $_(e,t){return t.type instanceof wg?t.type.simplify(e.scope):t.type}function ev(e,t){let n=e.raw;if(!n||typeof n!=`object`)return;let r=n[t];return r instanceof W?r:void 0}function tv(e){return e instanceof bg||e instanceof Ng||e instanceof vg&&tv(e.base)}function nv(e,t,n){let r=[];for(let e=n;e<t.length;e++){let n=t[e];if(n instanceof iv)r.push(n.prop);else break}if(r.length===0)return``;let i=zp(e,e=>Object.keys(e.props()),e=>{let t=[];for(let n of Object.keys(e.props())){let r=e.prop(n)?.type;r&&tv(r)&&t.push([n,r])}return t},r);if(!i||i.length===0)return``;if(i.length===1)return` \u2014 did you mean \`${i[0]}\`?`;let a=[];for(let e=0;e<n;e++){let n=t[e];if(n instanceof iv)a.push(n.prop);else{a.length=0;break}}return` \u2014 did you mean \`${[...a,...i].join(`.`)}\`?`}var rv=class{static from(e,t){if(Yp(e),`prop`in e)return new iv(e.prop);let n=t.registry;if(`args`in e){let r={};for(let[i,a]of Object.entries(e.args??{}))r[i]=n.parseExpr(a,t);return new av(r,e.generic,e.catch?n.parseExpr(e.catch,t):void 0)}if(`key`in e)return new ov(n.parseExpr(e.key,t));throw Error(`PathStep.from: unknown step shape`)}},iv=class e extends rv{constructor(e){super(),this.prop=e}prop;toJSON(){return{prop:this.prop}}clone(){return new e(this.prop)}complexity(){return 1}},av=class e extends rv{constructor(e,t,n){super(),this.args=e,this.generic=t,this.catch_=n}args;generic;catch_;resolvedEffects;toJSON(){let e={};for(let[t,n]of Object.entries(this.args))e[t]=n.toJSON();let t={args:e};return this.generic&&(t.generic=this.generic),this.catch_&&(t.catch=this.catch_.toJSON()),t}clone(){let t={};for(let[e,n]of Object.entries(this.args))t[e]=n.clone();return new e(t,this.generic,this.catch_?.clone())}callSiteScope(e){if(!this.generic||Object.keys(this.generic).length===0)return e.scope;let t={},n=e.generic??{};for(let[r,i]of Object.entries(this.generic)){let a=e.scope.parse(i),o=n[r];if(o&&(o.name!==`alias`||o.options?.name!==r)&&!o.compatible(a))throw Error(`path: generic '${r}' binding '${a.toCode()}' does not satisfy constraint '${o.toCode()}'`);t[r]=a}return new eh(e.scope,t)}complexity(){let e=1;for(let t of Object.values(this.args))e+=t.complexity();return this.catch_&&(e+=this.catch_.complexity()),e}async buildArgsValue(e,t,n){let r=this.callSiteScope(e),i=e.call?.(r)?.args??n.registry.obj({}),a={};for(let[e,r]of Object.entries(this.args))a[e]=await r.evaluate(n,t);return new W(i,a)}},ov=class e extends rv{constructor(e){super(),this.key=e}key;toJSON(){return{key:this.key.toJSON()}}clone(){return new e(this.key.clone())}complexity(){return 1+this.key.complexity()}},sv=class e{constructor(e){this.steps=e}steps;static from(t,n){return new e(t.map(e=>rv.from(e,n)))}toJSON(){return this.steps.map(e=>e.toJSON())}toJSONCode(e=[],t=2,n=0){let r=this.steps.map((r,i)=>lv(r,[...e,i],t,n+1));return V.jsonArray(r,{path:e},n,t)}clone(){return new e(this.steps.map(e=>e.clone()))}complexity(){let e=0;for(let t of this.steps)e+=t.complexity();return e}forEachExpr(e){for(let t of this.steps)if(t instanceof av){for(let n of Object.values(t.args))e(n);t.catch_&&e(t.catch_)}else t instanceof ov&&e(t.key)}toCode(e,t={}){return this.toGinCode(e,t).toString()}toGinCode(e,t={},n=[]){if(this.steps.length===0)return new V(``);let r=new V(``);for(let i=0;i<this.steps.length;i++){let a=this.steps[i],o=[...n,`path`,i];if(a instanceof iv){let e=i===0?a.prop:`.${a.prop}`;r=i===0?Lm(e,{path:o}):H`${r}${Lm(e,{path:o})}`}else if(a instanceof av){let n=Object.entries(a.args),i;if(n.length===0)i=new V(`()`);else{let r=n.map(([n,r])=>{let i=[...o,`args`,n];return H`${n}: ${r.toGinCode(e,{...t,expectsValue:!0},i)}`});i=Hh(r.map(e=>e.toString())).startsWith(`
108
+ `)?H`({\n ${Rm(r,`,
109
+ `)}\n})`:H`({ ${Rm(r,`, `)} })`}if(r=H`${r}${Lm(i,{path:o})}`,a.catch_){let n=a.catch_.toGinCode(e,{...t,expectsValue:!0},[...o,`catch`]);r=H`${r}.catch((error) => ${n})`}}else if(a instanceof ov){let n=a.key.toGinCode(e,{...t,expectsValue:!0},[...o,`key`]);r=H`${r}${Lm(H`[${n}]`,{path:o})}`}}return r}async walk(e,t,n={mode:`get`}){if(this.steps.length===0)throw Error(`Path.walk: empty path`);let r=()=>G(t.registry.bool(),!1),i=()=>G(t.registry.bool(),!0),a=null,o=0;for(;o<this.steps.length;){let s=this.steps[o],c=o===this.steps.length-1;if(n.mode===`set`&&a!==null&&cv(a)&&!(s instanceof av))return r();if(s instanceof iv){if(a===null){let t=e.get(s.prop);if(t===void 0)throw Error(`path: unknown variable '${s.prop}'${Ip(s.prop,e.names())}`);a=t,o++;continue}let r=a.type.prop(s.prop);if(!r){let e=n.mode===`get`?ev(a,s.prop):void 0;if(e){a=e,o++;continue}throw Error(`path: no prop '${s.prop}' on type '${a.type.name}'${nv(a.type,this.steps,o)}`)}let l=$_(a.type,r),u=this.steps[o+1],d=u instanceof av;if(d&&l.call()){let c=await u.buildArgsValue(l,e,t);if(o+1===this.steps.length-1&&n.mode===`set`)return await r.invokeMethodSet(a,s.prop,c,n.setValue,e,t,l),i();try{a=await r.invokeMethod(a,s.prop,c,e,t,l)}catch(n){if(n instanceof hh&&u.catch_){let r=e.child({error:n.error});a=await u.catch_.evaluate(t,r)}else throw n}o+=2;continue}if(!d&&Z_(l)){let u=await new av({},void 0,void 0).buildArgsValue(l,e,t);if(c&&n.mode===`set`)return await r.invokeMethodSet(a,s.prop,u,n.setValue,e,t,l),i();a=await r.invokeMethod(a,s.prop,u,e,t,l),o++;continue}if(c&&n.mode===`set`)return await r.write(a,s.prop,n.setValue,e,t),i();a=await r.read(a,s.prop,e,t,l),o++}else if(s instanceof ov){if(a===null)throw Error(`path: [key] cannot be the first step`);let r=a.type.get();if(!r)throw Error(`path: type '${a.type.name}' has no indexed access`);let l=await s.key.evaluate(t,e);if(c&&n.mode===`set`)return await r.indexWrite(a,l,n.setValue,e,t),i();a=await r.indexRead(a,l,e,t),o++}else if(s instanceof av){if(a===null)throw Error(`path: (args) cannot be the first step`);let r=a.raw,l=a.type,u=l.call(),d=await s.buildArgsValue(l,e,t);if(c&&n.mode===`set`){if(!u?.set)throw Error(`path: call on type '${l.name}' has no call.set`);let r=u.set,a=async i=>{let o=new W(l,a);return await r.evaluate(t,e.child({args:i,value:n.setValue,recurse:o})),G(t.registry.void(),void 0)};return await a(d),i()}try{if(typeof r==`function`)a=await r(d);else if(u?.get){let n=u.get,r=async i=>{let a=new W(l,r);try{return await n.evaluate(t,e.child({args:i,recurse:a}))}catch(e){if(e instanceof ph)return e.value??G(t.registry.void(),void 0);throw e}};a=await r(d)}else throw Error(`path: value of type '${l.name}' is not callable`)}catch(n){if(n instanceof hh&&s.catch_){let r=e.child({error:n.error});a=await s.catch_.evaluate(t,r)}else throw n}o++}else throw Error(`path: unknown step at index ${o}`)}return a}typeOf(e,t){if(this.steps.length===0)return e.registry.any();let n=null,r=0;for(;r<this.steps.length;){let i=this.steps[r];if(i instanceof iv){if(n===null){n=t.get(i.prop)??e.registry.any(),r++;continue}let a=n.prop(i.prop);if(!a)return e.registry.any();let o=$_(n,a),s=this.steps[r+1];if(s instanceof av&&o.call()){let t=s.callSiteScope(o),i=o.call(t)?.returns;n=i?.simplify(t)??i??e.registry.any(),r+=2;continue}if(!(s instanceof av)&&Z_(o)){n=o.call()?.returns??e.registry.any(),r++;continue}n=o,r++}else if(i instanceof ov)n=n?.get()?.value??e.registry.any(),r++;else if(i instanceof av){if(n){let t=i.callSiteScope(n),r=n.call(t)?.returns;n=r?.simplify(t)??r??e.registry.any()}else n=e.registry.any();r++}else r++}return n??e.registry.any()}validateWalk(e,t,n,r,i=`get`){if(this.steps.length===0)return n.error(`path.empty`,`path is empty`),e.registry.any();if(i===`set`&&this.steps.length===1&&this.steps[0]instanceof iv)return e.registry.any();let a=null,o=0;for(;o<this.steps.length;){let s=this.steps[o],c=o===this.steps.length-1;if(s instanceof iv){if(a===null){let r=t.get(s.prop);r?a=r:(n.at([`path`,o],()=>n.error(`var.unknown`,`unknown variable '${s.prop}'${Ip(s.prop,[...t.keys()])}`)),a=e.registry.any()),o++;continue}let l=a.prop(s.prop);if(!l){n.at([`path`,o],()=>n.error(`prop.unknown`,`no prop '${s.prop}' on type '${a.name}'${nv(a,this.steps,o)}`)),a=e.registry.any(),o++;continue}let u=$_(a,l),d=this.steps[o+1];if(d instanceof av&&u.call()){for(let[i,a]of Object.entries(d.args))n.at([`path`,o+1,`args`,i],()=>a.validateWalk(e,t,n,r));d.catch_&&n.at([`path`,o+1,`catch`],()=>d.catch_.validateWalk(e,t,n,r));let c=d.callSiteScope(u),l=u.call(c);Q_(l,d.args,n,[`path`,o+1]),i===`set`&&o+1===this.steps.length-1&&(l?.set||n.at([`path`,o+1],()=>n.error(`set.call.no-set`,`method '${s.prop}' has no call.set`))),d.resolvedEffects=l?.effects()??0;let f=l?.returns;a=f?.simplify(c)??f??e.registry.any(),o+=2;continue}if(!(d instanceof av)&&Z_(u)){a=u.call()?.returns??e.registry.any(),o++;continue}i===`set`&&c&&!l.set&&l.get&&!u.call()&&n.at([`path`,o],()=>n.error(`set.prop.computed`,`prop '${s.prop}' is computed (read-only); cannot assign to it`));let f=i===`get`?u.call():void 0;if(f&&!Z_(u)){n.at([`path`,o],()=>n.error(`call.uncalled`,`method '${s.prop}' needs arguments \u2014 add an {args:{\u2026}} step to call it`)),a=f.returns??e.registry.any(),o++;continue}a=u,o++}else if(s instanceof ov){n.at([`path`,o,`key`],()=>s.key.validateWalk(e,t,n,r));let l=a?.get();i===`set`&&c?l?.set||n.at([`path`,o],()=>n.error(`set.index.no-set`,`type '${a?.name??`?`}' has no index set`)):l?.get||n.at([`path`,o],()=>n.error(`index.unsupported`,`type '${a?.name??`?`}' has no indexed access`)),a=l?.value??e.registry.any(),o++}else if(s instanceof av){for(let[i,a]of Object.entries(s.args))n.at([`path`,o,`args`,i],()=>a.validateWalk(e,t,n,r));if(a){let t=s.callSiteScope(a),r=a.call(t);Q_(r,s.args,n,[`path`,o]),i===`set`&&c&&(r?.set||n.at([`path`,o],()=>n.error(`set.call.no-set`,`call on type '${a?.name??`?`}' has no call.set`))),s.resolvedEffects=r?.effects()??0;let l=r?.returns;a=l?.simplify(t)??l??e.registry.any()}else s.resolvedEffects=0,a=e.registry.any();o++}else o++}return a??e.registry.any()}};function cv(e){return e.raw===null||e.raw===void 0}function lv(e,t,n,r){if(e instanceof iv)return V.jsonObject([{key:`prop`,value:V.jsonString(e.prop)}],{path:t},r,n);if(e instanceof av){let i=Object.entries(e.args).map(([e,i])=>({key:e,value:i.toJSONCode([...t,`args`,e],n,r+2)})),a=[{key:`args`,value:V.jsonObject(i,{path:[...t,`args`]},r+1,n)}];return e.generic&&a.push({key:`generic`,value:JSON.stringify(e.generic,null,n).replace(/\n/g,`
110
+ `+` `.repeat(r*n))}),e.catch_&&a.push({key:`catch`,value:e.catch_.toJSONCode([...t,`catch`],n,r+1)}),V.jsonObject(a,{path:t},r,n)}return e instanceof ov?V.jsonObject([{key:`key`,value:e.key.toJSONCode([...t,`key`],n,r+1)}],{path:t},r,n):new V(JSON.stringify(e.toJSON(),null,n))}var uv=class e extends th{constructor(e){super(),this.path=e}path;static KIND=`get`;kind=e.KIND;static from(t,n){return new e(sv.from(t.path,n)).withComment(t.comment)}async evaluate(e,t){return this.path.walk(t,e,{mode:`get`})}typeOf(e,t){return this.path.typeOf(e,t)}validateWalk(e,t,n,r){return this.path.validateWalk(e,t,n,r,`get`)}toGinCode(e,t={},n=[]){let r=this.path.toGinCode(e,t,n);return Lm(H`${this.commentPrefix(t)}${r}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`get`,path:this.path.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.path.toJSONCode([...e,`path`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`get`)},{key:`path`,value:r},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.path.clone()).withComment(this.comment)}forEachChild(e){this.path.forEachExpr(t=>e(t,`inherit`))}effects(){let e=[];this.path.forEachExpr(t=>{e.push(t.effects())});for(let t of this.path.steps)t instanceof av&&t.resolvedEffects!==void 0&&e.push(t.resolvedEffects);return Im(...e)}complexity(){return this.path.complexity()}},dv=class e extends th{constructor(e,t){super(),this.path=e,this.value=t}path;value;static KIND=`set`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){return new e(sv.from(t.path,n),n.registry.parseExpr(t.value,n)).withComment(t.comment)}async evaluate(e,t){let n=await this.value.evaluate(e,t);return this.path.steps.length===1&&this.path.steps[0]instanceof iv?(t.set(this.path.steps[0].prop,n),G(e.registry.bool(),!0)):this.path.walk(t,e,{mode:`set`,setValue:n})}typeOf(e,t){return e.registry.bool()}validateWalk(e,t,n,r){let i=n.at(`value`,()=>this.value.validateWalk(e,t,n,r)),a=this.path.validateWalk(e,t,n,r,`set`);return a.name!==`any`&&!a.compatible(i)&&n.at(`value`,()=>n.warn(`set.type-mismatch`,`value type '${i.name}' not compatible with target '${a.name}'`)),e.registry.bool()}toGinCode(e,t={},n=[]){let r=this.path.toGinCode(e,t,n),i=this.value.toGinCode(e,{...t,expectsValue:!0},[...n,`value`]);return Lm(H`${this.commentPrefix(t)}${r} = ${i}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`set`,path:this.path.toJSON(),value:this.value.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.path.toJSONCode([...e,`path`],t,n+1),i=this.value.toJSONCode([...e,`value`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`set`)},{key:`path`,value:r},{key:`value`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.path.clone(),this.value.clone()).withComment(this.comment)}forEachChild(e){this.path.forEachExpr(t=>e(t,`inherit`)),e(this.value,`inherit`)}effects(){let e=B.STATE|this.value.effects();this.path.forEachExpr(t=>{e|=t.effects()});for(let t of this.path.steps)t instanceof av&&t.resolvedEffects!==void 0&&(e|=t.resolvedEffects);return e}complexity(){return this.path.complexity()+this.value.complexity()}},fv=class e extends th{constructor(e,t){super(),this.vars=e,this.body=t}vars;body;static KIND=`define`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.vars.map(e=>({name:e.name,type:e.type?r.parse(e.type,n):void 0,value:r.parseExpr(e.value,n)}));return new e(i,r.parseExpr(t.body,n)).withComment(t.comment)}async evaluate(e,t){let n=t.child();for(let t of this.vars){let r=await t.value.evaluate(e,n);n.vars.set(t.name,r)}return this.body.evaluate(e,n)}typeOf(e,t){let n=new Map(t);for(let t of this.vars){let r=t.type??ah(e,t.value,n);n.set(t.name,r)}return ah(e,this.body,n)}validateWalk(e,t,n,r){let i=new Map(t);for(let t=0;t<this.vars.length;t++){let a=this.vars[t];n.at([`vars`,t,`name`],()=>lh(a.name,i,n));let o=n.at([`vars`,t,`value`],()=>ch(e,a.value,i,n,r));if(a.type&&!o.isUniversal()&&!a.type.compatible(o)){let e=pv(a.type),r=pv(o),i=o.name===`alias`?` (hint: '${r}' is an unbound generic \u2014 either bind it via \`generic: {${r}: ...}\` on the call site, pass \`output: typ<...>\`, or omit the declared type so the alias flows through)`:``;n.at([`vars`,t,`value`],()=>n.error(`define.var.type-mismatch`,`var '${a.name}' value type '${r}' not compatible with declared '${e}'${i}`))}i.set(a.name,a.type??o)}return n.at(`body`,()=>ch(e,this.body,i,n,r))}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i={...t,expectsValue:!0},a={...t,expectsValue:!1},o=this.vars.map((r,a)=>{let o=r.type?H`: ${r.type.toGinCode(void 0,t,[...n,`vars`,a,`type`])}`:``,s=r.value.toGinCode(e,i,[...n,`vars`,a,`value`]),c=H`let ${r.name}${o} = ${s};`;return c.text.split(`
111
+ `,1)[0].length<=80?c:H`let ${r.name}${o} =\n ${s.indent(` `)};`});if(r){let r=this.body.toGinCode(e,i,[...n,`body`]),a=o.map(e=>H` ${e}`),s=H` return ${r.indent(` `)};`,c=zm([...a,s]);return Lm(H`${this.commentPrefix(t)}(() => {\n${c}\n})()`,{path:n,expr:this})}let s=this.body.kind,c=this.body.toGinCode(e,a,[...n,`body`]),l=s===`if`||s===`switch`||s===`loop`||s===`block`?c:H`${c};`;return Lm(H`${this.commentPrefix(t)}${zm([...o,l])}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`define`,vars:this.vars.map(e=>{let t={name:e.name,value:e.value.toJSON()};return e.type&&(t.type=e.type.toJSON()),t}),body:this.body.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.vars.map((r,i)=>{let a=[...e,`vars`,i],o=r.value.toJSONCode([...a,`value`],t,n+3),s=r.type?r.type.toJSONCode([...a,`type`],t,n+3):void 0;return V.jsonObject([{key:`name`,value:V.jsonString(r.name)},{key:`value`,value:o},{key:`type`,value:s}],{path:a},n+2,t)}),i=this.body.toJSONCode([...e,`body`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`define`)},{key:`vars`,value:V.jsonArray(r,{path:[...e,`vars`]},n+1,t)},{key:`body`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.vars.map(e=>({name:e.name,type:e.type?.clone(),value:e.value.clone()})),this.body.clone()).withComment(this.comment)}forEachChild(e){for(let t of this.vars)e(t.value,`inherit`);e(this.body,`inherit`)}effects(){let e=this.body.effects();for(let t of this.vars)e|=t.value.effects();return e}complexity(){let e=1+this.body.complexity();for(let t of this.vars)e+=1+t.value.complexity();return e}};function pv(e){try{return e.toCode()}catch{return e.name}}var mv=class e extends th{constructor(e){super(),this.lines=e}lines;static KIND=`block`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(t.lines.map(e=>r.parseExpr(e,n))).withComment(t.comment)}async evaluate(e,t){let n=G(e.registry.void(),void 0);for(let r of this.lines)n=await r.evaluate(e,t);return n}typeOf(e,t){return this.lines.length===0?e.registry.void():ah(e,this.lines[this.lines.length-1],t)}validateWalk(e,t,n,r){let i=e.registry.void();for(let a=0;a<this.lines.length;a++)i=n.at(a,()=>ch(e,this.lines[a],t,n,r));return i}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1;if(this.lines.length===0)return Lm(r?`undefined`:``,{path:n,expr:this});if(this.lines.length===1)return Lm(this.lines[0].toGinCode(e,t,[...n,0]),{path:n,expr:this});let i=this.commentPrefix(t);return Lm(r?H`${i}(() => {\n${zm(this.lines.map((r,i)=>{let a=i===this.lines.length-1,o=r.toGinCode(e,{...t,expectsValue:a},[...n,i]).indent(` `);return a?H` return ${o};`:H` ${o};`}))}\n})()`:H`${i}${zm(this.lines.map((r,i)=>{let a=r.kind,o=r.toGinCode(e,{...t,expectsValue:!1},[...n,i]);return a===`if`||a===`switch`||a===`loop`||a===`block`?o:H`${o};`}))}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`block`,lines:this.lines.map(e=>e.toJSON())})}toJSONCode(e=[],t=2,n=0){let r=this.lines.map((r,i)=>r.toJSONCode([...e,i],t,n+2));return V.jsonObject([{key:`kind`,value:V.jsonString(`block`)},{key:`lines`,value:V.jsonArray(r,{path:[...e,`lines`]},n+1,t)},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.lines.map(e=>e.clone())).withComment(this.comment)}forEachChild(e){for(let t of this.lines)e(t,`inherit`)}effects(){let e=B.NONE;for(let t of this.lines)e|=t.effects();return e}complexity(){let e=1;for(let t of this.lines)e+=t.complexity();return e}},hv=class e extends th{constructor(e,t,n){super(),this.action=e,this.value=t,this.error=n}action;value;error;static KIND=`flow`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(t.action,t.value?r.parseExpr(t.value,n):void 0,t.error?r.parseExpr(t.error,n):void 0).withComment(t.comment)}async evaluate(e,t){switch(this.action){case`break`:throw new dh;case`continue`:throw new fh;case`return`:throw new ph(this.value?await this.value.evaluate(e,t):void 0);case`exit`:throw new mh(this.value?await this.value.evaluate(e,t):void 0);case`throw`:throw this.error?new hh(await this.error.evaluate(e,t)):Error("flow.throw requires `error`")}}typeOf(e,t){return e.registry.void()}validateWalk(e,t,n,r){return this.action!==`break`&&this.action!==`continue`||r.inLoop||n.error(`flow.outside-loop`,`${this.action} used outside a loop`),this.action===`return`&&!r.inLambda&&n.warn(`flow.outside-lambda`,`return used outside a lambda`),this.action===`throw`&&!this.error&&n.error(`flow.throw.no-error`,"throw requires an `error` expression"),this.value&&n.at(`value`,()=>ch(e,this.value,t,n,r)),this.error&&n.at(`error`,()=>ch(e,this.error,t,n,r)),e.registry.void()}toGinCode(e,t={},n=[]){let r=this.commentPrefix(t),i={...t,expectsValue:!0},a;switch(this.action){case`break`:a=new V(`break`);break;case`continue`:a=new V(`continue`);break;case`return`:a=this.value?H`return ${this.value.toGinCode(e,i,[...n,`value`])}`:new V(`return`);break;case`throw`:a=this.error?H`throw ${this.error.toGinCode(e,i,[...n,`error`])}`:new V(`throw`);break;case`exit`:a=this.value?H`exit ${this.value.toGinCode(e,i,[...n,`value`])}`:new V(`exit`);break;default:a=new V(``)}return Lm(H`${r}${a}`,{path:n,expr:this})}toJSONCode(e=[],t=2,n=0){let r=this.value?this.value.toJSONCode([...e,`value`],t,n+1):void 0,i=this.error?this.error.toJSONCode([...e,`error`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`flow`)},{key:`action`,value:V.jsonString(this.action)},{key:`value`,value:r},{key:`error`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}toJSON(){let e={kind:`flow`,action:this.action};return this.value&&(e.value=this.value.toJSON()),this.error&&(e.error=this.error.toJSON()),this.withCommentOn(e)}clone(){return new e(this.action,this.value?.clone(),this.error?.clone()).withComment(this.comment)}forEachChild(e){this.value&&e(this.value,`inherit`),this.error&&e(this.error,`inherit`)}effects(){return B.STATE|(this.value?.effects()??B.NONE)|(this.error?.effects()??B.NONE)}complexity(){return 1+(this.value?.complexity()??0)+(this.error?.complexity()??0)}};function gv(e){return e.replace(/\n/g,`
112
+ `)}function _v(e,t=`inherit`){if(e instanceof hv)return e.action===`throw`||e.action===`exit`?e:e.action===`return`?t===`lambda`?void 0:e:e.action===`break`||e.action===`continue`?t===`loop`?void 0:e:void 0;let n;return e.forEachChild((e,r)=>{if(n)return;let i=_v(e,r===`inherit`?t:r);i&&(n=i)}),n}var vv=class e extends th{constructor(e,t){super(),this.ifs=e,this.otherwise=t}ifs;otherwise;static KIND=`if`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.ifs.map(e=>({condition:r.parseExpr(e.condition,n),body:r.parseExpr(e.body,n)}));return new e(i,t.else?r.parseExpr(t.else,n):void 0).withComment(t.comment)}async evaluate(e,t){for(let n of this.ifs)if((await n.condition.evaluate(e,t)).raw)return n.body.evaluate(e,t);return this.otherwise?this.otherwise.evaluate(e,t):G(e.registry.void(),void 0)}typeOf(e,t){let n=this.ifs.map(n=>ah(e,n.body,t));return this.otherwise&&n.push(ah(e,this.otherwise,t)),n.length===1?n[0]:e.registry.or(n)}validateWalk(e,t,n,r){let i=e.registry.bool(),a=[];for(let o=0;o<this.ifs.length;o++){let s=this.ifs[o],c=n.at([`ifs`,o,`condition`],()=>ch(e,s.condition,t,n,r));if(!i.compatible(c)){let e;try{e=c.toCode()}catch{e=c.name}n.at([`ifs`,o,`condition`],()=>n.warn(`if.condition.type`,`if condition should be bool, got '${e}' (did you forget to call a method?)`))}a.push(n.at([`ifs`,o,`body`],()=>ch(e,s.body,t,n,r)))}for(let e=0;e<this.ifs.length;e++)this.ifs[e].body.effects()===B.NONE&&n.at([`ifs`,e,`body`],()=>n.warn(`if.branch.no-effect`,"if branch body has no observable effect — when this branch matches, nothing happens. Either give it a `set`/`flow`/native call, or drop the branch entirely"));return this.otherwise&&(a.push(n.at(`else`,()=>ch(e,this.otherwise,t,n,r))),this.otherwise.effects()===B.NONE&&n.at(`else`,()=>n.warn(`if.else.no-effect`,"else arm has no observable effect — `else` is optional; OMIT it entirely when its only purpose is producing a placeholder value"))),a.length===1?a[0]:e.registry.or(a)}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i=this.ifs.some(e=>!!_v(e.body))||(this.otherwise?!!_v(this.otherwise):!1),a=this.commentPrefix(t),o={...t,expectsValue:!0};if(r&&!i){if(this.ifs.length===1&&this.otherwise){let t=this.ifs[0];return Lm(H`${a}(${t.condition.toGinCode(e,o,[...n,`ifs`,0,`condition`])} ? ${t.body.toGinCode(e,o,[...n,`ifs`,0,`body`])} : ${this.otherwise.toGinCode(e,o,[...n,`else`])})`,{path:n,expr:this})}let t=H``;for(let r=0;r<this.ifs.length;r++){let i=this.ifs[r],a=r===0?`if`:`else if`,s=i.condition.toGinCode(e,o,[...n,`ifs`,r,`condition`]),c=i.body.toGinCode(e,o,[...n,`ifs`,r,`body`]);t=H`${t}${r===0?``:`
113
+ `} ${a} (${s}) return ${c.indent(` `)};`}let r=``;return this.otherwise&&(r=H`\n return ${this.otherwise.toGinCode(e,o,[...n,`else`]).indent(` `)};`),Lm(H`${a}(() => {\n${t}${r}\n})()`,{path:n,expr:this})}let s=H``;for(let r=0;r<this.ifs.length;r++){let i=this.ifs[r],a=r===0?`if`:`else if`,c=r===0?``:` `,l=i.condition.toGinCode(e,o,[...n,`ifs`,r,`condition`]),u=i.body.renderStatementBodyRich(e,t,[...n,`ifs`,r,`body`]);s=H`${s}${c}${a} (${l}) ${u}`}if(this.otherwise){let r=this.otherwise.renderStatementBodyRich(e,t,[...n,`else`],!0);s=H`${s} else ${r}`}return Lm(H`${a}${s}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`if`,ifs:this.ifs.map(e=>({condition:e.condition.toJSON(),body:e.body.toJSON()})),else:this.otherwise?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.ifs.map((r,i)=>{let a=[...e,`ifs`,i];return V.jsonObject([{key:`condition`,value:r.condition.toJSONCode([...a,`condition`],t,n+3)},{key:`body`,value:r.body.toJSONCode([...a,`body`],t,n+3)}],{path:a},n+2,t)}),i=this.otherwise?this.otherwise.toJSONCode([...e,`else`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`if`)},{key:`ifs`,value:V.jsonArray(r,{path:[...e,`ifs`]},n+1,t)},{key:`else`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.ifs.map(e=>({condition:e.condition.clone(),body:e.body.clone()})),this.otherwise?.clone()).withComment(this.comment)}forEachChild(e){for(let t of this.ifs)e(t.condition,`inherit`),e(t.body,`inherit`);this.otherwise&&e(this.otherwise,`inherit`)}effects(){let e=B.NONE;for(let t of this.ifs)e|=t.condition.effects()|t.body.effects();return this.otherwise&&(e|=this.otherwise.effects()),e}complexity(){let e=1;for(let t of this.ifs)e+=t.condition.complexity()+t.body.complexity();return this.otherwise&&(e+=this.otherwise.complexity()),e}},yv=class e extends th{constructor(e,t,n){super(),this.value=e,this.cases=t,this.otherwise=n}value;cases;otherwise;static KIND=`switch`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(r.parseExpr(t.value,n),t.cases.map(e=>({equals:e.equals.map(e=>r.parseExpr(e,n)),body:r.parseExpr(e.body,n)})),t.else?r.parseExpr(t.else,n):void 0).withComment(t.comment)}async evaluate(e,t){let n=await this.value.evaluate(e,t);for(let r of this.cases)for(let i of r.equals)if((await i.evaluate(e,t)).raw===n.raw)return r.body.evaluate(e,t);return this.otherwise?this.otherwise.evaluate(e,t):G(e.registry.void(),void 0)}typeOf(e,t){let n=this.cases.map(n=>ah(e,n.body,t));return this.otherwise&&n.push(ah(e,this.otherwise,t)),n.length===0?e.registry.void():n.length===1?n[0]:e.registry.or(n)}validateWalk(e,t,n,r){let i=n.at(`value`,()=>ch(e,this.value,t,n,r)),a=[];for(let o=0;o<this.cases.length;o++){let s=this.cases[o];for(let a=0;a<s.equals.length;a++){let c=n.at([`cases`,o,`equals`,a],()=>ch(e,s.equals[a],t,n,r));i.compatible(c)||n.at([`cases`,o,`equals`,a],()=>n.warn(`switch.case.type`,`case value type '${c.name}' not compatible with switch value '${i.name}'`))}a.push(n.at([`cases`,o,`body`],()=>ch(e,s.body,t,n,r))),s.body.effects()===B.NONE&&n.at([`cases`,o,`body`],()=>n.warn(`switch.case.no-effect`,"switch case body has no observable effect — when this case matches, nothing happens. Either give it a `set`/`flow`/native call, or drop the case"))}return this.otherwise&&(a.push(n.at(`else`,()=>ch(e,this.otherwise,t,n,r))),this.otherwise.effects()===B.NONE&&n.at(`else`,()=>n.warn(`switch.else.no-effect`,`switch default has no observable effect — OMIT it instead of carrying a placeholder fallback`))),a.length===0?e.registry.void():a.length===1?a[0]:e.registry.or(a)}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i=this.cases.some(e=>!!_v(e.body))||(this.otherwise?!!_v(this.otherwise):!1),a={...t,expectsValue:!0},o=this.value.toGinCode(e,a,[...n,`value`]),s=this.commentPrefix(t);if(r&&!i){let t=zm(this.cases.map((t,r)=>H`${zm(t.equals.map((t,i)=>H` case ${t.toGinCode(e,a,[...n,`cases`,r,`equals`,i])}:`))}\n return ${t.body.toGinCode(e,a,[...n,`cases`,r,`body`]).indent(` `)};`)),r=``;return this.otherwise&&(r=H`\n default:\n return ${this.otherwise.toGinCode(e,a,[...n,`else`]).indent(` `)};`),Lm(H`${s}(() => {\n switch (${o}) {\n${t}${r}\n }\n})()`,{path:n,expr:this})}let c=(n,r)=>{let i=n.kind;return n instanceof hv?H`${n.toGinCode(e,{...t,expectsValue:!1},r)};`:i===`block`||i===`if`||i===`switch`||i===`loop`?n.toGinCode(e,{...t,expectsValue:!1},r):H`${n.toGinCode(e,{...t,expectsValue:!0},r)};`},l=zm(this.cases.map((t,r)=>{let i=zm(t.equals.map((t,i)=>H` case ${t.toGinCode(e,a,[...n,`cases`,r,`equals`,i])}:`)),o=[...n,`cases`,r,`body`];return H`${i}\n ${c(t.body,o).indent(` `)}${t.body instanceof hv?``:`
114
+ break;`}`})),u=``;return this.otherwise&&(u=H`\n default:\n ${c(this.otherwise,[...n,`else`]).indent(` `)}`),Lm(H`${s}switch (${o}) {\n${l}${u}\n}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`switch`,value:this.value.toJSON(),cases:this.cases.map(e=>({equals:e.equals.map(e=>e.toJSON()),body:e.body.toJSON()})),else:this.otherwise?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.value.toJSONCode([...e,`value`],t,n+1),i=this.cases.map((r,i)=>{let a=[...e,`cases`,i],o=r.equals.map((e,r)=>e.toJSONCode([...a,`equals`,r],t,n+4));return V.jsonObject([{key:`equals`,value:V.jsonArray(o,{path:[...a,`equals`]},n+3,t)},{key:`body`,value:r.body.toJSONCode([...a,`body`],t,n+3)}],{path:a},n+2,t)}),a=this.otherwise?this.otherwise.toJSONCode([...e,`else`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`switch`)},{key:`value`,value:r},{key:`cases`,value:V.jsonArray(i,{path:[...e,`cases`]},n+1,t)},{key:`else`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.value.clone(),this.cases.map(e=>({equals:e.equals.map(e=>e.clone()),body:e.body.clone()})),this.otherwise?.clone()).withComment(this.comment)}forEachChild(e){e(this.value,`inherit`);for(let t of this.cases){for(let n of t.equals)e(n,`inherit`);e(t.body,`inherit`)}this.otherwise&&e(this.otherwise,`inherit`)}effects(){let e=this.value.effects();for(let t of this.cases){for(let n of t.equals)e|=n.effects();e|=t.body.effects()}return this.otherwise&&(e|=this.otherwise.effects()),e}complexity(){let e=1+this.value.complexity();for(let t of this.cases){for(let n of t.equals)e+=n.complexity();e+=t.body.complexity()}return this.otherwise&&(e+=this.otherwise.complexity()),e}},bv=class e extends th{constructor(e,t,n,r,i){super(),this.over=e,this.body=t,this.keyName=n,this.valueName=r,this.parallel=i}over;body;keyName;valueName;parallel;static KIND=`loop`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.parallel?{concurrent:t.parallel.concurrent?r.parseExpr(t.parallel.concurrent,n):void 0,rate:t.parallel.rate?r.parseExpr(t.parallel.rate,n):void 0}:void 0;return new e(r.parseExpr(t.over,n),r.parseExpr(t.body,n),t.key,t.value,i).withComment(t.comment)}async evaluate(e,t){let n=await this.over.evaluate(e,t),r=n.type.get();if(!(r?.loop||r?.loopDynamic))throw Error(`loop: type '${n.type.name}' has no loop or loopDynamic defined on its GetSet`);let i=this.keyName??`key`,a=this.valueName??`value`,o=this.parallel?.concurrent?Number((await this.parallel.concurrent.evaluate(e,t)).raw):void 0,s=this.parallel?.rate?Number((await this.parallel.rate.evaluate(e,t)).raw):void 0,c=o!==void 0||s!==void 0;if(r.loopDynamic){let r=e.registry.num({whole:!0,min:0});if(!c){let o=n,s=0;for(;o.raw;){await t.checkpoint();let n=t.child({[i]:G(r,s),[a]:o});try{await this.body.evaluate(e,n)}catch(e){if(e instanceof dh)break;if(!(e instanceof fh))throw e}s++,o=await this.over.evaluate(e,t)}return G(e.registry.void(),void 0)}let l=new Set,u=o??1/0,d=!1,f=0,p=0,m=async()=>{if(d)return!1;await t.checkpoint();let n=await this.over.evaluate(e,t);if(!n.raw)return!1;if(s&&s>0){let e=Date.now()-f;e<s&&await new Promise(t=>setTimeout(t,s-e)),f=Date.now()}let o=t.child({[i]:G(r,p),[a]:n}),c=(async()=>{try{await this.body.evaluate(e,o)}catch(e){if(e instanceof fh)return;if(e instanceof dh){d=!0;return}throw e}})().finally(()=>l.delete(c));return l.add(c),p++,!0},h=Number.isFinite(u)?u:1;for(;l.size<h&&await m(););for(;l.size>0;)for(await Promise.race(l);!d&&l.size<h&&await m(););return G(e.registry.void(),void 0)}let l=r.loop;if(!l)throw Error(`loop: type '${n.type.name}' has no loop ExprDef on its GetSet`);if(!c)return await xv(l,t,e,n,async(n,r)=>{let o=t.child({[i]:n,[a]:r});try{return await this.body.evaluate(e,o)}catch(t){if(t instanceof fh)return G(e.registry.void(),void 0);throw t}}),G(e.registry.void(),void 0);let u=new Set,d=o??1/0,f=!1,p=0;return await xv(r.loop,t,e,n,async(n,r)=>{if(f)return G(e.registry.void(),void 0);if(s&&s>0){let e=Date.now()-p;e<s&&await new Promise(t=>setTimeout(t,s-e)),p=Date.now()}for(;u.size>=d;)await Promise.race(u);let o=t.child({[i]:n,[a]:r}),c=(async()=>{try{await this.body.evaluate(e,o)}catch(e){if(e instanceof fh)return;if(e instanceof dh){f=!0;return}throw e}})().finally(()=>u.delete(c));return u.add(c),G(e.registry.void(),void 0)}),await Promise.all(u),G(e.registry.void(),void 0)}typeOf(e,t){return e.registry.void()}validateWalk(e,t,n,r){let i=n.at(`over`,()=>ch(e,this.over,t,n,r)),a=i.get();if(a?.loop||a?.loopDynamic||n.error(`loop.not-iterable`,`type '${i.name}' has no loop defined`),this.parallel?.concurrent){let i=n.at([`parallel`,`concurrent`],()=>ch(e,this.parallel.concurrent,t,n,r));e.registry.num().compatible(i)||n.at([`parallel`,`concurrent`],()=>n.error(`loop.parallel.concurrent.type`,`parallel.concurrent must be a number, got '${i.name}'`))}if(this.parallel?.rate){let i=n.at([`parallel`,`rate`],()=>ch(e,this.parallel.rate,t,n,r)),a=e.registry.num().compatible(i),o=e.registry.duration().compatible(i);!a&&!o&&n.at([`parallel`,`rate`],()=>n.error(`loop.parallel.rate.type`,`parallel.rate must be a number or duration, got '${i.name}'`))}this.keyName===void 0?t.has(`key`)&&n.error(`loop.key.shadow`,`loop's default 'key' is already in scope from an enclosing loop — set the \`key\` field on this loop to a distinct name (e.g. "i", "j", "outerKey") so the inner loop doesn't shadow the outer iteration index`):n.at(`key`,()=>lh(this.keyName,t,n)),this.valueName===void 0?t.has(`value`)&&n.error(`loop.value.shadow`,`loop's default 'value' is already in scope from an enclosing loop — set the \`value\` field on this loop to a distinct name (e.g. "v", "row", "outerValue") so the inner loop doesn't shadow the outer iteration value`):n.at(`value`,()=>lh(this.valueName,t,n));let o=a?.key??e.registry.any(),s=a?.value??e.registry.any(),c=new Map(t);return c.set(this.keyName??`key`,o),c.set(this.valueName??`value`,s),n.at(`body`,()=>ch(e,this.body,c,n,{...r,inLoop:!0})),this.body.effects()===B.NONE&&n.at(`body`,()=>n.warn(`loop.body.no-effect`,"loop body has no observable effect — the iteration's computed value is discarded. Add a `set` to accumulate into an outer var, a `flow` to control iteration, or invoke a side-effecting native (e.g. `fns.log`, `fns.fetch`)")),e.registry.void()}toCode(e,t={}){let n=t.expectsValue??!1,r={...t,expectsValue:!0},i={...t,expectsValue:!1},a=this.over.toCode(e,r),o=this.keyName??`key`,s=this.valueName??`value`,c=``;t.includeComments!==!1&&(this.parallel?.concurrent&&(c+=`/* parallel.concurrent: ${this.parallel.concurrent.toCode(e,r)} */ `),this.parallel?.rate&&(c+=`/* parallel.rate: ${this.parallel.rate.toCode(e,r)} */ `));let l=(()=>{let t=this.body.kind;if(t===`flow`)return`${this.body.toCode(e,i)};`;if(t===`block`){let t=this.body.toCode(e,i);return t.startsWith(`{`)?t.slice(1,-1).trim():t}return t===`if`||t===`switch`||t===`loop`?this.body.toCode(e,i):`${this.body.toCode(e,i)};`})(),u=`${c}for (const [${o}, ${s}] of ${a}) {
115
+ ${gv(l)}
116
+ }`,d=this.commentPrefix(t);return n?d+`(() => { ${u}; return undefined; })()`:d+u}toJSON(){let e={kind:`loop`,over:this.over.toJSON(),body:this.body.toJSON()};return this.keyName!==void 0&&(e.key=this.keyName),this.valueName!==void 0&&(e.value=this.valueName),this.parallel&&(e.parallel={concurrent:this.parallel.concurrent?.toJSON(),rate:this.parallel.rate?.toJSON()}),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.over.toJSONCode([...e,`over`],t,n+1),i=this.body.toJSONCode([...e,`body`],t,n+1),a=this.parallel?V.jsonObject([{key:`concurrent`,value:this.parallel.concurrent?.toJSONCode([...e,`parallel`,`concurrent`],t,n+2)},{key:`rate`,value:this.parallel.rate?.toJSONCode([...e,`parallel`,`rate`],t,n+2)}],{path:[...e,`parallel`]},n+1,t):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`loop`)},{key:`over`,value:r},{key:`body`,value:i},{key:`key`,value:this.keyName===void 0?void 0:V.jsonString(this.keyName)},{key:`value`,value:this.valueName===void 0?void 0:V.jsonString(this.valueName)},{key:`parallel`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.over.clone(),this.body.clone(),this.keyName,this.valueName,this.parallel?{concurrent:this.parallel.concurrent?.clone(),rate:this.parallel.rate?.clone()}:void 0).withComment(this.comment)}forEachChild(e){e(this.over,`inherit`),e(this.body,`loop`),this.parallel?.concurrent&&e(this.parallel.concurrent,`inherit`),this.parallel?.rate&&e(this.parallel.rate,`inherit`)}effects(){return this.over.effects()|this.body.effects()|(this.parallel?.concurrent?.effects()??B.NONE)|(this.parallel?.rate?.effects()??B.NONE)}complexity(){return 6+this.over.complexity()+this.body.complexity()+(this.parallel?.concurrent?.complexity()??0)+(this.parallel?.rate?.complexity()??0)}};async function xv(e,t,n,r,i){let a=n.registry,o=new W(a.fn({args:a.obj({key:{type:a.any()},value:{type:a.any()}}),returns:a.void()}),async e=>{let t=e.raw;if(!t)throw Error(`yield: missing args`);return await s.checkpoint(),i(t.key,t.value)}),s=t.child({this:r,yield:o});try{await e.evaluate(n,s)}catch(e){if(!(e instanceof dh))throw e}}var Sv=class e extends th{constructor(e,t,n){super(),this.fnType=e,this.body=t,this.constraint=n}fnType;body;constraint;static KIND=`lambda`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=r.parse(t.type,n),a=Tv(n,i),o=r.parseExpr(t.body,a),s=t.constraint?r.parseExpr(t.constraint,a):void 0;return new e(i,o,s).withComment(t.comment)}async evaluate(e,t){let n=this.fnType,r=this.body,i=t,a=this.constraint,o=async t=>{await i.checkpoint();let s=new W(n,o),c=i.child({args:t,recurse:s});if(a&&(await a.evaluate(e,c)).raw!==!0)throw Error(`lambda constraint failed: ${a.toCode(e.registry,{expectsValue:!0})}`);try{return await r.evaluate(e,c)}catch(t){if(t instanceof ph)return t.value??new W(e.registry.void(),void 0);throw t}};return new W(n,o)}typeOf(e,t){return this.fnType}validateWalk(e,t,n,r){let i=this.fnType.call(),a=new Map(t);a.set(`args`,i?.args??e.registry.any());let o=n.at(`body`,()=>ch(e,this.body,a,n,{...r,inLambda:!0}));if(i?.returns&&!i.returns.compatible(o)&&n.at(`body`,()=>n.warn(`lambda.returns.type`,`body type '${o.name}' not compatible with declared returns '${i.returns.name}'`)),this.constraint){let t=e.registry.bool(),i=n.at(`constraint`,()=>ch(e,this.constraint,a,n,{...r,inLambda:!0}));t.compatible(i)||n.at(`constraint`,()=>n.warn(`lambda.constraint.type`,`constraint must return bool, got '${i.name}'`))}return this.fnType}toGinCode(e,t={},n=[]){let r=this.fnType.call(),i={...t,expectsValue:!0},a=this.commentPrefix(t),o=`(${Cv(r?.args,t)})${r?.returns?`: ${r.returns.toCode(void 0,t)}`:``}`,s=this.body.toGinCode(e,i,[...n,`body`]),c=s.text,l;return l=this.constraint?H`${o} => {\n if (!(${wv(this.constraint.toGinCode(e,i,[...n,`constraint`]))})) throw new Error('constraint');\n return ${s.indent(` `)};\n}`:c.includes(`
117
+ `)?H`${o} => {\n ${s.indent(` `)}\n}`:H`${o} => ${s}`,Lm(a?H`${a}${l}`:l,{path:n,expr:this})}toCode(e,t={}){return this.toGinCode(e,t).toString()}toJSON(){return this.withCommentOn({kind:`lambda`,type:this.fnType.toJSON(),body:this.body.toJSON(),constraint:this.constraint?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.fnType.toJSONCode([...e,`type`],t,n+1),i=this.body.toJSONCode([...e,`body`],t,n+1),a=this.constraint?this.constraint.toJSONCode([...e,`constraint`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`lambda`)},{key:`type`,value:r},{key:`body`,value:i},{key:`constraint`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.fnType.clone(),this.body.clone(),this.constraint?.clone()).withComment(this.comment)}forEachChild(e){e(this.body,`lambda`),this.constraint&&e(this.constraint,`lambda`)}effects(){return B.NONE}complexity(){return 10+this.body.complexity()+(this.constraint?.complexity()??0)}};function Cv(e,t){if(!e||e.name===`void`||e.name===`any`)return``;let n=e.fields;if(!n)return`args: ${e.toCode(void 0,t)}`;let r=Object.entries(n);return r.length===0?``:r.map(([e,n])=>{let r=n.type.isOptional?.()??!1,i=r&&typeof n.type.required==`function`?n.type.required():n.type;return`${n.docs&&t.includeComments!==!1?`/* ${n.docs} */ `:``}${e}${r?`?`:``}: ${i.toCode(void 0,t)}`}).join(`, `)}function wv(e){return e.text.includes(`
118
+ `)?new V(e.text.replace(/\n\s*/g,` `),e.spans):e}function Tv(e,t){let n=new eh(e),r=t.call();if(r?.types)for(let[e,t]of Object.entries(r.types))n.bind(e,t);return n}var Ev=class e extends th{constructor(e,t){super(),this.template=e,this.params=t}template;params;static KIND=`template`;kind=e.KIND;static from(t,n){let r=n.registry,i=t.template,a=i&&typeof i==`object`&&`kind`in i?r.parseExpr(i,n):r.parseExpr({kind:`new`,type:{name:`text`},value:String(i)},n),o=t.params?r.parseExpr(t.params,n):void 0;return new e(a,o).withComment(t.comment)}async evaluate(e,t){let n=await this.template.evaluate(e,t),r=String(n.raw),i;this.params&&(i=(await this.params.evaluate(e,t)).raw);let a=r.replace(/\{(\w+)\}/g,(e,n)=>{if(i&&Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];return e==null?``:e instanceof W?String(e.raw??``):String(e)}let r=t.get(n);return r===void 0?``:r instanceof W?String(r.raw??``):String(r)});return G(e.registry.text(),a)}typeOf(e,t){return e.registry.text()}validateWalk(e,t,n,r){let i=e.registry.text(),a=n.at(`template`,()=>ch(e,this.template,t,n,r));i.compatible(a)||n.at(`template`,()=>n.warn(`template.template.type`,`template should resolve to text, got '${a.name}'`));let o,s=!1;if(this.params){let i=n.at(`params`,()=>ch(e,this.params,t,n,r));if(i.name===`any`)s=!0;else if(i.name===`obj`||i.name===`iface`){let e=i.props(),t=Object.entries(e).filter(([,e])=>!e.type.call()).map(([e])=>e);o=new Set(t)}else n.at(`params`,()=>n.warn(`template.params.type`,`template params should be an object, got '${i.name}'`)),s=!0}let c=this.template instanceof K_&&typeof this.template.value==`string`?this.template.value:void 0;if(c!==void 0){let e=new Set,r=/\{(\w+)\}/g,i;for(;(i=r.exec(c))!==null;){let r=i[1];if(e.has(r))continue;e.add(r);let a=o?.has(r)??!1,c=t.has(r);s?c||n.error(`template.placeholder.unresolved`,`placeholder '{${r}}' isn't a scope variable; either define '${r}' in scope or pass a typed obj as \`params\` so it can be checked`):!a&&!c&&n.error(`template.placeholder.unresolved`,this.params?`placeholder '{${r}}' is not a key of \`params\` (keys: [${[...o??[]].join(`, `)||`none`}]) and not a scope variable`:`placeholder '{${r}}' does not match any scope variable; either \`define ${r} = ...\` first or pass it via \`params\``)}}return e.registry.text()}toCode(e,t={}){let n=this.commentPrefix(t),r=this.template instanceof K_&&typeof this.template.value==`string`?this.template.value:void 0;if(r===void 0){let r=e.toCode(this.template,{...t,expectsValue:!0});return this.params?`${n}template(${r}, ${e.toCode(this.params,{...t,expectsValue:!0})})`:`${n}template(${r})`}let i=this.params?Dv(this.params,e):void 0;return`${n}${`\`${r.replace(/\{(\w+)\}/g,(e,t)=>{if(i&&Object.prototype.hasOwnProperty.call(i,t)){let e=i[t];return e.length>64?`\${
119
119
  `+e+`
120
- }`:"${"+e+`}`}return"${"+t+`}`}).replace(/`/g,"\\`")}\``}`}toJSON(){return this.withCommentOn({kind:`template`,template:this.template.toJSON(),...this.params?{params:this.params.toJSON()}:{}})}toJSONCode(e=[],t=2,n=0){let r=this.template.toJSONCode([...e,`template`],t,n+1),i=this.params?this.params.toJSONCode([...e,`params`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`template`)},{key:`template`,value:r},{key:`params`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.template.clone(),this.params?.clone()).withComment(this.comment)}forEachChild(e){e(this.template,`inherit`),this.params&&e(this.params,`inherit`)}effects(){return this.template.effects()|(this.params?.effects()??B.NONE)}complexity(){return 1+this.template.complexity()+(this.params?.complexity()??0)}};function Tv(e,t){if(!(e instanceof W_))return;let n=e.value;if(!n||typeof n!=`object`||Array.isArray(n))return;let r={};for(let[e,i]of Object.entries(n))if(typeof i==`string`)r[e]=JSON.stringify(i);else if(typeof i==`number`||typeof i==`boolean`)r[e]=String(i);else if(i===null)r[e]=`null`;else if(i&&typeof i==`object`&&`kind`in i&&typeof i.kind==`string`&&t.exprClass(i.kind))try{r[e]=t.parseExpr(i).toCode(t,{expectsValue:!0})}catch{return}else return;return r}var Ev=class e extends $m{constructor(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){super(),this.id=e,this.type=t,this.resolvedEffects=n}id;type;resolvedEffects;static KIND=`native`;kind=e.KIND;static from(t,n){return new e(t.id,t.type?n.registry.parse(t.type,n):void 0,n.registry.nativeEffects(t.id)).withComment(t.comment)}async evaluate(e,t){let n=e.registry.getNative(this.id);if(!n)throw Error(`native: no impl registered for '${this.id}'`);let r=await n(t,e.registry);return r instanceof W?r:G(this.type??e.registry.any(),r)}typeOf(e,t){return this.type??e.registry.any()}validateWalk(e,t,n,r){return e.registry.getNative(this.id)||n.warn(`native.unknown`,`native impl '${this.id}' is not registered`),this.type??e.registry.any()}toCode(e,t={}){return this.commentPrefix(t)+`/* native: ${this.id} */`}toJSON(){let e={kind:`native`,id:this.id};return this.type&&(e.type=this.type.toJSON()),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.type?this.type.toJSONCode([...e,`type`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`native`)},{key:`id`,value:V.jsonString(this.id)},{key:`type`,value:r},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.id,this.type?.clone(),this.resolvedEffects).withComment(this.comment)}effects(){return this.resolvedEffects}complexity(){return 1}},Dv=[`props`,`get`,`call`,`init`],Ov=class{classes=new Map;namedTypes=new Map;natives=new Map;nativeEffectsMap=new Map;exprClasses=new Map;augments=new Map;_version=0;get version(){return this._version}parent=void 0;get registry(){return this}define(e){return this.classes.set(e.NAME,e),this._version++,this}register(e){return this.namedTypes.set(e.name,e),this._version++,this}scope(e){return new Qm(this,{...e})}augment(e,t){this._version++;let n={props:t.props?jh.fromMap(t.props,this):void 0,get:t.get?Mh.from(t.get,this):void 0,call:t.call?Nh.from(t.call,this):void 0,init:t.init?Ph.from(t.init,this):void 0},r=this.augments.get(e);return r?(this.augments.set(e,{props:n.props?{...r.props??{},...n.props}:r.props,get:r.get??n.get,call:r.call??n.call,init:r.init??n.init}),this):(this.augments.set(e,{props:n.props?{...n.props}:void 0,get:n.get,call:n.call,init:n.init}),this)}augmentation(e){return this.augments.get(e)}lookup(e){if(this.namedTypes.has(e))return this.namedTypes.get(e);let t=this.classes.get(e);if(t)return t.from({name:e},this)}localLookup(e){}setNative(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){return this.natives.set(e,t),this.nativeEffectsMap.set(e,n),this}getNative(e){return this.natives.get(e)}nativeEffects(e){let t=this.nativeEffectsMap.get(e);return t===void 0?B.STATE|B.SYSTEM|B.EXTERNAL:t}defineExpr(e){return this.exprClasses.set(e.KIND,e),this._version++,this}exprClass(e){return this.exprClasses.get(e)}typeClasses(){return Array.from(this.classes.values())}typeClass(e){return this.classes.get(e)}namedTypeList(){return Array.from(this.namedTypes.values())}exprClassList(){return Array.from(this.exprClasses.values())}typeNameCandidates(){return[...this.typeClasses().map(e=>e.NAME),...this.namedTypeList().map(e=>e.name)]}parseExpr(e,t=this){if(e==null)return;if(e instanceof $m)return e;if(typeof e!=`object`||!(`kind`in e))throw Error(`registry.parseExpr: expected ExprDef with kind, got ${typeof e}`);let n=e,r=this.exprClasses.get(n.kind);if(!r)throw Error(`registry.parseExpr: unknown expr kind '${n.kind}'`);return r.from(n,t)}toCode(e,t){return(e instanceof $m?e:this.parseExpr(e)).toCode(this,t)}toGinCode(e,t){return(e instanceof $m?e:this.parseExpr(e)).toGinCode(this,t,[])}toJSONCode(e,t=2){return(e instanceof $m?e:this.parseExpr(e)).toJSONCode([],t)}validate(e){let t=new Mm,n=new Set,r=(r,i)=>{if(n.has(r))return;n.add(r);let a=i.validate(e);for(let e of a.list)t.list.push({...e,path:[r,...e.path]})};for(let[e,t]of this.namedTypes)r(e,t);for(let e of this.augments.keys()){let t=this.lookup(e);t&&r(e,t)}return t}parseValue(e,t,n=this){if(e instanceof W)return this.checkSlot(e,t,n);if(t?.parsesExprValue(n)&&this.exprShaped(e))return t.parse(e,n);if(e&&typeof e==`object`&&`type`in e&&`value`in e&&this.typeDefShaped(e.type)){let r=e.kind;if(typeof r==`string`&&this.exprClass(r))throw TypeError(`registry.parseValue: this node is an EXPRESSION (kind:'${r}'), not a value envelope \u2014 an Expr only evaluates inside a program (\`Engine.run\`/\`Engine.evaluate\`); a bare \`parse\` takes data. Drop the \`kind\` to mean the literal ${JSON.stringify(e.type)} value.`+(t?` (This slot is declared \`${t.toCode()}\`.)`:``));return this.checkSlot(this.parse(e.type,n).parse(e.value,n),t,n)}if(!t)throw TypeError(`registry.parseValue: expected Value or JSONValue, got ${typeof e}`);return t.parse(e,n)}typeDefShaped(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&typeof e.name==`string`}exprShaped(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e.kind;return typeof t==`string`&&!!this.exprClass(t)}checkSlot(e,t,n){if(!t||Sh(t,e.type,n))return e;throw TypeError(`registry.parseValue: this slot is declared \`${t.toCode()}\` but the value carries \`${e.type.toCode()}\``)}parse(e,t=this){if(!e||typeof e!=`object`)throw Error(`registry.parse: expected object, got ${typeof e}`);if(e instanceof U)throw Error(`registry.parse: expected a serialized TypeDef, got a LIVE ${e.constructor.name} instance (\`${e.name}\`) \u2014 pass \`type.toJSON()\`, or use the type as it stands.`);let n=e;if(!am(n.name))throw Error(`registry.parse: type 'name' must match ${im}, got ${JSON.stringify(n.name)}`);if(n.extends!==void 0&&!am(n.extends))throw Error(`registry.parse: type 'extends' must match ${im}, got ${JSON.stringify(n.extends)}`);if(n.satisfies){for(let e of n.satisfies)if(!am(e))throw Error(`registry.parse: 'satisfies' entries must match ${im}, got ${JSON.stringify(e)}`)}let r=n.extends??n.name;Up(n,this.namedTypes.has(r)?void 0:this.classes.get(r),n.extends===void 0,this);let i=this.parseInner(n,t);if(n.satisfies&&n.satisfies.length>0)for(let e of n.satisfies){let r=t.lookup(e)??this.lookup(e);if(!r)throw Error(`registry.parse: satisfies references unknown interface '${e}'${Pp(e,this.typeNameCandidates())}`);if(!r.compatible(i))throw Error(`registry.parse: type '${n.name}' claims to satisfy '${e}' but does not structurally match`)}return i}isUseSiteDef(e){return e.generic===void 0&&e.options===void 0?!1:[`extends`,`satisfies`,`init`,`props`,`get`,`call`,`constraint`].every(t=>e[t]===void 0)}boundAboveRegistry(e,t){for(let n=t;n&&n!==this;n=n.parent)if(n.localLookup(e)!==void 0)return!0;return!1}parseGenericArgs(e,t){return Object.fromEntries(Object.entries(e.generic??{}).map(([e,n])=>[e,this.parse(n,t)]))}useSiteAlias(e,t){return new Sg(t,e.options===void 0?{name:e.name}:{name:e.name,options:e.options},this.parseGenericArgs(e,t))}applyUse(e,t,n,r){let i=e;return Object.keys(t).length>0&&i instanceof gg&&(i=i.specialize(t)),n!==void 0&&Object.keys(n).length>0&&!pg(i.narrow(n),i.options)&&(i=new gg(this,i,{name:i.name,docs:i.docs,options:n,generic:i instanceof gg?i.local.generic:void 0,useSite:!0},i instanceof gg&&i.bindings?i.scope:void 0,r)),i}nearBuiltin(e){return e[0]===e[0]?.toLowerCase()&&Pp(e,this.typeClasses().map(e=>e.NAME))!==``}isBareNameDef(e){for(let t of[`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`])if(e[t]!==void 0)return!1;return!0}parseInner(e,t){if(e.extends){let n=t.lookup(e.extends)??this.lookup(e.extends);if(!n)throw Error(`registry.parse: extends references unknown type '${e.extends}'${Pp(e.extends,this.typeNameCandidates())}`);let r=this.classes.get(e.extends),i=e.generic!==void 0&&Object.keys(e.generic).length>0,a=r&&!i?Dv.filter(t=>e[t]!==void 0&&(r.consumes??[]).includes(t)):[];if(r&&a.length>0){let n={name:e.extends,...a.includes(`props`)?{props:e.props}:{},...a.includes(`get`)?{get:e.get}:{},...a.includes(`call`)?{call:e.call}:{},...a.includes(`init`)?{init:e.init}:{}},i=r.from(n,t),o={...e};delete o.extends;for(let e of a)delete o[e];return new gg(this,i,this.buildLocal(o,t))}return new gg(this,n,this.buildLocal(e,t))}if(this.isBareNameDef(e)){let n=t;for(;n&&n!==this;){if(n.localLookup(e.name)!==void 0)return new Sg(t,{name:e.name});n=n.parent}if(this.namedTypes.has(e.name))return this.namedTypes.get(e.name);let r=this.classes.get(e.name);return r?r.from(e,t):new Sg(t,{name:e.name})}let n=this.isUseSiteDef(e);if(n&&this.boundAboveRegistry(e.name,t))return this.useSiteAlias(e,t);if(this.namedTypes.has(e.name)){let r=this.namedTypes.get(e.name);return n?this.applyUse(r,this.parseGenericArgs(e,t),e.options,t):e.generic&&r instanceof gg?r.specialize(this.parseGenericArgs(e,t)):r}let r=this.classes.get(e.name);if(!r){if(n&&!this.nearBuiltin(e.name))return this.useSiteAlias(e,t);throw Error(`registry.parse: unknown type '${e.name}'${Pp(e.name,this.typeNameCandidates())}`)}let i=new Set(r.consumes??[]),a=Dv.filter(t=>e[t]!==void 0&&!i.has(t));if(a.length===0)return r.from(e,t);let o={...e};for(let e of a)delete o[e];let s=r.from(o,t),c={name:e.name,docs:e.docs,props:a.includes(`props`)&&e.props?jh.fromMap(e.props,t):void 0,get:a.includes(`get`)&&e.get?Mh.from(e.get,t):void 0,call:a.includes(`call`)&&e.call?Nh.from(e.call,t):void 0,init:a.includes(`init`)&&e.init?Ph.from(e.init,t):void 0};return new gg(this,s,c)}getTypesFor(e){let t=this.lookup(e);if(!t)return[];let n=[];for(let e of this.namedTypes.values())if(e!==t)try{t.compatible(e)&&n.push(e)}catch{}for(let[r,i]of this.classes){if(r===e)continue;let a;try{a=i.from({name:r},this)}catch{continue}try{t.compatible(a)&&n.push(a)}catch{}}return n}buildLocal(e,t){let n=e.generic?Object.fromEntries(Object.entries(e.generic).map(([e,n])=>[e,this.parse(n,t)])):void 0;return{name:e.name,docs:e.docs,options:e.options,generic:n,props:e.props?jh.fromMap(e.props,t):void 0,get:e.get?Mh.from(e.get,t):void 0,call:e.call?Nh.from(e.call,t):void 0,init:e.init?Ph.from(e.init,t):void 0,constraint:e.constraint?this.parseExpr(e.constraint,t):void 0}}any(){return new _g(this,{})}void(){return new Yg(this,{})}null(){return new zg(this,{})}bool(e){return new Cg(this,e??{})}num(e){return new Vg(this,e??{})}text(e){return new Wg(this,e??{})}list(e,t){return new Ng(this,e,t??{})}map(e,t){return new Lg(this,e,t)}tuple(e){return new qg(this,[...e])}obj(e){return new vg(this,e)}field(e,t){return{type:e,docs:t?.docs,default:t?.default===void 0?void 0:this.parseExpr(t.default)}}optional(e){return new Hg(this,e)}nullable(e){return new Bg(this,e)}not(e){return new Rg(this,e)}or(e){return new Ug(this,[...e])}and(e){return new bg(this,[...e])}enum(e,t){return kv(e)?new Dg(this,this.text(),{values:Object.fromEntries(e.map(e=>[e,e]))}):new Dg(this,t??this.text(),{values:e})}literal(e,t){if(e instanceof U)return new Mg(this,e,t);let n=this.primitiveOf(e);return new Mg(this,n,e)}primitiveOf(e){switch(typeof e){case`string`:return this.text();case`number`:return this.num();case`boolean`:return this.bool()}}date(e){return new Tg(this,e??{})}timestamp(e){return new Gg(this,e??{})}duration(){return new Eg(this,{})}color(e){return new wg(this,e??{})}fn(e){return new Ag(this,{args:e.args,returns:e.returns,throws:e.throws,get:e.call},e.generic??{})}iface(e){return new jg(this,{props:e.props?jh.fromMap(e.props,this):{},get:e.get?Mh.from(e.get,this):void 0,call:e.call?Nh.from(e.call,this):void 0})}alias(e){return new Sg(this,{name:e})}typ(e){return new Jg(this,e)}compatible(e){let t=[],n=new Set,r=e=>{n.has(e.name)||(n.add(e.name),t.push(e))};for(let t of this.typeClasses()){let n;try{n=t.from({name:t.NAME},this)}catch{continue}if(!(n.isUniversal()&&e.name!==t.NAME))try{n.compatible(e)&&r(n)}catch{continue}}for(let t of this.namedTypeList())try{t.compatible(e)&&r(t)}catch{continue}return t}like(e){let t=this.compatible(e).map(t=>t.like(e));return t.length===0?this.null():t.length===1?t[0]:this.or(t)}extend(e,t){let n=typeof e==`string`?this.lookup(e)??(()=>{throw Error(`extend: unknown base '${e}'`)})():e;return new gg(this,n,t)}nativeExpr(e){return this.parseExpr({kind:`native`,id:e})}prop(e,t,n){return Av(new jh({type:e,get:this.nativeExpr(t),docs:n}))}method(e,t,n,r){return Av(new jh({type:this.fn({args:this.obj(e),returns:t,generic:r?.generic}),get:this.nativeExpr(n),docs:r?.docs}))}};function kv(e){return Array.isArray(e)}function Av(e){if(!jv(e))throw Error(`registry: a computed prop must carry a get expression`);return e}function jv(e){return e.get!==void 0}var Mv=[_g,Yg,zg,Cg,Vg,Wg,Ng,Lg,qg,vg,Hg,Bg,Rg,Ug,bg,Dg,Mg,Ag,jg,Jg,Tg,Gg,Eg,wg],Nv=[W_,cv,lv,uv,fv,gv,_v,vv,bv,wv,pv,Ev];function Pv(){let e=new Ov;for(let t of Mv)e.define(t);for(let t of Nv)e.defineExpr(t);return U_(e),e}var Fv={$Exit:{code:"/** gin `flow: exit` — unwinds to the outermost exported function, whose result becomes `value`. */\nclass $Exit {\n constructor(readonly value: unknown) {}\n}"},$Throw:{code:"/** gin `flow: throw` — a thrown gin value; a call step's `catch` handler receives `error`. */\nclass $Throw extends Error {\n constructor(readonly error: unknown) { super(typeof error === 'string' ? error : 'gin throw'); }\n}"},$str:{code:"/** Template placeholder text — `null`/`undefined` read as the empty string. */\nfunction $str(v: unknown): string {\n return v === undefined || v === null ? '' : String(v);\n}"},$template:{code:`/** A template whose text is only known at run time: \`{name}\` reads \`params.name\`. */
120
+ }`:"${"+e+`}`}return"${"+t+`}`}).replace(/`/g,"\\`")}\``}`}toJSON(){return this.withCommentOn({kind:`template`,template:this.template.toJSON(),...this.params?{params:this.params.toJSON()}:{}})}toJSONCode(e=[],t=2,n=0){let r=this.template.toJSONCode([...e,`template`],t,n+1),i=this.params?this.params.toJSONCode([...e,`params`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`template`)},{key:`template`,value:r},{key:`params`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.template.clone(),this.params?.clone()).withComment(this.comment)}forEachChild(e){e(this.template,`inherit`),this.params&&e(this.params,`inherit`)}effects(){return this.template.effects()|(this.params?.effects()??B.NONE)}complexity(){return 1+this.template.complexity()+(this.params?.complexity()??0)}};function Dv(e,t){if(!(e instanceof K_))return;let n=e.value;if(!n||typeof n!=`object`||Array.isArray(n))return;let r={};for(let[e,i]of Object.entries(n))if(typeof i==`string`)r[e]=JSON.stringify(i);else if(typeof i==`number`||typeof i==`boolean`)r[e]=String(i);else if(i===null)r[e]=`null`;else if(i&&typeof i==`object`&&`kind`in i&&typeof i.kind==`string`&&t.exprClass(i.kind))try{r[e]=t.parseExpr(i).toCode(t,{expectsValue:!0})}catch{return}else return;return r}var Ov=class e extends th{constructor(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){super(),this.id=e,this.type=t,this.resolvedEffects=n}id;type;resolvedEffects;static KIND=`native`;kind=e.KIND;static from(t,n){return new e(t.id,t.type?n.registry.parse(t.type,n):void 0,n.registry.nativeEffects(t.id)).withComment(t.comment)}async evaluate(e,t){let n=e.registry.getNative(this.id);if(!n)throw Error(`native: no impl registered for '${this.id}'`);let r=await n(t,e.registry);return r instanceof W?r:G(this.type??e.registry.any(),r)}typeOf(e,t){return this.type??e.registry.any()}validateWalk(e,t,n,r){return e.registry.getNative(this.id)||n.warn(`native.unknown`,`native impl '${this.id}' is not registered`),this.type??e.registry.any()}toCode(e,t={}){return this.commentPrefix(t)+`/* native: ${this.id} */`}toJSON(){let e={kind:`native`,id:this.id};return this.type&&(e.type=this.type.toJSON()),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.type?this.type.toJSONCode([...e,`type`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`native`)},{key:`id`,value:V.jsonString(this.id)},{key:`type`,value:r},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.id,this.type?.clone(),this.resolvedEffects).withComment(this.comment)}effects(){return this.resolvedEffects}complexity(){return 1}},kv=[`props`,`get`,`call`,`init`],Av=class{classes=new Map;namedTypes=new Map;natives=new Map;nativeEffectsMap=new Map;exprClasses=new Map;augments=new Map;_version=0;get version(){return this._version}parent=void 0;get registry(){return this}define(e){return this.classes.set(e.NAME,e),this._version++,this}register(e){return this.namedTypes.set(e.name,e),this._version++,this}scope(e){return new eh(this,{...e})}augment(e,t){this._version++;let n={props:t.props?Nh.fromMap(t.props,this):void 0,get:t.get?Ph.from(t.get,this):void 0,call:t.call?Fh.from(t.call,this):void 0,init:t.init?Ih.from(t.init,this):void 0},r=this.augments.get(e);return r?(this.augments.set(e,{props:n.props?{...r.props??{},...n.props}:r.props,get:r.get??n.get,call:r.call??n.call,init:r.init??n.init}),this):(this.augments.set(e,{props:n.props?{...n.props}:void 0,get:n.get,call:n.call,init:n.init}),this)}augmentation(e){return this.augments.get(e)}lookup(e){if(this.namedTypes.has(e))return this.namedTypes.get(e);let t=this.classes.get(e);if(t)return t.from({name:e},this)}localLookup(e){}setNative(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){return this.natives.set(e,t),this.nativeEffectsMap.set(e,n),this}getNative(e){return this.natives.get(e)}nativeEffects(e){let t=this.nativeEffectsMap.get(e);return t===void 0?B.STATE|B.SYSTEM|B.EXTERNAL:t}defineExpr(e){return this.exprClasses.set(e.KIND,e),this._version++,this}exprClass(e){return this.exprClasses.get(e)}typeClasses(){return Array.from(this.classes.values())}typeClass(e){return this.classes.get(e)}namedTypeList(){return Array.from(this.namedTypes.values())}exprClassList(){return Array.from(this.exprClasses.values())}typeNameCandidates(){return[...this.typeClasses().map(e=>e.NAME),...this.namedTypeList().map(e=>e.name)]}parseExpr(e,t=this){if(e==null)return;if(e instanceof th)return e;if(typeof e!=`object`||!(`kind`in e))throw Error(`registry.parseExpr: expected ExprDef with kind, got ${typeof e}`);let n=e,r=this.exprClasses.get(n.kind);if(!r)throw Error(`registry.parseExpr: unknown expr kind '${n.kind}'`);return r.from(n,t)}toCode(e,t){return(e instanceof th?e:this.parseExpr(e)).toCode(this,t)}toGinCode(e,t){return(e instanceof th?e:this.parseExpr(e)).toGinCode(this,t,[])}toJSONCode(e,t=2){return(e instanceof th?e:this.parseExpr(e)).toJSONCode([],t)}validate(e){let t=new Pm,n=new Set,r=(r,i)=>{if(n.has(r))return;n.add(r);let a=i.validate(e);for(let e of a.list)t.list.push({...e,path:[r,...e.path]})};for(let[e,t]of this.namedTypes)r(e,t);for(let e of this.augments.keys()){let t=this.lookup(e);t&&r(e,t)}return t}parseValue(e,t,n=this){if(e instanceof W)return this.checkSlot(e,t,n);if(t?.parsesExprValue(n)&&this.exprShaped(e))return t.parse(e,n);if(e&&typeof e==`object`&&`type`in e&&`value`in e&&this.typeDefShaped(e.type)){let r=e.kind;if(typeof r==`string`&&this.exprClass(r))throw TypeError(`registry.parseValue: this node is an EXPRESSION (kind:'${r}'), not a value envelope \u2014 an Expr only evaluates inside a program (\`Engine.run\`/\`Engine.evaluate\`); a bare \`parse\` takes data. Drop the \`kind\` to mean the literal ${JSON.stringify(e.type)} value.`+(t?` (This slot is declared \`${t.toCode()}\`.)`:``));return this.checkSlot(this.parse(e.type,n).parse(e.value,n),t,n)}if(!t)throw TypeError(`registry.parseValue: expected Value or JSONValue, got ${typeof e}`);return t.parse(e,n)}typeDefShaped(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&typeof e.name==`string`}exprShaped(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e.kind;return typeof t==`string`&&!!this.exprClass(t)}checkSlot(e,t,n){if(!t||wh(t,e.type,n))return e;throw TypeError(`registry.parseValue: this slot is declared \`${t.toCode()}\` but the value carries \`${e.type.toCode()}\``)}parse(e,t=this){if(!e||typeof e!=`object`)throw Error(`registry.parse: expected object, got ${typeof e}`);if(e instanceof U)throw Error(`registry.parse: expected a serialized TypeDef, got a LIVE ${e.constructor.name} instance (\`${e.name}\`) \u2014 pass \`type.toJSON()\`, or use the type as it stands.`);let n=e;if(!sm(n.name))throw Error(`registry.parse: type 'name' must match ${om}, got ${JSON.stringify(n.name)}`);if(n.extends!==void 0&&!sm(n.extends))throw Error(`registry.parse: type 'extends' must match ${om}, got ${JSON.stringify(n.extends)}`);if(n.satisfies){for(let e of n.satisfies)if(!sm(e))throw Error(`registry.parse: 'satisfies' entries must match ${om}, got ${JSON.stringify(e)}`)}let r=n.extends??n.name;Gp(n,this.namedTypes.has(r)?void 0:this.classes.get(r),n.extends===void 0,this);let i=this.parseInner(n,t);if(n.satisfies&&n.satisfies.length>0)for(let e of n.satisfies){let r=t.lookup(e)??this.lookup(e);if(!r)throw Error(`registry.parse: satisfies references unknown interface '${e}'${Ip(e,this.typeNameCandidates())}`);if(!r.compatible(i))throw Error(`registry.parse: type '${n.name}' claims to satisfy '${e}' but does not structurally match`)}return i}isUseSiteDef(e){return e.generic===void 0&&e.options===void 0?!1:[`extends`,`satisfies`,`init`,`props`,`get`,`call`,`constraint`].every(t=>e[t]===void 0)}boundAboveRegistry(e,t){for(let n=t;n&&n!==this;n=n.parent)if(n.localLookup(e)!==void 0)return!0;return!1}parseGenericArgs(e,t){return Object.fromEntries(Object.entries(e.generic??{}).map(([e,n])=>[e,this.parse(n,t)]))}useSiteAlias(e,t){return new wg(t,e.options===void 0?{name:e.name}:{name:e.name,options:e.options},this.parseGenericArgs(e,t))}applyUse(e,t,n,r){let i=e;return Object.keys(t).length>0&&i instanceof vg&&(i=i.specialize(t)),n!==void 0&&Object.keys(n).length>0&&!hg(i.narrow(n),i.options)&&(i=new vg(this,i,{name:i.name,docs:i.docs,options:n,generic:i instanceof vg?i.local.generic:void 0,useSite:!0},i instanceof vg&&i.bindings?i.scope:void 0,r)),i}nearBuiltin(e){return e[0]===e[0]?.toLowerCase()&&Ip(e,this.typeClasses().map(e=>e.NAME))!==``}isBareNameDef(e){for(let t of[`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`])if(e[t]!==void 0)return!1;return!0}parseInner(e,t){if(e.extends){let n=t.lookup(e.extends)??this.lookup(e.extends);if(!n)throw Error(`registry.parse: extends references unknown type '${e.extends}'${Ip(e.extends,this.typeNameCandidates())}`);let r=this.classes.get(e.extends),i=e.generic!==void 0&&Object.keys(e.generic).length>0,a=r&&!i?kv.filter(t=>e[t]!==void 0&&(r.consumes??[]).includes(t)):[];if(r&&a.length>0){let n={name:e.extends,...a.includes(`props`)?{props:e.props}:{},...a.includes(`get`)?{get:e.get}:{},...a.includes(`call`)?{call:e.call}:{},...a.includes(`init`)?{init:e.init}:{}},i=r.from(n,t),o={...e};delete o.extends;for(let e of a)delete o[e];return new vg(this,i,this.buildLocal(o,t))}return new vg(this,n,this.buildLocal(e,t))}if(this.isBareNameDef(e)){let n=t;for(;n&&n!==this;){if(n.localLookup(e.name)!==void 0)return new wg(t,{name:e.name});n=n.parent}if(this.namedTypes.has(e.name))return this.namedTypes.get(e.name);let r=this.classes.get(e.name);return r?r.from(e,t):new wg(t,{name:e.name})}let n=this.isUseSiteDef(e);if(n&&this.boundAboveRegistry(e.name,t))return this.useSiteAlias(e,t);if(this.namedTypes.has(e.name)){let r=this.namedTypes.get(e.name);return n?this.applyUse(r,this.parseGenericArgs(e,t),e.options,t):e.generic&&r instanceof vg?r.specialize(this.parseGenericArgs(e,t)):r}let r=this.classes.get(e.name);if(!r){if(n&&!this.nearBuiltin(e.name))return this.useSiteAlias(e,t);throw Error(`registry.parse: unknown type '${e.name}'${Ip(e.name,this.typeNameCandidates())}`)}let i=new Set(r.consumes??[]),a=kv.filter(t=>e[t]!==void 0&&!i.has(t));if(a.length===0)return r.from(e,t);let o={...e};for(let e of a)delete o[e];let s=r.from(o,t),c={name:e.name,docs:e.docs,props:a.includes(`props`)&&e.props?Nh.fromMap(e.props,t):void 0,get:a.includes(`get`)&&e.get?Ph.from(e.get,t):void 0,call:a.includes(`call`)&&e.call?Fh.from(e.call,t):void 0,init:a.includes(`init`)&&e.init?Ih.from(e.init,t):void 0};return new vg(this,s,c)}getTypesFor(e){let t=this.lookup(e);if(!t)return[];let n=[];for(let e of this.namedTypes.values())if(e!==t)try{t.compatible(e)&&n.push(e)}catch{}for(let[r,i]of this.classes){if(r===e)continue;let a;try{a=i.from({name:r},this)}catch{continue}try{t.compatible(a)&&n.push(a)}catch{}}return n}buildLocal(e,t){let n=e.generic?Object.fromEntries(Object.entries(e.generic).map(([e,n])=>[e,this.parse(n,t)])):void 0;return{name:e.name,docs:e.docs,options:e.options,generic:n,props:e.props?Nh.fromMap(e.props,t):void 0,get:e.get?Ph.from(e.get,t):void 0,call:e.call?Fh.from(e.call,t):void 0,init:e.init?Ih.from(e.init,t):void 0,constraint:e.constraint?this.parseExpr(e.constraint,t):void 0}}any(){return new yg(this,{})}void(){return new Zg(this,{})}null(){return new Vg(this,{})}bool(e){return new Tg(this,e??{})}num(e){return new Ug(this,e??{})}text(e){return new Kg(this,e??{})}list(e,t){return new Fg(this,e,t??{})}map(e,t){return new zg(this,e,t)}tuple(e){return new Yg(this,[...e])}obj(e){return new bg(this,e)}field(e,t){return{type:e,docs:t?.docs,default:t?.default===void 0?void 0:this.parseExpr(t.default)}}optional(e){return new Wg(this,e)}nullable(e){return new Hg(this,e)}not(e){return new Bg(this,e)}or(e){return new Gg(this,[...e])}and(e){return new Sg(this,[...e])}enum(e,t){return jv(e)?new kg(this,this.text(),{values:Object.fromEntries(e.map(e=>[e,e]))}):new kg(this,t??this.text(),{values:e})}literal(e,t){if(e instanceof U)return new Pg(this,e,t);let n=this.primitiveOf(e);return new Pg(this,n,e)}primitiveOf(e){switch(typeof e){case`string`:return this.text();case`number`:return this.num();case`boolean`:return this.bool()}}date(e){return new Dg(this,e??{})}timestamp(e){return new qg(this,e??{})}duration(){return new Og(this,{})}color(e){return new Eg(this,e??{})}fn(e){return new Mg(this,{args:e.args,returns:e.returns,throws:e.throws,get:e.call},e.generic??{})}iface(e){return new Ng(this,{props:e.props?Nh.fromMap(e.props,this):{},get:e.get?Ph.from(e.get,this):void 0,call:e.call?Fh.from(e.call,this):void 0})}alias(e){return new wg(this,{name:e})}typ(e){return new Xg(this,e)}compatible(e){let t=[],n=new Set,r=e=>{n.has(e.name)||(n.add(e.name),t.push(e))};for(let t of this.typeClasses()){let n;try{n=t.from({name:t.NAME},this)}catch{continue}if(!(n.isUniversal()&&e.name!==t.NAME))try{n.compatible(e)&&r(n)}catch{continue}}for(let t of this.namedTypeList())try{t.compatible(e)&&r(t)}catch{continue}return t}like(e){let t=this.compatible(e).map(t=>t.like(e));return t.length===0?this.null():t.length===1?t[0]:this.or(t)}extend(e,t){let n=typeof e==`string`?this.lookup(e)??(()=>{throw Error(`extend: unknown base '${e}'`)})():e;return new vg(this,n,t)}nativeExpr(e){return this.parseExpr({kind:`native`,id:e})}prop(e,t,n){return Mv(new Nh({type:e,get:this.nativeExpr(t),docs:n}))}method(e,t,n,r){return Mv(new Nh({type:this.fn({args:this.obj(e),returns:t,generic:r?.generic}),get:this.nativeExpr(n),docs:r?.docs}))}};function jv(e){return Array.isArray(e)}function Mv(e){if(!Nv(e))throw Error(`registry: a computed prop must carry a get expression`);return e}function Nv(e){return e.get!==void 0}var Pv=[yg,Zg,Vg,Tg,Ug,Kg,Fg,zg,Yg,bg,Wg,Hg,Bg,Gg,Sg,kg,Pg,Mg,Ng,Xg,Dg,qg,Og,Eg],Fv=[K_,uv,dv,fv,mv,vv,yv,bv,Sv,Ev,hv,Ov];function Iv(){let e=new Av;for(let t of Pv)e.define(t);for(let t of Fv)e.defineExpr(t);return G_(e),e}var Lv={$Exit:{code:"/** gin `flow: exit` — unwinds to the outermost exported function, whose result becomes `value`. */\nclass $Exit {\n constructor(readonly value: unknown) {}\n}"},$Throw:{code:"/** gin `flow: throw` — a thrown gin value; a call step's `catch` handler receives `error`. */\nclass $Throw extends Error {\n constructor(readonly error: unknown) { super(typeof error === 'string' ? error : 'gin throw'); }\n}"},$str:{code:"/** Template placeholder text — `null`/`undefined` read as the empty string. */\nfunction $str(v: unknown): string {\n return v === undefined || v === null ? '' : String(v);\n}"},$template:{code:`/** A template whose text is only known at run time: \`{name}\` reads \`params.name\`. */
121
121
  function $template(tmpl: string, params: Record<string, unknown> | undefined): string {
122
122
  return tmpl.replace(/\\{(\\w+)\\}/g, (_, name: string) =>
123
123
  params && Object.prototype.hasOwnProperty.call(params, name) ? $str(params[name]) : '');
@@ -366,37 +366,37 @@ const $color = {
366
366
  const { h, s, l } = $color.hsl(c);
367
367
  return \`hsl(\${Math.round(h)},\${Math.round(s * 100)}%,\${Math.round(l * 100)}%)\`;
368
368
  },
369
- };`}},Iv=new Set(`any.unknown.never.object.string.number.boolean.symbol.bigint.undefined.null.void.true.false.this.keyof.typeof.infer.is.asserts.readonly.unique.type.interface.enum.class.function.let.const.var.new.in.of.as.extends.implements.namespace.module.declare.abstract.async.await.yield.import.export.default.return.if.else.for.while.do.switch.case.break.continue.try.catch.finally.throw.delete.instanceof.super.with.debugger.package.private.protected.public.static.global.require.Array.ArrayBuffer.ArrayLike.AsyncGenerator.AsyncIterable.AsyncIterator.Atomics.Awaited.BigInt.BigInt64Array.BigUint64Array.Boolean.Capitalize.ConstructorParameters.DataView.Date.Error.EvalError.Exclude.Extract.Float32Array.Float64Array.Function.Generator.Infinity.InstanceType.Int16Array.Int32Array.Int8Array.Intl.Iterable.IterableIterator.Iterator.JSON.Lowercase.Map.Math.NaN.NonNullable.Number.Object.Omit.OmitThisParameter.Parameters.Partial.Pick.Promise.PromiseLike.PropertyKey.Proxy.RangeError.Readonly.ReadonlyArray.ReadonlyMap.ReadonlySet.Record.ReferenceError.Reflect.RegExp.Required.ReturnType.Set.SharedArrayBuffer.String.Symbol.SyntaxError.TemplateStringsArray.ThisParameterType.ThisType.TypeError.URIError.Uint16Array.Uint32Array.Uint8Array.Uint8ClampedArray.Uncapitalize.Uppercase.WeakMap.WeakRef.WeakSet.globalThis.console.eval.arguments`.split(`.`));function Lv(e){return/^[A-Za-z_][\w$]*$/.test(e)&&!Iv.has(e)&&!(e in Fv)}function Rv(e){let t=e.replace(/[^\w]/g,`_`);return/^[A-Za-z_]/.test(t)||(t=`_`+t),Lv(t)?t:`${t}_`}var zv=class{taken=new Set;types=new Map;data=new Map;constructor(e,t){let n=e.namedTypeList().filter(e=>e instanceof gg&&!e.local.useSite).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of n)Lv(e.name)&&!this.taken.has(e.name)&&this.claim(this.types,e.name,e.name);for(let e of n)this.types.has(e.name)||this.type(e.name);for(let e of n){let n=!1;try{n=t(e)}catch{n=!1}n&&this.dataName(e.name)}}claim(e,t,n){let r=n;for(let e=2;this.taken.has(r);e++)r=`${n.replace(/_$/,``)}_${e}`;return this.taken.add(r),e.set(t,r),r}type(e){return this.types.get(e)??this.claim(this.types,e,Rv(e))}dataName(e){return this.data.get(e)??this.claim(this.data,e,`${this.type(e)}Data`)}fresh(e){return this.claim(new Map,e,Rv(e))}},Bv=(e,t)=>e===void 0||e===`undefined`||e===`null`?t:/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false)$/.test(e)?e:`(${e} ?? ${t})`,J=(e,t)=>e.arg(t)??`undefined`,Vv=e=>t=>`(${t.self()} ${e} ${J(t,`other`)})`,Hv=(e,...t)=>n=>`${e}(${[n.self(),...t.map(e=>J(n,e))].join(`, `)})`,Uv=(e,...t)=>n=>`${n.self()}.${e}(${t.map(e=>J(n,e)).join(`, `)})`,Wv=e=>t=>`${t.self()}.${e}`,Gv=e=>t=>`void ${e(t)}`,Kv=(e,...t)=>{let n=t.map(t=>e.arg(t));for(;n.length>0&&n[n.length-1]===void 0;)n.pop();return n.map(e=>e??`undefined`).join(`, `)},qv=(e,...t)=>n=>{let r=n.fn(`fn`),i=t.map(e=>J(n,e));return r?r.sync?`${n.helper(`$`+e)}(${[n.self(),r.code,...i].join(`, `)})`:n.aw(`${n.helper(`$`+e+`Async`)}(${[n.self(),r.code,...i].join(`, `)})`):`${n.helper(`$`+e)}(${[n.self(),`undefined as any`,...i].join(`, `)})`},Jv=e=>t=>{let n=t.once(),r=t.fn(`fn`);if(!r)return n;let i=`(${r.code})({ value: ${n} })`;return`(${n} === ${e} ? ${e} : ${r.sync?i:t.aw(i)})`},Yv={"type.toAny":e=>e.self(),"any.typeOf":e=>{let t=e.staticTypeName();return t===void 0?`${e.helper(`$typeOf`)}(${e.self()})`:(e.discard(),JSON.stringify(t))},"any.is":e=>{let t=e.guard();return t?`${t}(${e.self()})`:(e.discard(),`true`)},"any.as":e=>{let t=e.guard();if(!t)return e.self();let n=e.once();return`(${t}(${n}) ? ${n} : undefined)`},"any.toText":e=>`String(${e.self()})`,"any.toBool":e=>`Boolean(${e.self()})`,"any.eq":Vv(`===`),"any.neq":Vv(`!==`),"void.toText":e=>(e.discard(),`"void"`),"void.toBool":e=>(e.discard(),`false`),"null.toText":e=>(e.discard(),`"null"`),"null.toBool":e=>(e.discard(),`false`),"not.typeOf":e=>`${e.helper(`$typeOf`)}(${e.self()})`,"not.toText":e=>`String(${e.self()})`,"bool.eq":Vv(`===`),"bool.neq":Vv(`!==`),"bool.and":Vv(`&&`),"bool.or":Vv(`||`),"bool.xor":Vv(`!==`),"bool.not":e=>`!${e.self()}`,"bool.toText":e=>{let t=e.arg(`trueText`),n=e.arg(`falseText`);return t===void 0&&n===void 0?`String(${e.self()})`:`(${e.self()} ? ${Bv(t,`"true"`)} : ${Bv(n,`"false"`)})`},"bool.toNum":e=>{let t=e.arg(`trueValue`),n=e.arg(`falseValue`);return`(${e.self()} ? ${Bv(t,`1`)} : ${Bv(n,`0`)})`},"num.eq":e=>e.arg(`epsilon`)===void 0?`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.neq":e=>e.arg(`epsilon`)===void 0?`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.lt":Vv(`<`),"num.lte":Vv(`<=`),"num.gt":Vv(`>`),"num.gte":Vv(`>=`),"num.add":Vv(`+`),"num.sub":Vv(`-`),"num.mul":Vv(`*`),"num.div":Vv(`/`),"num.mod":Vv(`%`),"num.pow":Vv(`**`),"num.abs":Hv(`Math.abs`),"num.neg":e=>`(-${e.self()})`,"num.sign":Hv(`Math.sign`),"num.sqrt":Hv(`Math.sqrt`),"num.min":Hv(`Math.min`,`other`),"num.max":Hv(`Math.max`,`other`),"num.clamp":e=>`Math.min(Math.max(${e.self()}, ${J(e,`min`)}), ${J(e,`max`)})`,"num.floor":Hv(`Math.floor`),"num.ceil":Hv(`Math.ceil`),"num.round":Hv(`Math.round`),"num.isZero":e=>`(Math.abs(${e.self()}) <= 0)`,"num.isPositive":e=>`(${e.self()} > 0)`,"num.isNegative":e=>`(${e.self()} < 0)`,"num.isInteger":Hv(`Number.isInteger`),"num.isEven":e=>`(${e.self()} % 2 === 0)`,"num.isOdd":e=>`(Math.abs(${e.self()}) % 2 === 1)`,"num.toText":e=>e.arg(`precision`)===void 0?`String(${e.self()})`:`${e.helper(`$numText`)}(${e.self()}, ${e.arg(`precision`)})`,"num.toBool":e=>`(${e.self()} !== 0)`,"text.length":Wv(`length`),"text.eq":Vv(`===`),"text.neq":Vv(`!==`),"text.contains":Uv(`includes`,`search`),"text.startsWith":Uv(`startsWith`,`prefix`),"text.endsWith":Uv(`endsWith`,`suffix`),"text.trim":Uv(`trim`),"text.trimStart":Uv(`trimStart`),"text.trimEnd":Uv(`trimEnd`),"text.upper":Uv(`toUpperCase`),"text.lower":Uv(`toLowerCase`),"text.slice":e=>`${e.self()}.slice(${Kv(e,`start`,`end`)})`,"text.replace":e=>`${e.self()}.split(${J(e,`search`)}).join(${J(e,`replacement`)})`,"text.split":Uv(`split`,`separator`),"text.concat":Vv(`+`),"text.repeat":Uv(`repeat`,`count`),"text.indexOf":e=>`${e.self()}.indexOf(${Kv(e,`search`,`from`)})`,"text.lastIndexOf":e=>`${e.self()}.lastIndexOf(${Kv(e,`search`,`from`)})`,"text.match":e=>`(${e.self()}.match(new RegExp(${J(e,`pattern`)}, "g")) ?? [] as string[])`,"text.test":e=>`new RegExp(${J(e,`pattern`)}).test(${e.self()})`,"text.isEmpty":e=>`(${e.self()}.length === 0)`,"text.isNotEmpty":e=>`(${e.self()}.length > 0)`,"text.toNum":Hv(`Number`),"text.toBool":e=>`(${e.self()}.length > 0)`,"list.length":Wv(`length`),"list.at":e=>`${e.helper(`$listAt`)}(${e.self()}, ${J(e,`index`)})`,"list.push":Gv(Uv(`push`,`value`)),"list.pop":Uv(`pop`),"list.shift":Uv(`shift`),"list.unshift":Gv(Uv(`unshift`,`value`)),"list.insert":e=>`void ${e.self()}.splice(${J(e,`index`)}, 0, ${J(e,`value`)})`,"list.remove":e=>`${e.self()}.splice(${J(e,`index`)}, 1)[0]!`,"list.clear":e=>`void (${e.self()}.length = 0)`,"list.slice":e=>`${e.self()}.slice(${Kv(e,`start`,`end`)})`,"list.concat":Uv(`concat`,`other`),"list.reverse":e=>`[...${e.self()}].reverse()`,"list.join":e=>`${e.self()}.map(String).join(${Bv(e.arg(`separator`),`","`)})`,"list.indexOf":Uv(`indexOf`,`value`),"list.contains":e=>`(${e.self()}.indexOf(${J(e,`value`)}) !== -1)`,"list.unique":e=>`[...new Set(${e.self()})]`,"list.duplicates":e=>`${e.helper(`$duplicates`)}(${e.self()})`,"list.map":qv(`map`),"list.filter":qv(`filter`),"list.find":qv(`find`),"list.reduce":qv(`reduce`,`initial`),"list.some":qv(`some`),"list.every":qv(`every`),"list.sort":e=>e.arg(`fn`)===void 0?`${e.helper(`$sortNatural`)}(${e.self()})`:qv(`sort`)(e),"list.isEmpty":e=>`(${e.self()}.length === 0)`,"list.isNotEmpty":e=>`(${e.self()}.length > 0)`,"list.first":e=>`${e.self()}[0]`,"list.last":e=>`${e.self()}.at(-1)`,"map.size":Wv(`size`),"map.at":Uv(`get`,`key`),"map.has":Uv(`has`,`key`),"map.delete":Uv(`delete`,`key`),"map.clear":Gv(Uv(`clear`)),"map.keys":e=>`[...${e.self()}.keys()]`,"map.values":e=>`[...${e.self()}.values()]`,"map.isEmpty":e=>`(${e.self()}.size === 0)`,"map.isNotEmpty":e=>`(${e.self()}.size > 0)`,"object.keys":e=>(e.discard(),JSON.stringify(e.fields())),"object.values":e=>{let t=e.once();return`[${e.fields().map(e=>Qv(t,e)).join(`, `)}]`},"object.entries":e=>{let t=e.once();return`[${e.fields().map(e=>`[${JSON.stringify(e)}, ${Qv(t,e)}] as [string, unknown]`).join(`, `)}]`},"object.has":e=>(e.discard(),`(${JSON.stringify(e.fields())} as string[]).includes(${J(e,`key`)})`),"object.eq":e=>`${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.neq":e=>`!${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.toText":e=>`${e.helper(`$objText`)}(${e.self()} as any, ${JSON.stringify(e.fields())})`,"tuple.length":Wv(`length`),"tuple.first":e=>`${e.self()}[0]`,"tuple.last":e=>{let t=e.once();return`${t}[${t}.length - 1]`},"tuple.toList":e=>`[...${e.self()}]`,"optional.value":e=>`${e.helper(`$optValue`)}(${e.self()})`,"optional.has":e=>`(${e.self()} !== undefined)`,"optional.or":e=>{let t=e.once();return`(${t} !== undefined ? ${t} : ${J(e,`fallback`)})`},"optional.map":Jv(`undefined`),"nullable.value":e=>`${e.helper(`$nullValue`)}(${e.self()})`,"nullable.isNull":e=>`(${e.self()} === null)`,"nullable.or":e=>{let t=e.once();return`(${t} !== null ? ${t} : ${J(e,`fallback`)})`},"nullable.map":Jv(`null`),"enum.name":e=>{let t=ey(e.selfType),n={};for(let[e,r]of Object.entries(t?.options.values??{}))n[String(r)]=e;return`((${JSON.stringify(n)} as Record<string, string>)[String(${e.self()})] ?? "")`},"enum.value":e=>e.self(),"enum.eq":Vv(`===`),"enum.neq":Vv(`!==`),"enum.toText":e=>`String(${e.self()})`,"date.year":Uv(`getUTCFullYear`),"date.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"date.day":Uv(`getUTCDate`),"date.dayOfWeek":Uv(`getUTCDay`),"date.dayOfYear":e=>`${e.helper(`$date`)}.dayOfYear(${e.self()})`,"date.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"date.neq":e=>`(${e.self()}.getTime() !== ${J(e,`other`)}.getTime())`,"date.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"date.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"date.addDays":e=>`${e.helper(`$date`)}.addDays(${e.self()}, ${J(e,`days`)})`,"date.addMonths":e=>`${e.helper(`$date`)}.addMonths(${e.self()}, ${J(e,`months`)})`,"date.addYears":e=>`${e.helper(`$date`)}.addYears(${e.self()}, ${J(e,`years`)})`,"date.diffDays":e=>`${e.helper(`$date`)}.diffDays(${e.self()}, ${J(e,`other`)})`,"date.diffMonths":e=>`${e.helper(`$date`)}.diffMonths(${e.self()}, ${J(e,`other`)})`,"date.diffYears":e=>`(${e.self()}.getUTCFullYear() - ${J(e,`other`)}.getUTCFullYear())`,"date.toText":e=>`${e.self()}.toISOString().slice(0, 10)`,"timestamp.year":Uv(`getUTCFullYear`),"timestamp.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"timestamp.day":Uv(`getUTCDate`),"timestamp.hour":Uv(`getUTCHours`),"timestamp.minute":Uv(`getUTCMinutes`),"timestamp.second":Uv(`getUTCSeconds`),"timestamp.millisecond":Uv(`getUTCMilliseconds`),"timestamp.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"timestamp.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"timestamp.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"timestamp.addDuration":e=>`new Date(${e.self()}.getTime() + ${J(e,`duration`)})`,"timestamp.subDuration":e=>`new Date(${e.self()}.getTime() - ${J(e,`duration`)})`,"timestamp.diff":e=>`(${e.self()}.getTime() - ${J(e,`other`)}.getTime())`,"timestamp.toDate":e=>`${e.helper(`$date`)}.toDate(${e.self()})`,"timestamp.toEpoch":Uv(`getTime`),"timestamp.toText":Uv(`toISOString`),"duration.init":e=>`${e.helper(`$duration`)}.init(${e.self()})`,"duration.totalSeconds":e=>`(${e.self()} / 1000)`,"duration.totalMinutes":e=>`(${e.self()} / 60000)`,"duration.totalHours":e=>`(${e.self()} / 3600000)`,"duration.totalDays":e=>`(${e.self()} / 86400000)`,"duration.days":e=>`Math.trunc(${e.self()} / 86400000)`,"duration.hours":e=>`(Math.trunc(${e.self()} / 3600000) % 24)`,"duration.minutes":e=>`(Math.trunc(${e.self()} / 60000) % 60)`,"duration.seconds":e=>`(Math.trunc(${e.self()} / 1000) % 60)`,"duration.ms":e=>`(${e.self()} % 1000)`,"duration.toText":e=>`${e.helper(`$duration`)}.toText(${e.self()})`,"color.init":e=>`${e.helper(`$color`)}.init(${e.self()})`,"color.hue":e=>`${e.helper(`$color`)}.hsl(${e.self()}).h`,"color.saturation":e=>`${e.helper(`$color`)}.hsl(${e.self()}).s`,"color.lightness":e=>`${e.helper(`$color`)}.hsl(${e.self()}).l`,"color.eq":Vv(`===`),"color.neq":Vv(`!==`),"color.lighten":e=>`${e.helper(`$color`)}.lighten(${e.self()}, ${J(e,`amount`)})`,"color.darken":e=>`${e.helper(`$color`)}.lighten(${e.self()}, -${J(e,`amount`)})`,"color.saturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, ${J(e,`amount`)})`,"color.desaturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, -${J(e,`amount`)})`,"color.opacity":e=>`${e.helper(`$color`)}.opacity(${e.self()}, ${J(e,`alpha`)})`,"color.invert":e=>`${e.helper(`$color`)}.invert(${e.self()})`,"color.mix":e=>`${e.helper(`$color`)}.mix(${e.self()}, ${Kv(e,`other`,`weight`)})`,"color.complement":e=>`${e.helper(`$color`)}.complement(${e.self()})`,"color.toHex":e=>`${e.helper(`$color`)}.toHex(${e.self()})`,"color.toRgb":e=>`${e.helper(`$color`)}.toRgb(${e.self()})`,"color.toHsl":e=>`${e.helper(`$color`)}.toHsl(${e.self()})`,"color.toText":e=>`${e.helper(`$color`)}.toHex(${e.self()})`};for(let e of[`color.r`,`color.g`,`color.b`,`color.a`]){let t=e.slice(-1);Yv[e]=e=>`${e.helper(`$color`)}.${t}(${e.self()})`}var Xv={"list.indexGet":e=>`${e.helper(`$listGet`)}(${e.self}, ${e.key})`,"text.charAt":e=>`${e.helper(`$charAt`)}(${e.self}, ${e.key})`,"map.indexGet":e=>`${e.helper(`$mapGet`)}(${e.self}, ${e.key})`,"object.indexGet":e=>`(${e.self} as any)[${e.key}]`,"tuple.at":e=>`${e.self}[${e.key}]`},Zv={"list.indexSet":e=>`${e.helper(`$listSet`)}(${e.self}, ${e.key}, ${e.value})`,"map.indexSet":e=>`${e.self}.set(${e.key}, ${e.value})`,"object.indexSet":e=>`(${e.self} as any)[${e.key}] = ${e.value}`,"tuple.setAt":e=>`${e.self}[${e.key}] = ${e.value}`};function Qv(e,t){return $v(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function $v(e){return/^[A-Za-z_$][\w$]*$/.test(e)}function ey(e){let t=e;for(let e=0;e<10&&t;e++){if(t instanceof Dg)return t;t=t.base}}var ty=class extends Error{constructor(e){super(`gin \u2192 TypeScript: ${e.length} problem${e.length===1?``:`s`}
369
+ };`}},Rv=new Set(`any.unknown.never.object.string.number.boolean.symbol.bigint.undefined.null.void.true.false.this.keyof.typeof.infer.is.asserts.readonly.unique.type.interface.enum.class.function.let.const.var.new.in.of.as.extends.implements.namespace.module.declare.abstract.async.await.yield.import.export.default.return.if.else.for.while.do.switch.case.break.continue.try.catch.finally.throw.delete.instanceof.super.with.debugger.package.private.protected.public.static.global.require.Array.ArrayBuffer.ArrayLike.AsyncGenerator.AsyncIterable.AsyncIterator.Atomics.Awaited.BigInt.BigInt64Array.BigUint64Array.Boolean.Capitalize.ConstructorParameters.DataView.Date.Error.EvalError.Exclude.Extract.Float32Array.Float64Array.Function.Generator.Infinity.InstanceType.Int16Array.Int32Array.Int8Array.Intl.Iterable.IterableIterator.Iterator.JSON.Lowercase.Map.Math.NaN.NonNullable.Number.Object.Omit.OmitThisParameter.Parameters.Partial.Pick.Promise.PromiseLike.PropertyKey.Proxy.RangeError.Readonly.ReadonlyArray.ReadonlyMap.ReadonlySet.Record.ReferenceError.Reflect.RegExp.Required.ReturnType.Set.SharedArrayBuffer.String.Symbol.SyntaxError.TemplateStringsArray.ThisParameterType.ThisType.TypeError.URIError.Uint16Array.Uint32Array.Uint8Array.Uint8ClampedArray.Uncapitalize.Uppercase.WeakMap.WeakRef.WeakSet.globalThis.console.eval.arguments`.split(`.`));function zv(e){return/^[A-Za-z_][\w$]*$/.test(e)&&!Rv.has(e)&&!(e in Lv)}function Bv(e){let t=e.replace(/[^\w]/g,`_`);return/^[A-Za-z_]/.test(t)||(t=`_`+t),zv(t)?t:`${t}_`}var Vv=class{taken=new Set;types=new Map;data=new Map;constructor(e,t){let n=e.namedTypeList().filter(e=>e instanceof vg&&!e.local.useSite).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of n)zv(e.name)&&!this.taken.has(e.name)&&this.claim(this.types,e.name,e.name);for(let e of n)this.types.has(e.name)||this.type(e.name);for(let e of n){let n=!1;try{n=t(e)}catch{n=!1}n&&this.dataName(e.name)}}claim(e,t,n){let r=n;for(let e=2;this.taken.has(r);e++)r=`${n.replace(/_$/,``)}_${e}`;return this.taken.add(r),e.set(t,r),r}type(e){return this.types.get(e)??this.claim(this.types,e,Bv(e))}dataName(e){return this.data.get(e)??this.claim(this.data,e,`${this.type(e)}Data`)}fresh(e){return this.claim(new Map,e,Bv(e))}},Hv=(e,t)=>e===void 0||e===`undefined`||e===`null`?t:/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false)$/.test(e)?e:`(${e} ?? ${t})`,J=(e,t)=>e.arg(t)??`undefined`,Uv=e=>t=>`(${t.self()} ${e} ${J(t,`other`)})`,Wv=(e,...t)=>n=>`${e}(${[n.self(),...t.map(e=>J(n,e))].join(`, `)})`,Gv=(e,...t)=>n=>`${n.self()}.${e}(${t.map(e=>J(n,e)).join(`, `)})`,Kv=e=>t=>`${t.self()}.${e}`,qv=e=>t=>`void ${e(t)}`,Jv=(e,...t)=>{let n=t.map(t=>e.arg(t));for(;n.length>0&&n[n.length-1]===void 0;)n.pop();return n.map(e=>e??`undefined`).join(`, `)},Yv=(e,...t)=>n=>{let r=n.fn(`fn`),i=t.map(e=>J(n,e));return r?r.sync?`${n.helper(`$`+e)}(${[n.self(),r.code,...i].join(`, `)})`:n.aw(`${n.helper(`$`+e+`Async`)}(${[n.self(),r.code,...i].join(`, `)})`):`${n.helper(`$`+e)}(${[n.self(),`undefined as any`,...i].join(`, `)})`},Xv=e=>t=>{let n=t.once(),r=t.fn(`fn`);if(!r)return n;let i=`(${r.code})({ value: ${n} })`;return`(${n} === ${e} ? ${e} : ${r.sync?i:t.aw(i)})`},Zv={"type.toAny":e=>e.self(),"any.typeOf":e=>{let t=e.staticTypeName();return t===void 0?`${e.helper(`$typeOf`)}(${e.self()})`:(e.discard(),JSON.stringify(t))},"any.is":e=>{let t=e.guard();return t?`${t}(${e.self()})`:(e.discard(),`true`)},"any.as":e=>{let t=e.guard();if(!t)return e.self();let n=e.once();return`(${t}(${n}) ? ${n} : undefined)`},"any.toText":e=>`String(${e.self()})`,"any.toBool":e=>`Boolean(${e.self()})`,"any.eq":Uv(`===`),"any.neq":Uv(`!==`),"void.toText":e=>(e.discard(),`"void"`),"void.toBool":e=>(e.discard(),`false`),"null.toText":e=>(e.discard(),`"null"`),"null.toBool":e=>(e.discard(),`false`),"not.typeOf":e=>`${e.helper(`$typeOf`)}(${e.self()})`,"not.toText":e=>`String(${e.self()})`,"bool.eq":Uv(`===`),"bool.neq":Uv(`!==`),"bool.and":Uv(`&&`),"bool.or":Uv(`||`),"bool.xor":Uv(`!==`),"bool.not":e=>`!${e.self()}`,"bool.toText":e=>{let t=e.arg(`trueText`),n=e.arg(`falseText`);return t===void 0&&n===void 0?`String(${e.self()})`:`(${e.self()} ? ${Hv(t,`"true"`)} : ${Hv(n,`"false"`)})`},"bool.toNum":e=>{let t=e.arg(`trueValue`),n=e.arg(`falseValue`);return`(${e.self()} ? ${Hv(t,`1`)} : ${Hv(n,`0`)})`},"num.eq":e=>e.arg(`epsilon`)===void 0?`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.neq":e=>e.arg(`epsilon`)===void 0?`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.lt":Uv(`<`),"num.lte":Uv(`<=`),"num.gt":Uv(`>`),"num.gte":Uv(`>=`),"num.add":Uv(`+`),"num.sub":Uv(`-`),"num.mul":Uv(`*`),"num.div":Uv(`/`),"num.mod":Uv(`%`),"num.pow":Uv(`**`),"num.abs":Wv(`Math.abs`),"num.neg":e=>`(-${e.self()})`,"num.sign":Wv(`Math.sign`),"num.sqrt":Wv(`Math.sqrt`),"num.min":Wv(`Math.min`,`other`),"num.max":Wv(`Math.max`,`other`),"num.clamp":e=>`Math.min(Math.max(${e.self()}, ${J(e,`min`)}), ${J(e,`max`)})`,"num.floor":Wv(`Math.floor`),"num.ceil":Wv(`Math.ceil`),"num.round":Wv(`Math.round`),"num.isZero":e=>`(Math.abs(${e.self()}) <= 0)`,"num.isPositive":e=>`(${e.self()} > 0)`,"num.isNegative":e=>`(${e.self()} < 0)`,"num.isInteger":Wv(`Number.isInteger`),"num.isEven":e=>`(${e.self()} % 2 === 0)`,"num.isOdd":e=>`(Math.abs(${e.self()}) % 2 === 1)`,"num.toText":e=>e.arg(`precision`)===void 0?`String(${e.self()})`:`${e.helper(`$numText`)}(${e.self()}, ${e.arg(`precision`)})`,"num.toBool":e=>`(${e.self()} !== 0)`,"text.length":Kv(`length`),"text.eq":Uv(`===`),"text.neq":Uv(`!==`),"text.contains":Gv(`includes`,`search`),"text.startsWith":Gv(`startsWith`,`prefix`),"text.endsWith":Gv(`endsWith`,`suffix`),"text.trim":Gv(`trim`),"text.trimStart":Gv(`trimStart`),"text.trimEnd":Gv(`trimEnd`),"text.upper":Gv(`toUpperCase`),"text.lower":Gv(`toLowerCase`),"text.slice":e=>`${e.self()}.slice(${Jv(e,`start`,`end`)})`,"text.replace":e=>`${e.self()}.split(${J(e,`search`)}).join(${J(e,`replacement`)})`,"text.split":Gv(`split`,`separator`),"text.concat":Uv(`+`),"text.repeat":Gv(`repeat`,`count`),"text.indexOf":e=>`${e.self()}.indexOf(${Jv(e,`search`,`from`)})`,"text.lastIndexOf":e=>`${e.self()}.lastIndexOf(${Jv(e,`search`,`from`)})`,"text.match":e=>`(${e.self()}.match(new RegExp(${J(e,`pattern`)}, "g")) ?? [] as string[])`,"text.test":e=>`new RegExp(${J(e,`pattern`)}).test(${e.self()})`,"text.isEmpty":e=>`(${e.self()}.length === 0)`,"text.isNotEmpty":e=>`(${e.self()}.length > 0)`,"text.toNum":Wv(`Number`),"text.toBool":e=>`(${e.self()}.length > 0)`,"list.length":Kv(`length`),"list.at":e=>`${e.helper(`$listAt`)}(${e.self()}, ${J(e,`index`)})`,"list.push":qv(Gv(`push`,`value`)),"list.pop":Gv(`pop`),"list.shift":Gv(`shift`),"list.unshift":qv(Gv(`unshift`,`value`)),"list.insert":e=>`void ${e.self()}.splice(${J(e,`index`)}, 0, ${J(e,`value`)})`,"list.remove":e=>`${e.self()}.splice(${J(e,`index`)}, 1)[0]!`,"list.clear":e=>`void (${e.self()}.length = 0)`,"list.slice":e=>`${e.self()}.slice(${Jv(e,`start`,`end`)})`,"list.concat":Gv(`concat`,`other`),"list.reverse":e=>`[...${e.self()}].reverse()`,"list.join":e=>`${e.self()}.map(String).join(${Hv(e.arg(`separator`),`","`)})`,"list.indexOf":Gv(`indexOf`,`value`),"list.contains":e=>`(${e.self()}.indexOf(${J(e,`value`)}) !== -1)`,"list.unique":e=>`[...new Set(${e.self()})]`,"list.duplicates":e=>`${e.helper(`$duplicates`)}(${e.self()})`,"list.map":Yv(`map`),"list.filter":Yv(`filter`),"list.find":Yv(`find`),"list.reduce":Yv(`reduce`,`initial`),"list.some":Yv(`some`),"list.every":Yv(`every`),"list.sort":e=>e.arg(`fn`)===void 0?`${e.helper(`$sortNatural`)}(${e.self()})`:Yv(`sort`)(e),"list.isEmpty":e=>`(${e.self()}.length === 0)`,"list.isNotEmpty":e=>`(${e.self()}.length > 0)`,"list.first":e=>`${e.self()}[0]`,"list.last":e=>`${e.self()}.at(-1)`,"map.size":Kv(`size`),"map.at":Gv(`get`,`key`),"map.has":Gv(`has`,`key`),"map.delete":Gv(`delete`,`key`),"map.clear":qv(Gv(`clear`)),"map.keys":e=>`[...${e.self()}.keys()]`,"map.values":e=>`[...${e.self()}.values()]`,"map.isEmpty":e=>`(${e.self()}.size === 0)`,"map.isNotEmpty":e=>`(${e.self()}.size > 0)`,"object.keys":e=>(e.discard(),JSON.stringify(e.fields())),"object.values":e=>{let t=e.once();return`[${e.fields().map(e=>ey(t,e)).join(`, `)}]`},"object.entries":e=>{let t=e.once();return`[${e.fields().map(e=>`[${JSON.stringify(e)}, ${ey(t,e)}] as [string, unknown]`).join(`, `)}]`},"object.has":e=>(e.discard(),`(${JSON.stringify(e.fields())} as string[]).includes(${J(e,`key`)})`),"object.eq":e=>`${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.neq":e=>`!${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.toText":e=>`${e.helper(`$objText`)}(${e.self()} as any, ${JSON.stringify(e.fields())})`,"tuple.length":Kv(`length`),"tuple.first":e=>`${e.self()}[0]`,"tuple.last":e=>{let t=e.once();return`${t}[${t}.length - 1]`},"tuple.toList":e=>`[...${e.self()}]`,"optional.value":e=>`${e.helper(`$optValue`)}(${e.self()})`,"optional.has":e=>`(${e.self()} !== undefined)`,"optional.or":e=>{let t=e.once();return`(${t} !== undefined ? ${t} : ${J(e,`fallback`)})`},"optional.map":Xv(`undefined`),"nullable.value":e=>`${e.helper(`$nullValue`)}(${e.self()})`,"nullable.isNull":e=>`(${e.self()} === null)`,"nullable.or":e=>{let t=e.once();return`(${t} !== null ? ${t} : ${J(e,`fallback`)})`},"nullable.map":Xv(`null`),"enum.name":e=>{let t=ny(e.selfType),n={};for(let[e,r]of Object.entries(t?.options.values??{}))n[String(r)]=e;return`((${JSON.stringify(n)} as Record<string, string>)[String(${e.self()})] ?? "")`},"enum.value":e=>e.self(),"enum.eq":Uv(`===`),"enum.neq":Uv(`!==`),"enum.toText":e=>`String(${e.self()})`,"date.year":Gv(`getUTCFullYear`),"date.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"date.day":Gv(`getUTCDate`),"date.dayOfWeek":Gv(`getUTCDay`),"date.dayOfYear":e=>`${e.helper(`$date`)}.dayOfYear(${e.self()})`,"date.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"date.neq":e=>`(${e.self()}.getTime() !== ${J(e,`other`)}.getTime())`,"date.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"date.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"date.addDays":e=>`${e.helper(`$date`)}.addDays(${e.self()}, ${J(e,`days`)})`,"date.addMonths":e=>`${e.helper(`$date`)}.addMonths(${e.self()}, ${J(e,`months`)})`,"date.addYears":e=>`${e.helper(`$date`)}.addYears(${e.self()}, ${J(e,`years`)})`,"date.diffDays":e=>`${e.helper(`$date`)}.diffDays(${e.self()}, ${J(e,`other`)})`,"date.diffMonths":e=>`${e.helper(`$date`)}.diffMonths(${e.self()}, ${J(e,`other`)})`,"date.diffYears":e=>`(${e.self()}.getUTCFullYear() - ${J(e,`other`)}.getUTCFullYear())`,"date.toText":e=>`${e.self()}.toISOString().slice(0, 10)`,"timestamp.year":Gv(`getUTCFullYear`),"timestamp.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"timestamp.day":Gv(`getUTCDate`),"timestamp.hour":Gv(`getUTCHours`),"timestamp.minute":Gv(`getUTCMinutes`),"timestamp.second":Gv(`getUTCSeconds`),"timestamp.millisecond":Gv(`getUTCMilliseconds`),"timestamp.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"timestamp.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"timestamp.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"timestamp.addDuration":e=>`new Date(${e.self()}.getTime() + ${J(e,`duration`)})`,"timestamp.subDuration":e=>`new Date(${e.self()}.getTime() - ${J(e,`duration`)})`,"timestamp.diff":e=>`(${e.self()}.getTime() - ${J(e,`other`)}.getTime())`,"timestamp.toDate":e=>`${e.helper(`$date`)}.toDate(${e.self()})`,"timestamp.toEpoch":Gv(`getTime`),"timestamp.toText":Gv(`toISOString`),"duration.init":e=>`${e.helper(`$duration`)}.init(${e.self()})`,"duration.totalSeconds":e=>`(${e.self()} / 1000)`,"duration.totalMinutes":e=>`(${e.self()} / 60000)`,"duration.totalHours":e=>`(${e.self()} / 3600000)`,"duration.totalDays":e=>`(${e.self()} / 86400000)`,"duration.days":e=>`Math.trunc(${e.self()} / 86400000)`,"duration.hours":e=>`(Math.trunc(${e.self()} / 3600000) % 24)`,"duration.minutes":e=>`(Math.trunc(${e.self()} / 60000) % 60)`,"duration.seconds":e=>`(Math.trunc(${e.self()} / 1000) % 60)`,"duration.ms":e=>`(${e.self()} % 1000)`,"duration.toText":e=>`${e.helper(`$duration`)}.toText(${e.self()})`,"color.init":e=>`${e.helper(`$color`)}.init(${e.self()})`,"color.hue":e=>`${e.helper(`$color`)}.hsl(${e.self()}).h`,"color.saturation":e=>`${e.helper(`$color`)}.hsl(${e.self()}).s`,"color.lightness":e=>`${e.helper(`$color`)}.hsl(${e.self()}).l`,"color.eq":Uv(`===`),"color.neq":Uv(`!==`),"color.lighten":e=>`${e.helper(`$color`)}.lighten(${e.self()}, ${J(e,`amount`)})`,"color.darken":e=>`${e.helper(`$color`)}.lighten(${e.self()}, -${J(e,`amount`)})`,"color.saturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, ${J(e,`amount`)})`,"color.desaturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, -${J(e,`amount`)})`,"color.opacity":e=>`${e.helper(`$color`)}.opacity(${e.self()}, ${J(e,`alpha`)})`,"color.invert":e=>`${e.helper(`$color`)}.invert(${e.self()})`,"color.mix":e=>`${e.helper(`$color`)}.mix(${e.self()}, ${Jv(e,`other`,`weight`)})`,"color.complement":e=>`${e.helper(`$color`)}.complement(${e.self()})`,"color.toHex":e=>`${e.helper(`$color`)}.toHex(${e.self()})`,"color.toRgb":e=>`${e.helper(`$color`)}.toRgb(${e.self()})`,"color.toHsl":e=>`${e.helper(`$color`)}.toHsl(${e.self()})`,"color.toText":e=>`${e.helper(`$color`)}.toHex(${e.self()})`};for(let e of[`color.r`,`color.g`,`color.b`,`color.a`]){let t=e.slice(-1);Zv[e]=e=>`${e.helper(`$color`)}.${t}(${e.self()})`}var Qv={"list.indexGet":e=>`${e.helper(`$listGet`)}(${e.self}, ${e.key})`,"text.charAt":e=>`${e.helper(`$charAt`)}(${e.self}, ${e.key})`,"map.indexGet":e=>`${e.helper(`$mapGet`)}(${e.self}, ${e.key})`,"object.indexGet":e=>`(${e.self} as any)[${e.key}]`,"tuple.at":e=>`${e.self}[${e.key}]`},$v={"list.indexSet":e=>`${e.helper(`$listSet`)}(${e.self}, ${e.key}, ${e.value})`,"map.indexSet":e=>`${e.self}.set(${e.key}, ${e.value})`,"object.indexSet":e=>`(${e.self} as any)[${e.key}] = ${e.value}`,"tuple.setAt":e=>`${e.self}[${e.key}] = ${e.value}`};function ey(e,t){return ty(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function ty(e){return/^[A-Za-z_$][\w$]*$/.test(e)}function ny(e){let t=e;for(let e=0;e<10&&t;e++){if(t instanceof kg)return t;t=t.base}}var ry=class extends Error{constructor(e){super(`gin \u2192 TypeScript: ${e.length} problem${e.length===1?``:`s`}
370
370
  - ${e.join(`
371
- - `)}`),this.problems=e,this.name=`TypeScriptExportError`}problems},ny=class{constructor(e){this.ctxAllowed=e}ctxAllowed;awaited=!1;loops=[]},ry=new Set(`break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.export.extends.false.finally.for.function.if.import.in.instanceof.new.null.return.super.switch.this.throw.true.try.typeof.var.void.while.with.as.implements.interface.let.package.private.protected.public.static.yield.await.async.undefined.arguments.eval.ctx.args.self.Promise.Math.Number.String.Boolean.Date.Map.Set.Array.Object.JSON.Error.RegExp`.split(`.`)),iy=/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false|null|undefined)$/,ay=class{constructor(e,t={}){this.engine=e,this.registry=e.registry,this.opt={types:t.types??`referenced`,includeComments:t.includeComments??!0,prelude:t.prelude??`separate`,async:t.async??`always`,export:t.export??!1,scope:t.scope??{}},this.names=new zv(this.registry,e=>this.splits(this.decl(e)))}engine;registry;types=new Map;helpers=new Map;problems=new Set;opt;names;defined=new Set;makers=new Map;guards=new Map;used=new Set;ctxVars=new Map;usesExit=!1;get always(){return this.opt.async===`always`}get exp(){return this.opt.export?`export `:``}problem(e){this.problems.add(e)}check(){if(this.problems.size>0)throw new ty([...this.problems])}uniq(e){let t=e.replace(/[^\w$]/g,`_`);/^[A-Za-z_$]/.test(t)||(t=`_`+t),(/^make[A-Z]/.test(t)||/^is[A-Z]/.test(t)||t.startsWith(`$`))&&(t=`_`+t);let n=ry.has(t)||this.used.has(t)?`${t}_1`:t;for(let e=2;this.used.has(n);e++)n=`${t}_${e}`;return this.used.add(n),n}tsName(e){return this.names.type(e)}helper(e){if(this.helpers.has(e))return e;let t=Fv[e];if(!t)throw Error(`gin \u2192 TypeScript: no prelude helper '${e}'`);for(let e of t.deps??[])this.helper(e);return this.helpers.set(e,t.code),e}ref(e,t={generics:new Set}){if(e instanceof Sg){let n=e.options.name;if(t.generics.has(n))return n;let r=e.simplify();if(r!==e&&!(r instanceof Sg))return this.ref(r,t);let i=this.registry.lookup(n);return i&&!(i instanceof Sg)?this.ref(i,t):`any`}if(e instanceof gg)return this.namedRef(e,t);if(e instanceof _g)return`any`;if(e instanceof Yg)return`void`;if(e instanceof zg)return`null`;if(e instanceof Cg)return`boolean`;if(e instanceof Vg||e instanceof Eg||e instanceof wg)return`number`;if(e instanceof Wg)return`string`;if(e instanceof Tg||e instanceof Gg)return`Date`;if(e instanceof Ng)return Cy(this.ref(e.item,t));if(e instanceof Lg)return`Map<${this.ref(e.key,t)}, ${this.ref(e.value,t)}>`;if(e instanceof qg)return`[${e.elements.map(e=>this.ref(e,t)).join(`, `)}]`;if(e instanceof Hg)return Sy([this.ref(e.inner,t),`undefined`]);if(e instanceof Bg)return Sy([this.ref(e.inner,t),`null`]);if(e instanceof Ug)return Sy(e.variants.map(e=>this.ref(e,t)));if(e instanceof bg)return e.parts.map(e=>xy(this.ref(e,t))).join(` & `)||`unknown`;if(e instanceof Dg){let t=Object.values(e.options.values).map(e=>JSON.stringify(e));return t.length?t.join(` | `):`never`}if(e instanceof Mg)return JSON.stringify(e.literal);if(e instanceof Ag){let n=e.call();return n?this.fnSig(n,t,`unknown`,e.generic):`(...args: any[]) => any`}if(e instanceof vg)return this.objLiteralType(Object.entries(e.fields),t);if(e instanceof jg){let n=this.members(Object.entries(e._props),t,void 0);return e._call&&n.push(`(${this.params(e._call.args,t)}): ${this.returns(e._call,t,`unknown`)}`),by(n)}return e instanceof Rg||e instanceof Jg?`unknown`:`any`}decl(e){let t=this.registry.lookup(e.name);return t instanceof gg&&t.name===e.name?t:e}namedRef(e,t,n=!1){if(e.local.useSite)return e.original instanceof gg?this.namedRef(e.original,t,n):this.ref(e.original,t);let r=this.decl(e);this.define(r);let i=n&&this.splits(r)?this.dataName(r):this.tsName(r.name),a=Object.keys(r.generic??{});if(a.length===0)return i;let o=a.map(n=>{let r=e.generic?.[n];return r&&!U.isGenericPlaceholder(n,r)?this.ref(r,t):t.generics.has(n)?n:`any`});return o.every(e=>e===`any`)?i:`${i}<${o.join(`, `)}>`}define(e){if(this.defined.has(e.name))return;this.defined.add(e.name);let t=this.maker(e);this.declaration(e,t)}surface(e){let t=e.definitionProps();return Object.entries(t).map(([e,t])=>[e,jh.from(t)])}definitionCall(e){return e.definitionCall()}splits(e){if(!cy(e.base))return!1;if(this.definitionCall(e)||this.surface(e).some(([,e])=>sy(e)))return!0;let t=e.original;return t instanceof gg&&!t.local.useSite&&this.splits(this.decl(t))}carriedMembers(e){let t=new Map,n=new Set;for(let r=e;r instanceof gg&&!r.local.useSite;r=r.original)for(let[e,i]of this.surface(this.decl(r)))n.has(e)||(n.add(e),sy(i)&&(!i.get||i.get instanceof Ev)&&t.set(e,i));return[...t]}dataName(e){return this.names.dataName(e.name)}declaration(e,t){if(this.opt.types===`none`)return;let n=this.tsName(e.name),r=e.generic??{},i={generics:new Set(Object.keys(r))},a=this.genericParams(r,i);if(!this.splits(e)){this.types.set(n,this.singleDeclaration(e,t));return}let o=Object.keys(r).length?`<${Object.keys(r).join(`, `)}>`:``,s=e.original,c=s instanceof gg&&!s.local.useSite,l=this.surface(e),u=this.members(l.filter(([,e])=>!sy(e)),i,t),d=this.members(l.filter(([,e])=>sy(e)),i,t),f=this.definitionCall(e);f&&d.push(`(${this.params(f.args,i)}): ${this.returns(f,i,`unknown`)}`);let p=this.dataName(e),m=[];c&&m.push(this.namedRef(s,i,!0)),(u.length||m.length===0)&&m.push(by(u));let h=[`The stored fields of ${n}${t?` \u2014 what \`${t.name}\` takes`:``}.`];this.types.set(p,`${this.docBlock(h)}${this.exp}type ${p}${a} = ${m.join(` & `)};`);let ee=[];c&&ee.push(this.namedRef(s,i)),ee.push(`${p}${o}`),d.length&&ee.push(by(d)),this.types.set(n,`${this.docBlock(this.typeDocs(e))}${this.exp}type ${n}${a} = ${ee.join(` & `)};`)}typeDocs(e){let t=[];return e.docs&&t.push(e.docs),e.local.options&&Object.keys(e.local.options).length>0&&t.push(`gin: ${e.base.toCode(void 0,{includeComments:!1})}`),e.local.constraint&&t.push(`constraint: ${e.local.constraint.toCode(this.registry,{expectsValue:!0,includeComments:!1})}`),t}singleDeclaration(e,t){let n=this.tsName(e.name),r=e.generic??{},i={generics:new Set(Object.keys(r))},a=this.genericParams(r,i),o=this.typeDocs(e),s=e.original,c=s instanceof gg&&!s.local.useSite,l=cy(e.base),u=this.definitionCall(e),d=l||c?this.members(this.surface(e),i,t):[];u&&d.push(`(${this.params(u.args,i)}): ${this.returns(u,i,`unknown`)}`);let f;if(c){let e=this.ref(s,i);f=d.length?`${e} & ${by(d)}`:e}else l?f=by(d):(f=this.ref(e.base,i),d.length&&(f=`${xy(f)} & ${by(d)}`));return`${this.docBlock(o)}${this.exp}type ${n}${a} = ${f};`}genericParams(e,t){let n=Object.keys(e);return n.length===0?``:`<${n.map(n=>{let r=e[n];if(U.isGenericPlaceholder(n,r))return`${n} = any`;let i=this.ref(r,t);return`${n} extends ${i} = ${i}`}).join(`, `)}>`}members(e,t,n){let r=[];for(let[i,a]of e){let e=$v(i)?i:JSON.stringify(i),o=[];a.docs&&o.push(a.docs);let s=a.type.call(),c=n?.members.get(i);if(s&&(a.get||a.type instanceof Ag)){let n=c?c.async===!1?`sync`:`async`:this.hostMemberKind(a);r.push(`${this.docLine(o)}${e}: ${this.fnSig(s,t,n,a.type.generic)}`);continue}if(a.get){let n=this.ref(a.type,t);r.push(`${this.docLine(o)}readonly ${e}: ${c?.async===!0?`Promise<${n}>`:n}`);continue}let l=a.type.isOptional(),u=l?a.type.required():a.type,d=_y(u);d&&o.push(d),r.push(`${this.docLine(o)}${e}${l?`?`:``}: ${this.ref(u,t)}`)}return r}hostMemberKind(e){return this.always?`async`:e.get instanceof Ev&&!Yv[e.get.id]?e.get.effects()&(B.EXTERNAL|B.SYSTEM)?`async`:`sync`:e.get instanceof Ev?`sync`:`unknown`}objLiteralType(e,t){return by(this.members(e,t,void 0))}fnSig(e,t,n,r){let i=Object.keys(r??{}),a=i.length?{generics:new Set([...t.generics,...i])}:t;return`${i.length?this.genericParams(r,a):``}(${this.params(e.args,a)}) => ${this.returns(e,a,n)}`}returns(e,t,n){let r=e.returns?this.ref(e.returns,t):`any`;return n===`sync`?r:n===`async`||this.always?`Promise<${r}>`:`${xy(r)} | Promise<${r}>`}params(e,t){if(e instanceof vg){let n=Object.entries(e.fields);return n.length===0?``:`args${n.every(([,e])=>e.type.isOptional()||e.default!==void 0)?`?`:``}: ${this.objLiteralType(n,t)}`}return e instanceof _g||e instanceof Yg?``:`args: ${this.ref(e,t)}`}defParams(e,t){let n=this.params(e,t);return n.startsWith(`args?:`)?`args:${n.slice(6)} = {}`:n}docBlock(e){if(!this.opt.includeComments||e.length===0)return``;let t=e.flatMap(e=>e.split(`
372
- `));return t.length===1?`/** ${Ty(t[0])} */
371
+ - `)}`),this.problems=e,this.name=`TypeScriptExportError`}problems},iy=class{constructor(e){this.ctxAllowed=e}ctxAllowed;awaited=!1;loops=[]},ay=new Set(`break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.export.extends.false.finally.for.function.if.import.in.instanceof.new.null.return.super.switch.this.throw.true.try.typeof.var.void.while.with.as.implements.interface.let.package.private.protected.public.static.yield.await.async.undefined.arguments.eval.ctx.args.self.Promise.Math.Number.String.Boolean.Date.Map.Set.Array.Object.JSON.Error.RegExp`.split(`.`)),oy=/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false|null|undefined)$/,sy=class{constructor(e,t={}){this.engine=e,this.registry=e.registry,this.opt={types:t.types??`referenced`,includeComments:t.includeComments??!0,prelude:t.prelude??`separate`,async:t.async??`always`,export:t.export??!1,scope:t.scope??{}},this.names=new Vv(this.registry,e=>this.splits(this.decl(e)))}engine;registry;types=new Map;helpers=new Map;problems=new Set;opt;names;defined=new Set;makers=new Map;guards=new Map;used=new Set;ctxVars=new Map;usesExit=!1;get always(){return this.opt.async===`always`}get exp(){return this.opt.export?`export `:``}problem(e){this.problems.add(e)}check(){if(this.problems.size>0)throw new ry([...this.problems])}uniq(e){let t=e.replace(/[^\w$]/g,`_`);/^[A-Za-z_$]/.test(t)||(t=`_`+t),(/^make[A-Z]/.test(t)||/^is[A-Z]/.test(t)||t.startsWith(`$`))&&(t=`_`+t);let n=ay.has(t)||this.used.has(t)?`${t}_1`:t;for(let e=2;this.used.has(n);e++)n=`${t}_${e}`;return this.used.add(n),n}tsName(e){return this.names.type(e)}helper(e){if(this.helpers.has(e))return e;let t=Lv[e];if(!t)throw Error(`gin \u2192 TypeScript: no prelude helper '${e}'`);for(let e of t.deps??[])this.helper(e);return this.helpers.set(e,t.code),e}ref(e,t={generics:new Set}){if(e instanceof wg){let n=e.options.name;if(t.generics.has(n))return n;let r=e.simplify();if(r!==e&&!(r instanceof wg))return this.ref(r,t);let i=this.registry.lookup(n);return i&&!(i instanceof wg)?this.ref(i,t):`any`}if(e instanceof vg)return this.namedRef(e,t);if(e instanceof yg)return`any`;if(e instanceof Zg)return`void`;if(e instanceof Vg)return`null`;if(e instanceof Tg)return`boolean`;if(e instanceof Ug||e instanceof Og||e instanceof Eg)return`number`;if(e instanceof Kg)return`string`;if(e instanceof Dg||e instanceof qg)return`Date`;if(e instanceof Fg)return Ty(this.ref(e.item,t));if(e instanceof zg)return`Map<${this.ref(e.key,t)}, ${this.ref(e.value,t)}>`;if(e instanceof Yg)return`[${e.elements.map(e=>this.ref(e,t)).join(`, `)}]`;if(e instanceof Wg)return wy([this.ref(e.inner,t),`undefined`]);if(e instanceof Hg)return wy([this.ref(e.inner,t),`null`]);if(e instanceof Gg)return wy(e.variants.map(e=>this.ref(e,t)));if(e instanceof Sg)return e.parts.map(e=>Cy(this.ref(e,t))).join(` & `)||`unknown`;if(e instanceof kg){let t=Object.values(e.options.values).map(e=>JSON.stringify(e));return t.length?t.join(` | `):`never`}if(e instanceof Pg)return JSON.stringify(e.literal);if(e instanceof Mg){let n=e.call();return n?this.fnSig(n,t,`unknown`,e.generic):`(...args: any[]) => any`}if(e instanceof bg)return this.objLiteralType(Object.entries(e.fields),t);if(e instanceof Ng){let n=this.members(Object.entries(e._props),t,void 0);return e._call&&n.push(`(${this.params(e._call.args,t)}): ${this.returns(e._call,t,`unknown`)}`),Sy(n)}return e instanceof Bg||e instanceof Xg?`unknown`:`any`}decl(e){let t=this.registry.lookup(e.name);return t instanceof vg&&t.name===e.name?t:e}namedRef(e,t,n=!1){if(e.local.useSite)return e.original instanceof vg?this.namedRef(e.original,t,n):this.ref(e.original,t);let r=this.decl(e);this.define(r);let i=n&&this.splits(r)?this.dataName(r):this.tsName(r.name),a=Object.keys(r.generic??{});if(a.length===0)return i;let o=a.map(n=>{let r=e.generic?.[n];return r&&!U.isGenericPlaceholder(n,r)?this.ref(r,t):t.generics.has(n)?n:`any`});return o.every(e=>e===`any`)?i:`${i}<${o.join(`, `)}>`}define(e){if(this.defined.has(e.name))return;this.defined.add(e.name);let t=this.maker(e);this.declaration(e,t)}surface(e){let t=e.definitionProps();return Object.entries(t).map(([e,t])=>[e,Nh.from(t)])}definitionCall(e){return e.definitionCall()}splits(e){if(!uy(e.base))return!1;if(this.definitionCall(e)||this.surface(e).some(([,e])=>ly(e)))return!0;let t=e.original;return t instanceof vg&&!t.local.useSite&&this.splits(this.decl(t))}carriedMembers(e){let t=new Map,n=new Set;for(let r=e;r instanceof vg&&!r.local.useSite;r=r.original)for(let[e,i]of this.surface(this.decl(r)))n.has(e)||(n.add(e),ly(i)&&(!i.get||i.get instanceof Ov)&&t.set(e,i));return[...t]}dataName(e){return this.names.dataName(e.name)}declaration(e,t){if(this.opt.types===`none`)return;let n=this.tsName(e.name),r=e.generic??{},i={generics:new Set(Object.keys(r))},a=this.genericParams(r,i);if(!this.splits(e)){this.types.set(n,this.singleDeclaration(e,t));return}let o=Object.keys(r).length?`<${Object.keys(r).join(`, `)}>`:``,s=e.original,c=s instanceof vg&&!s.local.useSite,l=this.surface(e),u=this.members(l.filter(([,e])=>!ly(e)),i,t),d=this.members(l.filter(([,e])=>ly(e)),i,t),f=this.definitionCall(e);f&&d.push(`(${this.params(f.args,i)}): ${this.returns(f,i,`unknown`)}`);let p=this.dataName(e),m=[];c&&m.push(this.namedRef(s,i,!0)),(u.length||m.length===0)&&m.push(Sy(u));let h=[`The stored fields of ${n}${t?` \u2014 what \`${t.name}\` takes`:``}.`];this.types.set(p,`${this.docBlock(h)}${this.exp}type ${p}${a} = ${m.join(` & `)};`);let ee=[];c&&ee.push(this.namedRef(s,i)),ee.push(`${p}${o}`),d.length&&ee.push(Sy(d)),this.types.set(n,`${this.docBlock(this.typeDocs(e))}${this.exp}type ${n}${a} = ${ee.join(` & `)};`)}typeDocs(e){let t=[];return e.docs&&t.push(e.docs),e.local.options&&Object.keys(e.local.options).length>0&&t.push(`gin: ${e.base.toCode(void 0,{includeComments:!1})}`),e.local.constraint&&t.push(`constraint: ${e.local.constraint.toCode(this.registry,{expectsValue:!0,includeComments:!1})}`),t}singleDeclaration(e,t){let n=this.tsName(e.name),r=e.generic??{},i={generics:new Set(Object.keys(r))},a=this.genericParams(r,i),o=this.typeDocs(e),s=e.original,c=s instanceof vg&&!s.local.useSite,l=uy(e.base),u=this.definitionCall(e),d=l||c?this.members(this.surface(e),i,t):[];u&&d.push(`(${this.params(u.args,i)}): ${this.returns(u,i,`unknown`)}`);let f;if(c){let e=this.ref(s,i);f=d.length?`${e} & ${Sy(d)}`:e}else l?f=Sy(d):(f=this.ref(e.base,i),d.length&&(f=`${Cy(f)} & ${Sy(d)}`));return`${this.docBlock(o)}${this.exp}type ${n}${a} = ${f};`}genericParams(e,t){let n=Object.keys(e);return n.length===0?``:`<${n.map(n=>{let r=e[n];if(U.isGenericPlaceholder(n,r))return`${n} = any`;let i=this.ref(r,t);return`${n} extends ${i} = ${i}`}).join(`, `)}>`}members(e,t,n){let r=[];for(let[i,a]of e){let e=ty(i)?i:JSON.stringify(i),o=[];a.docs&&o.push(a.docs);let s=a.type.call(),c=n?.members.get(i);if(s&&(a.get||a.type instanceof Mg)){let n=c?c.async===!1?`sync`:`async`:this.hostMemberKind(a);r.push(`${this.docLine(o)}${e}: ${this.fnSig(s,t,n,a.type.generic)}`);continue}if(a.get){let n=this.ref(a.type,t);r.push(`${this.docLine(o)}readonly ${e}: ${c?.async===!0?`Promise<${n}>`:n}`);continue}let l=a.type.isOptional(),u=l?a.type.required():a.type,d=yy(u);d&&o.push(d),r.push(`${this.docLine(o)}${e}${l?`?`:``}: ${this.ref(u,t)}`)}return r}hostMemberKind(e){return this.always?`async`:e.get instanceof Ov&&!Zv[e.get.id]?e.get.effects()&(B.EXTERNAL|B.SYSTEM)?`async`:`sync`:e.get instanceof Ov?`sync`:`unknown`}objLiteralType(e,t){return Sy(this.members(e,t,void 0))}fnSig(e,t,n,r){let i=Object.keys(r??{}),a=i.length?{generics:new Set([...t.generics,...i])}:t;return`${i.length?this.genericParams(r,a):``}(${this.params(e.args,a)}) => ${this.returns(e,a,n)}`}returns(e,t,n){let r=e.returns?this.ref(e.returns,t):`any`;return n===`sync`?r:n===`async`||this.always?`Promise<${r}>`:`${Cy(r)} | Promise<${r}>`}params(e,t){if(e instanceof bg){let n=Object.entries(e.fields);return n.length===0?``:`args${n.every(([,e])=>e.type.isOptional()||e.default!==void 0)?`?`:``}: ${this.objLiteralType(n,t)}`}return e instanceof yg||e instanceof Zg?``:`args: ${this.ref(e,t)}`}defParams(e,t){let n=this.params(e,t);return n.startsWith(`args?:`)?`args:${n.slice(6)} = {}`:n}docBlock(e){if(!this.opt.includeComments||e.length===0)return``;let t=e.flatMap(e=>e.split(`
372
+ `));return t.length===1?`/** ${Dy(t[0])} */
373
373
  `:`/**
374
- ${t.map(e=>` * ${Ty(e)}`).join(`
374
+ ${t.map(e=>` * ${Dy(e)}`).join(`
375
375
  `)}
376
376
  */
377
- `}docLine(e){return!this.opt.includeComments||e.length===0?``:`/** ${Ty(e.join(` · `).replace(/\n/g,` `))} */ `}maker(e){if(this.makers.has(e.name))return this.makers.get(e.name)??void 0;let t=e.definitionProps(),n=Object.entries(t).map(([e,t])=>[e,jh.from(t)]).filter(([,e])=>e.get&&!(e.get instanceof Ev)),r=e.original instanceof gg&&!e.original.local.useSite?this.maker(this.decl(e.original)):void 0;if(n.length===0&&!r){this.makers.set(e.name,null);return}if(!cy(e.base)){this.problem(`type '${e.name}': members written in gin on a non-object type are not supported`),this.makers.set(e.name,null);return}let i={name:`make${this.tsName(e.name)}`,members:new Map(r?.members??[])};for(let[e,t]of n)i.members.set(e,{kind:t.type.call()?`method`:`computed`,async:`pending`});this.makers.set(e.name,i);let a=e.generic??{},o={generics:new Set(Object.keys(a))},s=this.genericParams(a,o),c=Object.keys(a).length?`<${Object.keys(a).join(`, `)}>`:``,l=`${this.tsName(e.name)}${c}`;this.define(e);let u=new Set(this.used);this.used.clear();let d=`self`,f=[];f.push(r?`const ${d} = ${r.name}(data) as ${l};`:`const ${d} = data as ${l};`);for(let[t,r]of n){let n=new ny(!1),a=[],s=new Map([[`this`,{ts:d,type:e}]]),c=r.type.call();if(c){let e=this.uniq(t);s.set(`args`,{ts:`args`,type:c.args}),s.set(`recurse`,{ts:e,type:r.type}),this.stmt(r.get,s,n,a,{kind:`return`});let l=this.always||n.awaited;i.members.set(t,{kind:`method`,async:l});let u=this.defParams(c.args,o);f.push(`${Qv(d,t)} = ${l?`async `:``}function ${e}(${u}) {`),f.push(...vy(a),`};`)}else this.stmt(r.get,s,n,a,{kind:`return`}),i.members.set(t,{kind:`computed`,async:n.awaited}),f.push(`Object.defineProperty(${d}, ${JSON.stringify(t)}, {`),f.push(` get: ${n.awaited?`async `:``}() => {`,...vy(vy(a)),` },`),f.push(` enumerable: false,`,` configurable: true,`,`});`)}f.push(`return ${d};`),this.used.clear();for(let e of u)this.used.add(e);let p=this.members(this.carriedMembers(e),o,i),m=`${this.dataName(e)}${c}${p.length?` & ${by(p)}`:``}`,h=[`/** Attach ${e.name}'s gin-written members to its data. */`,`${this.exp}function ${i.name}${s}(data: ${m}): ${l} {`,...vy(f),`}`].join(`
378
- `);return this.helpers.set(i.name,h),this.declaration(e,i),i}guard(e){let t=this.ref(e),n=t,r=this.guards.get(n);if(r)return r;let i=e instanceof gg?`$is${this.tsName(this.decl(e).name)}`:`$is_${Oy(t)}`;this.guards.set(n,i);let a=this.checkExpr(e,`v`,0,!0);return this.helpers.set(i,`function ${i}(v: unknown): v is ${t} {
377
+ `}docLine(e){return!this.opt.includeComments||e.length===0?``:`/** ${Dy(e.join(` · `).replace(/\n/g,` `))} */ `}maker(e){if(this.makers.has(e.name))return this.makers.get(e.name)??void 0;let t=e.definitionProps(),n=Object.entries(t).map(([e,t])=>[e,Nh.from(t)]).filter(([,e])=>e.get&&!(e.get instanceof Ov)),r=e.original instanceof vg&&!e.original.local.useSite?this.maker(this.decl(e.original)):void 0;if(n.length===0&&!r){this.makers.set(e.name,null);return}if(!uy(e.base)){this.problem(`type '${e.name}': members written in gin on a non-object type are not supported`),this.makers.set(e.name,null);return}let i={name:`make${this.tsName(e.name)}`,members:new Map(r?.members??[])};for(let[e,t]of n)i.members.set(e,{kind:t.type.call()?`method`:`computed`,async:`pending`});this.makers.set(e.name,i);let a=e.generic??{},o={generics:new Set(Object.keys(a))},s=this.genericParams(a,o),c=Object.keys(a).length?`<${Object.keys(a).join(`, `)}>`:``,l=`${this.tsName(e.name)}${c}`;this.define(e);let u=new Set(this.used);this.used.clear();let d=`self`,f=[];f.push(r?`const ${d} = ${r.name}(data) as ${l};`:`const ${d} = data as ${l};`);for(let[t,r]of n){let n=new iy(!1),a=[],s=new Map([[`this`,{ts:d,type:e}]]),c=r.type.call();if(c){let e=this.uniq(t);s.set(`args`,{ts:`args`,type:c.args}),s.set(`recurse`,{ts:e,type:r.type}),this.stmt(r.get,s,n,a,{kind:`return`});let l=this.always||n.awaited;i.members.set(t,{kind:`method`,async:l});let u=this.defParams(c.args,o);f.push(`${ey(d,t)} = ${l?`async `:``}function ${e}(${u}) {`),f.push(...by(a),`};`)}else this.stmt(r.get,s,n,a,{kind:`return`}),i.members.set(t,{kind:`computed`,async:n.awaited}),f.push(`Object.defineProperty(${d}, ${JSON.stringify(t)}, {`),f.push(` get: ${n.awaited?`async `:``}() => {`,...by(by(a)),` },`),f.push(` enumerable: false,`,` configurable: true,`,`});`)}f.push(`return ${d};`),this.used.clear();for(let e of u)this.used.add(e);let p=this.members(this.carriedMembers(e),o,i),m=`${this.dataName(e)}${c}${p.length?` & ${Sy(p)}`:``}`,h=[`/** Attach ${e.name}'s gin-written members to its data. */`,`${this.exp}function ${i.name}${s}(data: ${m}): ${l} {`,...by(f),`}`].join(`
378
+ `);return this.helpers.set(i.name,h),this.declaration(e,i),i}guard(e){let t=this.ref(e),n=t,r=this.guards.get(n);if(r)return r;let i=e instanceof vg?`$is${this.tsName(this.decl(e).name)}`:`$is_${Ay(t)}`;this.guards.set(n,i);let a=this.checkExpr(e,`v`,0,!0);return this.helpers.set(i,`function ${i}(v: unknown): v is ${t} {
379
379
  return ${a};
380
- }`),i}checkExpr(e,t,n,r=!1){let i=`x${n}`;if(e instanceof Sg){let r=e.simplify();return r===e?`true`:this.checkExpr(r,t,n)}if(e instanceof gg)return r?this.checkExpr(e.base,t,n):`${this.guard(e)}(${t})`;if(e instanceof Vg||e instanceof Eg||e instanceof wg)return`typeof ${t} === "number"`;if(e instanceof Wg)return`typeof ${t} === "string"`;if(e instanceof Cg)return`typeof ${t} === "boolean"`;if(e instanceof zg)return`${t} === null`;if(e instanceof Yg)return`${t} === undefined`;if(e instanceof Tg||e instanceof Gg)return`${t} instanceof Date`;if(e instanceof Ag)return`typeof ${t} === "function"`;if(e instanceof Lg)return`${t} instanceof Map`;if(e instanceof Ng){let r=this.checkExpr(e.item,i,n+1);return r===`true`?`Array.isArray(${t})`:`(Array.isArray(${t}) && ${t}.every((${i}: unknown) => ${r}))`}if(e instanceof qg){let r=e.elements.map((e,r)=>this.checkExpr(e,`${t}[${r}]`,n+1));return`(Array.isArray(${t}) && ${t}.length === ${e.elements.length}${r.map(e=>` && ${e}`).join(``)})`}if(e instanceof Hg)return`(${t} === undefined || ${this.checkExpr(e.inner,t,n)})`;if(e instanceof Bg)return`(${t} === null || ${this.checkExpr(e.inner,t,n)})`;if(e instanceof Ug)return`(${e.variants.map(e=>this.checkExpr(e,t,n)).join(` || `)})`;if(e instanceof bg)return`(${e.parts.map(e=>this.checkExpr(e,t,n)).join(` && `)})`;if(e instanceof Dg)return`${JSON.stringify(Object.values(e.options.values))}.includes(${t} as any)`;if(e instanceof Mg)return`${t} === ${JSON.stringify(e.literal)}`;if(e instanceof vg||e instanceof jg){let r=e instanceof vg?Object.entries(e.fields):Object.entries(e._props),i=[`typeof ${t} === "object"`,`${t} !== null`];for(let[e,a]of r){if(a.get||a.type.call())continue;let r=`(${t} as any)${$v(e)?`.`+e:`[${JSON.stringify(e)}]`}`;i.push(a.type.isOptional()?`(${r} === undefined || ${this.checkExpr(a.type.required(),r,n+1)})`:this.checkExpr(a.type,r,n+1))}return`(${i.join(` && `)})`}return`true`}exportFunction(e,t){this.ctxVars=new Map,this.usesExit=!1,(!$v(t)||ry.has(t))&&this.problem(`'${t}' is not usable as a function name`);let n=t;this.used.add(t);let r=new ny(!0),i=[],a=[],o=``;if(e instanceof bv){let t=e.fnType.call(),s={generics:new Set(Object.keys(e.fnType.generic??{}))},c=new Map([[`args`,{ts:`args`,type:t?.args??this.registry.obj({})}],[`recurse`,{ts:n,type:e.fnType}]]);e.constraint&&this.constraint(e.constraint,c,r,i),this.stmt(e.body,c,r,i,{kind:`return`}),a=[(t?this.defParams(t.args,s):``)||`args: {} = {}`],t?.returns&&(o=this.ref(t.returns,s))}else this.stmt(e,new Map,r,i,{kind:`return`});let s=this.always||r.awaited;if(this.ctxVars.size>0){let e=this.names.fresh(`${Dy(t)}Ctx`),n=[...this.ctxVars].map(([e,t])=>{let n=this.engine.getGlobal(e),r=n?.docs?[n.docs]:[];return`${this.docLine(r)}${$v(e)?e:JSON.stringify(e)}: ${this.ref(t)}`});this.types.set(e,`${this.docBlock([`Free variables ${t} reads (engine globals and run extras).`])}${this.exp}type ${e} = ${by(n)};`),a.push(`ctx: ${e}`)}let c=i;if(this.usesExit){let e=this.helper(`$Exit`);c=[`try {`,...vy(i),`} catch ($exit) {`,` if ($exit instanceof ${e}) return $exit.value as any;`,` throw $exit;`,`}`]}let l=o?`: ${s?`Promise<${o}>`:o}`:``;return[`${e.comment?this.docBlock([e.comment]):``}${this.exp}${s?`async `:``}function ${n}(${a.join(`, `)})${l} {`,...vy(c),`}`].join(`
380
+ }`),i}checkExpr(e,t,n,r=!1){let i=`x${n}`;if(e instanceof wg){let r=e.simplify();return r===e?`true`:this.checkExpr(r,t,n)}if(e instanceof vg)return r?this.checkExpr(e.base,t,n):`${this.guard(e)}(${t})`;if(e instanceof Ug||e instanceof Og||e instanceof Eg)return`typeof ${t} === "number"`;if(e instanceof Kg)return`typeof ${t} === "string"`;if(e instanceof Tg)return`typeof ${t} === "boolean"`;if(e instanceof Vg)return`${t} === null`;if(e instanceof Zg)return`${t} === undefined`;if(e instanceof Dg||e instanceof qg)return`${t} instanceof Date`;if(e instanceof Mg)return`typeof ${t} === "function"`;if(e instanceof zg)return`${t} instanceof Map`;if(e instanceof Fg){let r=this.checkExpr(e.item,i,n+1);return r===`true`?`Array.isArray(${t})`:`(Array.isArray(${t}) && ${t}.every((${i}: unknown) => ${r}))`}if(e instanceof Yg){let r=e.elements.map((e,r)=>this.checkExpr(e,`${t}[${r}]`,n+1));return`(Array.isArray(${t}) && ${t}.length === ${e.elements.length}${r.map(e=>` && ${e}`).join(``)})`}if(e instanceof Wg)return`(${t} === undefined || ${this.checkExpr(e.inner,t,n)})`;if(e instanceof Hg)return`(${t} === null || ${this.checkExpr(e.inner,t,n)})`;if(e instanceof Gg)return`(${e.variants.map(e=>this.checkExpr(e,t,n)).join(` || `)})`;if(e instanceof Sg)return`(${e.parts.map(e=>this.checkExpr(e,t,n)).join(` && `)})`;if(e instanceof kg)return`${JSON.stringify(Object.values(e.options.values))}.includes(${t} as any)`;if(e instanceof Pg)return`${t} === ${JSON.stringify(e.literal)}`;if(e instanceof bg||e instanceof Ng){let r=e instanceof bg?Object.entries(e.fields):Object.entries(e._props),i=[`typeof ${t} === "object"`,`${t} !== null`];for(let[e,a]of r){if(a.get||a.type.call())continue;let r=`(${t} as any)${ty(e)?`.`+e:`[${JSON.stringify(e)}]`}`;i.push(a.type.isOptional()?`(${r} === undefined || ${this.checkExpr(a.type.required(),r,n+1)})`:this.checkExpr(a.type,r,n+1))}return`(${i.join(` && `)})`}return`true`}exportFunction(e,t){this.ctxVars=new Map,this.usesExit=!1,(!ty(t)||ay.has(t))&&this.problem(`'${t}' is not usable as a function name`);let n=t;this.used.add(t);let r=new iy(!0),i=[],a=[],o=``;if(e instanceof Sv){let t=e.fnType.call(),s={generics:new Set(Object.keys(e.fnType.generic??{}))},c=new Map([[`args`,{ts:`args`,type:t?.args??this.registry.obj({})}],[`recurse`,{ts:n,type:e.fnType}]]);e.constraint&&this.constraint(e.constraint,c,r,i),this.stmt(e.body,c,r,i,{kind:`return`}),a=[(t?this.defParams(t.args,s):``)||`args: {} = {}`],t?.returns&&(o=this.ref(t.returns,s))}else this.stmt(e,new Map,r,i,{kind:`return`});let s=this.always||r.awaited;if(this.ctxVars.size>0){let e=this.names.fresh(`${ky(t)}Ctx`),n=[...this.ctxVars].map(([e,t])=>{let n=this.engine.getGlobal(e),r=n?.docs?[n.docs]:[];return`${this.docLine(r)}${ty(e)?e:JSON.stringify(e)}: ${this.ref(t)}`});this.types.set(e,`${this.docBlock([`Free variables ${t} reads (engine globals and run extras).`])}${this.exp}type ${e} = ${Sy(n)};`),a.push(`ctx: ${e}`)}let c=i;if(this.usesExit){let e=this.helper(`$Exit`);c=[`try {`,...by(i),`} catch ($exit) {`,` if ($exit instanceof ${e}) return $exit.value as any;`,` throw $exit;`,`}`]}let l=o?`: ${s?`Promise<${o}>`:o}`:``;return[`${e.comment?this.docBlock([e.comment]):``}${this.exp}${s?`async `:``}function ${n}(${a.join(`, `)})${l} {`,...by(c),`}`].join(`
381
381
  `)}constraint(e,t,n,r){let i=this.val(e,t,n,r),a=JSON.stringify(`lambda constraint failed: ${e.toCode(this.registry,{expectsValue:!0,includeComments:!1})}`);r.push(`if (${i.code} !== true) throw new Error(${a});`)}stmt(e,t,n,r,i){if(e.comment&&this.opt.includeComments&&r.push(...e.comment.split(`
382
- `).map(e=>`// ${e}`)),e instanceof fv){if(e.lines.length===0)return this.finish(`undefined`,r,i,!0);e.lines.forEach((a,o)=>this.stmt(a,t,n,r,o===e.lines.length-1?i:{kind:`discard`}));return}if(e instanceof uv){let a=this.defineVars(e,t,n,r);return this.stmt(e.body,a,n,r,i)}if(e instanceof gv)return this.ifStmt(e,t,n,r,i);if(e instanceof _v)return this.switchStmt(e,t,n,r,i);if(e instanceof vv){this.loop(e,t,n,r),i.kind===`assign`&&r.push(`${i.name} = undefined;`);return}if(e instanceof pv)return this.flow(e,t,n,r);if(e instanceof lv)return this.set(e,t,n,r),this.finish(`true`,r,i,!0);let a=this.val(e,t,n,r);this.finish(a.code,r,i,a.pure)}finish(e,t,n,r){n.kind===`return`?e!==`undefined`&&t.push(`return ${wy(e)};`):n.kind===`assign`?t.push(`${n.name} = ${wy(e)};`):r||t.push(`${wy(e)};`)}defineVars(e,t,n,r){let i=new Map(t);for(let t of e.vars){let e=this.val(t.value,i,n,r),a=this.uniq(t.name),o=t.type??e.type,s=t.type?`: ${this.ref(t.type)}`:``;r.push(`let ${a}${s} = ${wy(e.code)};`),i.set(t.name,{ts:a,type:o,sync:e.sync})}return i}ifStmt(e,t,n,r,i){let a=(r,o)=>{if(r>=e.ifs.length){e.otherwise&&this.stmt(e.otherwise,t,n,o,i);return}let s=e.ifs[r],c=this.val(s.condition,t,n,o),l=[];this.stmt(s.body,t,n,l,i),o.push(`if (${wy(c.code)}) {`,...vy(l),`}`);let u=[];a(r+1,u),u.length!==0&&(u[0].startsWith(`if (`)&&yy(u)?(o[o.length-1]=`} else ${u[0]}`,o.push(...u.slice(1))):(o[o.length-1]=`} else {`,o.push(...vy(u),`}`)))};a(0,r)}switchStmt(e,t,n,r,i){let a=this.spill(this.val(e.value,t,n,r),r,`sw`),o=[];if(e.cases.forEach((e,r)=>{let s=[],c=e.equals.map(e=>this.val(e,t,n,s).code);s.length&&this.problem(`switch: a case value that needs statements is not supported`);let l=[];this.stmt(e.body,t,n,l,i);let u=c.length?c.map(e=>`${a} === ${e}`).join(` || `):`false`;o.push(`${r===0?`if`:`} else if`} (${u}) {`,...vy(l))}),e.otherwise){let a=[];if(this.stmt(e.otherwise,t,n,a,i),o.length===0){r.push(...a);return}o.push(`} else {`,...vy(a))}o.length&&r.push(...o,`}`)}flow(e,t,n,r){let i=n.loops[n.loops.length-1];switch(e.action){case`break`:i===`for`?r.push(`break;`):this.problem(i===`parallel`?`flow: break inside a parallel loop is not supported`:`flow: break outside a loop`);return;case`continue`:i===`for`?r.push(`continue;`):i===`parallel`?r.push(`return;`):this.problem(`flow: continue outside a loop`);return;case`return`:{i===`parallel`&&this.problem(`flow: return inside a parallel loop is not supported`);let a=e.value?this.val(e.value,t,n,r).code:void 0;r.push(a&&a!==`undefined`?`return ${wy(a)};`:`return;`);return}case`exit`:{let i=e.value?this.val(e.value,t,n,r).code:`undefined`;this.usesExit=!0,r.push(`throw new ${this.helper(`$Exit`)}(${wy(i)});`);return}case`throw`:{let i=e.error?this.val(e.error,t,n,r).code:`undefined`;r.push(`throw new ${this.helper(`$Throw`)}(${wy(i)});`);return}}}loop(e,t,n,r){let i=this.registry.any(),a=this.typeOfExpr(e.over,t),o=a.get(),s=o?.loop instanceof Ev?o.loop.id:void 0,c=e.keyName??`key`,l=e.valueName??`value`,u=this.uniq(c),d=this.uniq(l),f=new Map(t);if(f.set(c,{ts:u,type:o?.key??i}),f.set(l,{ts:d,type:o?.value??i}),e.parallel)return this.parallelLoop(e,t,n,r,f,s,u,d,!!o?.loopDynamic);let p=[];if(n.loops.push(`for`),this.stmt(e.body,f,n,p,{kind:`discard`}),n.loops.pop(),o?.loopDynamic){let i=[],a=this.val(e.over,t,n,i);r.push(`for (let ${u} = 0; ; ${u}++) {`,...vy(i),` const ${d} = ${wy(a.code)};`,` if (!${d}) break;`,...vy(p),`}`);return}let m=this.spill(this.val(e.over,t,n,r),r,`over`);switch(s){case`list.iterate`:case`tuple.iterate`:r.push(`for (let ${u} = 0; ${u} < ${m}.length; ${u}++) {`,` const ${d} = ${m}[${u}];`,...vy(p),`}`);return;case`text.chars`:r.push(`for (let ${u} = 0; ${u} < ${m}.length; ${u}++) {`,` const ${d} = ${m}[${u}]!;`,...vy(p),`}`);return;case`map.iterate`:r.push(`for (const [${u}, ${d}] of ${m}) {`,...vy(p),`}`);return;case`num.loop`:{let e=this.uniq(`count`);r.push(`for (let ${u} = 0, ${e} = Math.abs(Math.trunc(${m})); ${u} < ${e}; ${u}++) {`,` const ${d} = ${m} < 0 ? -${u} : ${u};`,...vy(p),`}`);return}case`object.iterate`:{let e=JSON.stringify(uy(a));r.push(`for (const ${u} of ${e}) {`,` const ${d} = (${m} as any)[${u}];`,` if (${d} === undefined) continue;`,...vy(p),`}`);return}default:this.problem(`loop: iterating '${a.toCode()}' is not supported (only built-in iterables)`)}}parallelLoop(e,t,n,r,i,a,o,s,c){if(c){this.problem(`loop: a parallel while-loop is not supported`);return}let l=e.parallel?.concurrent?this.val(e.parallel.concurrent,t,n,r).code:`undefined`,u=e.parallel?.rate?this.val(e.parallel.rate,t,n,r).code:`undefined`,d=this.typeOfExpr(e.over,t),f=this.spill(this.val(e.over,t,n,r),r,`over`),p;switch(a){case`list.iterate`:case`tuple.iterate`:p=`${f}.entries()`;break;case`text.chars`:p=`${f}.split("").entries()`;break;case`map.iterate`:p=f;break;case`num.loop`:p=`Array.from({ length: Math.abs(Math.trunc(${f})) }, (_, i) => [i, ${f} < 0 ? -i : i] as [number, number])`;break;case`object.iterate`:p=`${JSON.stringify(uy(d))}.map((f) => [f, (${f} as any)[f]] as [string, any]).filter((e) => e[1] !== undefined)`;break;default:this.problem(`loop: iterating '${d.toCode()}' is not supported (only built-in iterables)`);return}let m=[],h=new ny(n.ctxAllowed);h.loops.push(`parallel`),this.stmt(e.body,i,h,m,{kind:`discard`}),n.awaited=!0,r.push(`await ${this.helper(`$parallel`)}(${p}, ${l}, ${u}, async (${o}, ${s}) => {`,...vy(m),`});`)}val(e,t,n,r){if(e instanceof W_)return this.newValue(e,t,n,r);if(e instanceof cv)return this.path(e.path.steps,t,n,r);if(e instanceof lv)return this.set(e,t,n,r),{code:`true`,type:this.registry.bool(),pure:!0};if(e instanceof bv)return this.lambda(e,t,n);if(e instanceof wv)return this.template(e,t,n,r);if(e instanceof fv){if(e.lines.length===0)return{code:`undefined`,type:this.registry.void(),pure:!0};for(let i of e.lines.slice(0,-1))this.stmt(i,t,n,r,{kind:`discard`});return this.val(e.lines[e.lines.length-1],t,n,r)}if(e instanceof uv)return this.val(e.body,this.defineVars(e,t,n,r),n,r);if(e instanceof gv)return this.ifValue(e,t,n,r);if(e instanceof _v||e instanceof vv){let i=this.uniq(`v`);return r.push(`let ${i};`),this.stmt(e,t,n,r,{kind:`assign`,name:i}),{code:i,type:this.typeOfExpr(e,t),pure:!0}}return e instanceof pv?(this.flow(e,t,n,r),{code:`undefined as never`,type:this.registry.void(),pure:!0}):e instanceof Ev?(this.problem(`native '${e.id}' used directly as an expression is not supported`),{code:`undefined as any`,type:this.registry.any(),pure:!0}):(this.problem(`expression kind '${e.kind}' is not supported`),{code:`undefined as any`,type:this.registry.any(),pure:!0})}ifValue(e,t,n,r){let i=[],a=e.ifs.map(e=>{let r=[],a=this.val(e.condition,t,n,r),o=[],s=this.val(e.body,t,n,o);return i.push(r,o),{cb:r,c:a,bb:o,v:s}}),o=[],s=e.otherwise?this.val(e.otherwise,t,n,o):void 0;i.push(o);let c=this.typeOfExpr(e,t);if(i.every(e=>e.length===0)){let e=s?s.code:`undefined`;for(let t=a.length-1;t>=0;t--)e=`${a[t].c.code} ? ${a[t].v.code} : ${e}`;return{code:`(${e})`,type:c,pure:a.every(e=>e.c.pure&&e.v.pure)&&(s?.pure??!0)}}let l=this.uniq(`v`);r.push(`let ${l};`);let u=(e,t)=>{if(e>=a.length){s&&t.push(...o,`${l} = ${wy(s.code)};`);return}let n=a[e];t.push(...n.cb,`if (${wy(n.c.code)}) {`,...vy([...n.bb,`${l} = ${wy(n.v.code)};`]),`}`);let r=[];u(e+1,r),r.length&&(t[t.length-1]=`} else {`,t.push(...vy(r),`}`))};return u(0,r),{code:l,type:c,pure:!0}}template(e,t,n,r){let i=this.registry.text(),a=e.params?this.val(e.params,t,n,r):void 0,o=a?this.spill(a,r,`params`):void 0,s=e.template instanceof W_&&typeof e.template.value==`string`?e.template.value:void 0;if(s===void 0){let a=this.val(e.template,t,n,r);return{code:`${this.helper(`$template`)}(${a.code}, ${o??`undefined`} as any)`,type:i,pure:!1}}let c=a?dy(a.type):void 0,l="`",u=0;for(let e of s.matchAll(/\{(\w+)\}/g)){l+=Ey(s.slice(u,e.index)),u=e.index+e[0].length;let r=e[1],i;if(o&&c?.has(r))i={code:Qv(o,r),type:c.get(r)};else if(o&&!c)i={code:`(${o} as any)[${JSON.stringify(r)}]`,type:this.registry.any()};else{let e=this.lookup(r,t,n);e&&(i={code:e.ts,type:e.type})}i&&(l+="${"+(py(i.type)?i.code:`${this.helper(`$str`)}(${i.code})`)+`}`)}return l+=Ey(s.slice(u))+"`",{code:l,type:i,pure:!0}}lambda(e,t,n){let r=e.fnType.call(),i={generics:new Set(Object.keys(e.fnType.generic??{}))},a=this.uniq(`recurse`),o=new ny(n.ctxAllowed),s=new Map(t);s.set(`args`,{ts:`args`,type:r?.args??this.registry.obj({})}),s.set(`recurse`,{ts:a,type:e.fnType});let c=[];e.constraint&&this.constraint(e.constraint,s,o,c),this.stmt(e.body,s,o,c,{kind:`return`});let l=this.always||o.awaited,u=r?this.defParams(r.args,i):``,d=r?.returns?`: ${l?`Promise<${this.ref(r.returns,i)}>`:this.ref(r.returns,i)}`:``,f=Object.keys(e.fnType.generic??{}).length?this.genericParams(e.fnType.generic,i):``,p=c.some(e=>RegExp(`\\b${a.replace(/\$/g,`\\$`)}\\b`).test(e)),m;if(p)m=[`${l?`async `:``}function ${a}${f}(${u})${d} {`,...vy(c),`}`].join(`
382
+ `).map(e=>`// ${e}`)),e instanceof mv){if(e.lines.length===0)return this.finish(`undefined`,r,i,!0);e.lines.forEach((a,o)=>this.stmt(a,t,n,r,o===e.lines.length-1?i:{kind:`discard`}));return}if(e instanceof fv){let a=this.defineVars(e,t,n,r);return this.stmt(e.body,a,n,r,i)}if(e instanceof vv)return this.ifStmt(e,t,n,r,i);if(e instanceof yv)return this.switchStmt(e,t,n,r,i);if(e instanceof bv){this.loop(e,t,n,r),i.kind===`assign`&&r.push(`${i.name} = undefined;`);return}if(e instanceof hv)return this.flow(e,t,n,r);if(e instanceof dv)return this.set(e,t,n,r),this.finish(`true`,r,i,!0);let a=this.val(e,t,n,r);this.finish(a.code,r,i,a.pure)}finish(e,t,n,r){n.kind===`return`?e!==`undefined`&&t.push(`return ${Ey(e)};`):n.kind===`assign`?t.push(`${n.name} = ${Ey(e)};`):r||t.push(`${Ey(e)};`)}defineVars(e,t,n,r){let i=new Map(t);for(let t of e.vars){let e=this.val(t.value,i,n,r),a=this.uniq(t.name),o=t.type??e.type,s=t.type?`: ${this.ref(t.type)}`:``;r.push(`let ${a}${s} = ${Ey(e.code)};`),i.set(t.name,{ts:a,type:o,sync:e.sync})}return i}ifStmt(e,t,n,r,i){let a=(r,o)=>{if(r>=e.ifs.length){e.otherwise&&this.stmt(e.otherwise,t,n,o,i);return}let s=e.ifs[r],c=this.val(s.condition,t,n,o),l=[];this.stmt(s.body,t,n,l,i),o.push(`if (${Ey(c.code)}) {`,...by(l),`}`);let u=[];a(r+1,u),u.length!==0&&(u[0].startsWith(`if (`)&&xy(u)?(o[o.length-1]=`} else ${u[0]}`,o.push(...u.slice(1))):(o[o.length-1]=`} else {`,o.push(...by(u),`}`)))};a(0,r)}switchStmt(e,t,n,r,i){let a=this.spill(this.val(e.value,t,n,r),r,`sw`),o=[];if(e.cases.forEach((e,r)=>{let s=[],c=e.equals.map(e=>this.val(e,t,n,s).code);s.length&&this.problem(`switch: a case value that needs statements is not supported`);let l=[];this.stmt(e.body,t,n,l,i);let u=c.length?c.map(e=>`${a} === ${e}`).join(` || `):`false`;o.push(`${r===0?`if`:`} else if`} (${u}) {`,...by(l))}),e.otherwise){let a=[];if(this.stmt(e.otherwise,t,n,a,i),o.length===0){r.push(...a);return}o.push(`} else {`,...by(a))}o.length&&r.push(...o,`}`)}flow(e,t,n,r){let i=n.loops[n.loops.length-1];switch(e.action){case`break`:i===`for`?r.push(`break;`):this.problem(i===`parallel`?`flow: break inside a parallel loop is not supported`:`flow: break outside a loop`);return;case`continue`:i===`for`?r.push(`continue;`):i===`parallel`?r.push(`return;`):this.problem(`flow: continue outside a loop`);return;case`return`:{i===`parallel`&&this.problem(`flow: return inside a parallel loop is not supported`);let a=e.value?this.val(e.value,t,n,r).code:void 0;r.push(a&&a!==`undefined`?`return ${Ey(a)};`:`return;`);return}case`exit`:{let i=e.value?this.val(e.value,t,n,r).code:`undefined`;this.usesExit=!0,r.push(`throw new ${this.helper(`$Exit`)}(${Ey(i)});`);return}case`throw`:{let i=e.error?this.val(e.error,t,n,r).code:`undefined`;r.push(`throw new ${this.helper(`$Throw`)}(${Ey(i)});`);return}}}loop(e,t,n,r){let i=this.registry.any(),a=this.typeOfExpr(e.over,t),o=a.get(),s=o?.loop instanceof Ov?o.loop.id:void 0,c=e.keyName??`key`,l=e.valueName??`value`,u=this.uniq(c),d=this.uniq(l),f=new Map(t);if(f.set(c,{ts:u,type:o?.key??i}),f.set(l,{ts:d,type:o?.value??i}),e.parallel)return this.parallelLoop(e,t,n,r,f,s,u,d,!!o?.loopDynamic);let p=[];if(n.loops.push(`for`),this.stmt(e.body,f,n,p,{kind:`discard`}),n.loops.pop(),o?.loopDynamic){let i=[],a=this.val(e.over,t,n,i);r.push(`for (let ${u} = 0; ; ${u}++) {`,...by(i),` const ${d} = ${Ey(a.code)};`,` if (!${d}) break;`,...by(p),`}`);return}let m=this.spill(this.val(e.over,t,n,r),r,`over`);switch(s){case`list.iterate`:case`tuple.iterate`:r.push(`for (let ${u} = 0; ${u} < ${m}.length; ${u}++) {`,` const ${d} = ${m}[${u}];`,...by(p),`}`);return;case`text.chars`:r.push(`for (let ${u} = 0; ${u} < ${m}.length; ${u}++) {`,` const ${d} = ${m}[${u}]!;`,...by(p),`}`);return;case`map.iterate`:r.push(`for (const [${u}, ${d}] of ${m}) {`,...by(p),`}`);return;case`num.loop`:{let e=this.uniq(`count`);r.push(`for (let ${u} = 0, ${e} = Math.abs(Math.trunc(${m})); ${u} < ${e}; ${u}++) {`,` const ${d} = ${m} < 0 ? -${u} : ${u};`,...by(p),`}`);return}case`object.iterate`:{let e=JSON.stringify(fy(a));r.push(`for (const ${u} of ${e}) {`,` const ${d} = (${m} as any)[${u}];`,` if (${d} === undefined) continue;`,...by(p),`}`);return}default:this.problem(`loop: iterating '${a.toCode()}' is not supported (only built-in iterables)`)}}parallelLoop(e,t,n,r,i,a,o,s,c){if(c){this.problem(`loop: a parallel while-loop is not supported`);return}let l=e.parallel?.concurrent?this.val(e.parallel.concurrent,t,n,r).code:`undefined`,u=e.parallel?.rate?this.val(e.parallel.rate,t,n,r).code:`undefined`,d=this.typeOfExpr(e.over,t),f=this.spill(this.val(e.over,t,n,r),r,`over`),p;switch(a){case`list.iterate`:case`tuple.iterate`:p=`${f}.entries()`;break;case`text.chars`:p=`${f}.split("").entries()`;break;case`map.iterate`:p=f;break;case`num.loop`:p=`Array.from({ length: Math.abs(Math.trunc(${f})) }, (_, i) => [i, ${f} < 0 ? -i : i] as [number, number])`;break;case`object.iterate`:p=`${JSON.stringify(fy(d))}.map((f) => [f, (${f} as any)[f]] as [string, any]).filter((e) => e[1] !== undefined)`;break;default:this.problem(`loop: iterating '${d.toCode()}' is not supported (only built-in iterables)`);return}let m=[],h=new iy(n.ctxAllowed);h.loops.push(`parallel`),this.stmt(e.body,i,h,m,{kind:`discard`}),n.awaited=!0,r.push(`await ${this.helper(`$parallel`)}(${p}, ${l}, ${u}, async (${o}, ${s}) => {`,...by(m),`});`)}val(e,t,n,r){if(e instanceof K_)return this.newValue(e,t,n,r);if(e instanceof uv)return this.path(e.path.steps,t,n,r);if(e instanceof dv)return this.set(e,t,n,r),{code:`true`,type:this.registry.bool(),pure:!0};if(e instanceof Sv)return this.lambda(e,t,n);if(e instanceof Ev)return this.template(e,t,n,r);if(e instanceof mv){if(e.lines.length===0)return{code:`undefined`,type:this.registry.void(),pure:!0};for(let i of e.lines.slice(0,-1))this.stmt(i,t,n,r,{kind:`discard`});return this.val(e.lines[e.lines.length-1],t,n,r)}if(e instanceof fv)return this.val(e.body,this.defineVars(e,t,n,r),n,r);if(e instanceof vv)return this.ifValue(e,t,n,r);if(e instanceof yv||e instanceof bv){let i=this.uniq(`v`);return r.push(`let ${i};`),this.stmt(e,t,n,r,{kind:`assign`,name:i}),{code:i,type:this.typeOfExpr(e,t),pure:!0}}return e instanceof hv?(this.flow(e,t,n,r),{code:`undefined as never`,type:this.registry.void(),pure:!0}):e instanceof Ov?(this.problem(`native '${e.id}' used directly as an expression is not supported`),{code:`undefined as any`,type:this.registry.any(),pure:!0}):(this.problem(`expression kind '${e.kind}' is not supported`),{code:`undefined as any`,type:this.registry.any(),pure:!0})}ifValue(e,t,n,r){let i=[],a=e.ifs.map(e=>{let r=[],a=this.val(e.condition,t,n,r),o=[],s=this.val(e.body,t,n,o);return i.push(r,o),{cb:r,c:a,bb:o,v:s}}),o=[],s=e.otherwise?this.val(e.otherwise,t,n,o):void 0;i.push(o);let c=this.typeOfExpr(e,t);if(i.every(e=>e.length===0)){let e=s?s.code:`undefined`;for(let t=a.length-1;t>=0;t--)e=`${a[t].c.code} ? ${a[t].v.code} : ${e}`;return{code:`(${e})`,type:c,pure:a.every(e=>e.c.pure&&e.v.pure)&&(s?.pure??!0)}}let l=this.uniq(`v`);r.push(`let ${l};`);let u=(e,t)=>{if(e>=a.length){s&&t.push(...o,`${l} = ${Ey(s.code)};`);return}let n=a[e];t.push(...n.cb,`if (${Ey(n.c.code)}) {`,...by([...n.bb,`${l} = ${Ey(n.v.code)};`]),`}`);let r=[];u(e+1,r),r.length&&(t[t.length-1]=`} else {`,t.push(...by(r),`}`))};return u(0,r),{code:l,type:c,pure:!0}}template(e,t,n,r){let i=this.registry.text(),a=e.params?this.val(e.params,t,n,r):void 0,o=a?this.spill(a,r,`params`):void 0,s=e.template instanceof K_&&typeof e.template.value==`string`?e.template.value:void 0;if(s===void 0){let a=this.val(e.template,t,n,r);return{code:`${this.helper(`$template`)}(${a.code}, ${o??`undefined`} as any)`,type:i,pure:!1}}let c=a?py(a.type):void 0,l="`",u=0;for(let e of s.matchAll(/\{(\w+)\}/g)){l+=Oy(s.slice(u,e.index)),u=e.index+e[0].length;let r=e[1],i;if(o&&c?.has(r))i={code:ey(o,r),type:c.get(r)};else if(o&&!c)i={code:`(${o} as any)[${JSON.stringify(r)}]`,type:this.registry.any()};else{let e=this.lookup(r,t,n);e&&(i={code:e.ts,type:e.type})}i&&(l+="${"+(hy(i.type)?i.code:`${this.helper(`$str`)}(${i.code})`)+`}`)}return l+=Oy(s.slice(u))+"`",{code:l,type:i,pure:!0}}lambda(e,t,n){let r=e.fnType.call(),i={generics:new Set(Object.keys(e.fnType.generic??{}))},a=this.uniq(`recurse`),o=new iy(n.ctxAllowed),s=new Map(t);s.set(`args`,{ts:`args`,type:r?.args??this.registry.obj({})}),s.set(`recurse`,{ts:a,type:e.fnType});let c=[];e.constraint&&this.constraint(e.constraint,s,o,c),this.stmt(e.body,s,o,c,{kind:`return`});let l=this.always||o.awaited,u=r?this.defParams(r.args,i):``,d=r?.returns?`: ${l?`Promise<${this.ref(r.returns,i)}>`:this.ref(r.returns,i)}`:``,f=Object.keys(e.fnType.generic??{}).length?this.genericParams(e.fnType.generic,i):``,p=c.some(e=>RegExp(`\\b${a.replace(/\$/g,`\\$`)}\\b`).test(e)),m;if(p)m=[`${l?`async `:``}function ${a}${f}(${u})${d} {`,...by(c),`}`].join(`
383
383
  `);else if(c.length===1&&c[0].startsWith(`return `)&&!c[0].includes(`
384
- `)){let e=c[0].slice(7,-1);e.startsWith(`{`)&&(e=`(${e})`),m=`${l?`async `:``}${f}(${u})${d} => ${e}`}else m=[`${l?`async `:``}${f}(${u})${d} => {`,...vy(c),`}`].join(`
385
- `);return{code:`(${m})`,type:e.fnType,pure:!0,sync:!l}}newValue(e,t,n,r){let i=e.type,a=i.init();if(e.value!==void 0&&a){let t=a.run instanceof Ev?a.run.id:void 0;if(t!==`duration.init`&&t!==`color.init`)return this.problem(`new ${i.toCode()}: a constructor written in gin is not supported`),{code:`undefined as any`,type:i,pure:!0};let n=this.literal(a.args.parse(e.value).toLogical(),a.args);return{code:`${this.helper(t===`duration.init`?`$duration`:`$color`)}.init(${n})`,type:i,pure:!0}}if(e.value===void 0){let e=this.construct(i,this.literal(new W(i,i.create()).toLogical(),i));return{code:e,type:i,pure:!e.startsWith(`make`)}}let o=this.fill(e.value,i,t,n,r);return{code:o.code,type:i,pure:o.pure}}fill(e,t,n,r,i){let a=e instanceof $m?e:Ah(e,t.scope??this.registry);if(a){let e=this.val(a,n,r,i);return{code:e.code,pure:e.pure}}if(!hy(e,this.registry))try{let n=this.construct(t,this.literal(t.parse(e).toLogical(),t));return{code:n,pure:!n.startsWith(`make`)}}catch(e){return this.problem(`new ${t.toCode()}: ${e instanceof Error?e.message:String(e)}`),{code:`undefined as any`,pure:!0}}if(t instanceof Sg)return this.fill(e,t.simplify(),n,r,i);if(t instanceof Hg||t instanceof Bg)return e===void 0?{code:`undefined`,pure:!0}:e===null?{code:`null`,pure:!0}:this.fill(e,t.inner,n,r,i);let o=e=>this.ordered(e.map(([e,t,i])=>a=>{let o=this.fill(t,i,n,r,a);return{code:o.code,pure:o.pure,key:e}}),i);if(t instanceof Ng&&Array.isArray(e))return{code:`[${o(e.map(e=>[void 0,e,t.item])).map(e=>e.code).join(`, `)}]`,pure:!1};if(t instanceof qg&&Array.isArray(e))return{code:`[${o(e.map((e,n)=>[void 0,e,t.elements[n]??this.registry.any()])).map(e=>e.code).join(`, `)}] as ${this.ref(t)}`,pure:!1};if(t instanceof Lg&&Array.isArray(e)){let n=[];for(let r of e){let[e,i]=Array.isArray(r)?r:[r?.key,r?.value];n.push([void 0,e,t.key],[void 0,i,t.value])}let r=o(n),i=[];for(let e=0;e<r.length;e+=2)i.push(`[${r[e].code}, ${r[e+1].code}]`);return{code:`new Map<${this.ref(t.key)}, ${this.ref(t.value)}>([${i.join(`, `)}])`,pure:!1}}let s=ly(t);if(s&&e&&typeof e==`object`&&!Array.isArray(e)){let a=e,c=[],l=[];for(let[e,t]of s)e in a?c.push([e,a[e],t.type]):t.default&&l.push([e,t.default]);let u=o(c);for(let[e,t]of l)u.push({key:e,code:this.val(t,n,r,i).code});let d=u.map(e=>`${$v(e.key)?e.key:JSON.stringify(e.key)}: ${e.code}`);return{code:this.construct(t,`{ ${d.join(`, `)} }`),pure:!1}}return this.problem(`new ${t.toCode()}: payload shape not supported`),{code:`undefined as any`,pure:!0}}construct(e,t){let n=e instanceof gg&&!e.local.useSite?this.decl(e):void 0;if(n){this.define(n);let e=this.carriedMembers(n).map(([e])=>e);e.length&&this.problem(`new ${n.name}: its host member${e.length>1?`s`:``} ${e.join(`, `)} cannot be supplied in TypeScript \u2014 build the value on the host (\`make${this.tsName(n.name)}\` / \`${this.dataName(n)}\`) and pass it in`);let r=this.maker(n);if(r)return`${r.name}(${t})`}return t.startsWith(`[`)||t.startsWith(`{`)||n?`(${t} as ${this.ref(e)})`:t}literal(e,t){if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`number`)return Object.is(e,-0)?`-0`:Number.isFinite(e)?String(e):e>0?`Infinity`:e<0?`-Infinity`:`NaN`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(e instanceof Date)return`new Date(${JSON.stringify(e.toISOString())})`;let n=t instanceof gg?t.base:t instanceof Hg||t instanceof Bg?t.inner:t;if(e instanceof Map){let t=n instanceof Lg?n.key:this.registry.any(),r=n instanceof Lg?n.value:this.registry.any(),i=[...e].map(([e,n])=>`[${this.literal(e,t)}, ${this.literal(n,r)}]`);return`new Map<${this.ref(t)}, ${this.ref(r)}>([${i.join(`, `)}])`}if(Array.isArray(e)){if(n instanceof qg)return`[${e.map((e,t)=>this.literal(e,n.elements[t]??this.registry.any())).join(`, `)}]`;let t=n instanceof Ng?n.item:this.registry.any();return`[${e.map(e=>this.literal(e,t)).join(`, `)}]`}if(typeof e==`object`){let n=new Map(ly(t)??[]);return`{ ${Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${$v(e)?e:JSON.stringify(e)}: ${this.literal(t,n.get(e)?.type??this.registry.any())}`).join(`, `)} }`}return`undefined`}set(e,t,n,r){let i=e.path.steps,a=this.val(e.value,t,n,r);if(i.length===1&&i[0]instanceof nv){let e=i[0].prop,o=this.lookup(e,t,n);if(!o){this.problem(`set: unknown variable '${e}'`);return}r.push(`${o.ts} = ${wy(a.code)};`);return}let o=iy.test(a.code)?a.code:this.spill(a,r,`value`),s=i[i.length-1];if(s instanceof rv){this.problem(`set: assigning through a method call is not supported`);return}let c=this.path(i.slice(0,-1),t,n,r);if(s instanceof nv){let e=c.type.prop(s.prop);if(e?.set){this.problem(`set: prop '${s.prop}' has a gin setter, which is not supported`);return}if(e?.get&&!e.type.call()){this.problem(`set: prop '${s.prop}' is computed and cannot be assigned`);return}r.push(`${Qv(c.code,s.prop)} = ${o};`)}else if(s instanceof iv){let e=this.val(s.key,t,n,r).code,i=c.type.get(),a=i?.set instanceof Ev?i.set.id:void 0,l=a?Zv[a]:void 0;if(!l){this.problem(`set: indexed assignment on '${c.type.toCode()}' is not supported`);return}r.push(`${l({self:c.code,key:e,value:o,helper:e=>this.helper(e)})};`)}}lookup(e,t,n){let r=t.get(e);if(r)return r;let i=this.engine.getGlobal(e),a=this.opt.scope[e]??i?.type;if(a)return n.ctxAllowed?(this.ctxVars.set(e,a),{ts:Qv(`ctx`,e),type:a}):(this.problem(`'${e}' is read inside a gin-written member, where only this / args / recurse are in scope`),{ts:`undefined as any`,type:a})}path(e,t,n,r){let i;for(let a=0;a<e.length;a++){let o=e[a];if(o instanceof nv){if(!i){let e=this.lookup(o.prop,t,n);e?i={code:e.ts,type:e.type,pure:!0,sync:e.sync}:(this.problem(`unknown variable '${o.prop}'`),i={code:`undefined as any`,type:this.registry.any(),pure:!0});continue}this.touch(i.type);let s=i.type.prop(o.prop);if(!s){this.problem(`no prop '${o.prop}' on '${i.type.toCode()}' (the TypeScript export dispatches on the static type)`),i={code:Qv(i.code,o.prop),type:this.registry.any(),pure:!1};continue}let c=s.type instanceof Sg?s.type.simplify(i.type.scope):s.type,l=e[a+1];if(l instanceof rv&&c.call()){i=this.invoke(i,o.prop,s,c,l,t,n,r),a++;continue}if(!(l instanceof rv)&&oy(c)){i=this.invoke(i,o.prop,s,c,new rv({}),t,n,r);continue}i=this.readProp(i,o.prop,s,c,n,r)}else{if(!i)return this.problem(`path: must start with a variable`),{code:`undefined as any`,type:this.registry.any(),pure:!0};if(o instanceof iv){this.touch(i.type);let e=i,a=[],s=this.val(o.key,t,n,a),c=a.length||!s.pure?this.spill(e,r,`recv`):e.code;r.push(...a);let l=e.type.get(),u=l?.get instanceof Ev?l.get.id:void 0,d=u?Xv[u]:void 0;d||this.problem(`indexing '${e.type.toCode()}' is not supported`),i={code:d?d({self:c,key:s.code,helper:e=>this.helper(e)}):`undefined as any`,type:l?.value??this.registry.any(),pure:!1}}else if(o instanceof rv){let e=i.type,a=e.scope;try{a=o.callSiteScope(e)}catch(e){this.problem(String(e instanceof Error?e.message:e))}let s=e.call(a);s?.get&&this.problem(`calling a '${e.toCode()}' value implemented in gin is not supported`);let{recv:c,args:l}=this.orderedArgs(i,o.args,t,n,r),u=`${c}(${gy(l,s)})`;i.sync!==!0&&(u=this.aw(u,n));let d=s?.returns?.simplify(a)??s?.returns??this.registry.any();i=o.catch_?this.withCatch(u,o.catch_,d,t,n,r):{code:u,type:d,pure:!1}}}}return i??{code:`undefined as any`,type:this.registry.any(),pure:!0}}touch(e){e instanceof gg&&!e.local.useSite&&this.define(this.decl(e))}readProp(e,t,n,r,i,a){let o=n.get instanceof Ev?n.get.id:void 0,s=o?Yv[o]:void 0;if(s)return{code:s(this.nativeCtx(e,{},void 0,i,a)),type:r,pure:e.pure};let c=Qv(e.code,t);return n.get&&this.memberAsync(e.type,t,n,`computed`)&&(c=this.aw(c,i)),{code:c,type:r,pure:e.pure&&!n.get}}invoke(e,t,n,r,i,a,o,s){let c=r.scope;try{c=i.callSiteScope(r)}catch(e){this.problem(String(e instanceof Error?e.message:e))}let l=r.call(c),u=l?.returns?.simplify(c)??l?.returns??this.registry.any(),d=n.get instanceof Ev?n.get.id:void 0,f=d?Yv[d]:void 0,{recv:p,args:m}=this.orderedArgs(e,i.args,a,o,s),h;if(f){let t=i.generic?.T?this.registry.parse(i.generic.T,c):void 0;h=f(this.nativeCtx({...e,code:p},m,t,o,s))}else h=`${Qv(p,t)}(${gy(m,l)})`,this.memberAsync(e.type,t,n,`method`)&&(h=this.aw(h,o));return i.catch_?this.withCatch(h,i.catch_,u,a,o,s):{code:h,type:u,pure:!!f&&e.pure&&Object.values(m).every(e=>e.pure)&&!(d&&my(d))}}memberAsync(e,t,n,r){if(n.get&&!(n.get instanceof Ev)){let n=e instanceof gg?this.decl(e):void 0,i=this.findMember(n,t);return i?i.async!==!1:r===`method`}return r!==`computed`&&this.hostMemberKind(n)!==`sync`}findMember(e,t){for(let n=e;n instanceof gg;n=n.original){let e=this.makers.get(this.decl(n).name)?.members.get(t);if(e)return e}}orderedArgs(e,t,n,r,i){let a=Object.entries(t).map(([e,t])=>{let i=[];return{k:e,r:this.val(t,n,r,i),buf:i}}),o=a.some(e=>e.buf.length>0||!e.r.pure),s=o&&!iy.test(e.code)?this.spill(e,i,`recv`):e.code,c={};for(let e of a)i.push(...e.buf),c[e.k]=o&&!e.r.pure&&e.r.sync===void 0?{...e.r,code:this.spill(e.r,i,e.k),pure:!0}:e.r;return{recv:s,args:c}}ordered(e,t){let n=e.map(e=>{let t=[];return{r:e(t),buf:t}}),r=n.reduce((e,t,n)=>t.buf.length?n:e,-1);return n.map((e,n)=>{if(t.push(...e.buf),n<r&&!e.r.pure&&!iy.test(e.r.code)){let n=this.uniq(`slot`);return t.push(`const ${n} = ${wy(e.r.code)};`),{...e.r,code:n,pure:!0}}return e.r})}nativeCtx(e,t,n,r,i){let a=e.code,o={};for(let[e,n]of Object.entries(t))o[e]=n.code;return{self:()=>a,once:()=>($v(a)||(a=this.spill({...e,code:a},i,`recv`)),a),discard:()=>{e.pure||i.push(`${wy(a)};`)},arg:e=>o[e],argOnce:e=>{let n=o[e];return n===void 0||$v(n)?n:(o[e]=this.spill({...t[e],code:n},i,e),o[e])},fn:e=>{let n=t[e];if(n)return{code:n.code,sync:!this.always&&n.sync===!0}},helper:e=>this.helper(e),aw:e=>this.aw(e,r),selfType:e.type,fields:()=>uy(e.type),guard:()=>n?this.guard(n):void 0,staticTypeName:()=>fy(e.type)}}withCatch(e,t,n,r,i,a){let o=this.uniq(`result`),s=this.uniq(`e`),c=this.uniq(`error`),l=this.helper(`$Throw`);a.push(`let ${o};`,`try {`,` ${o} = ${wy(e)};`,`} catch (${s}) {`,` if (!(${s} instanceof ${l})) throw ${s};`);let u=[`const ${c} = ${s}.error as any;`],d=new Map(r);d.set(`error`,{ts:c,type:this.registry.any()});let f=this.val(t,d,i,u);return u.push(`${o} = ${wy(f.code)};`),a.push(...vy(u),`}`),{code:o,type:n,pure:!0}}aw(e,t){return t.awaited=!0,`(await ${e})`}spill(e,t,n){if($v(e.code)||iy.test(e.code))return e.code;let r=this.uniq(n);return t.push(`const ${r} = ${wy(e.code)};`),r}typeOfExpr(e,t){let n=new Map;for(let[e,t]of this.engine.getGlobals())n.set(e,t.type);for(let[e,t]of Object.entries(this.opt.scope))n.set(e,t);for(let[e,r]of t)n.set(e,r.type);try{return e.typeOf(this.engine,n)}catch{return this.registry.any()}}};function oy(e){let t=e.call();return t?t.args instanceof vg?Object.values(t.args.fields).every(e=>e.type.isOptional()):!0:!1}function sy(e){return!!e.get||e.type instanceof Ag}function cy(e){return e instanceof vg||e instanceof jg||e instanceof gg&&cy(e.base)}function ly(e){if(e instanceof vg)return Object.entries(e.fields);if(e instanceof jg)return Object.entries(e._props);if(e instanceof gg){let t=ly(e.base);if(!t)return;let n=new Map(t);for(let[t,r]of Object.entries(e.local.props??{}))n.set(t,jh.from(r));return[...n]}}function uy(e){return(ly(e)??[]).filter(([,e])=>!e.get&&!e.type.call()).map(([e])=>e)}function dy(e){let t=ly(e);if(t)return new Map(t.filter(([,e])=>!e.get).map(([e,t])=>[e,t.type]))}function fy(e){if(!(e instanceof _g||e instanceof Ug||e instanceof bg||e instanceof Rg||e instanceof Sg||e instanceof Hg||e instanceof Bg))return e.name}function py(e){let t=e instanceof gg?e.base:e;return t instanceof Wg||t instanceof Vg||t instanceof Cg||t instanceof Dg}function my(e){return/\.(push|pop|shift|unshift|insert|remove|clear|delete|indexSet|setAt)$/.test(e)}function hy(e,t){return e instanceof $m?!0:!e||typeof e!=`object`?!1:!Array.isArray(e)&&typeof e.kind==`string`&&t.exprClass(e.kind)?!0:Object.values(e).some(e=>hy(e,t))}function gy(e,t){let n=Object.entries(e);return n.length===0?(t?.args instanceof vg?Object.values(t.args.fields):[]).some(e=>!e.type.isOptional()&&e.default===void 0)?`{} as any`:``:`{ ${n.map(([e,t])=>e===t.code?e:`${$v(e)?e:JSON.stringify(e)}: ${wy(t.code)}`).join(`, `)} }`}function _y(e){let t=e.options;if(t&&typeof t==`object`&&Object.keys(t).length!==0&&(e instanceof Vg||e instanceof Wg||e instanceof Ng||e instanceof Tg||e instanceof Gg))return`gin: ${e.toCode(void 0,{includeComments:!1})}`}function vy(e){return e.flatMap(e=>e.split(`
386
- `)).map(e=>e&&` ${e}`)}function yy(e){return e[e.length-1]===`}`}function by(e){if(e.length===0)return`{}`;let t=`{ ${e.join(`; `)} }`;return t.length<=80&&!t.includes(`
384
+ `)){let e=c[0].slice(7,-1);e.startsWith(`{`)&&(e=`(${e})`),m=`${l?`async `:``}${f}(${u})${d} => ${e}`}else m=[`${l?`async `:``}${f}(${u})${d} => {`,...by(c),`}`].join(`
385
+ `);return{code:`(${m})`,type:e.fnType,pure:!0,sync:!l}}newValue(e,t,n,r){let i=e.type,a=i.init();if(e.value!==void 0&&a){let t=a.run instanceof Ov?a.run.id:void 0;if(t!==`duration.init`&&t!==`color.init`)return this.problem(`new ${i.toCode()}: a constructor written in gin is not supported`),{code:`undefined as any`,type:i,pure:!0};let n=this.literal(a.args.parse(e.value).toLogical(),a.args);return{code:`${this.helper(t===`duration.init`?`$duration`:`$color`)}.init(${n})`,type:i,pure:!0}}if(e.value===void 0){let e=this.construct(i,this.literal(new W(i,i.create()).toLogical(),i));return{code:e,type:i,pure:!e.startsWith(`make`)}}let o=this.fill(e.value,i,t,n,r);return{code:o.code,type:i,pure:o.pure}}fill(e,t,n,r,i){let a=e instanceof th?e:Mh(e,t.scope??this.registry);if(a){let e=this.val(a,n,r,i);return{code:e.code,pure:e.pure}}if(!_y(e,this.registry))try{let n=this.construct(t,this.literal(t.parse(e).toLogical(),t));return{code:n,pure:!n.startsWith(`make`)}}catch(e){return this.problem(`new ${t.toCode()}: ${e instanceof Error?e.message:String(e)}`),{code:`undefined as any`,pure:!0}}if(t instanceof wg)return this.fill(e,t.simplify(),n,r,i);if(t instanceof Wg||t instanceof Hg)return e===void 0?{code:`undefined`,pure:!0}:e===null?{code:`null`,pure:!0}:this.fill(e,t.inner,n,r,i);let o=e=>this.ordered(e.map(([e,t,i])=>a=>{let o=this.fill(t,i,n,r,a);return{code:o.code,pure:o.pure,key:e}}),i);if(t instanceof Fg&&Array.isArray(e))return{code:`[${o(e.map(e=>[void 0,e,t.item])).map(e=>e.code).join(`, `)}]`,pure:!1};if(t instanceof Yg&&Array.isArray(e))return{code:`[${o(e.map((e,n)=>[void 0,e,t.elements[n]??this.registry.any()])).map(e=>e.code).join(`, `)}] as ${this.ref(t)}`,pure:!1};if(t instanceof zg&&Array.isArray(e)){let n=[];for(let r of e){let[e,i]=Array.isArray(r)?r:[r?.key,r?.value];n.push([void 0,e,t.key],[void 0,i,t.value])}let r=o(n),i=[];for(let e=0;e<r.length;e+=2)i.push(`[${r[e].code}, ${r[e+1].code}]`);return{code:`new Map<${this.ref(t.key)}, ${this.ref(t.value)}>([${i.join(`, `)}])`,pure:!1}}let s=dy(t);if(s&&e&&typeof e==`object`&&!Array.isArray(e)){let a=e,c=[],l=[];for(let[e,t]of s)e in a?c.push([e,a[e],t.type]):t.default&&l.push([e,t.default]);let u=o(c);for(let[e,t]of l)u.push({key:e,code:this.val(t,n,r,i).code});let d=u.map(e=>`${ty(e.key)?e.key:JSON.stringify(e.key)}: ${e.code}`);return{code:this.construct(t,`{ ${d.join(`, `)} }`),pure:!1}}return this.problem(`new ${t.toCode()}: payload shape not supported`),{code:`undefined as any`,pure:!0}}construct(e,t){let n=e instanceof vg&&!e.local.useSite?this.decl(e):void 0;if(n){this.define(n);let e=this.carriedMembers(n).map(([e])=>e);e.length&&this.problem(`new ${n.name}: its host member${e.length>1?`s`:``} ${e.join(`, `)} cannot be supplied in TypeScript \u2014 build the value on the host (\`make${this.tsName(n.name)}\` / \`${this.dataName(n)}\`) and pass it in`);let r=this.maker(n);if(r)return`${r.name}(${t})`}return t.startsWith(`[`)||t.startsWith(`{`)||n?`(${t} as ${this.ref(e)})`:t}literal(e,t){if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`number`)return Object.is(e,-0)?`-0`:Number.isFinite(e)?String(e):e>0?`Infinity`:e<0?`-Infinity`:`NaN`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(e instanceof Date)return`new Date(${JSON.stringify(e.toISOString())})`;let n=t instanceof vg?t.base:t instanceof Wg||t instanceof Hg?t.inner:t;if(e instanceof Map){let t=n instanceof zg?n.key:this.registry.any(),r=n instanceof zg?n.value:this.registry.any(),i=[...e].map(([e,n])=>`[${this.literal(e,t)}, ${this.literal(n,r)}]`);return`new Map<${this.ref(t)}, ${this.ref(r)}>([${i.join(`, `)}])`}if(Array.isArray(e)){if(n instanceof Yg)return`[${e.map((e,t)=>this.literal(e,n.elements[t]??this.registry.any())).join(`, `)}]`;let t=n instanceof Fg?n.item:this.registry.any();return`[${e.map(e=>this.literal(e,t)).join(`, `)}]`}if(typeof e==`object`){let n=new Map(dy(t)??[]);return`{ ${Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${ty(e)?e:JSON.stringify(e)}: ${this.literal(t,n.get(e)?.type??this.registry.any())}`).join(`, `)} }`}return`undefined`}set(e,t,n,r){let i=e.path.steps,a=this.val(e.value,t,n,r);if(i.length===1&&i[0]instanceof iv){let e=i[0].prop,o=this.lookup(e,t,n);if(!o){this.problem(`set: unknown variable '${e}'`);return}r.push(`${o.ts} = ${Ey(a.code)};`);return}let o=oy.test(a.code)?a.code:this.spill(a,r,`value`),s=i[i.length-1];if(s instanceof av){this.problem(`set: assigning through a method call is not supported`);return}let c=this.path(i.slice(0,-1),t,n,r);if(s instanceof iv){let e=c.type.prop(s.prop);if(e?.set){this.problem(`set: prop '${s.prop}' has a gin setter, which is not supported`);return}if(e?.get&&!e.type.call()){this.problem(`set: prop '${s.prop}' is computed and cannot be assigned`);return}r.push(`${ey(c.code,s.prop)} = ${o};`)}else if(s instanceof ov){let e=this.val(s.key,t,n,r).code,i=c.type.get(),a=i?.set instanceof Ov?i.set.id:void 0,l=a?$v[a]:void 0;if(!l){this.problem(`set: indexed assignment on '${c.type.toCode()}' is not supported`);return}r.push(`${l({self:c.code,key:e,value:o,helper:e=>this.helper(e)})};`)}}lookup(e,t,n){let r=t.get(e);if(r)return r;let i=this.engine.getGlobal(e),a=this.opt.scope[e]??i?.type;if(a)return n.ctxAllowed?(this.ctxVars.set(e,a),{ts:ey(`ctx`,e),type:a}):(this.problem(`'${e}' is read inside a gin-written member, where only this / args / recurse are in scope`),{ts:`undefined as any`,type:a})}path(e,t,n,r){let i;for(let a=0;a<e.length;a++){let o=e[a];if(o instanceof iv){if(!i){let e=this.lookup(o.prop,t,n);e?i={code:e.ts,type:e.type,pure:!0,sync:e.sync}:(this.problem(`unknown variable '${o.prop}'`),i={code:`undefined as any`,type:this.registry.any(),pure:!0});continue}this.touch(i.type);let s=i.type.prop(o.prop);if(!s){this.problem(`no prop '${o.prop}' on '${i.type.toCode()}' (the TypeScript export dispatches on the static type)`),i={code:ey(i.code,o.prop),type:this.registry.any(),pure:!1};continue}let c=s.type instanceof wg?s.type.simplify(i.type.scope):s.type,l=e[a+1];if(l instanceof av&&c.call()){i=this.invoke(i,o.prop,s,c,l,t,n,r),a++;continue}if(!(l instanceof av)&&cy(c)){i=this.invoke(i,o.prop,s,c,new av({}),t,n,r);continue}i=this.readProp(i,o.prop,s,c,n,r)}else{if(!i)return this.problem(`path: must start with a variable`),{code:`undefined as any`,type:this.registry.any(),pure:!0};if(o instanceof ov){this.touch(i.type);let e=i,a=[],s=this.val(o.key,t,n,a),c=a.length||!s.pure?this.spill(e,r,`recv`):e.code;r.push(...a);let l=e.type.get(),u=l?.get instanceof Ov?l.get.id:void 0,d=u?Qv[u]:void 0;d||this.problem(`indexing '${e.type.toCode()}' is not supported`),i={code:d?d({self:c,key:s.code,helper:e=>this.helper(e)}):`undefined as any`,type:l?.value??this.registry.any(),pure:!1}}else if(o instanceof av){let e=i.type,a=e.scope;try{a=o.callSiteScope(e)}catch(e){this.problem(String(e instanceof Error?e.message:e))}let s=e.call(a);s?.get&&this.problem(`calling a '${e.toCode()}' value implemented in gin is not supported`);let{recv:c,args:l}=this.orderedArgs(i,o.args,t,n,r),u=`${c}(${vy(l,s)})`;i.sync!==!0&&(u=this.aw(u,n));let d=s?.returns?.simplify(a)??s?.returns??this.registry.any();i=o.catch_?this.withCatch(u,o.catch_,d,t,n,r):{code:u,type:d,pure:!1}}}}return i??{code:`undefined as any`,type:this.registry.any(),pure:!0}}touch(e){e instanceof vg&&!e.local.useSite&&this.define(this.decl(e))}readProp(e,t,n,r,i,a){let o=n.get instanceof Ov?n.get.id:void 0,s=o?Zv[o]:void 0;if(s)return{code:s(this.nativeCtx(e,{},void 0,i,a)),type:r,pure:e.pure};let c=ey(e.code,t);return n.get&&this.memberAsync(e.type,t,n,`computed`)&&(c=this.aw(c,i)),{code:c,type:r,pure:e.pure&&!n.get}}invoke(e,t,n,r,i,a,o,s){let c=r.scope;try{c=i.callSiteScope(r)}catch(e){this.problem(String(e instanceof Error?e.message:e))}let l=r.call(c),u=l?.returns?.simplify(c)??l?.returns??this.registry.any(),d=n.get instanceof Ov?n.get.id:void 0,f=d?Zv[d]:void 0,{recv:p,args:m}=this.orderedArgs(e,i.args,a,o,s),h;if(f){let t=i.generic?.T?this.registry.parse(i.generic.T,c):void 0;h=f(this.nativeCtx({...e,code:p},m,t,o,s))}else h=`${ey(p,t)}(${vy(m,l)})`,this.memberAsync(e.type,t,n,`method`)&&(h=this.aw(h,o));return i.catch_?this.withCatch(h,i.catch_,u,a,o,s):{code:h,type:u,pure:!!f&&e.pure&&Object.values(m).every(e=>e.pure)&&!(d&&gy(d))}}memberAsync(e,t,n,r){if(n.get&&!(n.get instanceof Ov)){let n=e instanceof vg?this.decl(e):void 0,i=this.findMember(n,t);return i?i.async!==!1:r===`method`}return r!==`computed`&&this.hostMemberKind(n)!==`sync`}findMember(e,t){for(let n=e;n instanceof vg;n=n.original){let e=this.makers.get(this.decl(n).name)?.members.get(t);if(e)return e}}orderedArgs(e,t,n,r,i){let a=Object.entries(t).map(([e,t])=>{let i=[];return{k:e,r:this.val(t,n,r,i),buf:i}}),o=a.some(e=>e.buf.length>0||!e.r.pure),s=o&&!oy.test(e.code)?this.spill(e,i,`recv`):e.code,c={};for(let e of a)i.push(...e.buf),c[e.k]=o&&!e.r.pure&&e.r.sync===void 0?{...e.r,code:this.spill(e.r,i,e.k),pure:!0}:e.r;return{recv:s,args:c}}ordered(e,t){let n=e.map(e=>{let t=[];return{r:e(t),buf:t}}),r=n.reduce((e,t,n)=>t.buf.length?n:e,-1);return n.map((e,n)=>{if(t.push(...e.buf),n<r&&!e.r.pure&&!oy.test(e.r.code)){let n=this.uniq(`slot`);return t.push(`const ${n} = ${Ey(e.r.code)};`),{...e.r,code:n,pure:!0}}return e.r})}nativeCtx(e,t,n,r,i){let a=e.code,o={};for(let[e,n]of Object.entries(t))o[e]=n.code;return{self:()=>a,once:()=>(ty(a)||(a=this.spill({...e,code:a},i,`recv`)),a),discard:()=>{e.pure||i.push(`${Ey(a)};`)},arg:e=>o[e],argOnce:e=>{let n=o[e];return n===void 0||ty(n)?n:(o[e]=this.spill({...t[e],code:n},i,e),o[e])},fn:e=>{let n=t[e];if(n)return{code:n.code,sync:!this.always&&n.sync===!0}},helper:e=>this.helper(e),aw:e=>this.aw(e,r),selfType:e.type,fields:()=>fy(e.type),guard:()=>n?this.guard(n):void 0,staticTypeName:()=>my(e.type)}}withCatch(e,t,n,r,i,a){let o=this.uniq(`result`),s=this.uniq(`e`),c=this.uniq(`error`),l=this.helper(`$Throw`);a.push(`let ${o};`,`try {`,` ${o} = ${Ey(e)};`,`} catch (${s}) {`,` if (!(${s} instanceof ${l})) throw ${s};`);let u=[`const ${c} = ${s}.error as any;`],d=new Map(r);d.set(`error`,{ts:c,type:this.registry.any()});let f=this.val(t,d,i,u);return u.push(`${o} = ${Ey(f.code)};`),a.push(...by(u),`}`),{code:o,type:n,pure:!0}}aw(e,t){return t.awaited=!0,`(await ${e})`}spill(e,t,n){if(ty(e.code)||oy.test(e.code))return e.code;let r=this.uniq(n);return t.push(`const ${r} = ${Ey(e.code)};`),r}typeOfExpr(e,t){let n=new Map;for(let[e,t]of this.engine.getGlobals())n.set(e,t.type);for(let[e,t]of Object.entries(this.opt.scope))n.set(e,t);for(let[e,r]of t)n.set(e,r.type);try{return e.typeOf(this.engine,n)}catch{return this.registry.any()}}};function cy(e){let t=e.call();return t?t.args instanceof bg?Object.values(t.args.fields).every(e=>e.type.isOptional()):!0:!1}function ly(e){return!!e.get||e.type instanceof Mg}function uy(e){return e instanceof bg||e instanceof Ng||e instanceof vg&&uy(e.base)}function dy(e){if(e instanceof bg)return Object.entries(e.fields);if(e instanceof Ng)return Object.entries(e._props);if(e instanceof vg){let t=dy(e.base);if(!t)return;let n=new Map(t);for(let[t,r]of Object.entries(e.local.props??{}))n.set(t,Nh.from(r));return[...n]}}function fy(e){return(dy(e)??[]).filter(([,e])=>!e.get&&!e.type.call()).map(([e])=>e)}function py(e){let t=dy(e);if(t)return new Map(t.filter(([,e])=>!e.get).map(([e,t])=>[e,t.type]))}function my(e){if(!(e instanceof yg||e instanceof Gg||e instanceof Sg||e instanceof Bg||e instanceof wg||e instanceof Wg||e instanceof Hg))return e.name}function hy(e){let t=e instanceof vg?e.base:e;return t instanceof Kg||t instanceof Ug||t instanceof Tg||t instanceof kg}function gy(e){return/\.(push|pop|shift|unshift|insert|remove|clear|delete|indexSet|setAt)$/.test(e)}function _y(e,t){return e instanceof th?!0:!e||typeof e!=`object`?!1:!Array.isArray(e)&&typeof e.kind==`string`&&t.exprClass(e.kind)?!0:Object.values(e).some(e=>_y(e,t))}function vy(e,t){let n=Object.entries(e);return n.length===0?(t?.args instanceof bg?Object.values(t.args.fields):[]).some(e=>!e.type.isOptional()&&e.default===void 0)?`{} as any`:``:`{ ${n.map(([e,t])=>e===t.code?e:`${ty(e)?e:JSON.stringify(e)}: ${Ey(t.code)}`).join(`, `)} }`}function yy(e){let t=e.options;if(t&&typeof t==`object`&&Object.keys(t).length!==0&&(e instanceof Ug||e instanceof Kg||e instanceof Fg||e instanceof Dg||e instanceof qg))return`gin: ${e.toCode(void 0,{includeComments:!1})}`}function by(e){return e.flatMap(e=>e.split(`
386
+ `)).map(e=>e&&` ${e}`)}function xy(e){return e[e.length-1]===`}`}function Sy(e){if(e.length===0)return`{}`;let t=`{ ${e.join(`; `)} }`;return t.length<=80&&!t.includes(`
387
387
  `)&&!t.includes(`/**`)?t:`{
388
- ${vy(e.map(e=>`${e};`)).join(`
388
+ ${by(e.map(e=>`${e};`)).join(`
389
389
  `)}
390
- }`}function xy(e){return e.includes(`=>`)||e.includes(` | `)||e.includes(` & `)?`(${e})`:e}function Sy(e){let t=[];for(let n of e.map(e=>e.includes(`=>`)?`(${e})`:e))t.includes(n)||t.push(n);return t.join(` | `)}function Cy(e){return/^[\w$.]+(<.*>)?$/.test(e)&&!e.includes(` `)?`${e}[]`:`Array<${e}>`}function wy(e){if(!e.startsWith(`(`)||!e.endsWith(`)`))return e;let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===`(`)t++;else if(r===`)`){if(t--,t===0&&n<e.length-1)return e}else if(r===`"`||r==="`"||r===`'`)return e}return e.slice(1,-1)}function Ty(e){return e.replace(/\*\//g,`*\\/`)}function Ey(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function Dy(e){let t=e.replace(/[^\w$]+(.)/g,(e,t)=>t.toUpperCase());return t.charAt(0).toUpperCase()+t.slice(1)}function Oy(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)>>>0;return t.toString(36)}function ky(e,t,n={}){let r=e.registry.parseExpr(t),i=new ay(e,n),a=n.name??`main`,o=i.exportFunction(r,a);i.helpers.has(a)&&i.problem(`function name '${a}' is also the name of a helper the code needs \u2014 pick another`),i.check();let s=new Map(i.helpers);return n.prelude===`inline`&&s.size>0&&(o=`${[...s.values()].join(`
390
+ }`}function Cy(e){return e.includes(`=>`)||e.includes(` | `)||e.includes(` & `)?`(${e})`:e}function wy(e){let t=[];for(let n of e.map(e=>e.includes(`=>`)?`(${e})`:e))t.includes(n)||t.push(n);return t.join(` | `)}function Ty(e){return/^[\w$.]+(<.*>)?$/.test(e)&&!e.includes(` `)?`${e}[]`:`Array<${e}>`}function Ey(e){if(!e.startsWith(`(`)||!e.endsWith(`)`))return e;let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===`(`)t++;else if(r===`)`){if(t--,t===0&&n<e.length-1)return e}else if(r===`"`||r==="`"||r===`'`)return e}return e.slice(1,-1)}function Dy(e){return e.replace(/\*\//g,`*\\/`)}function Oy(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function ky(e){let t=e.replace(/[^\w$]+(.)/g,(e,t)=>t.toUpperCase());return t.charAt(0).toUpperCase()+t.slice(1)}function Ay(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)>>>0;return t.toString(36)}function jy(e,t,n={}){let r=e.registry.parseExpr(t),i=new sy(e,n),a=n.name??`main`,o=i.exportFunction(r,a);i.helpers.has(a)&&i.problem(`function name '${a}' is also the name of a helper the code needs \u2014 pick another`),i.check();let s=new Map(i.helpers);return n.prelude===`inline`&&s.size>0&&(o=`${[...s.values()].join(`
391
391
 
392
392
  `)}
393
393
 
394
- ${o}`,s.clear()),{code:o,types:new Map(i.types),helpers:s,functions:[a]}}var Ay=class{constructor(e){this.registry=e}registry;globals=new Map;registerGlobal(e,t){return this.globals.set(e,t),this}getGlobal(e){return this.globals.get(e)}getGlobals(){return this.globals}parse(e){if(!e||typeof e!=`object`||!(`kind`in e))throw Error(`engine.parse: expected ExprDef with kind, got ${typeof e}`);return e}createRootScope(e,t){let n=new nh(null,void 0,t);for(let[e,t]of this.globals)n.vars.set(e,G(t.type,t.value));if(e)for(let[t,r]of Object.entries(e))n.vars.set(t,r);return n}async run(e,t,n){let r=n?new cg(n):void 0;r?.check();let i=this.createRootScope(t,r);try{return await this.evaluate(e,i)}catch(e){if(e instanceof fh)return e.value??G(this.registry.void(),void 0);throw e}}typeOf(e,t){let n=t??this.globalTypeScope();return rh(this,e,n)}validate(e,t,n){let r=t??this.globalTypeScope();return ah(this,e,r,n)}toCode(e,t){return this.registry.toCode(e,t)}toGinCode(e,t){return this.registry.toGinCode(e,t)}toJSONCode(e,t=2){return this.registry.toJSONCode(e,t)}toTypeScript(e,t){return ky(this,e,t)}globalTypeScope(){let e=new Map;for(let[t,n]of this.globals)e.set(t,n.type);return e}async evaluate(e,t){return(e instanceof $m?e:this.registry.parseExpr(e)).evaluate(this,t)}async validateValue(e,t){let n=new Mm,r=e.type.constraints();if(r.length===0)return n;let i=t??this.createRootScope();for(let t=0;t<r.length;t++){let a=r[t],o=i.child({this:e});try{(await a.evaluate(this,o)).raw!==!0&&n.at(`constraint[${t}]`,()=>n.error(`constraint.failed`,`value failed constraint: ${a.toCode(this.registry,{expectsValue:!0})}`))}catch(e){n.at(`constraint[${t}]`,()=>n.error(`constraint.threw`,`constraint threw: ${e.message}`))}}return n}};function jy(e){return new Ay(e)}var My=`^[a-z]\\S*$`,Ny=`A fn's name, as your tools spell it.`;function Py(e){if(e.name!==`text`)return!1;let t=e.options;return typeof t==`object`&&!!t&&`pattern`in t&&t.pattern===`^[a-z]\\S*$`}var Fy=R.string().pattern(My).describe(Ny);function Iy(e){return R.codec(Fy,{decode:t=>e.fn(t)??Error(`${t} names no fn: write a fn's name as your tools spell it.`),encode:t=>e.name(t)})}var Ly=new WeakMap,Ry=0;function zy(e){if(e===void 0)return 0;let t=Ly.get(e);return t===void 0&&Ly.set(e,t=++Ry),t}var By=Am.declare().dynamic((e,t,n)=>({...Tm(e,n),FnName:t===void 0?Fy:Iy(t)}),{key:(e,t,n)=>`${km(e,n)}|${zy(t)}`,cacheSize:4}),Vy={result:e=>By.result(e)},Hy=e=>Py(e)?R.ref(`FnName`):void 0;function Uy(e,t={}){return e.toA({...t.scope===void 0?{}:{scope:t.scope},...t.includeDocs===void 0?{}:{includeDocs:t.includeDocs},...t.unknownKeys===void 0?{}:{unknownKeys:t.unknownKeys},override:Hy})}function Wy(e,t={}){return Vy.result(Uy(e,t))}var Gy=new WeakMap,Ky=new WeakMap;function qy(e,t){let n=t.unknownKeys??`strip`,r=Gy;t.scope!==void 0&&(r=Ky.get(t.scope)??new WeakMap,Ky.set(t.scope,r));let i=r.get(e)??new Map;r.set(e,i);let a=i.get(n);if(a!==void 0)return a;let o=Wy(e,{...t,includeDocs:`none`});return i.set(n,o),o}function Jy(e,t={}){return qy(e,t).bind(e.registry)}function Yy(e){return e.map(String).join(`.`)}function Xy(e,t,n={}){let r=Jy(e,n).render(Xl).parse(t,{inPlace:!1,...n.repair===void 0?{}:{repair:n.repair},...n.label===void 0?{}:{label:n.label}});return r.ok?{ok:!0,value:r.value}:{ok:!1,problems:r.issues.map(e=>({path:Yy(e.codePath),message:e.message})),message:r.message}}var Zy=v().regex(/^[a-z][A-Za-z0-9_-]{0,63}$/).brand(),Qy=`[A-Za-z0-9](?:[A-Za-z0-9-]|_(?![_.]|$))*`,$y=RegExp(`^${Qy}(?:\\.${Qy})*$`),eb=v().regex($y,"a fn name is letters, digits, `_` and `-` in dot-separated parts, each starting with a letter or digit, with no `__` and no part ending in `_`");function tb(e){if(!$y.test(e))return e.includes(`__`)?`${e} holds \`__\`, which separates the parts of the name the model calls it by: write one \`_\``:/(?:^|\.)_|_(?:\.|$)/.test(e)?`a part of ${e} starts or ends with \`_\`: start each part with a letter or digit and end it with no \`_\``:`${e} is not a fn name: letters, digits, \`_\` and \`-\` in dot-separated parts, each starting with a letter or digit`}function nb(e){let{system:t,local:n}=Nl(e);return`${t}__${n.replaceAll(`.`,`__`)}`}function rb(e){return e.length===64&&/_x[0-9a-f]{8}$/.test(e)}function ib(e){return nb(e).length>64}function ab(e){if(rb(e))return;let t=e.indexOf(`__`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+2).split(`__`).join(`.`);if(!Al.test(n)||!$y.test(r))return;let i=I.safeParse(`${n}/${r}`);return i.success&&!ib(i.data)&&nb(i.data)===e?i.data:void 0}function ob(e,t){let n=I.safeParse(e);if(n.success)return n.data;let r=t?.(e);return r===void 0?e.includes(`--`)?sb(e)??ab(e):ab(e)??sb(e):r}function sb(e){if(e.length>=64)return;let t=I.safeParse(e.replace(`__`,`/`).replaceAll(`--`,`.`));if(t.success)return t.data.replaceAll(`/`,`__`).replaceAll(`.`,`--`).replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,64)===e?t.data:void 0}S({model:Zy,fn:I,until:N}),S({model:Zy,fn:I,system:F});var cb=I.describe(Ny),lb=v().min(1).regex(/^\S+$/,`a type's name, with no spaces`);Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);var ub=/^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i;function db(e){try{let{protocol:t}=new URL(e);return t===`http:`||t===`https:`}catch{return!1}}var fb=v().regex(ub,`expected an http or https URL`).refine(db,`expected an http or https URL`);function pb(e){return fb.safeParse(e).success}var mb=`outsideImages`,hb=E([`ask`,`always`]),gb=S({value:hb,setBy:M.optional(),updatedAt:N.optional()}),_b=`https`,vb={der:`/harness-ca.crt`,pem:`/harness-ca.pem`},yb=E([`own`,`files`]),bb=S({on:b(),source:yb,setBy:M.optional(),updatedAt:N.optional(),fingerprint:v().optional(),authorityName:v().optional(),host:v(),links:x(v())}),xb=v().regex(/^(?:\*|[a-z*][a-z0-9*-]*\/[A-Za-z0-9_*][A-Za-z0-9_.*-]*)$/,`an agent's name (crm/reviewer) or a pattern (hub/chat*, crm/*, *)`).refine(e=>!e.includes(`**`),`write one *`),Sb=S({into:x(xb).min(1),order:y().int().min(0).max(1e3).default(100),requires:x(I).default([]),mode:E([`tools`,`static`]).optional(),replaces:x(I).optional()}),Cb=C([D(`none`),S({detail:E([`full`,`summary`]).default(`full`),maxTokens:y().int().min(1).optional()})]),wb=S({target:xb,agents:x(I)}),Tb=E([`approved`,`pending`,`declined`]);S({context:I,system:F,title:v(),inject:Sb,fns:x(I),targets:x(wb),agents:x(I),review:Tb,off:b(),dynamic:b()}),S({hook:I,system:F,explains:v(),review:Tb});var Eb=S({section:E([`context`,`hooks`]),name:I,title:v(),change:E([`added`,`changed`,`removed`]),tokens:y().int().min(0).optional(),targets:x(wb),agents:x(I),replaces:x(I).optional()});S({agent:I,context:I,on:b(),order:y().int().min(0).max(1e3).optional(),by:M,at:N});var Db=E([`off`,`pending`,`declined`,`system-off`,`fns-unusable`,`mode`,`replaced`,`no-fit`]),Ob=S({agent:I,context:I,source:w(`type`,[S({type:D(`context`)}),S({type:D(`hook`),hook:I})]),system:F,via:xb,title:v(),detail:E([`full`,`summary`]),text:v(),tokens:y().int().min(0),order:y().int(),on:b(),leftOut:S({why:Db,reason:v()}).optional(),switched:S({by:M,at:N}).optional()}),kb=S({injections:x(Ob),targets:x(wb)}),Ab=S({agent:I,context:I,on:b().optional(),order:y().int().min(0).max(1e3).nullable().optional()}),jb=[`listed`,`signature`,`full`],Mb=E(jb),Nb=S({fn:I,detail:Mb}),Pb=S({type:D(`tools`)}),Fb=E([`auto`,`native`,`text`]),Ib=E([`system-end`,`tail`]),Lb=w(`type`,[Pb,S({type:D(`static`),protocol:Fb.default(`auto`),placement:Ib.default(`system-end`),loadDetail:Mb.default(`full`)})]),Rb=E(Lb.options.map(e=>e.shape.type.value));E([`find`,`find_ctx`,`inspect`,`load`,`unload`,`run`]);var zb=S({fn:v().min(1).describe(`The fn to run, by its qualified name (fs/read).`),args:T(v(),Zc()).default({}).describe(`Its args, as its card shows them.`),on:L.optional().describe(`For a system with several machines connected, which one runs it (laptop).`)}),Bb=S({type:D(`plain`)}),Vb=S({type:D(`suggest`),topN:y().int().min(0).default(6),autoInject:S({tokens:y().int().min(0),items:y().int().min(0)}).optional()}),Hb=E([`embedding`,`words`,`turnsAgo`,`age`,`selectedBefore`,`used`]),Ub=S({weight:y().min(0),target:y().optional(),k:y().positive().optional()}),Wb=E([`perMessage`,`perIteration`]),Gb=[`history`,`context`,`fns`],Kb=E(Gb),qb=T(Kb,y().min(0)),Jb=w(`type`,[Bb,Vb,S({type:D(`graph`),metrics:bc(Hb,Ub).default({}),spread:S({damping:y().min(0).max(.95).default(.5),hops:y().int().min(0).max(4).default(2)}).prefault({}),floorExchanges:y().int().min(0).default(1),shares:qb.default({history:.45,context:.35,fns:.2}),threshold:y().min(0).default(.15),evaluate:Wb.default(`perMessage`)})]),Yb=E(Jb.options.map(e=>e.shape.type.value)),Xb=S({contextWindow:y().int().min(256).optional(),maxOutputTokens:y().int().min(16).optional(),reasoningTokens:y().int().min(0).optional(),charsPerToken:y().min(1).max(8).optional()}),Zb=Xb.keyof();Zb.options;var Qb=Xb.required(),$b=E([`admin`,`probe`,`model-info`,`default`]),ex=S({model:v(),limits:Qb,sources:T(Zb,$b),ratio:y()});S({model:v(),limits:Xb,setBy:M,updatedAt:N}),S({model:v(),ratio:y().min(.5).max(2),samples:y().int().min(0),updatedAt:N});var tx=S({asked:y().int().min(0),got:y().int().min(0)}),nx=S({window:y().int().min(0),output:y().int().min(0),reasoning:y().int().min(0),margin:y().int().min(0),fixed:y().int().min(0),pools:T(Kb,tx),estimate:y().int().min(0),cut:x(S({what:v(),why:v()}))}),rx=S({name:I,detail:Mb,activation:y().min(0)}),ix=S({tokens:y().int().min(0),items:x(S({name:I,detail:E([`full`,`summary`,`listed`]),tokens:y().int().min(0)})),leftOut:x(S({name:I,why:Db,reason:v()})),rebuilt:S({added:x(I),dropped:x(I)}).optional()}),ax=S({contextor:Yb,mode:Rb,context:x(rx),fns:x(rx),linear:y().int().min(0),earlier:x(y().int().min(0)),budget:nx,injected:ix.optional()}),ox=S({session:j,text:v().min(1),model:v().min(1).optional(),count:x(v()).max(200).optional()}),sx=S({agent:I,model:v(),window:y().int().min(0),maxTokens:y().int().min(0),estimate:y().int().min(0),system:v(),tools:x(S({name:v(),description:v(),parameters:Zc(),tokens:y().int().min(0)})),messages:x(S({role:v(),content:v(),tokens:y().int().min(0)})),parts:S({instructions:v(),injected:v(),context:v(),guide:v(),tokens:S({instructions:y().int(),injected:y().int(),context:y().int(),guide:y().int(),system:y().int()})}),counts:x(y().int().min(0)),report:ax}),cx=S({turn:al,items:x(rx),at:N}),lx=[`none`,`read`,`write`,`delete`,`auto`],ux=E(lx),dx=S({name:v().optional(),sheetName:v().optional(),sheetIndex:y().int().nonnegative().optional(),headers:x(v()),rows:x(x(v()))});E([`empty`,`boolean`,`integer`,`number`,`date`,`text`]);var fx=E([`file`,`folder`,`link`,`other`]);S({entries:x(S({name:v(),location:v(),kind:fx,type:v().optional(),size:y().nonnegative().optional(),modifiedAt:y().optional()})),truncated:b(),total:y().int().nonnegative()});var px={converter:v(),from:v(),title:v().optional(),metadata:T(v(),sc()).optional()},mx=w(`kind`,[S({kind:D(`markdown`),...px,text:v()}),S({kind:D(`text`),...px,text:v()}),S({kind:D(`code`),...px,language:v(),text:v()}),S({kind:D(`pages`),...px,pages:x(v())}),S({kind:D(`table`),...px,tables:x(dx)})]),hx=mx.options.map(e=>e.shape.kind.value),gx=/^(?:true|false|yes|no)$/i,_x=/^[-+]?\d{1,15}$/,vx=/^[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)?(?:\.\d+)?(?:e[-+]?\d+)?%?$/i,yx=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[-+]\d{2}:?\d{2})?)?$|^\d{1,2}\/\d{1,2}\/\d{2,4}$/;function bx(e){return gx.test(e)?`boolean`:_x.test(e)?`integer`:/\d/.test(e)&&vx.test(e)?`number`:yx.test(e)&&!Number.isNaN(Date.parse(e))?`date`:`text`}function xx(e,t){return e===`empty`||e===t?t:e===`integer`&&t===`number`||e===`number`&&t===`integer`?`number`:`text`}function Sx(e){let t=Math.max(e.headers.length,...e.rows.map(e=>e.length));return Array.from({length:t},(t,n)=>{let r=`empty`;for(let t of e.rows){let e=(t[n]??``).trim();e!==``&&(r=xx(r,bx(e)))}return r})}var Cx=Wc([v().regex(/^[a-z][a-z0-9+.-]*$/),`://`,v()]),wx=v().min(1).brand(),Tx=`^[0-9a-f]{64}$`,Ex=new RegExp(Tx),Dx=S({hash:v().regex(Ex),size:y().int().min(0),mime:v()});S({content:Dx,mime:v(),finalUrl:v(),status:y().int(),rendered:b(),title:v().optional()});var Ox=S({uri:Cx,name:v(),description:v(),index:E([`all`,`on-read`,`none`]),ignore:x(v()),watch:b()}),kx=S({uri:Cx,name:v(),type:E([`folder`,`file`,`page`,`record`,`other`]),mime:v().optional(),format:v().optional(),size:y().int().min(0).optional(),modifiedAt:N.optional(),version:v()}),Ax=S({uri:Cx.optional(),raw:v(),kind:E([`child`,`import`,`link`,`embed`,`external`]),title:v().optional()}),jx=E([`links`,`text`,`bytes`]),Mx=C([S({inline:v()}),S({ref:Dx})]),Nx=S({stat:kx,links:x(Ax).optional(),text:Mx.optional(),bytes:Dx.optional()});E(hx);var Px=[`description`,`ocr`,`transcript`,`thumbnail`];E(Px);var Fx=E([...hx,...Px]),Ix=S({key:wx,path:x(v()),title:v(),start:y().int().min(0),end:y().int().min(0),embedText:v().optional(),form:Fx.optional()}),Lx=S({uri:Cx,change:E([`added`,`changed`,`removed`]),version:v().optional()}),Rx=S({format:v().optional(),mime:v().optional(),glob:v().optional(),form:Fx.optional()}),zx=C([S({resource:Cx,section:wx.optional(),title:v().optional()}),S({url:fb,title:v()}),S({file:Dx,title:v()}),S({run:A,title:v()})]),Bx=S({uri:Cx,section:wx.optional(),title:v(),preview:v(),rank:y()}),Vx=Gi();function Hx(e,t){return Vx.add(e,{why:t}),e}function Ux(e){let t=e;for(;t!==void 0;){if(Vx.has(t))return!0;t=t instanceof Tc||t instanceof jc||t instanceof Nc||t instanceof kc||t instanceof Vc?t.unwrap():void 0}return!1}function Wx(e){let t=e.shape;return Object.entries(t).filter(([,e])=>Ux(e)).map(([e])=>e)}var Gx=new WeakMap;function Kx(e,t){return Gx.set(e,{schema:t}),e}var qx=w(`to`,[S({to:D(`session`),session:j}),S({to:D(`user`),user:M}),S({to:D(`everyone`)})]),Jx=E([`live`,`snapshot`]),Yx=w(`type`,[S({type:D(`system`)}),S({type:D(`memory`),scope:qx,author:M,run:A.optional()}),S({type:D(`resource`),uri:Cx,section:wx.optional(),version:v(),copy:Jx})]),Xx=[`system`,`memory`,`resource`],Zx=S({full:y().int().min(0),summary:y().int().min(0)}),Qx=E([`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`mentions`,`about`,`learned`]),$x=[`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`about`],eS=E($x),tS=w(`kind`,[S({kind:D(`context`),name:I}),S({kind:D(`fn`),name:cb}),S({kind:D(`type`),name:I}),S({kind:D(`resource`),uri:Cx,section:wx.optional()})]),nS=[`fn`,`context`,`resource`,`type`],rS=S({to:tS,relation:eS,weight:y().min(0).max(1).default(.5)}),iS=E([`declared`,`mentioned`,`resource`,`learned`,`authored`]),aS=S({from:I,to:tS,toKey:v(),relation:Qx,weight:y().min(0).max(1),source:iS,uses:y().min(0).optional(),by:M.optional(),updatedAt:N}),oS=S({weight:y().min(0).max(2).optional(),summary:v().optional(),tags:x(v().min(1)).optional(),fns:x(cb).optional(),suggestFns:x(cb).optional(),inject:Hx(Sb.optional(),`a model never writes text that lands in later prompts`),command:v().regex(/^[a-z][a-z0-9-]*$/).optional(),visible:Il.optional(),suggest:Il.optional(),parent:I.optional()}),sS=S({text:v().min(1),title:v().optional(),scope:E([`session`,`user`,`everyone`]).default(`session`),about:x(tS).optional()}).extend(oS.shape),cS=oS.keyof().exclude(oS.keyof().options.filter(e=>Wx(oS).includes(e))),lS=sS.omit({scope:!0}).partial().extend({name:I,clear:Kx(x(oS.keyof()).optional(),x(cS).optional())}),uS=S({uri:Cx,sections:x(wx).optional(),copy:Jx.default(`live`)}).extend(oS.omit({summary:!0,parent:!0}).shape),dS=S({created:x(I),updated:x(I),links:y().int().min(0)}),fS={maxDepth:3,maxDecisions:256,maxTokens:8e3};y().int().min(1).max(65535).default({hub:4300,web:4310,mockHub:4320}.hub);function pS(e){return e.split(`/`).filter((e,t)=>t!==0||e!==``).map(e=>e.startsWith(`:`)?{t:`param`,k:e.slice(1)}:{t:`lit`,v:e})}function mS(e){return`/`+e.map(e=>e.t===`param`?`:${e.k}`:e.v).join(`/`)}function hS(e,t){return`/`+e.map(e=>{if(e.t===`lit`)return e.v;let n=t[e.k];if(n===void 0)throw Error(`path is missing a value for ":${e.k}"`);return encodeURIComponent(String(n))}).join(`/`)}function gS(e){return e.filter(e=>e.t===`param`).map(e=>e.k)}var _S=class extends Error{status;code;data;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.data=r,this.name=`ApiError`}},vS=()=>{let e=globalThis.navigator;return typeof e?.onLine==`boolean`?e.onLine:void 0};function yS(e={}){let t=new Set,n=e.initial??(vS()===!1?`offline`:`online`),r=e=>{if(e!==n){n=e;for(let n of[...t])n(e)}},i=e=>(t.add(e),()=>void t.delete(e)),a=()=>{},o=globalThis;if((e.browser??!0)&&typeof o.addEventListener==`function`&&typeof o.removeEventListener==`function`){let e=()=>r(`online`),t=()=>r(`offline`);o.addEventListener(`online`,e),o.addEventListener(`offline`,t),a=()=>{o.removeEventListener(`online`,e),o.removeEventListener(`offline`,t)}}return{get status(){return n},subscribe:i,whenOnline:(e,t)=>new Promise((r,a)=>{if(n===`online`){r();return}if(e?.aborted){a(e.reason);return}let o=null,s=t=>{l(),o&&clearTimeout(o),e?.removeEventListener(`abort`,c),t()};function c(){s(()=>a(e.reason))}let l=i(e=>{e===`online`&&s(r)});t?.timeout!==void 0&&(o=setTimeout(()=>s(r),t.timeout)),e?.addEventListener(`abort`,c,{once:!0})}),report:r,dispose:()=>{a(),a=()=>{}}}}var bS=e=>{if(Array.isArray(e))return e.map(bS);if(e&&typeof e==`object`){let t={};for(let n of Object.keys(e).sort())t[n]=bS(e[n]);return t}return e},xS=e=>JSON.stringify(bS(e))??`null`,SS=e=>{try{return JSON.stringify(e)!==void 0}catch{return!1}},CS=(e,t)=>({get:n=>e.getItem(t+n)??void 0,set:(n,r)=>e.setItem(t+n,r),delete:n=>{let r=t+n,i=e.getItem(r)!==null;return e.removeItem(r),i},keys:function*(){for(let n=0;n<e.length;n++){let r=e.key(n);r!==null&&r.startsWith(t)&&(yield r.slice(t.length))}}}),wS=(e,t)=>{if(typeof e==`object`)return e;if(e!==`memory`)try{let n=e===`local`?globalThis.localStorage:globalThis.sessionStorage;if(n)return CS(n,t)}catch{}let n=new Map;return{get:e=>n.get(e),set:(e,t)=>void n.set(e,t),delete:e=>n.delete(e),keys:()=>n.keys()}};function TS(e={}){let t=e.max??500,n=e.ttl??0,r=e.now??Date.now,i=wS(e.store??`memory`,e.prefix??`ayepi:cache:`),a=new Map;for(let e of i.keys())a.set(e,!0);let o=e=>{a.delete(e),a.set(e,!0)},s=e=>{let t=i.get(e);if(t!==void 0)try{return JSON.parse(t)}catch{i.delete(e);return}},c=e=>(a.delete(e),i.delete(e)),l=()=>{for(;a.size>t;)c(a.keys().next().value)};return{read:e=>{let t=s(e);if(!t)return;let n=r();if(t.exp&&n>=t.exp){if(!t.stale||n>=t.stale){c(e);return}return o(e),{value:t.v,stale:!0}}return o(e),{value:t.v,stale:!1}},write:(e,t,a)=>{if(!SS(t))return;let s=a?.ttl??n,c=s>0?r()+s:0,u={v:t,exp:c,stale:c&&a?.staleWhileRevalidate?c+a.staleWhileRevalidate:0,tags:a?.tags??[]};i.set(e,JSON.stringify(u)),o(e),l()},remove:e=>void c(e),removeWhere:e=>{let t=0;for(let n of[...i.keys()])e(n)&&c(n)&&(t+=1);return t},invalidateTags:e=>{if(e.length===0)return 0;let t=new Set(e),n=0;for(let e of[...i.keys()]){let r=s(e);r&&r.tags.some(e=>t.has(e))&&c(e)&&(n+=1)}return n},clear:()=>{for(let e of[...i.keys()])i.delete(e);a.clear()}}}function ES(e={},t=yS()){let n=new Map,r=t=>{let r=t??e.store??`memory`,i=n.get(r);return i||(i=TS({...e,store:r}),n.set(r,i)),i};return{cacheFor:r,invalidateTags:e=>{r(void 0);for(let t of n.values())t.invalidateTags(e)},connectivity:t}}var DS=class extends Error{constructor(e=`caller rate limit exceeded`){super(e),this.name=`CallerRateLimited`}},OS=`\0`,kS=e=>new DOMException(e,`AbortError`),AS=e=>{let t=e.filter(e=>e!==void 0);if(t.length===1)return t[0];let n=new AbortController,r=()=>{n.abort();for(let e of t)e.removeEventListener(`abort`,r)};for(let e of t){if(e.aborted)return n.abort(),n.signal;e.addEventListener(`abort`,r,{once:!0})}return n.signal},jS=(e,t)=>new Promise((n,r)=>{if(t.aborted){r(kS(`aborted`));return}let i=()=>{clearTimeout(a),r(kS(`aborted`))},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e);t.addEventListener(`abort`,i,{once:!0})}),MS=(e,t)=>t.reduceRight((e,t)=>t(e),e),NS=(e,t,n)=>e===void 0?[]:typeof e==`function`?e(t,n):e,PS=(e,t)=>n=>async(r,i)=>{t.n+=1,e.onStart?.(r.data);try{let t=await n(r,i);return e.onSuccess?.(t,r.data),t}catch(t){throw e.onError?.(t,r.data),t}finally{--t.n,e.onSettled?.(r.data)}},FS=(e,t,n)=>r=>async(i,a)=>{t!==`success`&&n.invalidateTags(NS(e,i.data,void 0));let o=await r(i,a);return t!==`start`&&n.invalidateTags(NS(e,i.data,o)),o},IS=(e,t,n)=>r=>async(i,a)=>{let o=n(i.data),s=n=>t.write(o,n,{ttl:e.ttl,staleWhileRevalidate:e.staleWhileRevalidate,tags:NS(e.tags,i.data,n)}),c=t.read(o);if(c&&!c.stale)return c.value;if(c&&c.stale)return r(i,a).then(s).catch(()=>{}),c.value;let l=await r(i,a);return s(l),l},LS=e=>{let t=new Map;return n=>(r,i)=>{let a=e(r.data),o=t.get(a);if(o)return o;let s=n(r,i).finally(()=>t.delete(a));return t.set(a,s),s}},RS=()=>{let e=null;return t=>(n,r)=>{e?.abort(kS(`superseded`));let i=new AbortController;e=i;let a=AS([r,i.signal]);return new Promise((e,r)=>{a.addEventListener(`abort`,()=>r(kS(`superseded`)),{once:!0}),t(n,a).then(e,r)}).finally(()=>{e===i&&(e=null)})}},zS=e=>{let t=e.onLimit??`wait`,n=e.window/e.limit,r=e.limit,i=Date.now(),a=()=>{let t=Date.now(),n=(t-i)/e.window*e.limit;n>0&&(r=Math.min(e.limit,r+n),i=t)};return e=>async(i,o)=>{if(a(),r<1){if(t===`throw`||t===`drop`)throw new DS;await jS((1-r)*n,o),a()}return--r,e(i,o)}},BS=e=>{let t=e.attempts??3,n=e.base??200,r=e.factor??2,i=e.max??3e4,a=e.jitter??.5;return e=>async(o,s)=>{let c;for(let l=1;l<=t;l+=1)try{return await e(o,s)}catch(e){if(c=e,l>=t)break;await jS(Math.min(i,n*r**(l-1))*(1-a*Math.random()),s)}throw c}},VS=e=>e instanceof _S&&e.status===0&&e.code===`DISCONNECTED`,HS=(e,t)=>{let n=e.maxRetries??1/0,r=e.backoff??1e3;return i=>async(a,o)=>{let s=e.timeout===void 0?1/0:Date.now()+e.timeout,c=0;for(;;)try{return await i(a,o)}catch(e){if(!VS(e)||c>=n)throw e;let i=s-Date.now();if(i<=0)throw e;c+=1,await t.connectivity.whenOnline(o,{timeout:Math.min(r,i)})}}},US=(e,t)=>{let n=null,r=[],i=0;return a=>{let o=t=>{n&&=(clearTimeout(n),null);let o=r;r=[],i=0;let s=o.map(e=>e.call.data);a(e.accumulate?{data:e.accumulate(s),opts:o[o.length-1].call.opts}:o[o.length-1].call,t).then(t=>{let n=e.spread?e.spread(t,s):null;o.forEach((e,r)=>e.resolve(n?n[r]:t))},e=>o.forEach(t=>t.reject(e)))};return t.push(()=>{n&&=(clearTimeout(n),null);let e=r;r=[],i=0;for(let t of e)t.reject(kS(`cancelled`))}),(t,a)=>new Promise((s,c)=>{let l=Date.now();r.length===0&&(i=l),r.push({call:t,resolve:s,reject:c});let u=e.leading&&n===null&&r.length===1;n&&clearTimeout(n);let d=e.maxWait!==void 0&&l-i>=e.maxWait;if(u||d){o(a);return}let f=e.maxWait===void 0?e.wait:Math.min(e.wait,i+e.maxWait-l);n=setTimeout(()=>o(a),f)})}};function WS(e,t,n,r,i){if(t.items||t.itemsIn||t.streamIn!==null||t.streamOut!==null)return{call:(...e)=>n(...e),cancel:()=>{},invalidate:()=>{},pending:0};let a=t.p.length>0||t.q.length>0||t.hasBody||t.f.length>0,o=i.cache===!0||i.cache===void 0||i.cache===!1?{}:i.cache,s=e=>o.key?o.key(e):xS(e),c=t=>`${e}${OS}${s(t)}`,l=i.cache?r.cacheFor(o.store):null,u={n:0},d=[],f=new AbortController,p=(e,t)=>{let r={...e.opts??{},signal:t};return Promise.resolve(a?n(e.data,r):n(r))},m=[];if((i.onStart||i.onSuccess||i.onError||i.onSettled)&&m.push(PS(i,u)),i.invalidates&&m.push(FS(i.invalidates,i.invalidateOn??`success`,r)),l&&m.push(IS(o,l,c)),i.dedupe&&m.push(LS(c)),i.lastOnly&&m.push(RS()),i.debounce!==void 0){let e=typeof i.debounce==`number`?{wait:i.debounce}:i.debounce;m.push(US(e,d))}i.rateLimit&&m.push(zS(i.rateLimit)),i.retry&&m.push(BS(i.retry));let h=t.sideEffects===!1||t.sideEffects===void 0&&t.method===`GET`,ee=i.replay===!1?null:i.replay===void 0?h?{}:null:typeof i.replay==`object`?i.replay:{};ee&&(h||ee.force)&&m.push(HS(ee,r)),(i.onOnline||i.onOffline)&&r.connectivity.subscribe(e=>e===`online`?i.onOnline?.():i.onOffline?.());let te=MS(p,m);return{call:(...e)=>{let t=a?e[0]:void 0,n=a?e[1]:e[0],r=AS([n?.signal,f.signal]);return te({data:t,opts:n},r)},cancel:()=>{f.abort(kS(`cancelled`)),f=new AbortController;for(let e of d)e()},invalidate:()=>void l?.removeWhere(t=>t.startsWith(`${e}${OS}`)),get pending(){return u.n}}}function GS(e){try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}}function KS(e){let{id:t,...n}=e;return JSON.stringify({rid:typeof t==`string`?t:null,...n})}function qS(e){let{rid:t,...n}=e;return JSON.stringify(typeof t==`string`?{id:t,...n}:n)}function JS(e,t){return JSON.stringify({id:e,$status:0,$code:`DISCONNECTED`,$error:t})}function YS(e){return`$status`in e||e.end===!0}var XS=class{#e=new Set;add(e){this.#e.add(e)}settle(e){typeof e.id==`string`&&YS(e)&&this.#e.delete(e.id)}fail(e,t){let n=[...this.#e];this.#e.clear();for(let r of n)e(JS(r,t))}},ZS={$status:501,$code:`NOT_SERVED`,$error:`this client serves no spec`};function QS(e,t){let n=e.rid;typeof n==`string`&&typeof e.type==`string`&&t(JSON.stringify({rid:n,...ZS}))}var $S=class{app;send;request;#e=null;constructor(e,t,n){this.app=e,this.send=t,this.request=n}receive(e){let t=this.#e??this.#t();this.app.ws.message(t,qS(e))}drop(){let e=this.#e;e&&(this.#e=null,this.app.ws.close(e))}#t(){let e=this.app.ws.open(t=>{let n=GS(t);n&&this.#e===e&&this.send(KS(n))},this.request());return this.#e=e,e}},eC=new Set([101,204,205,304]);function tC(e,t,n,r,i,a){return new Promise((o,s)=>{if(i?.aborted){s(new DOMException(`The operation was aborted.`,`AbortError`));return}let c=new XMLHttpRequest;c.open(e,t,!0),c.responseType=`arraybuffer`;for(let[e,t]of Object.entries(n))c.setRequestHeader(e,t);c.upload.onprogress=e=>{e.lengthComputable&&a({loaded:e.loaded,total:e.total})};let l=()=>c.abort(),u=()=>i?.removeEventListener(`abort`,l);c.onload=()=>{u();let e=eC.has(c.status)?null:c.response;o(new Response(e,{status:c.status,statusText:c.statusText}))},c.onerror=()=>{u(),s(TypeError(`Network request failed`))},c.onabort=()=>{u(),s(new DOMException(`The operation was aborted.`,`AbortError`))},i?.addEventListener(`abort`,l,{once:!0}),c.send(r)})}function nC(e){return!!e&&typeof e.parse==`function`}function rC(e){let t=iC(e);return t?t():e}function iC(e){let t=e[Symbol.for(`ayepi.manifest`)];return typeof t==`function`?t:void 0}function aC(e){return typeof e==`number`&&e>=200&&e<300}var oC={400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,409:`Conflict`,410:`Gone`,422:`Unprocessable Entity`,429:`Too Many Requests`,500:`Internal Server Error`,502:`Bad Gateway`,503:`Service Unavailable`};function sC(e){let t=Number(e.$status);return new _S(t,typeof e.$code==`string`?e.$code:`ERROR`,typeof e.$error==`string`?e.$error:oC[t]??`Request failed with status ${t}`,e.data)}function cC(e){let t=rC(e.manifest),n=e.fetchImpl??(e=>fetch(e)),r=yS(),i=ES(e.cache,r);e.ws?.onState?.(e=>r.report(e===`open`?`online`:`offline`));let a=()=>typeof e.headers==`function`?e.headers():e.headers??{},o=t=>e.unauthorized!==void 0&&Object.keys(t).some(e=>e.toLowerCase()===`authorization`),s=null,c=()=>{let t=e.unauthorized;return t?(s??=t().catch(()=>!1).finally(()=>{s=null}),s):Promise.resolve(!1)},l=t=>e.validate?.endpoints[t]?.cfg,u=(e,t)=>{let n=l(e);return n?.response?n.response.parse(t):t},d=(e,t)=>{let n=l(e);return n&&nC(n.streamOut)?n.streamOut.parse(t):t},f=(e,t,n)=>{let r=l(e)?.responses?.[t];return r?r.parse(n):n},p=0,m=new Map,h=new Map,ee=new Map,te=new Map,ne=new Map,re=(t,n,r)=>{r&&o(a())&&ne.set(t,n),e.ws?.send(n)},ie=e=>{let t=te.get(e);t&&(te.delete(e),t())},ae=(t,n,r)=>{if(!n)return;let i=()=>{te.delete(t),ne.delete(t),r(n.reason)&&e.ws?.send(JSON.stringify({id:t,abort:!0}))};n.aborted?i():(n.addEventListener(`abort`,i,{once:!0}),te.set(t,()=>n.removeEventListener(`abort`,i)))},oe=e=>JSON.stringify(e??{},Object.keys(e??{}).sort());if(e.ws){let t=e.ws,n=e=>t.send(e),r=e.serve?new $S(e.serve,n,()=>new Request(new URL(e.baseUrl,`http://peer.invalid/`))):null;r&&t.onState?.(e=>{e!==`open`&&r.drop()}),t.onMessage(e=>{let i=GS(e);if(!i)return;if(`rid`in i){r?r.receive(i):QS(i,n);return}if(typeof i.id!=`string`){if(typeof i.type==`string`){let e=`${i.type}|${oe(i.params)}`;for(let t of ee.get(e)??[])t(i.data)}return}let a=i.id,o=ne.get(a);ne.delete(a),o!==void 0&&i.$status===401?c().then(e=>{(m.has(a)||h.has(a))&&(e?t.send(o):se(a,i))}):se(a,i)})}function se(e,t){let n=`$status`in t&&!aC(t.$status);if(h.has(e)){let r=h.get(e);`chunk`in t?r.push(t.chunk):t.end===!0?(h.delete(e),ie(e),r.end()):n&&(h.delete(e),ie(e),r.fail(sC(t)))}else if(m.has(e)){let r=m.get(e);m.delete(e),ie(e),n?r.reject(sC(t)):r.resolve(t.data)}}function ce(){let e=[],t=!1,n,r=null;return{push(t){e.push(t),r?.()},end(){t=!0,r?.()},fail(e){n=e,t=!0,r?.()},async*iterate(){for(;;)if(e.length>0)yield e.shift();else{if(n!==void 0)throw n;if(t)return;await new Promise(e=>r=e),r=null}}}}function le(t,n){let r=typeof n==`function`?n():n;(async()=>{try{for await(let n of r)e.ws.send(JSON.stringify({id:t,chunk:n}));e.ws.send(JSON.stringify({id:t,end:!0}))}catch{e.ws.send(JSON.stringify({id:t,end:!0}))}})()}function ue(e,t,n){return JSON.stringify(t.ws===null?{id:e,type:t.path,method:t.method,data:n}:{id:e,type:t.ws,data:n})}function de(t,n,r,i,a){if(!e.ws){let e=Error(`no websocket transport configured`);if(!n.items)return Promise.reject(e);throw e}let o=`c${++p}`;if(n.items){let e=ce();return h.set(o,e),ae(o,a,t=>h.delete(o)?(e.fail(t),!0):!1),re(o,ue(o,n,r),!n.itemsIn),n.itemsIn&&le(o,i),(async function*(){for await(let n of e.iterate())yield d(t,n)})()}let s=new Promise((e,t)=>{m.set(o,{resolve:e,reject:t}),ae(o,a,e=>{let t=m.get(o);return t?(m.delete(o),t.reject(e),!0):!1}),re(o,ue(o,n,r),!1)});return n.itemsIn&&le(o,i),s.then(e=>n.multi?e:u(t,e))}function fe(t,n){if(!e.ws)return Promise.reject(Error(`no websocket transport configured`));let r=`c${++p}`;return new Promise((e,i)=>{m.set(r,{resolve:e,reject:i}),ae(r,n,e=>{let t=m.get(r);return t?(m.delete(r),t.reject(e),!0):!1}),re(r,JSON.stringify({id:r,...t}),!0)})}function g(e,t){if(e.b===`raw`)return{p:{},q:{},b:t,f:{}};let n={},r={},i={},a={},o=new Set(e.p),s=new Set(e.q),c=new Set(e.b??[]),l=new Set(e.f);for(let[e,u]of Object.entries(t??{}))if(o.has(e))n[e]=u;else if(s.has(e))r[e]=u;else if(c.has(e))i[e]=u;else if(l.has(e))a[e]=u;else throw Error(`key "${e}" does not belong to endpoint data`);return{p:n,q:r,b:e.hasBody?i:void 0,f:a}}function pe(t,n,r){let i=hS(pS(t.path),n),a=new URL(i.slice(1),e.baseUrl.endsWith(`/`)?e.baseUrl:e.baseUrl+`/`);for(let[e,t]of Object.entries(r))if(t!==void 0){if(Array.isArray(t))for(let n of t)a.searchParams.append(e,String(n));else a.searchParams.set(e,String(t))}return a}function me(e){let t=(typeof e==`function`?e():e)[Symbol.asyncIterator](),n=new TextEncoder;return new ReadableStream({async pull(e){let{done:r,value:i}=await t.next();if(r)return e.close();e.enqueue(n.encode(JSON.stringify(i)+`
395
- `))},async cancel(){await t.return?.(void 0)}})}async function he(e,t,i,s=!1){let{p:l,q:u,b:d,f}=g(e,t),p=i?.stream,m=pe(e,l,u),h={...a(),...i?.headers??{}},ee=null,te=!1;if(e.streamIn)h[`content-type`]=e.streamIn,e.itemsIn?(ee=me(p),te=!0):(ee=p,te=p instanceof ReadableStream);else if(e.f.length>0){let e=new FormData;d!==void 0&&e.set(`body`,JSON.stringify(d));for(let[t,n]of Object.entries(f))if(n!==void 0){if(Array.isArray(n))for(let r of n)e.append(t,r);else e.set(t,n)}ee=e}else if(e.hasBody){if(e.bodyEnc===`urlencoded`){h[`content-type`]=`application/x-www-form-urlencoded`;let e=new URLSearchParams;for(let[t,n]of Object.entries(d??{}))if(n!==void 0){if(Array.isArray(n))for(let r of n)e.append(t,String(r));else e.set(t,String(n))}ee=e.toString()}else h[`content-type`]=`application/json`,ee=JSON.stringify(d)}let ne={method:e.method,headers:h,body:ee,signal:i?.signal};te&&(ne.duplex=`half`);let re=i?.onUploadProgress,ie;try{ie=re&&!e.streamIn&&!e.streamOut&&typeof XMLHttpRequest<`u`?await tC(e.method,m.toString(),h,ee,i?.signal,re):await n(new Request(m,ne))}catch(e){throw e instanceof TypeError?(r.report(`offline`),new _S(0,`DISCONNECTED`,`network request failed`)):e}if(r.report(`online`),ie.status===401&&!s&&e.streamIn===null&&o(h)&&await c())return await ie.body?.cancel().catch(()=>{}),he(e,t,i,!0);if(!ie.ok){let e=await ie.json().catch(()=>({})),t=e?.error;throw new _S(ie.status,t?.code??`ERROR`,t?.message,e)}return ie}async function ge(e,t,n,r){let i=await he(t,n,r);if(t.streamOut)return i.body??new ReadableStream({start:e=>e.close()});if(t.multi)return{status:i.status,data:f(e,i.status,await i.json())};if(i.status!==204)return u(e,await i.json())}async function*_e(e,t,n,r){let i=await he(t,n,r);if(!i.body)return;let a=t.streamOut===`text/event-stream`,o=a?`
394
+ ${o}`,s.clear()),{code:o,types:new Map(i.types),helpers:s,functions:[a]}}var My=class{constructor(e){this.registry=e}registry;globals=new Map;registerGlobal(e,t){return this.globals.set(e,t),this}getGlobal(e){return this.globals.get(e)}getGlobals(){return this.globals}parse(e){if(!e||typeof e!=`object`||!(`kind`in e))throw Error(`engine.parse: expected ExprDef with kind, got ${typeof e}`);return e}createRootScope(e,t){let n=new ih(null,void 0,t);for(let[e,t]of this.globals)n.vars.set(e,G(t.type,t.value));if(e)for(let[t,r]of Object.entries(e))n.vars.set(t,r);return n}async run(e,t,n){let r=n?new ug(n):void 0;r?.check();let i=this.createRootScope(t,r);try{return await this.evaluate(e,i)}catch(e){if(e instanceof mh)return e.value??G(this.registry.void(),void 0);throw e}}typeOf(e,t){let n=t??this.globalTypeScope();return ah(this,e,n)}validate(e,t,n){let r=t??this.globalTypeScope();return sh(this,e,r,n)}toCode(e,t){return this.registry.toCode(e,t)}toGinCode(e,t){return this.registry.toGinCode(e,t)}toJSONCode(e,t=2){return this.registry.toJSONCode(e,t)}toTypeScript(e,t){return jy(this,e,t)}globalTypeScope(){let e=new Map;for(let[t,n]of this.globals)e.set(t,n.type);return e}async evaluate(e,t){return(e instanceof th?e:this.registry.parseExpr(e)).evaluate(this,t)}async validateValue(e,t){let n=new Pm,r=e.type.constraints();if(r.length===0)return n;let i=t??this.createRootScope();for(let t=0;t<r.length;t++){let a=r[t],o=i.child({this:e});try{(await a.evaluate(this,o)).raw!==!0&&n.at(`constraint[${t}]`,()=>n.error(`constraint.failed`,`value failed constraint: ${a.toCode(this.registry,{expectsValue:!0})}`))}catch(e){n.at(`constraint[${t}]`,()=>n.error(`constraint.threw`,`constraint threw: ${e.message}`))}}return n}};function Ny(e){return new My(e)}var Py=`^[a-z]\\S*$`,Fy=`A fn's name, as your tools spell it.`;function Iy(e){if(e.name!==`text`)return!1;let t=e.options;return typeof t==`object`&&!!t&&`pattern`in t&&t.pattern===`^[a-z]\\S*$`}var Ly=R.string().pattern(Py).describe(Fy);function Ry(e){return R.codec(Ly,{decode:t=>e.fn(t)??Error(`${t} names no fn: write a fn's name as your tools spell it.`),encode:t=>e.name(t)})}var zy=new WeakMap,By=0;function Vy(e){if(e===void 0)return 0;let t=zy.get(e);return t===void 0&&zy.set(e,t=++By),t}var Hy=Mm.declare().dynamic((e,t,n)=>({...Dm(e,n),FnName:t===void 0?Ly:Ry(t)}),{key:(e,t,n)=>`${jm(e,n)}|${Vy(t)}`,cacheSize:4}),Uy={result:e=>Hy.result(e)},Wy=e=>Iy(e)?R.ref(`FnName`):void 0;function Gy(e,t={}){return e.toA({...t.scope===void 0?{}:{scope:t.scope},...t.includeDocs===void 0?{}:{includeDocs:t.includeDocs},...t.unknownKeys===void 0?{}:{unknownKeys:t.unknownKeys},override:Wy})}function Ky(e,t={}){return Uy.result(Gy(e,t))}var qy=new WeakMap,Jy=new WeakMap;function Yy(e,t){let n=t.unknownKeys??`strip`,r=qy;t.scope!==void 0&&(r=Jy.get(t.scope)??new WeakMap,Jy.set(t.scope,r));let i=r.get(e)??new Map;r.set(e,i);let a=i.get(n);if(a!==void 0)return a;let o=Ky(e,{...t,includeDocs:`none`});return i.set(n,o),o}function Xy(e,t={}){return Yy(e,t).bind(e.registry)}function Zy(e){return e.map(String).join(`.`)}function Qy(e,t,n={}){let r=Xy(e,n).render(Ql).parse(t,{inPlace:!1,...n.repair===void 0?{}:{repair:n.repair},...n.label===void 0?{}:{label:n.label}});return r.ok?{ok:!0,value:r.value}:{ok:!1,problems:r.issues.map(e=>({path:Zy(e.codePath),message:e.message})),message:r.message}}var $y=v().regex(/^[a-z][A-Za-z0-9_-]{0,63}$/).brand(),eb=`[A-Za-z0-9](?:[A-Za-z0-9-]|_(?![_.]|$))*`,tb=RegExp(`^${eb}(?:\\.${eb})*$`),nb=v().regex(tb,"a fn name is letters, digits, `_` and `-` in dot-separated parts, each starting with a letter or digit, with no `__` and no part ending in `_`");function rb(e){if(!tb.test(e))return e.includes(`__`)?`${e} holds \`__\`, which separates the parts of the name the model calls it by: write one \`_\``:/(?:^|\.)_|_(?:\.|$)/.test(e)?`a part of ${e} starts or ends with \`_\`: start each part with a letter or digit and end it with no \`_\``:`${e} is not a fn name: letters, digits, \`_\` and \`-\` in dot-separated parts, each starting with a letter or digit`}function ib(e){let{system:t,local:n}=Fl(e);return`${t}__${n.replaceAll(`.`,`__`)}`}function ab(e){return e.length===64&&/_x[0-9a-f]{8}$/.test(e)}function ob(e){return ib(e).length>64}function sb(e){if(ab(e))return;let t=e.indexOf(`__`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+2).split(`__`).join(`.`);if(!Ml.test(n)||!tb.test(r))return;let i=I.safeParse(`${n}/${r}`);return i.success&&!ob(i.data)&&ib(i.data)===e?i.data:void 0}function cb(e,t){let n=I.safeParse(e);if(n.success)return n.data;let r=t?.(e);return r===void 0?e.includes(`--`)?lb(e)??sb(e):sb(e)??lb(e):r}function lb(e){if(e.length>=64)return;let t=I.safeParse(e.replace(`__`,`/`).replaceAll(`--`,`.`));if(t.success)return t.data.replaceAll(`/`,`__`).replaceAll(`.`,`--`).replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,64)===e?t.data:void 0}S({model:$y,fn:I,until:N}),S({model:$y,fn:I,system:F});var ub=I.describe(Fy),db=v().min(1).regex(/^\S+$/,`a type's name, with no spaces`);Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);var fb=/^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i;function pb(e){try{let{protocol:t}=new URL(e);return t===`http:`||t===`https:`}catch{return!1}}var mb=v().regex(fb,`expected an http or https URL`).refine(pb,`expected an http or https URL`);function hb(e){return mb.safeParse(e).success}var gb=`outsideImages`,_b=E([`ask`,`always`]),vb=S({value:_b,setBy:M.optional(),updatedAt:N.optional()}),yb=`https`,bb={der:`/harness-ca.crt`,pem:`/harness-ca.pem`},xb=E([`own`,`files`]),Sb=S({on:b(),source:xb,setBy:M.optional(),updatedAt:N.optional(),fingerprint:v().optional(),authorityName:v().optional(),host:v(),links:x(v())}),Cb=v().regex(/^(?:\*|[a-z*][a-z0-9*-]*\/[A-Za-z0-9_*][A-Za-z0-9_.*-]*)$/,`an agent's name (crm/reviewer) or a pattern (hub/chat*, crm/*, *)`).refine(e=>!e.includes(`**`),`write one *`),wb=S({into:x(Cb).min(1),order:y().int().min(0).max(1e3).default(100),requires:x(I).default([]),mode:E([`tools`,`static`]).optional(),replaces:x(I).optional()}),Tb=C([D(`none`),S({detail:E([`full`,`summary`]).default(`full`),maxTokens:y().int().min(1).optional()})]),Eb=S({target:Cb,agents:x(I)}),Db=E([`approved`,`pending`,`declined`]);S({context:I,system:F,title:v(),inject:wb,fns:x(I),targets:x(Eb),agents:x(I),review:Db,off:b(),dynamic:b()}),S({hook:I,system:F,explains:v(),review:Db});var Ob=S({section:E([`context`,`hooks`]),name:I,title:v(),change:E([`added`,`changed`,`removed`]),tokens:y().int().min(0).optional(),targets:x(Eb),agents:x(I),replaces:x(I).optional()});S({agent:I,context:I,on:b(),order:y().int().min(0).max(1e3).optional(),by:M,at:N});var kb=E([`off`,`pending`,`declined`,`system-off`,`fns-unusable`,`mode`,`replaced`,`no-fit`]),Ab=S({agent:I,context:I,source:w(`type`,[S({type:D(`context`)}),S({type:D(`hook`),hook:I})]),system:F,via:Cb,title:v(),detail:E([`full`,`summary`]),text:v(),tokens:y().int().min(0),order:y().int(),on:b(),leftOut:S({why:kb,reason:v()}).optional(),switched:S({by:M,at:N}).optional()}),jb=S({injections:x(Ab),targets:x(Eb)}),Mb=S({agent:I,context:I,on:b().optional(),order:y().int().min(0).max(1e3).nullable().optional()}),Nb=[`listed`,`signature`,`full`],Pb=E(Nb),Fb=S({fn:I,detail:Pb}),Ib=S({type:D(`tools`)}),Lb=E([`auto`,`native`,`text`]),Rb=E([`system-end`,`tail`]),zb=w(`type`,[Ib,S({type:D(`static`),protocol:Lb.default(`auto`),placement:Rb.default(`system-end`),loadDetail:Pb.default(`full`)})]),Bb=E(zb.options.map(e=>e.shape.type.value));E([`find`,`find_ctx`,`inspect`,`load`,`unload`,`run`]);var Vb=S({fn:v().min(1).describe(`The fn to run, by its qualified name (fs/read).`),args:T(v(),Zc()).default({}).describe(`Its args, as its card shows them.`),on:L.optional().describe(`For a system with several machines connected, which one runs it (laptop).`)}),Hb=S({type:D(`plain`)}),Ub=S({type:D(`suggest`),topN:y().int().min(0).default(6),autoInject:S({tokens:y().int().min(0),items:y().int().min(0)}).optional()}),Wb=E([`embedding`,`words`,`turnsAgo`,`age`,`selectedBefore`,`used`]),Gb=S({weight:y().min(0),target:y().optional(),k:y().positive().optional()}),Kb=E([`perMessage`,`perIteration`]),qb=[`history`,`context`,`fns`],Jb=E(qb),Yb=T(Jb,y().min(0)),Xb=w(`type`,[Hb,Ub,S({type:D(`graph`),metrics:bc(Wb,Gb).default({}),spread:S({damping:y().min(0).max(.95).default(.5),hops:y().int().min(0).max(4).default(2)}).prefault({}),floorExchanges:y().int().min(0).default(1),shares:Yb.default({history:.45,context:.35,fns:.2}),threshold:y().min(0).default(.15),evaluate:Kb.default(`perMessage`)})]),Zb=E(Xb.options.map(e=>e.shape.type.value)),Qb=S({contextWindow:y().int().min(256).optional(),maxOutputTokens:y().int().min(16).optional(),reasoningTokens:y().int().min(0).optional(),charsPerToken:y().min(1).max(8).optional()}),$b=Qb.keyof();$b.options;var ex=Qb.required(),tx=E([`admin`,`probe`,`model-info`,`default`]),nx=S({model:v(),limits:ex,sources:T($b,tx),ratio:y()});S({model:v(),limits:Qb,setBy:M,updatedAt:N}),S({model:v(),ratio:y().min(.5).max(2),samples:y().int().min(0),updatedAt:N});var rx=S({asked:y().int().min(0),got:y().int().min(0)}),ix=S({window:y().int().min(0),output:y().int().min(0),reasoning:y().int().min(0),margin:y().int().min(0),fixed:y().int().min(0),pools:T(Jb,rx),estimate:y().int().min(0),cut:x(S({what:v(),why:v()}))}),ax=S({name:I,detail:Pb,activation:y().min(0)}),ox=S({tokens:y().int().min(0),items:x(S({name:I,detail:E([`full`,`summary`,`listed`]),tokens:y().int().min(0)})),leftOut:x(S({name:I,why:kb,reason:v()})),rebuilt:S({added:x(I),dropped:x(I)}).optional()}),sx=S({contextor:Zb,mode:Bb,context:x(ax),fns:x(ax),linear:y().int().min(0),earlier:x(y().int().min(0)),budget:ix,injected:ox.optional()}),cx=S({session:j,text:v().min(1),model:v().min(1).optional(),count:x(v()).max(200).optional()}),lx=S({agent:I,model:v(),window:y().int().min(0),maxTokens:y().int().min(0),estimate:y().int().min(0),system:v(),tools:x(S({name:v(),description:v(),parameters:Zc(),tokens:y().int().min(0)})),messages:x(S({role:v(),content:v(),tokens:y().int().min(0)})),parts:S({instructions:v(),injected:v(),context:v(),guide:v(),tokens:S({instructions:y().int(),injected:y().int(),context:y().int(),guide:y().int(),system:y().int()})}),counts:x(y().int().min(0)),report:sx}),ux=S({turn:sl,items:x(ax),at:N}),dx=[`none`,`read`,`write`,`delete`,`auto`],fx=E(dx),px=S({name:v().optional(),sheetName:v().optional(),sheetIndex:y().int().nonnegative().optional(),headers:x(v()),rows:x(x(v()))});E([`empty`,`boolean`,`integer`,`number`,`date`,`text`]);var mx=E([`file`,`folder`,`link`,`other`]);S({entries:x(S({name:v(),location:v(),kind:mx,type:v().optional(),size:y().nonnegative().optional(),modifiedAt:y().optional()})),truncated:b(),total:y().int().nonnegative()});var hx={converter:v(),from:v(),title:v().optional(),metadata:T(v(),sc()).optional()},gx=w(`kind`,[S({kind:D(`markdown`),...hx,text:v()}),S({kind:D(`text`),...hx,text:v()}),S({kind:D(`code`),...hx,language:v(),text:v()}),S({kind:D(`pages`),...hx,pages:x(v())}),S({kind:D(`table`),...hx,tables:x(px)})]),_x=gx.options.map(e=>e.shape.kind.value),vx=/^(?:true|false|yes|no)$/i,yx=/^[-+]?\d{1,15}$/,bx=/^[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)?(?:\.\d+)?(?:e[-+]?\d+)?%?$/i,xx=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[-+]\d{2}:?\d{2})?)?$|^\d{1,2}\/\d{1,2}\/\d{2,4}$/;function Sx(e){return vx.test(e)?`boolean`:yx.test(e)?`integer`:/\d/.test(e)&&bx.test(e)?`number`:xx.test(e)&&!Number.isNaN(Date.parse(e))?`date`:`text`}function Cx(e,t){return e===`empty`||e===t?t:e===`integer`&&t===`number`||e===`number`&&t===`integer`?`number`:`text`}function wx(e){let t=Math.max(e.headers.length,...e.rows.map(e=>e.length));return Array.from({length:t},(t,n)=>{let r=`empty`;for(let t of e.rows){let e=(t[n]??``).trim();e!==``&&(r=Cx(r,Sx(e)))}return r})}var Tx=Wc([v().regex(/^[a-z][a-z0-9+.-]*$/),`://`,v()]),Ex=v().min(1).brand(),Dx=`^[0-9a-f]{64}$`,Ox=new RegExp(Dx),kx=S({hash:v().regex(Ox),size:y().int().min(0),mime:v()});S({content:kx,mime:v(),finalUrl:v(),status:y().int(),rendered:b(),title:v().optional()});var Ax=S({uri:Tx,name:v(),description:v(),index:E([`all`,`on-read`,`none`]),ignore:x(v()),watch:b()}),jx=S({uri:Tx,name:v(),type:E([`folder`,`file`,`page`,`record`,`other`]),mime:v().optional(),format:v().optional(),size:y().int().min(0).optional(),modifiedAt:N.optional(),version:v()}),Mx=S({uri:Tx.optional(),raw:v(),kind:E([`child`,`import`,`link`,`embed`,`external`]),title:v().optional()}),Nx=E([`links`,`text`,`bytes`]),Px=C([S({inline:v()}),S({ref:kx})]),Fx=S({stat:jx,links:x(Mx).optional(),text:Px.optional(),bytes:kx.optional()});E(_x);var Ix=[`description`,`ocr`,`transcript`,`thumbnail`];E(Ix);var Lx=E([..._x,...Ix]),Rx=S({key:Ex,path:x(v()),title:v(),start:y().int().min(0),end:y().int().min(0),embedText:v().optional(),form:Lx.optional()}),zx=S({uri:Tx,change:E([`added`,`changed`,`removed`]),version:v().optional()}),Bx=S({format:v().optional(),mime:v().optional(),glob:v().optional(),form:Lx.optional()}),Vx=C([S({resource:Tx,section:Ex.optional(),title:v().optional()}),S({url:mb,title:v()}),S({file:kx,title:v()}),S({run:A,title:v()})]),Hx=S({uri:Tx,section:Ex.optional(),title:v(),preview:v(),rank:y()}),Ux=Gi();function Wx(e,t){return Ux.add(e,{why:t}),e}function Gx(e){let t=e;for(;t!==void 0;){if(Ux.has(t))return!0;t=t instanceof Tc||t instanceof jc||t instanceof Nc||t instanceof kc||t instanceof Vc?t.unwrap():void 0}return!1}function Kx(e){let t=e.shape;return Object.entries(t).filter(([,e])=>Gx(e)).map(([e])=>e)}var qx=new WeakMap;function Jx(e,t){return qx.set(e,{schema:t}),e}var Yx=w(`to`,[S({to:D(`session`),session:j}),S({to:D(`user`),user:M}),S({to:D(`everyone`)})]),Xx=E([`live`,`snapshot`]),Zx=w(`type`,[S({type:D(`system`)}),S({type:D(`memory`),scope:Yx,author:M,run:A.optional()}),S({type:D(`resource`),uri:Tx,section:Ex.optional(),version:v(),copy:Xx})]),Qx=[`system`,`memory`,`resource`],$x=S({full:y().int().min(0),summary:y().int().min(0)}),eS=E([`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`mentions`,`about`,`learned`]),tS=[`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`about`],nS=E(tS),rS=w(`kind`,[S({kind:D(`context`),name:I}),S({kind:D(`fn`),name:ub}),S({kind:D(`type`),name:I}),S({kind:D(`resource`),uri:Tx,section:Ex.optional()})]),iS=[`fn`,`context`,`resource`,`type`],aS=S({to:rS,relation:nS,weight:y().min(0).max(1).default(.5)}),oS=E([`declared`,`mentioned`,`resource`,`learned`,`authored`]),sS=S({from:I,to:rS,toKey:v(),relation:eS,weight:y().min(0).max(1),source:oS,uses:y().min(0).optional(),by:M.optional(),updatedAt:N}),cS=S({weight:y().min(0).max(2).optional(),summary:v().optional(),tags:x(v().min(1)).optional(),fns:x(ub).optional(),suggestFns:x(ub).optional(),inject:Wx(wb.optional(),`a model never writes text that lands in later prompts`),command:v().regex(/^[a-z][a-z0-9-]*$/).optional(),visible:Rl.optional(),suggest:Rl.optional(),parent:I.optional()}),lS=S({text:v().min(1),title:v().optional(),scope:E([`session`,`user`,`everyone`]).default(`session`),about:x(rS).optional(),question:v().min(1).max(500).optional(),when:v().min(1).max(500).optional()}).extend(cS.shape),uS=cS.keyof().exclude(cS.keyof().options.filter(e=>Kx(cS).includes(e))),dS=lS.omit({scope:!0}).partial().extend({name:I,clear:Jx(x(cS.keyof()).optional(),x(uS).optional())}),fS=S({uri:Tx,sections:x(Ex).optional(),copy:Xx.default(`live`)}).extend(cS.omit({summary:!0,parent:!0}).shape),pS=S({created:x(I),updated:x(I),links:y().int().min(0)}),mS={maxDepth:3,maxDecisions:256,maxTokens:8e3},hS=[`active`,`hidden`,`not_applicable`,`pending_approval`,`pending_removal`,`pending_plan`],gS=E(hS),_S=E([`active`,`hidden`,`not_applicable`,`pending_approval`,`pending_removal`]);function vS(e){return e===`active`||e===`pending_removal`}var yS=[`person`,`system`,`research`],bS=E(yS),xS=S({status:gS,from:gS.optional(),by:M,reason:v().optional(),at:N}),SS=S({of:I,similarity:y().min(0).max(1).optional(),reason:v(),at:N}),CS=E([`question`,`when`,`askedBy`,`validUntil`]),wS=S({model:v(),at:N,contentHash:v(),fields:x(CS)}),TS=S({from:I.optional(),into:x(I).optional()}),ES=`newContextStatus`,DS=E([`active`,`pending_approval`,`hidden`]),OS=S({value:DS,setBy:M.optional(),updatedAt:N.optional()}),kS=E([`question`,`content`]),AS=S({statuses:x(_S).min(1).optional(),returnNotApplicable:b().optional(),semanticOver:kS.optional()}),jS=[`approve`,`hide`,`restore`,`confirm_removal`],MS=E(jS),NS=S({names:x(I).min(1).max(200),action:MS,reason:v().min(1).max(500).optional()}),PS=S({changed:x(S({name:I,status:C([gS,D(`removed`)])})),skipped:x(S({name:I,reason:v()}))}),FS=[`duplicate`,`contradiction`,`pending_approval`,`pending_removal`],IS=E(FS),LS=S({kinds:x(IS).min(1).optional(),systems:x(v().min(1)).min(1).optional(),limit:y().int().min(1).max(200).optional(),cursor:v().optional()}),RS=S({name:I,system:v(),title:v(),question:v().optional(),status:gS,statusReason:v().optional(),lastModified:N,excerpt:v().optional()}),zS=S({items:x(S({kind:IS,item:RS,other:RS.optional(),flag:SS.optional()})),next:v().optional(),counts:S({duplicate:y().int().min(0),contradiction:y().int().min(0),pending_approval:y().int().min(0),pending_removal:y().int().min(0)})}),BS=S({keep:I,drop:I,reason:v().min(1).max(500).optional()}),VS=S({kept:I,hidden:I,links:y().int().min(0),mentions:y().int().min(0)}),HS=S({name:I,of:I}),US=S({names:x(I).min(1).max(20)}),WS=S({done:x(S({name:I,fields:x(CS),split:x(I).optional()})),failed:x(S({name:I,reason:v()}))}),GS=S({name:I,question:v().optional(),when:v().optional(),askedBy:bS.optional(),validUntil:N.optional(),lastModified:N,status:gS,statusReason:v().optional(),statusHistory:x(xS),metadata:wS.optional(),metadataStale:b(),duplicate:SS.optional(),contradiction:SS.optional(),notDuplicates:x(I),split:TS.optional()}),KS={openQuestions:60,depth:6,minutes:10,cost:2},qS=S({openQuestions:y().int().min(1).max(500).optional().describe(`The most open (unanswered) questions the plan may hold; planning stops when it is reached. Default 60.`),depth:y().int().min(1).max(12).optional().describe(`How many levels of questions deep the plan may go (1: only the first questions and their options). Default 6.`),minutes:y().min(.1).max(120).optional().describe(`The most minutes planning may take. Default 10.`),cost:y().min(0).max(100).optional().describe(`The most US dollars the model calls may cost. Default 2.`)}),JS=S({openQuestions:y().int().min(1),depth:y().int().min(1),minutes:y().min(0),cost:y().min(0)}),YS=E([`complete`,`open_questions`,`depth`,`time`,`cost`,`stopped`]),XS={complete:`Every question has its options`,open_questions:`Stopped at the open-question limit`,depth:`Stopped at the depth limit`,time:`Stopped at the time limit`,cost:`Stopped at the cost limit`,stopped:`Stopped before it finished`},ZS=v().regex(/^o\d+$/),QS=S({id:ZS,label:v().min(1).max(200),detail:v().max(1e3).optional(),raises:x(I),later:x(v().min(1).max(500)).optional()}),$S=S({question:I,option:ZS}),eC=S({name:I,question:v().min(1),askedBy:bS.optional(),depth:y().int().min(1),parents:x($S),options:x(QS),planned:b(),known:b().optional(),picked:x(ZS),text:v().max(4e3).optional(),answeredBy:M.optional(),answeredAt:N.optional(),status:gS,statusReason:v().optional(),reasonEdited:b().optional()}),tC=S({questions:y().int().min(0),answered:y().int().min(0),open:y().int().min(0),ruledOut:y().int().min(0),decide:y().int().min(0)}),nC=S({description:v().min(1),limits:JS,stop:YS,cost:P,time:y().min(0),startedAt:N,updatedAt:N,roots:x(I),questions:x(eC),counts:tC,revision:y().int().min(0)}),rC=S({description:v().trim().min(1).max(4e3).describe(`What is to be planned, in the person's words with whatever they said about it: the more it says, the better the questions.`),limits:qS.optional()}),iC=S({run:A.describe(`The run of hub/ctx_plan that made the plan (its id, such as run_01HZX3).`)}),aC=iC.extend({format:E([`plan`,`markdown`]).optional().describe("`plan` (the default): the plan itself; `markdown`: the questions, answers and what was ruled out, as markdown to read or share.")}),oC=S({run:A,plan:nC,markdown:v().optional()}),sC=S({question:I.describe(`The question, by its context name as the plan gives it.`),picked:x(v().min(1)).max(20).describe(`The options chosen, by id (o1) or label; several when more than one applies. Empty with no text clears the answer.`),text:v().max(4e3).optional().describe(`The person's own words with the answer: a detail, a condition, or an answer none of the options gives.`)}),cC=S({question:I,reason:v().trim().min(1).max(500)}),lC=iC.extend({answers:x(sC).max(100).optional(),reasons:x(cC).max(100).optional()}),uC=S({run:A,plan:nC,changed:x(S({name:I,status:gS})),deeper:x(I),skipped:x(S({question:v(),reason:v()}))}),dC=iC.extend({under:I.optional().describe(`The question to plan deeper under, by its context name; leave out to go on with the whole plan.`),replan:b().optional().describe(`Write the options of the open questions under it again, taking the answers given since into account (after an answer changed).`),limits:qS.optional().describe("Limits of its own. Its `depth` is counted from the question it plans under (1: only the questions right under it), or, without `under`, from the deepest level that already has options.")}),fC=S({run:A,description:v(),counts:tC,stop:YS.optional(),running:b(),actor:M,session:v().optional(),createdAt:N,updatedAt:N}),pC=S({limit:y().int().min(1).max(100).optional()}),mC=S({items:x(fC)});function hC(e){return e.known===!0||e.picked.length>0||(e.text??``).trim()!==``}function gC(e){return e.options.filter(t=>e.picked.includes(t.id)).map(e=>e.label)}function _C(e){let t=gC(e).map(e=>`"${e}"`);return`${t.length>0?t.join(` and `):`none of the options`} for '${e.question}'`}function vC(e){return`You chose ${_C(e)}`}function yC(e,t){return`'${e.question}' no longer applies${t===void 0?``:`: you chose ${_C(t)}`}`}function bC(e,t){return e.picked.length===0||e.picked.includes(t)}function xC(e,t){let n=new Set(t),r=[...t];for(let t=r.shift();t!==void 0;t=r.shift()){let i=e.get(t);if(i!==void 0){for(let t of i.options)if(bC(i,t.id))for(let i of t.raises)!n.has(i)&&e.has(i)&&(n.add(i),r.push(i))}}return n}function SC(e,t){return e.picked.length>0&&!e.picked.includes(t)}function CC(e){let t=new Map(e.questions.map(e=>[e.name,e])),n=xC(t,e.roots.filter(e=>{let n=(t.get(e)?.parents??[]).filter(n=>n.question!==e&&t.has(n.question));return n.length===0?t.has(e):!n.every(e=>{let n=t.get(e.question);return n!==void 0&&SC(n,e.option)})})),r=e=>e.parents.flatMap(n=>{let r=t.get(n.question);return r===void 0||n.question===e.name?[]:[{edge:n,parent:r}]}),i=e=>{let t=r(e).filter(e=>SC(e.parent,e.edge.option)).map(e=>e.parent);return t.find(e=>n.has(e.name))??t[0]},a=(e,t)=>{if(t.has(e.name))return;t.add(e.name);let n=i(e);if(n!==void 0)return n;for(let{parent:n}of r(e)){let e=a(n,t);if(e!==void 0)return e}},o=new Map;for(let t of e.questions){if(n.has(t.name)){o.set(t.name,{live:!0});continue}let e=i(t);if(e!==void 0){o.set(t.name,{live:!1,reason:vC(e)});continue}let s=r(t)[0]?.parent;s===void 0?o.set(t.name,{live:!1,reason:`It no longer sits under any question of the plan`}):o.set(t.name,{live:!1,reason:yC(s,a(s,new Set([t.name])))})}return o}function wC(e){return`${e.answered} answered · ${e.open} open · ${e.decide} ${e.decide===1?`decision`:`decisions`} to make now`}y().int().min(1).max(65535).default({hub:4300,web:4310,mockHub:4320}.hub);function TC(e){return e.split(`/`).filter((e,t)=>t!==0||e!==``).map(e=>e.startsWith(`:`)?{t:`param`,k:e.slice(1)}:{t:`lit`,v:e})}function EC(e){return`/`+e.map(e=>e.t===`param`?`:${e.k}`:e.v).join(`/`)}function DC(e,t){return`/`+e.map(e=>{if(e.t===`lit`)return e.v;let n=t[e.k];if(n===void 0)throw Error(`path is missing a value for ":${e.k}"`);return encodeURIComponent(String(n))}).join(`/`)}function OC(e){return e.filter(e=>e.t===`param`).map(e=>e.k)}var kC=class extends Error{status;code;data;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.data=r,this.name=`ApiError`}},AC=()=>{let e=globalThis.navigator;return typeof e?.onLine==`boolean`?e.onLine:void 0};function jC(e={}){let t=new Set,n=e.initial??(AC()===!1?`offline`:`online`),r=e=>{if(e!==n){n=e;for(let n of[...t])n(e)}},i=e=>(t.add(e),()=>void t.delete(e)),a=()=>{},o=globalThis;if((e.browser??!0)&&typeof o.addEventListener==`function`&&typeof o.removeEventListener==`function`){let e=()=>r(`online`),t=()=>r(`offline`);o.addEventListener(`online`,e),o.addEventListener(`offline`,t),a=()=>{o.removeEventListener(`online`,e),o.removeEventListener(`offline`,t)}}return{get status(){return n},subscribe:i,whenOnline:(e,t)=>new Promise((r,a)=>{if(n===`online`){r();return}if(e?.aborted){a(e.reason);return}let o=null,s=t=>{l(),o&&clearTimeout(o),e?.removeEventListener(`abort`,c),t()};function c(){s(()=>a(e.reason))}let l=i(e=>{e===`online`&&s(r)});t?.timeout!==void 0&&(o=setTimeout(()=>s(r),t.timeout)),e?.addEventListener(`abort`,c,{once:!0})}),report:r,dispose:()=>{a(),a=()=>{}}}}var MC=e=>{if(Array.isArray(e))return e.map(MC);if(e&&typeof e==`object`){let t={};for(let n of Object.keys(e).sort())t[n]=MC(e[n]);return t}return e},NC=e=>JSON.stringify(MC(e))??`null`,PC=e=>{try{return JSON.stringify(e)!==void 0}catch{return!1}},FC=(e,t)=>({get:n=>e.getItem(t+n)??void 0,set:(n,r)=>e.setItem(t+n,r),delete:n=>{let r=t+n,i=e.getItem(r)!==null;return e.removeItem(r),i},keys:function*(){for(let n=0;n<e.length;n++){let r=e.key(n);r!==null&&r.startsWith(t)&&(yield r.slice(t.length))}}}),IC=(e,t)=>{if(typeof e==`object`)return e;if(e!==`memory`)try{let n=e===`local`?globalThis.localStorage:globalThis.sessionStorage;if(n)return FC(n,t)}catch{}let n=new Map;return{get:e=>n.get(e),set:(e,t)=>void n.set(e,t),delete:e=>n.delete(e),keys:()=>n.keys()}};function LC(e={}){let t=e.max??500,n=e.ttl??0,r=e.now??Date.now,i=IC(e.store??`memory`,e.prefix??`ayepi:cache:`),a=new Map;for(let e of i.keys())a.set(e,!0);let o=e=>{a.delete(e),a.set(e,!0)},s=e=>{let t=i.get(e);if(t!==void 0)try{return JSON.parse(t)}catch{i.delete(e);return}},c=e=>(a.delete(e),i.delete(e)),l=()=>{for(;a.size>t;)c(a.keys().next().value)};return{read:e=>{let t=s(e);if(!t)return;let n=r();if(t.exp&&n>=t.exp){if(!t.stale||n>=t.stale){c(e);return}return o(e),{value:t.v,stale:!0}}return o(e),{value:t.v,stale:!1}},write:(e,t,a)=>{if(!PC(t))return;let s=a?.ttl??n,c=s>0?r()+s:0,u={v:t,exp:c,stale:c&&a?.staleWhileRevalidate?c+a.staleWhileRevalidate:0,tags:a?.tags??[]};i.set(e,JSON.stringify(u)),o(e),l()},remove:e=>void c(e),removeWhere:e=>{let t=0;for(let n of[...i.keys()])e(n)&&c(n)&&(t+=1);return t},invalidateTags:e=>{if(e.length===0)return 0;let t=new Set(e),n=0;for(let e of[...i.keys()]){let r=s(e);r&&r.tags.some(e=>t.has(e))&&c(e)&&(n+=1)}return n},clear:()=>{for(let e of[...i.keys()])i.delete(e);a.clear()}}}function RC(e={},t=jC()){let n=new Map,r=t=>{let r=t??e.store??`memory`,i=n.get(r);return i||(i=LC({...e,store:r}),n.set(r,i)),i};return{cacheFor:r,invalidateTags:e=>{r(void 0);for(let t of n.values())t.invalidateTags(e)},connectivity:t}}var zC=class extends Error{constructor(e=`caller rate limit exceeded`){super(e),this.name=`CallerRateLimited`}},BC=`\0`,VC=e=>new DOMException(e,`AbortError`),HC=e=>{let t=e.filter(e=>e!==void 0);if(t.length===1)return t[0];let n=new AbortController,r=()=>{n.abort();for(let e of t)e.removeEventListener(`abort`,r)};for(let e of t){if(e.aborted)return n.abort(),n.signal;e.addEventListener(`abort`,r,{once:!0})}return n.signal},UC=(e,t)=>new Promise((n,r)=>{if(t.aborted){r(VC(`aborted`));return}let i=()=>{clearTimeout(a),r(VC(`aborted`))},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e);t.addEventListener(`abort`,i,{once:!0})}),WC=(e,t)=>t.reduceRight((e,t)=>t(e),e),GC=(e,t,n)=>e===void 0?[]:typeof e==`function`?e(t,n):e,KC=(e,t)=>n=>async(r,i)=>{t.n+=1,e.onStart?.(r.data);try{let t=await n(r,i);return e.onSuccess?.(t,r.data),t}catch(t){throw e.onError?.(t,r.data),t}finally{--t.n,e.onSettled?.(r.data)}},qC=(e,t,n)=>r=>async(i,a)=>{t!==`success`&&n.invalidateTags(GC(e,i.data,void 0));let o=await r(i,a);return t!==`start`&&n.invalidateTags(GC(e,i.data,o)),o},JC=(e,t,n)=>r=>async(i,a)=>{let o=n(i.data),s=n=>t.write(o,n,{ttl:e.ttl,staleWhileRevalidate:e.staleWhileRevalidate,tags:GC(e.tags,i.data,n)}),c=t.read(o);if(c&&!c.stale)return c.value;if(c&&c.stale)return r(i,a).then(s).catch(()=>{}),c.value;let l=await r(i,a);return s(l),l},YC=e=>{let t=new Map;return n=>(r,i)=>{let a=e(r.data),o=t.get(a);if(o)return o;let s=n(r,i).finally(()=>t.delete(a));return t.set(a,s),s}},XC=()=>{let e=null;return t=>(n,r)=>{e?.abort(VC(`superseded`));let i=new AbortController;e=i;let a=HC([r,i.signal]);return new Promise((e,r)=>{a.addEventListener(`abort`,()=>r(VC(`superseded`)),{once:!0}),t(n,a).then(e,r)}).finally(()=>{e===i&&(e=null)})}},ZC=e=>{let t=e.onLimit??`wait`,n=e.window/e.limit,r=e.limit,i=Date.now(),a=()=>{let t=Date.now(),n=(t-i)/e.window*e.limit;n>0&&(r=Math.min(e.limit,r+n),i=t)};return e=>async(i,o)=>{if(a(),r<1){if(t===`throw`||t===`drop`)throw new zC;await UC((1-r)*n,o),a()}return--r,e(i,o)}},QC=e=>{let t=e.attempts??3,n=e.base??200,r=e.factor??2,i=e.max??3e4,a=e.jitter??.5;return e=>async(o,s)=>{let c;for(let l=1;l<=t;l+=1)try{return await e(o,s)}catch(e){if(c=e,l>=t)break;await UC(Math.min(i,n*r**(l-1))*(1-a*Math.random()),s)}throw c}},$C=e=>e instanceof kC&&e.status===0&&e.code===`DISCONNECTED`,ew=(e,t)=>{let n=e.maxRetries??1/0,r=e.backoff??1e3;return i=>async(a,o)=>{let s=e.timeout===void 0?1/0:Date.now()+e.timeout,c=0;for(;;)try{return await i(a,o)}catch(e){if(!$C(e)||c>=n)throw e;let i=s-Date.now();if(i<=0)throw e;c+=1,await t.connectivity.whenOnline(o,{timeout:Math.min(r,i)})}}},tw=(e,t)=>{let n=null,r=[],i=0;return a=>{let o=t=>{n&&=(clearTimeout(n),null);let o=r;r=[],i=0;let s=o.map(e=>e.call.data);a(e.accumulate?{data:e.accumulate(s),opts:o[o.length-1].call.opts}:o[o.length-1].call,t).then(t=>{let n=e.spread?e.spread(t,s):null;o.forEach((e,r)=>e.resolve(n?n[r]:t))},e=>o.forEach(t=>t.reject(e)))};return t.push(()=>{n&&=(clearTimeout(n),null);let e=r;r=[],i=0;for(let t of e)t.reject(VC(`cancelled`))}),(t,a)=>new Promise((s,c)=>{let l=Date.now();r.length===0&&(i=l),r.push({call:t,resolve:s,reject:c});let u=e.leading&&n===null&&r.length===1;n&&clearTimeout(n);let d=e.maxWait!==void 0&&l-i>=e.maxWait;if(u||d){o(a);return}let f=e.maxWait===void 0?e.wait:Math.min(e.wait,i+e.maxWait-l);n=setTimeout(()=>o(a),f)})}};function nw(e,t,n,r,i){if(t.items||t.itemsIn||t.streamIn!==null||t.streamOut!==null)return{call:(...e)=>n(...e),cancel:()=>{},invalidate:()=>{},pending:0};let a=t.p.length>0||t.q.length>0||t.hasBody||t.f.length>0,o=i.cache===!0||i.cache===void 0||i.cache===!1?{}:i.cache,s=e=>o.key?o.key(e):NC(e),c=t=>`${e}${BC}${s(t)}`,l=i.cache?r.cacheFor(o.store):null,u={n:0},d=[],f=new AbortController,p=(e,t)=>{let r={...e.opts??{},signal:t};return Promise.resolve(a?n(e.data,r):n(r))},m=[];if((i.onStart||i.onSuccess||i.onError||i.onSettled)&&m.push(KC(i,u)),i.invalidates&&m.push(qC(i.invalidates,i.invalidateOn??`success`,r)),l&&m.push(JC(o,l,c)),i.dedupe&&m.push(YC(c)),i.lastOnly&&m.push(XC()),i.debounce!==void 0){let e=typeof i.debounce==`number`?{wait:i.debounce}:i.debounce;m.push(tw(e,d))}i.rateLimit&&m.push(ZC(i.rateLimit)),i.retry&&m.push(QC(i.retry));let h=t.sideEffects===!1||t.sideEffects===void 0&&t.method===`GET`,ee=i.replay===!1?null:i.replay===void 0?h?{}:null:typeof i.replay==`object`?i.replay:{};ee&&(h||ee.force)&&m.push(ew(ee,r)),(i.onOnline||i.onOffline)&&r.connectivity.subscribe(e=>e===`online`?i.onOnline?.():i.onOffline?.());let te=WC(p,m);return{call:(...e)=>{let t=a?e[0]:void 0,n=a?e[1]:e[0],r=HC([n?.signal,f.signal]);return te({data:t,opts:n},r)},cancel:()=>{f.abort(VC(`cancelled`)),f=new AbortController;for(let e of d)e()},invalidate:()=>void l?.removeWhere(t=>t.startsWith(`${e}${BC}`)),get pending(){return u.n}}}function rw(e){try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}}function iw(e){let{id:t,...n}=e;return JSON.stringify({rid:typeof t==`string`?t:null,...n})}function aw(e){let{rid:t,...n}=e;return JSON.stringify(typeof t==`string`?{id:t,...n}:n)}function ow(e,t){return JSON.stringify({id:e,$status:0,$code:`DISCONNECTED`,$error:t})}function sw(e){return`$status`in e||e.end===!0}var cw=class{#e=new Set;add(e){this.#e.add(e)}settle(e){typeof e.id==`string`&&sw(e)&&this.#e.delete(e.id)}fail(e,t){let n=[...this.#e];this.#e.clear();for(let r of n)e(ow(r,t))}},lw={$status:501,$code:`NOT_SERVED`,$error:`this client serves no spec`};function uw(e,t){let n=e.rid;typeof n==`string`&&typeof e.type==`string`&&t(JSON.stringify({rid:n,...lw}))}var dw=class{app;send;request;#e=null;constructor(e,t,n){this.app=e,this.send=t,this.request=n}receive(e){let t=this.#e??this.#t();this.app.ws.message(t,aw(e))}drop(){let e=this.#e;e&&(this.#e=null,this.app.ws.close(e))}#t(){let e=this.app.ws.open(t=>{let n=rw(t);n&&this.#e===e&&this.send(iw(n))},this.request());return this.#e=e,e}},fw=new Set([101,204,205,304]);function pw(e,t,n,r,i,a){return new Promise((o,s)=>{if(i?.aborted){s(new DOMException(`The operation was aborted.`,`AbortError`));return}let c=new XMLHttpRequest;c.open(e,t,!0),c.responseType=`arraybuffer`;for(let[e,t]of Object.entries(n))c.setRequestHeader(e,t);c.upload.onprogress=e=>{e.lengthComputable&&a({loaded:e.loaded,total:e.total})};let l=()=>c.abort(),u=()=>i?.removeEventListener(`abort`,l);c.onload=()=>{u();let e=fw.has(c.status)?null:c.response;o(new Response(e,{status:c.status,statusText:c.statusText}))},c.onerror=()=>{u(),s(TypeError(`Network request failed`))},c.onabort=()=>{u(),s(new DOMException(`The operation was aborted.`,`AbortError`))},i?.addEventListener(`abort`,l,{once:!0}),c.send(r)})}function mw(e){return!!e&&typeof e.parse==`function`}function hw(e){let t=gw(e);return t?t():e}function gw(e){let t=e[Symbol.for(`ayepi.manifest`)];return typeof t==`function`?t:void 0}function _w(e){return typeof e==`number`&&e>=200&&e<300}var vw={400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,409:`Conflict`,410:`Gone`,422:`Unprocessable Entity`,429:`Too Many Requests`,500:`Internal Server Error`,502:`Bad Gateway`,503:`Service Unavailable`};function yw(e){let t=Number(e.$status);return new kC(t,typeof e.$code==`string`?e.$code:`ERROR`,typeof e.$error==`string`?e.$error:vw[t]??`Request failed with status ${t}`,e.data)}function bw(e){let t=hw(e.manifest),n=e.fetchImpl??(e=>fetch(e)),r=jC(),i=RC(e.cache,r);e.ws?.onState?.(e=>r.report(e===`open`?`online`:`offline`));let a=()=>typeof e.headers==`function`?e.headers():e.headers??{},o=t=>e.unauthorized!==void 0&&Object.keys(t).some(e=>e.toLowerCase()===`authorization`),s=null,c=()=>{let t=e.unauthorized;return t?(s??=t().catch(()=>!1).finally(()=>{s=null}),s):Promise.resolve(!1)},l=t=>e.validate?.endpoints[t]?.cfg,u=(e,t)=>{let n=l(e);return n?.response?n.response.parse(t):t},d=(e,t)=>{let n=l(e);return n&&mw(n.streamOut)?n.streamOut.parse(t):t},f=(e,t,n)=>{let r=l(e)?.responses?.[t];return r?r.parse(n):n},p=0,m=new Map,h=new Map,ee=new Map,te=new Map,ne=new Map,re=(t,n,r)=>{r&&o(a())&&ne.set(t,n),e.ws?.send(n)},ie=e=>{let t=te.get(e);t&&(te.delete(e),t())},ae=(t,n,r)=>{if(!n)return;let i=()=>{te.delete(t),ne.delete(t),r(n.reason)&&e.ws?.send(JSON.stringify({id:t,abort:!0}))};n.aborted?i():(n.addEventListener(`abort`,i,{once:!0}),te.set(t,()=>n.removeEventListener(`abort`,i)))},oe=e=>JSON.stringify(e??{},Object.keys(e??{}).sort());if(e.ws){let t=e.ws,n=e=>t.send(e),r=e.serve?new dw(e.serve,n,()=>new Request(new URL(e.baseUrl,`http://peer.invalid/`))):null;r&&t.onState?.(e=>{e!==`open`&&r.drop()}),t.onMessage(e=>{let i=rw(e);if(!i)return;if(`rid`in i){r?r.receive(i):uw(i,n);return}if(typeof i.id!=`string`){if(typeof i.type==`string`){let e=`${i.type}|${oe(i.params)}`;for(let t of ee.get(e)??[])t(i.data)}return}let a=i.id,o=ne.get(a);ne.delete(a),o!==void 0&&i.$status===401?c().then(e=>{(m.has(a)||h.has(a))&&(e?t.send(o):se(a,i))}):se(a,i)})}function se(e,t){let n=`$status`in t&&!_w(t.$status);if(h.has(e)){let r=h.get(e);`chunk`in t?r.push(t.chunk):t.end===!0?(h.delete(e),ie(e),r.end()):n&&(h.delete(e),ie(e),r.fail(yw(t)))}else if(m.has(e)){let r=m.get(e);m.delete(e),ie(e),n?r.reject(yw(t)):r.resolve(t.data)}}function ce(){let e=[],t=!1,n,r=null;return{push(t){e.push(t),r?.()},end(){t=!0,r?.()},fail(e){n=e,t=!0,r?.()},async*iterate(){for(;;)if(e.length>0)yield e.shift();else{if(n!==void 0)throw n;if(t)return;await new Promise(e=>r=e),r=null}}}}function le(t,n){let r=typeof n==`function`?n():n;(async()=>{try{for await(let n of r)e.ws.send(JSON.stringify({id:t,chunk:n}));e.ws.send(JSON.stringify({id:t,end:!0}))}catch{e.ws.send(JSON.stringify({id:t,end:!0}))}})()}function ue(e,t,n){return JSON.stringify(t.ws===null?{id:e,type:t.path,method:t.method,data:n}:{id:e,type:t.ws,data:n})}function de(t,n,r,i,a){if(!e.ws){let e=Error(`no websocket transport configured`);if(!n.items)return Promise.reject(e);throw e}let o=`c${++p}`;if(n.items){let e=ce();return h.set(o,e),ae(o,a,t=>h.delete(o)?(e.fail(t),!0):!1),re(o,ue(o,n,r),!n.itemsIn),n.itemsIn&&le(o,i),(async function*(){for await(let n of e.iterate())yield d(t,n)})()}let s=new Promise((e,t)=>{m.set(o,{resolve:e,reject:t}),ae(o,a,e=>{let t=m.get(o);return t?(m.delete(o),t.reject(e),!0):!1}),re(o,ue(o,n,r),!1)});return n.itemsIn&&le(o,i),s.then(e=>n.multi?e:u(t,e))}function fe(t,n){if(!e.ws)return Promise.reject(Error(`no websocket transport configured`));let r=`c${++p}`;return new Promise((e,i)=>{m.set(r,{resolve:e,reject:i}),ae(r,n,e=>{let t=m.get(r);return t?(m.delete(r),t.reject(e),!0):!1}),re(r,JSON.stringify({id:r,...t}),!0)})}function g(e,t){if(e.b===`raw`)return{p:{},q:{},b:t,f:{}};let n={},r={},i={},a={},o=new Set(e.p),s=new Set(e.q),c=new Set(e.b??[]),l=new Set(e.f);for(let[e,u]of Object.entries(t??{}))if(o.has(e))n[e]=u;else if(s.has(e))r[e]=u;else if(c.has(e))i[e]=u;else if(l.has(e))a[e]=u;else throw Error(`key "${e}" does not belong to endpoint data`);return{p:n,q:r,b:e.hasBody?i:void 0,f:a}}function pe(t,n,r){let i=DC(TC(t.path),n),a=new URL(i.slice(1),e.baseUrl.endsWith(`/`)?e.baseUrl:e.baseUrl+`/`);for(let[e,t]of Object.entries(r))if(t!==void 0){if(Array.isArray(t))for(let n of t)a.searchParams.append(e,String(n));else a.searchParams.set(e,String(t))}return a}function me(e){let t=(typeof e==`function`?e():e)[Symbol.asyncIterator](),n=new TextEncoder;return new ReadableStream({async pull(e){let{done:r,value:i}=await t.next();if(r)return e.close();e.enqueue(n.encode(JSON.stringify(i)+`
395
+ `))},async cancel(){await t.return?.(void 0)}})}async function he(e,t,i,s=!1){let{p:l,q:u,b:d,f}=g(e,t),p=i?.stream,m=pe(e,l,u),h={...a(),...i?.headers??{}},ee=null,te=!1;if(e.streamIn)h[`content-type`]=e.streamIn,e.itemsIn?(ee=me(p),te=!0):(ee=p,te=p instanceof ReadableStream);else if(e.f.length>0){let e=new FormData;d!==void 0&&e.set(`body`,JSON.stringify(d));for(let[t,n]of Object.entries(f))if(n!==void 0){if(Array.isArray(n))for(let r of n)e.append(t,r);else e.set(t,n)}ee=e}else if(e.hasBody){if(e.bodyEnc===`urlencoded`){h[`content-type`]=`application/x-www-form-urlencoded`;let e=new URLSearchParams;for(let[t,n]of Object.entries(d??{}))if(n!==void 0){if(Array.isArray(n))for(let r of n)e.append(t,String(r));else e.set(t,String(n))}ee=e.toString()}else h[`content-type`]=`application/json`,ee=JSON.stringify(d)}let ne={method:e.method,headers:h,body:ee,signal:i?.signal};te&&(ne.duplex=`half`);let re=i?.onUploadProgress,ie;try{ie=re&&!e.streamIn&&!e.streamOut&&typeof XMLHttpRequest<`u`?await pw(e.method,m.toString(),h,ee,i?.signal,re):await n(new Request(m,ne))}catch(e){throw e instanceof TypeError?(r.report(`offline`),new kC(0,`DISCONNECTED`,`network request failed`)):e}if(r.report(`online`),ie.status===401&&!s&&e.streamIn===null&&o(h)&&await c())return await ie.body?.cancel().catch(()=>{}),he(e,t,i,!0);if(!ie.ok){let e=await ie.json().catch(()=>({})),t=e?.error;throw new kC(ie.status,t?.code??`ERROR`,t?.message,e)}return ie}async function ge(e,t,n,r){let i=await he(t,n,r);if(t.streamOut)return i.body??new ReadableStream({start:e=>e.close()});if(t.multi)return{status:i.status,data:f(e,i.status,await i.json())};if(i.status!==204)return u(e,await i.json())}async function*_e(e,t,n,r){let i=await he(t,n,r);if(!i.body)return;let a=t.streamOut===`text/event-stream`,o=a?`
396
396
 
397
397
  `:`
398
398
  `,s=t=>{let n=a?t.split(`
399
399
  `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(`
400
- `):t;if(n.trim())return d(e,JSON.parse(n))},c=i.body.getReader(),l=new TextDecoder,u=``;try{for(;;){let{done:e,value:t}=await c.read();if(e)break;u+=l.decode(t,{stream:!0});let n;for(;(n=u.indexOf(o))>=0;){let e=u.slice(0,n);u=u.slice(n+o.length);let t=s(e);t!==void 0&&(yield t)}}u+=l.decode();let e=s(u);e!==void 0&&(yield e)}finally{await c.cancel().catch(()=>{})}}function ve(n,...r){let i=t.endpoints[n];if(!i)return Promise.reject(Error(`unknown endpoint "${n}"`));let a=i.p.length>0||i.q.length>0||i.hasBody||i.f.length>0||i.streamIn!==null,o=a?r[0]:void 0,s=a?r[1]:r[0],c=s?.transport??(e.prefer===`ws`&&!i.httpOnly&&e.ws?`ws`:`http`);if(c===`ws`&&i.httpOnly){let e=Error(`endpoint "${n}" is http-only`);if(i.items)throw e;return Promise.reject(e)}return i.items||i.itemsIn?c===`ws`?de(n,i,o,s?.stream,s?.signal):i.items?_e(n,i,o,s):ge(n,i,o,s):c===`ws`?fe(i.ws===null?{type:i.path,method:i.method,data:o}:{type:i.ws,data:o},s?.signal).then(e=>i.multi?e:u(n,e)):ge(n,i,o,s)}function ye(e,...n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);if(r.method!==`GET`)throw Error(`url() requires a GET endpoint; "${e}" is ${r.method}`);let{p:i,q:a}=g(r,n[0]);return pe(r,i,a).toString()}function be(n,...r){let i=t.events[n];if(!i)throw Error(`unknown event "${n}"`);if(!e.ws)throw Error(`no websocket transport configured`);let a=i.hasParams?r[0]:void 0,o=i.hasParams?r[1]:r[0],s=`${i.ws}|${oe(a)}`,c=ee.get(s);return c||ee.set(s,c=new Set),c.add(o),fe({sub:i.ws,params:a}),()=>{c.delete(o),c.size===0&&fe({unsub:i.ws,params:a})}}function xe(e,n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);return WS(e,r,(...t)=>ve(e,...t),i,n??{})}return{call:ve,on:be,url:ye,caller:xe,connection:{get status(){return r.status},subscribe:e=>r.subscribe(e)}}}var lC={initial:500,max:3e4,factor:2,jitter:!0},uC={interval:3e4,timeout:1e4};function dC(e,t={}){let n=t.WebSocket??globalThis.WebSocket;if(!n)throw Error(`wsTransport: no WebSocket implementation available; pass opts.WebSocket`);let r=n,i=t.whileDisconnected??`fail`,a={...lC,...t.backoff},o=t.heartbeat===!1?null:{...uC,...t.heartbeat??{}},s=t.maxRetries??1/0,c=null,l=`closed`,u=null,d=0,f=!1,p=!1,m=null,h=null,ee=null,te=[],ne=new Map,re=new XS,ie=new Set,ae=e=>{if(e!==l){l=e,t.onStateChange?.(e);for(let t of[...ie])t(e)}},oe=e=>u?.(e),se=e=>JSON.stringify(e??{},Object.keys(e??{}).sort());function ce(){re.fail(oe,`connection closed`)}function le(){h&&clearInterval(h),ee&&clearTimeout(ee),h=ee=null}function ue(){o&&(le(),h=setInterval(()=>{l===`open`&&c&&(c.send(JSON.stringify({ping:!0})),ee&&clearTimeout(ee),ee=setTimeout(()=>c?.close(),o.timeout))},o.interval))}function de(e){let t=null;try{t=JSON.parse(e)}catch{oe(e);return}t&&t.pong===!0?ee&&=(clearTimeout(ee),null):(t&&re.settle(t),oe(e))}function fe(){if(p)return;f=!0,d=0,ae(`open`);for(let e of ne.values())c?.send(e);let e=te.splice(0);for(let t of e)c?.send(t);ue()}function g(){le(),c=null,ce(),p?ae(`closed`):pe()}function pe(){if(p)return;if(d>=s){ae(`closed`);return}let e=Math.min(a.max,a.initial*a.factor**+d),t=a.jitter?e/2+e/2*Math.random():e;d++,ae(`connecting`),m=setTimeout(me,t)}function me(){if(p||c)return;m&&=(clearTimeout(m),null),ae(`connecting`);let n;try{n=new r(typeof e==`function`?e():e,typeof t.protocols==`function`?t.protocols():t.protocols)}catch(e){t.onError?.(e),pe();return}c=n;let i=!1,a=()=>{c===n&&g()};n.addEventListener(`open`,()=>{i=!0,fe()}),n.addEventListener(`message`,e=>de(String(e.data))),n.addEventListener(`close`,a),n.addEventListener(`error`,e=>{t.onError?.(e),i||a()})}function he(e){let t={};try{t=JSON.parse(e)}catch{}typeof t.sub==`string`?ne.set(`${t.sub}|${se(t.params)}`,e):typeof t.unsub==`string`&&ne.delete(`${t.unsub}|${se(t.params)}`),typeof t.id==`string`&&typeof t.type==`string`&&re.add(t.id);let n=typeof t.sub==`string`||typeof t.unsub==`string`;l===`open`&&c?c.send(e):`rid`in t||(me(),n||(!f||i===`queue`?te.push(e):typeof t.id==`string`&&oe(JS(t.id,`not connected`))))}return{send:he,onMessage(e){u=e},connect:me,reconnect(){if(p)return;let e=c;c=null,le(),ce(),e?.close(),d=0,me()},close(){p=!0,m&&clearTimeout(m),m=null,le(),ce(),c?.close(),c=null,ae(`closed`)},get state(){return l},onState(e){return ie.add(e),()=>void ie.delete(e)}}}function fC(e,t,n){return{kind:`endpoint`,cfg:e,mws:t,prefixes:n}}function pC(e){return fC(e,[],[])}function Y(e){for(let[t,n]of Object.entries(e.endpoints)){let e=n.cfg;if(e.streamIn&&(e.body||e.files))throw Error(`endpoint "${t}": streamIn excludes body/files`);if(e.files&&`body`in e.files)throw Error(`endpoint "${t}": "body" is reserved as the multipart JSON field name`);if(e.streamOut&&e.response)throw Error(`endpoint "${t}": streamOut excludes response`);if(e.responses&&e.response)throw Error(`endpoint "${t}": responses (multi-status) excludes response`);if(e.responses&&e.streamOut)throw Error(`endpoint "${t}": responses excludes streamOut`);if(e.streamEncoding&&!(e.streamOut instanceof ws))throw Error(`endpoint "${t}": streamEncoding requires a typed (schema) streamOut`);if(e.bodyEncoding===`urlencoded`&&!(e.body instanceof dc))throw Error(`endpoint "${t}": urlencoded bodies must be z.object(...)`);if(e.download&&typeof e.streamOut!=`string`)throw Error(`endpoint "${t}": download requires a raw (content-type) streamOut`);for(let n of[`params`,`query`,`headers`,`cookies`]){let r=e[n];if(r&&!(r instanceof dc))throw Error(`endpoint "${t}": ${n} must be a z.object(...)`)}_C(t,n)}let t;return Object.defineProperty(e,mC,{value:()=>t??=hC(e),enumerable:!1,configurable:!0}),e}var mC=Symbol.for(`ayepi.manifest`);function hC(e){let t=Object.entries(e.endpoints).map(([e,t])=>_C(e,t));return{endpoints:Object.fromEntries(t.map(e=>[e.name,{method:e.method,path:e.path,ws:e.ws,httpOnly:e.httpOnly,streamIn:e.streamInCt,itemsIn:e.itemsIn,streamOut:e.streamOutCt,items:e.items,p:e.p,q:e.q,b:e.bRaw?`raw`:e.b,f:e.f,hasBody:!!e.def.cfg.body,hasHeaders:!!e.def.cfg.headers,multi:e.multi,bodyEnc:e.bodyEnc,sideEffects:e.def.cfg.sideEffects}])),events:Object.fromEntries(Object.entries(e.events??{}).map(([e,t])=>[e,{ws:t.ws??e,hasParams:!!t.params}]))}}function gC(e){return e&&e instanceof dc?Object.keys(e.shape):null}function _C(e,t){let n=t.cfg,r=TC(t.mws),i=t=>{throw Error(`endpoint "${e}": ${t}`)},a=new Map;for(let e of r)e.paramKey&&e.paramSchema&&a.set(e.paramKey,e.paramSchema);let o=new Map,s=(e,t)=>{for(let n of e.keys)(a.has(n)||o.has(n))&&i(`param ":${n}" is declared more than once (${t})`),o.set(n,e.schemas[n])};for(let e of t.prefixes)typeof e!=`string`&&s(e,`prefix path`);let c=typeof n.path==`object`&&n.path!==null?n.path:null;c&&s(c,`endpoint path`);let l=gC(n.params)??[];for(let e of l)(a.has(e)||o.has(e))&&i(`param ":${e}" is declared more than once (params schema)`);let u=new Set([...a.keys(),...o.keys(),...l]),d=[];for(let e of t.prefixes)d.push(...typeof e==`string`?pS(e):e.parts);if(c)d.push(...c.parts);else if(typeof n.path==`string`)d.push(...pS(n.path));else{d.push({t:`lit`,v:e});let t=new Set(gS(d));for(let e of u)t.has(e)||d.push({t:`param`,k:e})}let f=gS(d),p=new Set(f);f.length!==p.size&&i(`path positions a param more than once: ${mS(d)}`);for(let e of f)u.has(e)||i(`path references undeclared param ":${e}"`);for(let e of u)p.has(e)||i(`declared param ":${e}" has no position in path ${mS(d)}`);let m=[...u],h=gC(n.query)??[],ee=n.body?gC(n.body):null,te=!!n.body&&ee===null,ne=Object.keys(n.files??{}),re=new Map;for(let[e,t]of[[`path`,m],[`query`,h],[`body`,ee??[]],[`files`,ne]])for(let n of t){let t=re.get(n);t&&i(`key "${n}" appears in both ${t} and ${e} — kinds must be disjoint`),re.set(n,e)}te&&(m.length>0||h.length>0||ne.length>0)&&i(`a non-object body is the entire data payload — params/query/files are not allowed alongside it`);let ie=n.streamIn instanceof ws,ae=typeof n.streamIn==`string`?n.streamIn:ie?`application/x-ndjson`:null,oe=n.streamOut instanceof ws,se=oe&&n.streamEncoding===`sse`,ce=typeof n.streamOut==`string`?n.streamOut:oe?se?`text/event-stream`:`application/x-ndjson`:null,le=!!(n.httpOnly||typeof n.streamIn==`string`||typeof n.streamOut==`string`||ne.length>0);return{name:e,def:t,method:n.method??`POST`,parts:d,path:mS(d),ws:n.ws??null,wsEligible:!le,httpOnly:le,streamInCt:ae,itemsIn:ie,streamOutCt:ce,items:oe,sse:se,multi:!!(n.responses&&Object.keys(n.responses).length>0),bodyEnc:n.body?n.bodyEncoding??`json`:null,p:m,q:h,b:ee,bRaw:te,f:ne,loaders:a,tplSchemas:o,chain:r}}function vC(){return{}}function yC(e){return()=>{throw Error(`middleware "${e}" has no implementation — bind it with implement(api).middleware(def, impl)`)}}function bC(e,t,n,r,i,a){let o={kind:`middleware`,name:e,requires:t,optional:n,paramKey:r,paramSchema:i,doc:a,run:yC(e),with(...e){return xC([o,...e],[])},path(e){return xC([o],[e])},endpoint(e){return xC([o],[]).endpoint(e)},group(e){return xC([o],[]).group(e)}};return o}function xC(e,t){return{kind:`stack`,mws:e,prefixes:t,with(...n){return xC([...e,...n],t)},path(n){return xC(e,[...t,n])},endpoint(n){return fC(n,e,t)},group(n){let r={};for(let[i,a]of Object.entries(n))r[i]=fC(a,e,t);return r}}}function X(...e){return xC([...e],[])}function SC(e,t){return bC(e,t?.requires??[],t?.optional??[],void 0,void 0,t?.doc)}function CC(e,t,n){return bC(e,n?.requires??[],n?.optional??[],e,t,n?.doc)}var wC=Object.assign(SC,{loader:CC});function TC(e){let t=new Set,n=[],r=(e,i)=>{if(!t.has(e)){if(i.has(e))throw Error(`middleware cycle involving "${e.name}"`);i.add(e);for(let t of e.requires)r(t,i);i.delete(e),t.add(e),n.push(e)}};for(let t of e)r(t,new Set);let i=new Map(n.map((e,t)=>[e,t]));return[...n].sort((e,t)=>e.optional.includes(t)?1:t.optional.includes(e)?-1:i.get(e)-i.get(t))}function EC(...e){let t={},n={};for(let r of e){for(let[e,n]of Object.entries(r.endpoints)){if(Object.hasOwn(t,e))throw Error(`mergeSpecs: endpoint "${e}" is in more than one spec`);t[e]=n}for(let[e,t]of Object.entries(r.events??{})){if(Object.hasOwn(n,e))throw Error(`mergeSpecs: event "${e}" is in more than one spec`);n[e]=t}}return Y({endpoints:t,events:n})}var DC=new WeakMap;function OC(e,t){return DC.set(e._zod.def,{source:t}),e}function kC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var AC=class e extends U{static NAME=`record`;name=e.NAME;static optionKeys=[];static genericKeys=[`V`];static from(t,n){let r=t.generic?.V;return new e(n,r===void 0?n.registry.any():n.parse(r))}static toA(){return R.object({name:R.literal(e.NAME),generic:R.object({V:R.ref(`TypeDef`)}).optional()}).describe(`A record: an object with any text keys, each value a V.`)}constructor(e,t){super(e,{},{V:t})}get value(){let e=this.generic.V;if(e===void 0)throw Error(`record has no value type`);return e}valid(e,t){return kC(e)&&Object.values(e).every(e=>{try{return this.value.parse(e,t),!0}catch{return!1}})}parse(e,t){if(!kC(e))throw new Nm({path:[],code:`record.invalid`,message:`record.parse: expected an object of values by key`,severity:`error`});for(let[n,r]of Object.entries(e))try{this.value.parse(r,t)}catch(e){throw new Nm({path:[n],code:`record.value`,message:`record.parse: ${n}: ${e instanceof Error?e.message:String(e)}`,severity:`error`})}return new W(this,e)}encode(e){return e}create(){return{}}random(e){return{}}compatibleType(t){return t instanceof e&&this.value.compatibleType(t.value)}or(t){return t instanceof e&&this.value.compatibleType(t.value)?this:t}narrow(){return{}}toJSON(){return{name:e.NAME,generic:{V:this.value.toJSON()}}}clone(){return new e(this.scope,this.value)}toCode(e,t){return`${this.docsPrefix(t)}record<${this.value.toCode(void 0,t)}>`}valueA(e){return R.record(this.value.toA(e))}toNewA(){return R.record(R.ref(`Expr`))}};function jC(e){return e.typeClass(AC.NAME)===void 0&&e.define(AC),e}function MC(){return jC(Pv())}var NC;function PC(){return NC??=MC(),NC}var FC=Vy.result(`TypeDef`),IC=Vy.result(`Expr`);function LC(e){return()=>{let{description:t,...n}=e(PC()).render(Xl).jsonSchema;return n}}function RC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zC(e){return RC(e)&&`name`in e&&typeof e.name==`string`}var Z=OC(Jc(zC,{message:`Expected a gin type definition ({ name, ... }).`}),LC(e=>FC.bind(e,void 0,{namedRefs:!0})));function BC(e){return zC(e)}var VC=OC(Jc(BC,{message:`Expected a gin object type definition ({ name: "obj", props: { ... } }).`}),LC(e=>Wy(e.typ(e.obj({}))).bind(e,void 0,{namedRefs:!0})));function HC(e){return RC(e)&&`kind`in e&&typeof e.kind==`string`}var UC=OC(Jc(HC,{message:`Expected a gin expression ({ kind, ... }).`}),LC(e=>IC.bind(e,void 0,{namedRefs:!0}))),WC=new Set(`id.uuid.guid.url.uri.api.json.csv.tsv.xml.html.css.yaml.sql.pdf.svg.png.jpg.ip.dns.http.https.ssh.tls.ssl.tcp.udp.vpn.os.cpu.gpu.ram.ui.ux.ai.llm.sku.sms.otp.jwt.utc.iso.gmt.ssn.vat.faq.crm.rgb.db.mime.ttl.oauth.sso.mfa`.split(`.`)),GC=new Map([[`ctx`,`context`]]);function KC(e,t){let n=e.toLowerCase();if(WC.has(n))return n.toUpperCase();let r=GC.get(n);return r===void 0?n.endsWith(`s`)&&WC.has(n.slice(0,-1))?`${n.slice(0,-1).toUpperCase()}s`:t?e:n:t?ZC(r):r}function qC(e){return ZC((/[\s._/:-]/.test(e)&&!/[a-z]/.test(e)?e.toLowerCase():e).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[\s._/:-]+/).filter(e=>e!==``).map((e,t)=>KC(e,t===0)).join(` `))||e}function JC(e){return e.label??qC(e.name)}function YC(e){return qC(Nl(e).local)}function XC(e){return/^[A-Z][a-z]/.test(e)?`${e.charAt(0).toLowerCase()}${e.slice(1)}`:e}function ZC(e){return e===``?e:`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function QC(e,t){let n=e.replace(/\s+/g,` `).trim();if(n.length<=t)return n;let r=n.slice(0,t-1),i=r.lastIndexOf(` `);return`${i>t*.6?r.slice(0,i):r}…`}var $C=[`path`,`file`,`uri`,`query`,`command`,`url`,`name`,`title`,`text`,`pattern`,`message`];function ew(e,t=60){if(e==null)return``;if(typeof e==`string`)return QC(e,t);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e))return e.length===0?``:`${e.length} item${e.length===1?``:`s`}`;let n=$C.map(t=>e[t]).find(e=>typeof e==`string`&&e!==``);if(typeof n==`string`)return QC(n,t);for(let[n,r]of Object.entries(e))if(typeof r==`string`||typeof r==`number`||typeof r==`boolean`)return QC(`${n}: ${String(r)}`,t);return``}var tw=[`active`,`retry`,`done`,`failed`],nw=E(tw),rw=S({one:v().min(1),many:v().min(1)}),iw=S({active:rw,retry:rw,done:rw,failed:rw}),aw=S({phase:nw,one:v(),many:v()}),ow={active:{one:`{fn}…`,many:`{fn} ×{n}…`},retry:{one:`Retrying {fn}…`,many:`Retrying {fn} ×{n}…`},done:{one:`{fn} done`,many:`{fn} ×{n} done`},failed:{one:`{fn} failed`,many:`{fn} ×{n} failed`}};function sw(e,t){switch(e){case`queued`:case`running`:case`waiting`:return t>1?`retry`:`active`;case`invalid-input`:return`retry`;case`done`:return`done`;case`failed`:return`failed`;case`awaiting-approval`:case`paused`:case`cancelled`:case`undone`:return}}var cw=60,lw=3,uw=/\{([^{}|]+)(?:\|([^{}]*))?\}/g;function dw(e,t,n){for(let r of e){if(r===void 0)continue;let e=pw(r[t].one,n,!1),i=pw(r[t].many,n,!0);if(e!==void 0&&i!==void 0)return{phase:t,one:e,many:i}}let r=ow[t];return{phase:t,one:pw(r.one,n,!1)??r.one,many:pw(r.many,n,!0)??r.many}}function fw(e,t){return t===1?e.one:e.many.replaceAll(`{n}`,String(t))}function pw(e,t,n){let r=[],i=e.replace(uw,(e,i,a)=>{let o=mw(i.trim(),t,n);return o===void 0?a===void 0?(r.push(i),e):a:o});return r.length>0?void 0:ZC(i.replace(/…{2,}/g,`…`))}function mw(e,t,n){if(e===`fn`)return XC(YC(t.fn));if(e===`n`)return n?`{n}`:void 0;let[r,...i]=e.split(`.`),a=r===`args`?t.args:r===`output`?t.output:void 0;return a===void 0?void 0:gw(hw(a,i))}function hw(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=Array.isArray(n)?n[Number(e)]:n[e]}return n}function gw(e){if(e!=null){if(typeof e==`string`)return e===``?void 0:vw(e);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e)){let t=e.map(gw).filter(e=>e!==void 0);if(t.length===0)return;let n=t.slice(0,lw),r=t.length-n.length;return _w(r>0?[...n,`${r} more`]:n)}for(let t of[`title`,`name`,`id`]){let n=e[t];if(typeof n==`string`&&n!==``)return vw(n)}}}function _w(e){return e.length<=2?e.join(` and `):`${e.slice(0,-1).join(`, `)} and ${e.at(-1)??``}`}function vw(e){let t=e.split(`
401
- `)[0]??``;return t.length>cw?`${t.slice(0,59)}…`:t}var yw=E([`system-needs-config`,`system-disconnected`,`system-removed`,`kind-missing`,`kind-system-disconnected`,`dep-unavailable`,`disabled`,`held`,`paused`,`role-unset`]),bw=C([D(!0),S({unavailable:yw,detail:v()})]),xw=S({code:E([...yw.options,`no-such-fn`,`not-a-name`,`other-system`,`not-for-model`,`connect-account`]),reason:v().min(1),system:F.optional()}),Sw=xw.extend({fn:v()}),Cw=xw.extend({name:v()}),ww=S({id:M,name:v(),email:v(),role:E([`admin`,`member`]),groups:x(S({id:M,name:v()})),timeZone:v(),locale:v()}),Tw=S({now:N,timeZone:v(),local:v()}),Ew=S({name:v(),instance:L,boot:v(),from:S({system:v(),fn:I,run:A}).optional()}),Dw=S({id:A,fn:I,parent:A.optional(),turn:al,session:j.optional(),user:ww,time:Tw,system:Ew,caller:M,attempt:y().int().min(1),priority:Fl,watched:b().optional(),inChat:b().optional()}),Ow=S({timeZone:v(),locale:v(),now:N}),kw=E([`card`,`message`,`hidden`]),Aw=S({cancel:b(),pause:b(),undo:b(),background:b()}),jw=Aw.pick({cancel:!0,pause:!0,background:!0}),Mw=S({timeout:kl.optional(),retries:y().int().min(0).optional(),cost:P.optional()}),Nw=w(`type`,[S({type:D(`none`)}),S({type:D(`linear`)}),S({type:D(`steps`),steps:T(v(),v())})]),Pw=E([`pending`,`active`,`done`,`failed`,`skipped`]),Fw=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({steps:T(v(),S({status:Pw,detail:v().optional()}))})]),Iw=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({step:v(),status:Pw,detail:v().optional()})]),Lw=[`retry`,`caller`,`fatal`],Rw=S({class:E(Lw),message:v(),code:v().optional(),data:O.optional()}),zw=E([`json`,`schema`,`validation`,`unavailable`,`result`]),Bw=S({path:v(),message:v()}),Vw=S({path:v(),repair:E([`json-string`])});function Hw(e){return e.path===``?e.message:`${e.path}: ${e.message}`}var Uw=S({source:zw,problems:x(Bw).min(1),raw:v().optional(),blocked:xw.optional()}),Ww=[`awaiting-approval`,`queued`,`running`,`waiting`,`paused`,`done`,`invalid-input`,`failed`,`cancelled`,`undone`],Gw=E(Ww),Kw={"awaiting-approval":!1,queued:!1,running:!1,waiting:!1,paused:!1,done:!0,"invalid-input":!0,failed:!0,cancelled:!0,undone:!0},qw={"awaiting-approval":`Needs approval`,queued:`Queued`,running:`Running`,waiting:`Waiting`,paused:`Paused`,done:`Done`,"invalid-input":`Thinking harder`,failed:`Failed`,cancelled:`Cancelled`,undone:`Undone`};function Jw(e){return Kw[e]}function Yw(e){return!Kw[e]}var Xw=Ww.filter(Jw),Zw=Ww.filter(Yw),Qw=w(`type`,[S({type:D(`status`),status:Gw,text:aw.optional()}),S({type:D(`progress`),progress:Fw}),S({type:D(`allowed`),operations:jw}),S({type:D(`cost`),cost:P,total:P}),S({type:D(`background`)})]),$w=w(`status`,[S({status:D(`done`),result:O,undo:O.optional(),cost:P.optional(),expose:x(Nb).optional()}),S({status:D(`invalid-input`),invalid:Uw,undo:O.optional(),cost:P.optional()}),S({status:D(`paused`),resume:O,cost:P.optional()}),S({status:D(`failed`),error:Rw,undo:O.optional(),cost:P.optional()}),S({status:D(`cancelled`),partial:O.optional(),undo:O.optional(),cost:P.optional(),error:Rw.optional()})]),eT=w(`status`,[S({status:D(`done`),result:O}),S({status:D(`failed`),error:Rw}),S({status:D(`cancelled`),error:Rw.optional()}),S({status:D(`background`),run:A})]),tT=w(`status`,[S({status:D(`undone`),summary:v()}),S({status:D(`failed`),error:Rw}),S({status:D(`gone`)})]),nT=w(`ok`,[S({ok:D(!0),value:O}),S({ok:D(!1),error:Rw})]),rT=S({cost:P,time:kl,limitedBy:v()}),iT=mx,aT=S({hash:v().regex(Ex),kind:Fx,converter:v().min(1),content:Dx,chars:y().int().min(0),tokens:y().int().min(0),call:Tl.optional(),createdAt:N}),oT=S({kind:Fx,model:v().optional(),estimate:y().min(0).optional()}),sT=w(`from`,[S({from:D(`system`),system:F,served:E([`bytes`,`text`]).optional()}),S({from:D(`upload`),by:M}),S({from:D(`web`),url:fb,finalUrl:fb.optional(),fetchedAt:N,rendered:b()}),S({from:D(`run`),run:A,fn:I})]),cT=[`system`,`upload`,`web`,`run`],lT=E([`auto`,`always`,`never`]),uT=`hub://resources/`,dT=[`document`,`code`,`image`,`table`,`audio`,`video`,`web`,`data`,`archive`,`folder`,`other`],fT=E(dT),pT={markdown:`document`,text:`document`,pdf:`document`,docx:`document`,pptx:`document`,rtf:`document`,odt:`document`,notebook:`document`,html:`web`,json:`data`,jsonl:`data`,yaml:`data`,toml:`data`,xml:`data`,ini:`data`,csv:`table`,tsv:`table`,excel:`table`,ods:`table`,image:`image`,svg:`image`,mermaid:`image`,audio:`audio`,video:`video`,zip:`archive`,folder:`folder`,...Object.fromEntries(`typescript.javascript.jsx.tsx.vue.python.ruby.go.rust.java.c.cpp.csharp.php.swift.kotlin.scala.css.scss.less.shell.sql.dockerfile.graphql.lua.r.dart`.split(`.`).map(e=>[e,`code`]))};function mT(e,t){let n=e===void 0?void 0:pT[e];if(n!==void 0)return n;let r=t?.split(`/`)[0];return r===`image`||r===`audio`||r===`video`?r:`other`}var hT=E([`type`,`source`,`path`,`date`]),gT=S({value:v(),label:v(),count:y().int().min(0)}),_T=zl.extend({search:v().optional(),system:F.optional(),family:fT.optional(),source:E(cT).optional(),under:v().optional(),form:Fx.optional(),missing:Fx.optional(),group:hT.optional(),in:v().optional()}),vT=S({uri:Cx}),yT=S({uri:Cx,section:wx.optional()}),bT=S({image:Cx,question:v().trim().min(1).max(2e3),page:y().int().min(1).optional()}),xT=S({answer:v(),model:v(),image:S({id:Cx,name:v()})}),ST=S({uri:Cx,form:C([Fx,D(`raw`)]).optional(),section:wx.optional(),offset:y().int().min(0).optional(),maxChars:y().int().min(1).max(2e5).optional(),rows:S({table:v(),from:y().int().min(0),to:y().int().min(0)}).optional()}),CT=S({uri:Cx,form:C([Fx,D(`raw`)]),text:v(),offset:y().int().min(0),total:y().int().min(0),truncated:b(),partial:v().optional(),note:v().optional(),forms:x(Fx),offers:x(oT)}),wT=C([S({url:fb,render:lT.optional(),name:v().optional(),folder:v().min(1).optional()}),S({content:Dx,name:v().min(1),path:v().optional()})]),TT=C([S({model:v().min(1)}),S({category:v().min(1)}),S({auto:S({cost:y().min(0).optional(),speed:y().min(0).optional(),accuracy:y().min(0).optional()})})]),ET=S({id:v(),name:v(),arguments:v(),invalid:v().optional()}),DT=S({type:E([`text`,`image`,`file`,`audio`,`video`]),content:v(),format:v().optional(),name:v().optional()}),OT=S({role:E([`system`,`user`,`assistant`,`tool`]),content:C([v(),x(DT)]),name:v().optional(),toolCallId:v().optional(),toolCalls:x(ET).optional(),refusal:v().optional(),tokens:y().int().optional()}),kT=S({input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional()}),AT=E([`stop`,`length`,`tool_calls`,`content_filter`,`refusal`]),jT=S({content:v().optional(),reasoning:v().optional(),toolCallNamed:ET.optional(),toolCallArguments:ET.optional(),toolCallMore:ET.optional(),toolCall:ET.optional(),finishReason:AT.optional(),refusal:v().optional(),usage:kT.optional()}),MT=C([b(),y().positive()]),NT=E([`summary`,`list`,`markers`,`full`]),PT=C([NT,S({detail:NT.optional(),maxErrors:y().int().min(0).optional(),maxChars:y().int().min(0).optional(),suggestions:b().optional(),expected:b().optional(),context:y().int().min(0).optional(),depth:y().int().min(0).optional(),header:b().optional()})]),FT=S({name:v(),description:v().optional(),parameters:O,strict:MT.optional(),errorFormat:PT.optional()}),IT=C([D(`text`),D(`json`),S({schema:O,strict:MT,errorFormat:PT.optional(),schemaDelivery:E([`auto`,`structured`,`json`,`prompt`]).optional()})]),LT=S({messages:x(OT),temperature:y().optional(),maxTokens:y().int().optional(),stop:x(v()).optional(),tools:x(FT).optional(),toolChoice:C([E([`auto`,`none`,`required`]),S({tool:v()})]).optional(),responseFormat:IT.optional(),errorFormat:PT.optional()}),RT=S({run:A.optional(),request:LT,model:TT.optional(),stream:b()}),zT=w(`type`,[S({type:D(`chunk`),chunk:jT}),S({type:D(`done`),usage:kT,cost:P,interaction:ll,model:v()}),S({type:D(`error`),message:v(),kind:E([`model`,`tool`,`limit`,`provider`])})]),BT=S({id:v().min(1),text:v().min(1),score:y().min(0).max(1)}),VT=S({run:A,question:v().min(1),candidates:x(BT).min(1).max(50),max:y().int().min(1).max(20)}),HT=w(`by`,[S({by:D(`decision`),picked:x(S({id:v(),why:v().optional()})),note:v().optional(),call:Tl.optional()}),S({by:D(`off`)}),S({by:D(`failed`),message:v()})]),UT=w(`type`,[S({type:D(`predicate`),instructions:v().min(1)}),S({type:D(`choice`),instructions:v().min(1),choices:T(v(),v())}),S({type:D(`score`),instructions:v().min(1),levels:x(v()).min(1)})]),WT=C([v().min(1),x(OT).min(1)]),GT=T(v().min(1),UT),KT=y().min(0).max(1),qT=w(`type`,[S({type:D(`predicate`),probability:KT}),S({type:D(`choice`),choice:v(),probabilities:T(v(),KT),confidence:KT}),S({type:D(`score`),score:y(),probabilities:x(KT),confidence:KT}),S({type:D(`refusal`)})]),JT=T(v(),qT),YT=.5,XT=[`chat`,`embed`,`image`,`transcribe`,`speech`,`decide`];E(XT);var ZT=E([`yes`,`no`,`unknown`]),QT=S({modality:D(`chat`),input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional(),caching:ZT.optional()}),$T=S({modality:D(`embed`),texts:y().int().min(0),characters:y().int().min(0),images:y().int().min(1).optional(),tokens:y().int().min(0).optional(),dimensions:y().int().min(1)}),eE=S({modality:D(`image`),images:y().int().min(0),size:v().optional()}),tE=S({modality:D(`transcribe`),seconds:y().min(0),bytes:y().int().min(0)}),nE=S({modality:D(`speech`),characters:y().int().min(0),seconds:y().min(0).optional()}),rE=S({modality:D(`decide`),questions:y().int().min(0),characters:y().int().min(0),images:y().int().min(0).optional(),tokens:y().int().min(0).optional()});w(`modality`,[QT,$T,eE,tE,nE,rE]);var iE=E([`mp3`,`wav`,`ogg`]),aE=E([`running`,`done`,`failed`,`aborted`]),oE=S({id:Tl,provider:v(),model:v(),run:A.optional(),turn:al.optional(),session:j.optional(),system:F.optional(),fn:I.optional(),purpose:v().optional(),interaction:ll.optional(),cost:P,status:aE,error:v().optional(),priority:Fl.optional(),sent:y().int().min(0),received:y().int().min(0),queued:kl,firstByte:kl.optional(),total:kl.optional(),startedAt:N,endedAt:N.optional()}),sE=e=>S({modality:e.shape.modality,units:e}),cE=w(`modality`,[sE(QT),sE($T),sE(eE),sE(tE),sE(nE),sE(rE)]),lE=e=>oE.extend(e.shape),uE=w(`modality`,[lE(cE.options[0]),lE(cE.options[1]),lE(cE.options[2]),lE(cE.options[3]),lE(cE.options[4]),lE(cE.options[5])]),dE=w(`modality`,[S({modality:D(`embed`),texts:x(v()).min(1),model:TT.optional()}),S({modality:D(`image`),prompt:v().min(1),model:TT.optional(),size:v().optional(),count:y().int().min(1).max(10).optional()}),S({modality:D(`transcribe`),audio:Dx,model:TT.optional(),language:v().optional()}),S({modality:D(`speech`),text:v().min(1),model:TT.optional(),voice:v().optional(),format:iE.optional()}),S({modality:D(`decide`),input:WT,questions:GT,model:TT.optional()})]).and(S({run:A.optional()})),fE=w(`modality`,[S({modality:D(`embed`),vectors:x(x(y()))}),S({modality:D(`image`),images:x(Dx)}),S({modality:D(`transcribe`),text:v(),segments:x(S({start:y().min(0),end:y().min(0),text:v()})).optional()}),S({modality:D(`speech`),audio:Dx}),S({modality:D(`decide`),answers:JT})]).and(S({call:Tl,cost:P,model:v()})),pE=E([`chat`,`transcribe`,`dictate`,`speak`,`describe`,`ocr`,`decide`]),mE={chat:`chat`,transcribe:`hearing`,dictate:`hearing`,speak:`audio`,describe:`vision`,ocr:`vision`,decide:`decision`},hE=S({model:TT,provider:Sl.optional()}),gE=w(`engine`,[S({engine:D(`browser`)}),hE.extend({engine:D(`model`)})]),_E=[`browser`,`model`],vE=pE.exclude([`dictate`,`decide`]),yE=hE.extend({role:D(`decide`),threshold:y().min(0).max(1).default(YT)}),bE=w(`role`,[S({role:D(`dictate`),engine:gE,language:v().optional()}),yE,hE.extend({role:vE,language:v().optional()})]);S({choice:bE,setBy:M,updatedAt:N});var xE=C([S({model:v(),provider:v()}),S({problem:v()})]),SE=S({role:pE,choice:bE.optional(),from:E([`setting`,`env`,`none`]),resolved:xE.optional()}),CE=[`done`,`invalid-input`,`failed`,`cancelled`],wE=T(E(CE),y().int().min(0));function TE(){return{done:0,"invalid-input":0,failed:0,cancelled:0}}function EE(e){return CE.reduce((t,n)=>t+e[n],0)}var DE=v().regex(/^\d{4}-\d{2}-\d{2}$/),OE=[50,100,250,500,1e3,2500,5e3,1e4,3e4,6e4,3e5],kE=S({count:y().int().min(0),sum:kl,max:kl,histogram:x(y().int().min(0)).length(OE.length+1)}),AE=S({fn:I,system:F,day:DE,outcomes:wE,queued:kE,approval:kE,ran:kE,cost:P,tokens:y().int().min(0),retries:y().int().min(0),modelCalls:y().int().min(0),updatedAt:N}),jE=S({fn:I,system:F,from:DE,to:DE,runs:y().int().min(0),outcomes:wE,p50:kl.optional(),p95:kl.optional(),averageQueued:kl.optional(),averageCost:P,cost:P,tokens:y().int().min(0),retries:y().int().min(0),lastRunAt:N.optional()}),ME=S({fn:cb.optional(),system:F.optional(),days:y().int().min(1).max(365).optional()}),NE=E([`private`,`shared`,`public`]),PE={private:`Only me`,shared:`Me and chosen people`,public:`Everyone`},FE=S({owner:M,visibility:NE,with:x(M)});E([`system`,`fn`,`context`,`root`,`connection`]);var IE=w(`kind`,[S({kind:D(`system`),system:F}),S({kind:D(`fn`),fn:I}),S({kind:D(`context`),context:I}),S({kind:D(`root`),uri:v().min(1)}),S({kind:D(`connection`),connection:Ol})]);function LE(e){switch(e.kind){case`system`:return`system:${e.system}`;case`fn`:return`fn:${e.fn}`;case`context`:return`context:${e.context}`;case`root`:return`root:${e.uri}`;case`connection`:return`connection:${e.connection}`}}S({key:v(),target:IE,sharing:FE,scoped:b().optional(),setBy:M,updatedAt:N});var RE=S({target:IE,sharing:FE,editable:b()}),zE=S({multiUser:b()}),BE=FE.omit({owner:!0}),VE=S({run:A,fn:k,share:BE}),HE=S({run:A,fns:x(k).max(1e3)}),UE=S({source:E([`fn`,`context`,`system`,`person`,`group`,`model`,`resource`,`type`,`kind`]),text:v().optional(),values:x(v()).max(200).optional(),limit:y().int().min(1).max(50).optional()}),WE=S({value:v(),label:v(),hint:v().optional(),icon:v().optional(),missing:b().optional()}),GE=E([`shared`,`person`]),KE=v().regex(/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/),qE=T(KE,v()),JE=S({kind:D(`none`)}),YE=S({kind:D(`bearer`),per:GE,token:v().min(1).optional()}),XE=S({kind:D(`headers`),per:GE,names:x(KE).min(1),values:qE.optional()}),ZE=w(`kind`,[JE,YE,XE,S({kind:D(`oauth`),per:GE,scopes:x(v().min(1)).optional(),clientId:v().min(1).optional(),clientSecret:v().min(1).optional()})]),QE=w(`kind`,[JE,YE,XE]),$E=w(`kind`,[JE,YE.omit({token:!0}),XE.omit({values:!0})]),eD=[`auth.token`,`auth.values`],tD=[`auth.token`,`auth.values`,`auth.clientSecret`];function nD(e){if(e.kind===`oauth`)return`oauth`;if(e.kind!==`none`&&e.per!==`shared`)return`form`}var rD=C([S({token:v().min(1)}),S({headers:qE}),S({accessToken:v().min(1),refreshToken:v().min(1).optional(),tokenType:v().default(`Bearer`),clientId:v().min(1).optional()})]),iD=S({on:b(),ask:b()}),aD=w(`flow`,[S({flow:D(`oauth`)}),S({flow:D(`form`),form:Z})]),oD=S({flow:aD.optional(),share:b().default(!1),title:v().min(1)}),sD=v().regex(Al).brand();fc({name:sD,label:v().min(1),auth:ZE,baseUrl:Ls().optional(),privateTo:M.optional()});var cD=C([sD,S({arg:k})]),lD=S({title:v(),description:v(),icon:v().optional(),how:aD,settings:Z,fns:T(k,iD),scope:E([`system`,`instance`,`key`]).optional(),keys:S({type:I}).optional(),defaults:iD.optional()}),uD=E([`pending`,`connected`,`expired`,`failed`]),dD=S({label:v(),detail:v().optional(),choices:T(v(),x(WE)).optional()}),fD=S({id:Ol,system:F,instance:L.optional(),key:sD.optional(),owner:M,status:uD,account:dD.optional(),credentials:bl.optional(),expiresAt:N.optional(),settings:O,fns:T(k,iD),share:BE,problem:v().optional(),createdAt:N,updatedAt:N}).omit({credentials:!0}),pD=S({system:F,decl:lD,ready:b(),connections:x(fD),instances:x(S({instance:L,label:v(),connect:oD})).optional(),keys:x(S({key:sD,label:v(),connect:oD,host:v().optional()})).optional()}),mD=S({id:Ol,owner:M,credentials:O,settings:O}),hD=S({connection:Ol,owner:M,redirect:Ls(),state:v(),instance:L.optional(),key:sD.optional()}),gD=S({connection:Ol,owner:M,instance:L.optional(),key:sD.optional(),redirect:Ls(),answer:C([S({params:T(v(),v())}),S({form:O})])}),_D=C([S({account:dD,credentials:O,expiresAt:N.optional()}),S({problem:v()})]),vD=S({connection:Ol,update:C([S({credentials:O,expiresAt:N.optional()}),S({expired:v()})])}),yD=S({connection:Ol,settings:O.optional(),fns:T(k,iD).optional(),share:BE.optional()}),bD=[`embedding`,`imageEmbedding`],xD=S({input:P,output:P,cached:P.optional(),cacheWrite:P.optional()}),SD=S({id:v().min(1),name:v().optional(),capabilities:x(v()),contextWindow:y().int().min(1),maxOutput:y().int().min(1).optional(),pricing:xD,caching:b(),dimensions:y().int().min(1).optional(),maxInput:y().int().min(1).optional(),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}).refine(e=>!bD.some(t=>e.capabilities.includes(t))||e.dimensions!==void 0,{message:`An embedding model says how many dimensions its vectors have.`,path:[`dimensions`]}),CD=S({name:k,description:v(),models:x(SD),runtime:D(!0).optional(),instance:L.optional()}),wD=S({provider:k,model:v(),request:LT,stream:b(),run:A.optional()}),TD=w(`type`,[S({type:D(`chunk`),chunk:jT}),S({type:D(`done`),usage:kT}),S({type:D(`error`),message:v(),kind:E([`model`,`limit`,`provider`,`auth`])})]),ED=S({id:v().min(1),contextWindow:y().int().min(1).optional(),maxOutput:y().int().min(1).optional(),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}),DD=S({provider:k}),OD=w(`listed`,[S({listed:D(!0),models:x(ED)}),S({listed:D(!1)})]),kD=S({provider:k,model:v(),input:WT,questions:GT}),AD=S({answers:JT,tokens:y().int().min(0).optional()}),jD=S({image:v().regex(/^(https?:|data:)/,`an http(s) or data URL`),mimeType:v().optional()}),MD=C([v(),jD]),ND=S({provider:k,model:v(),inputs:x(MD).min(1)}),PD=S({vectors:x(x(y())),tokens:y().int().min(0).optional()});function FD(e){return S({provider:D(`aws`),region:v().min(1),auth:w(`kind`,[S({kind:D(`keys`),accessKeyId:v().min(1),secretAccessKey:e,sessionToken:e.optional()}),S({kind:D(`apiKey`),apiKey:e})]),profilePrefix:v().optional()})}var ID=S({input:b(),output:b()}),LD=C([S({ok:D(!0)}),S({ok:D(!1),reason:v().min(1)})]),RD=C([S({ok:D(!0)}),S({ok:D(!1),action:E([`retry`,`stop`]),reason:v().min(1)})]),zD=w(`phase`,[S({phase:D(`input`),run:Dw,fn:v(),args:O}),S({phase:D(`output`),run:Dw,fn:v(),args:O,result:O,attempt:y().int().min(1)})]),BD=C([RD,LD]),VD=S({kind:E([`builtin`,`dynamic-import`,`dynamic-require`,`eval`,`new-function`]),line:y().int().min(1),detail:v(),code:v()}),HD=S({size:y().int().min(0),builtins:x(v()),concerns:x(VD),urls:x(v()),hosts:x(v())}),UD=E([`passed`,`failed`,`skipped`]),WD=S({file:v().min(1),name:v().min(1),status:UD,duration:kl,real:b().optional(),error:v().max(4e3).optional()}),GD=[`phone`,`desktop`],KD=E(GD);E([`empty`,`loading`,`error`,`typical`,`long`]);var qD=S({component:v().min(1),state:v().min(1),viewport:KD,theme:E([`light`,`dark`]),image:Dx}),JD=S({scan:HD,tests:S({system:F,version:v().min(1),ranAt:N,duration:kl,passed:y().int().min(0),failed:y().int().min(0),skipped:y().int().min(0),cases:x(WD).max(500),more:y().int().min(0).optional(),previews:x(qD).max(200).optional()}).optional()}),YD=E([`ai`,`embed`,`resources`,`fns`,`search`,`decide`,`approvals`,`connections`,`settings`,`state`,`data`,`runs`]),XD=S({roles:x(pE).optional(),models:x(v().min(1)).optional(),perRun:P.optional(),perDay:P.optional()}),ZD=S({read:x(v().min(1)),write:x(v().min(1))}),QD=S({hub:x(YD),models:XD.optional(),secrets:x(v().min(1)).optional(),calls:x(C([I,F])).optional(),network:x(v().min(1)).optional(),files:ZD.optional()}),$D=S({component:v().min(1),mode:E([`replace`,`beside`])}),eO=[`installed`,`live`],tO=E(eO),nO=[`text`,`integer`,`number`,`boolean`,`date`,`datetime`,`time`,`uuid`,`json`,`binary`],rO=E(nO),iO=E([`group`,`measure`,`attribute`]),aO=S({name:k,label:v().min(1),accepts:x(rO).min(1),required:b(),many:b(),min:y().int().min(1).optional(),role:E([`group`,`measure`]).optional()}),oO=w(`rule`,[S({rule:D(`distinct`),channel:k,max:y().int().min(1)}),S({rule:D(`non-negative`),channel:k}),S({rule:D(`bounded`),channel:k}),S({rule:D(`distinct-columns`),channels:x(k).min(2)}),S({rule:D(`links`),from:k,to:k})]),sO=E([`window`,`top-n`,`partition`,`aggregate`]),cO=S({name:k,label:v().min(1),whole:D(!0).optional(),needs:x(k).optional()}),lO=S({claim:D(`range`),channel:k}),uO=E([`floor`,`structural`,`encoded`,`time-encoded`]),dO=E([`temporal-key`,`low-cardinality`,`enum-key`,`high-null`,`many-categories`]),fO=S({channels:x(aO).min(1),rows:S({min:y().int().min(0),max:y().int().min(1).optional()}),whole:b(),rules:x(oO).default([]),size:sO.optional(),styles:x(cO).min(1).default([{name:`default`,label:`Default`}]),claims:x(lO).default([]),priority:S({band:uO,terms:x(dO)}).default({band:`structural`,terms:[]}),pageSize:y().int().min(1).max(500).optional()}),pO=S({name:k,description:v(),data:Z}),mO=S({registry:I,name:k,label:v().min(1),description:v().optional(),icon:v().optional(),shape:fO.optional()}),hO=mO.extend({system:F}),gO=S({name:v().min(1),label:v().optional(),kind:rO,nullable:b(),type:Z.optional(),ref:I.optional(),role:iO.optional(),key:b().optional(),editable:b().optional()}),_O=S({column:v().min(1),dir:E([`asc`,`desc`])}),vO=S({fn:I,args:T(v(),O),keys:x(v().min(1))}),yO=S({columns:x(gO),rows:x(x(O)),offset:y().int().min(0),limit:y().int().min(1).optional(),total:y().int().min(0).optional(),truncated:b(),sort:x(_O),write:S({affected:y().int().min(0)}).optional(),records:S({type:I,id:v().min(1)}).optional(),drill:vO.optional()}),bO=S({flag:E([`delete-fns`,`write-fns`,`runs`,`injects`,`effects`,`capabilities`,`secrets`,`hosts`,`files`,`calls`,`models`]),line:v().min(1),items:x(v().min(1)),lead:v().min(1).optional(),tail:v().min(1).optional()}),xO=S({section:v().min(1),added:y().int().min(0),changed:y().int().min(0),removed:y().int().min(0)}),SO=E([`widened`,`narrowed`,`changed`,`added`]),CO=S({line:v(),counts:x(xO),flags:x(bO),grants:SO.optional(),config:E([`added`,`changed`,`removed`]).optional()}),wO=E([`gitignored`,`env`,`key`,`credential`,`token`,`secret-content`,`runs-code`,`unknown-path`]),TO=E([`allow`,`ask`,`refuse`]),EO=E([`ask`,`refuse`]),DO=w(`type`,[S({type:D(`glob`),glob:v().min(1)}),S({type:D(`content`),pattern:v().min(1)}),S({type:D(`gitignored`)})]);S({name:v().min(1),kind:wO,match:DO,except:x(v().min(1)).optional(),read:TO,write:EO,why:v().min(1)});var OO=S({path:v().min(1),kind:wO,rule:v().min(1),access:E([`read`,`write`]),action:E([`allow`,`ask`,`refuse`]),why:v().min(1),certain:b()}),kO=S({flags:x(OO)}),AO=w(`type`,[S({type:D(`text`),text:v()}),S({type:D(`code`),language:v(),code:v(),title:v().optional()}),S({type:D(`table`),title:v(),table:yO}),S({type:D(`type-diff`),name:v(),before:Z.optional(),after:Z.optional(),changes:x(v()),breaks:x(S({fn:v(),why:v()}))}),S({type:D(`flags`),flags:x(OO).min(1)})]),jO=S({kind:D(`system-install`),system:F,instance:L,version:v().min(1),manifestHash:v().min(1),bundleHash:v().min(1),sourceHash:v().min(1),host:Wl,source:v().min(1).optional(),grants:QD.optional(),replaces:S({version:v().min(1),manifestHash:v().min(1)}).optional()}),MO=w(`kind`,[jO]),NO=S({title:v().min(1),parts:x(AO),irreversible:b(),subject:MO.optional(),checks:JD.optional(),summary:CO.optional()}),PO=E([`person`,`admins`]),FO=S({preview:b(),remember:b(),approver:PO.optional()}),IO=S({run:A,fn:k,args:O,user:ww,kind:jl.optional(),payload:O.optional()}),LO=S({run:A,fn:k,args:O,user:ww,deadline:N}),RO=S({problems:x(Bw)}),zO=S({type:Z,into:k,label:v().min(1).max(80).optional()}),BO=S({fn:k,args:O,key:v().min(1),parent:A.optional(),approver:PO,for:M.optional(),chat:j.optional(),ask:zO.optional(),preview:NO}).refine(e=>e.parent!==void 0||e.approver===`admins`||e.for!==void 0,{message:"A run proposed outside a run waits for an admin, or for the person named in `for`.",path:[`approver`]}),VO=S({by:M,preview:NO}),HO=S({run:A,subject:jO}),UO=S({token:v().min(1),expiresAt:N}),WO=S({run:A,approval:pl}),GO=v().regex(/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/),KO=x(GO),qO=`•••• kept`;S({$secret:bl,json:D(!0).optional()});var JO=v().regex(/^[a-z][a-z0-9-]{0,39}$/,`a page segment is lowercase letters, digits and dashes, starting with a letter (at most 40)`),YO=E([`main`,`hidden`]),XO=E([`everyone`,`admin`]),ZO=S({segment:JO,title:v().trim().min(1).max(40),description:v().optional(),icon:v().min(1).optional(),nav:YO.default(`main`),access:XO.default(`everyone`),component:v().min(1)});function QO(e){let t=new Set;return e.flatMap(e=>t.has(e.segment)?[`page ${e.segment} is declared twice`]:(t.add(e.segment),[]))}var $O=x(ZO).superRefine((e,t)=>{for(let n of QO(e))t.addIssue({code:`custom`,message:n})}),ek=ZO.extend({system:F,client:S({url:v().min(1),hash:v().min(1)})}),tk=`http://127.0.0.1:11434`;function nk(e){return w(`provider`,[S({provider:D(`openai`),apiKey:e,baseURL:Ls().optional()}),S({provider:D(`openrouter`),apiKey:e}),S({provider:D(`ollama`),baseURL:Ls().default(tk),contextWindow:y().int().min(256).optional(),decisionModels:x(v().min(1)).optional()}),FD(e)])}var rk=nk(bl),ik=E(rk.options.map(e=>e.shape.provider.value));S({id:Sl,config:rk,createdAt:N}),S({id:bl,name:v(),owner:M,ciphertext:v(),createdAt:N});var ak=S({id:xl,name:v(),description:v(),models:x(v())}),ok=w(`scope`,[S({scope:D(`hub`)}),S({scope:D(`group`),group:M}),S({scope:D(`user`),user:M}),S({scope:D(`session`),session:j}),S({scope:D(`turn`),turn:al}),S({scope:D(`system`),system:F}),S({scope:D(`fn`),fn:I}),S({scope:D(`model`),model:v()})]),sk=E([`hub`,`group`,`user`,`session`,`turn`]),ck=w(`scope`,[S({scope:D(`hub`)}),S({scope:D(`group`),group:M}),S({scope:D(`user`),user:M}),S({scope:D(`session`),session:j}),S({scope:D(`turn`),turn:al})]),lk=S({id:ml,target:ok,period:C([S({window:kl}),D(`all-time`),D(`per-turn`)]),maxCost:P,maxTokens:y().int().optional(),maxCalls:y().int().optional(),maxTime:kl.optional(),share:E([`pooled`,`each`]).optional(),onLimit:E([`wait`,`refuse`,`ask`]),setBy:M}),uk=S({id:hl,target:ck,default:Fl.optional(),max:Fl.optional(),setBy:M}),dk=S({priority:Fl,priorityFrom:S({default:sk,cappedBy:sk.optional()}),turn:S({cost:P,time:kl}),budgets:x(S({rule:ml,scope:ok,remaining:P})),limitedBy:ml.optional()});S({id:gl,budgets:x(ml),estimate:P,createdAt:N,settled:S({cost:P,at:N}).optional()}),S({id:_l,at:N,cost:P,tokens:y().int().min(0),actor:M,system:F.optional(),session:j.optional(),fn:I,model:v().optional(),llmCall:ll.optional(),modelCall:Tl.optional(),run:A});var fk=E([`chat`,`admin`,`disconnected`,`needs-config`,`held`,`removed`]),pk=S({prompt:x(S({name:F,label:v(),description:v(),summary:v().optional()})),on:x(F),off:x(S({name:F,why:fk}))}),mk=S({name:F,reason:v(),label:v().optional(),description:v().optional()}),hk=RegExp(`(\\d+)`,`g`);function gk(e,t=[]){let n=new Map(t.map(e=>[e.index,e.number]));return e.replace(hk,(e,t)=>{let r=n.get(Number(t));return r===void 0?``:`[${r}]`})}function _k(e){let t=e.trim().replace(/^\$\.?/,``);if(t===``)return[];let n=[],r=/\[\s*(?:"([^"]*)"|'([^']*)'|(\d+))\s*\]|([^.[\]]+)/y,i=0;for(;i<t.length;){if(t[i]===`.`){i+=1;continue}r.lastIndex=i;let e=r.exec(t);if(e===null)return;n.push(e[1]??e[2]??e[3]??e[4]??``),i=r.lastIndex}return n}function vk(e){try{return O.parse(JSON.parse(e))}catch{return}}function yk(e,t){let n=_k(t);if(n===void 0)return;let r=e;for(let e of n){let t=typeof r==`string`?vk(r):r;if(Array.isArray(t)){if(!/^\d+$/.test(e))return;let n=t[Number(e)];if(n===void 0)return;r=n}else if(typeof t==`object`&&t){if(!Object.hasOwn(t,e))return;let n=t[e];if(n===void 0)return;r=n}else return}return{value:r}}var bk=S({index:y().int().min(1),number:y().int().min(1),tool:v(),path:v(),note:v()}),xk=E([`result`,`reply`]),Sk=bk.extend({run:A.optional(),fn:I.optional(),found:xk.optional(),value:O.optional(),large:D(!0).optional(),problem:v().optional()}),Ck=S({prompt:b(),on:b()}),wk=y().int().min(0).max(3),Tk=S({agent:I,model:TT.optional(),mode:Lb.optional(),contextor:Jb.optional(),fnMode:ux.optional(),systems:C([x(F),D(`all`)]),instructions:v().optional(),citations:b().optional()}),Ek=Tk.partial(),Dk=x(S({label:v().trim().min(1).max(40).optional(),settings:Ek})).min(2).max(4),Ok=S({turn:al,variant:wk,label:v()}),kk=S({variant:wk,label:v(),settings:Ek,session:j,turn:al}),Ak=S({run:A,fn:I}),jk=S({variant:wk,effects:x(Ak)}),Mk=S({variant:wk,label:v(),effects:x(Ak).min(1)}),Nk=S({variants:x(kk).min(2).max(4),reserved:P,chosen:wk.optional(),chosenBy:M.optional(),chosenAt:N.optional(),discarded:x(jk)}),Pk=S({field:v(),type:v(),before:O.optional(),after:O.optional()}),Fk=S({id:A,fn:I,fnVersion:v(),kind:jl,system:F,instance:L.optional(),parent:A.optional(),root:A,turn:al,session:j.optional(),key:v(),actor:M,caller:M,connection:Ol.optional(),llmCall:ll.optional(),toolCallId:v().optional(),args:O,repairs:x(Vw).optional(),test:b().optional(),status:Gw,text:aw.optional(),outcome:$w.optional(),progress:Fw.optional(),allowed:jw,cost:P,totalCost:P,priority:Fl,background:b(),attempt:y().int().min(1),errors:x(S({attempt:y().int(),error:Rw,cost:P,at:N})),undo:O.optional(),resume:O.optional(),stateChanges:x(Pk),tokens:y().int().min(0).optional(),createdAt:N,approvedAt:N.optional(),startedAt:N.optional(),endedAt:N.optional()}),Ik=Fk.pick({id:!0,fn:!0,status:!0,cost:!0,totalCost:!0,startedAt:!0,endedAt:!0}),Lk=S({session:j,system:F,name:v(),type:v(),def:Z,value:O,version:y().int().min(1),updatedBy:C([S({run:A}),S({delivery:sl})]),updatedAt:N}).pick({name:!0,type:!0}).extend({value:O.optional()}),Rk=E([`queued`,`delivered`,`done`,`failed`,`expired`]),zk=S({id:sl,system:F,kind:C([S({action:v(),input:O}),S({form:A,value:O})]),session:j,actor:M,run:A.optional(),status:Rk,result:O.optional(),error:Rw.optional(),attempts:y().int().min(0),createdAt:N,deliveredAt:N.optional(),doneAt:N.optional(),expiresAt:N.optional()}).pick({id:!0,status:!0,result:!0,error:!0}),Bk=S({id:cl,run:A,handler:v(),args:O,decl:S({description:v(),args:Z,returns:Z}),answerer:C([S({user:M}),S({system:F,run:A})]),status:E([`pending`,`answered`,`failed`]),result:O.optional(),createdAt:N}),Vk=E([`running`,`done`,`failed`,`cancelled`,`paused`,`undone`]),Hk=S({transcript:y().int().min(0),tools:x(I),context:x(I),selection:cx.optional(),suggested:x(I).optional(),announcedSystems:pk.optional(),citationsTold:Ck.optional()});S({id:al,session:j.optional(),message:ol.optional(),actor:M,user:ww,time:Tw,client:Ow.optional(),root:A.optional(),status:Vk,limits:dk,cost:P,errors:C([S({max:y().int().min(1)}),D(`feed-back`)]),start:Hk.optional(),compare:Nk.optional(),createdAt:N,continuedAt:N.optional(),endedAt:N.optional()});var Uk=E([`queued`,`streaming`,`done`,`failed`,`aborted`]),Wk=S({content:v(),reasoning:v().optional(),toolCalls:x(jT.shape.toolCall.unwrap()).optional(),finishReason:jT.shape.finishReason.unwrap(),refusal:v().optional()}),Gk=S({id:ll,turn:al,run:A,session:j.optional(),system:F.optional(),iteration:y().int().min(0),provider:v(),model:v(),request:LT,response:Wk.optional(),usage:kT.optional(),cost:P,status:Uk,error:v().optional(),priority:Fl,selection:ax.optional(),modelCall:Tl.optional(),queuedAt:N,startedAt:N.optional(),firstTokenAt:N.optional(),endedAt:N.optional()}),Kk=Kc(()=>S({run:Ik,llmCalls:x(Gk.pick({id:!0,model:!0,cost:!0,status:!0})),children:x(Kk)})),qk=S({turn:al,undone:x(S({run:A,fn:I,summary:v()})),failed:x(S({run:A,fn:I,error:Rw})),notUndoable:x(S({run:A,fn:I})),kept:x(Mk).optional(),session:S({messages:y().int().min(0),unloaded:x(I),reloaded:x(I)}).optional()});S({run:A,turn:al,session:j.optional(),iteration:y().int().min(0),priority:Fl}),S({run:A,priority:Fl});var Jk=[`system`,`instance`,`fn`,`context`,`type`,`kind`,`resource`,`root`,`component`,`registry`,`command`,`provider`],Yk=E(Jk),Xk=[`brings`,`names`,`loads`,`next`,`reads`,`writes`,`calls`,`uses`,`kind`,`creates`,`updates`,`removes`,`refers`,`renders`,`contributes`,`belongs`],Zk=E(Xk),Qk=[...eO,`pending`];E(Qk);var $k=E([`text`,`enum`,`number`,`date`,`boolean`]);E([`is`,`isNot`,`in`,`notIn`,`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`,`contains`]);var eA={text:[`contains`,`is`,`isNot`,`in`,`notIn`,`empty`,`notEmpty`],enum:[`is`,`isNot`,`in`,`notIn`,`empty`,`notEmpty`],number:[`gt`,`gte`,`lt`,`lte`,`between`,`is`,`isNot`,`empty`,`notEmpty`],date:[`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`],boolean:[`is`]},tA={is:`is`,isNot:`is not`,in:`in`,notIn:`not in`,gt:`>`,gte:`≥`,lt:`<`,lte:`≤`,between:`between`,empty:`is empty`,notEmpty:`is not empty`,contains:`contains`},nA=C([v(),y(),b()]),rA=E([`usd`,`ms`,`tokens`,`bytes`,`count`]);S({label:v(),type:$k,sortable:b(),filterable:b(),values:x(v()).readonly().optional(),dynamic:b().optional(),unit:rA.optional()});var iA=v().min(1),aA=w(`op`,[S({field:iA,op:E([`is`,`isNot`,`gt`,`gte`,`lt`,`lte`,`contains`]),value:nA}),S({field:iA,op:E([`in`,`notIn`]),values:x(nA).min(1)}),S({field:iA,op:D(`between`),from:nA,to:nA}),S({field:iA,op:E([`empty`,`notEmpty`])})]),oA=S({field:iA,dir:E([`asc`,`desc`])}),sA=zl.extend({text:v().optional(),filters:x(aA).max(20).optional(),sort:x(oA).max(3).optional()}),cA=(e,t={})=>({label:e,type:`text`,sortable:!0,filterable:!0,...t}),lA=(e,t)=>({label:e,type:`enum`,sortable:!0,filterable:!0,values:t}),uA=e=>({label:e,type:`enum`,sortable:!0,filterable:!0,dynamic:!0}),dA=(e,t)=>({label:e,type:`number`,sortable:!0,filterable:!0,unit:t}),fA=e=>({label:e,type:`date`,sortable:!0,filterable:!0}),pA=e=>({label:e,type:`boolean`,sortable:!1,filterable:!0}),mA=e=>({...e,sortable:!1}),hA=[`resources`,`fns`,`runs`,`modelCalls`,`llmCalls`,`sessions`,`contexts`,`notifications`,`systems`,`types`,`graph`,`users`,`groups`],gA=E(hA),_A={resources:{fields:{name:cA(`Name`),system:uA(`System`),family:lA(`Type`,dT),source:lA(`Source`,cT),forms:{...lA(`Forms`,Fx.options),sortable:!1},size:dA(`Size`,`bytes`),seenAt:fA(`Seen`),modifiedAt:fA(`Modified`)},defaultSort:[{field:`seenAt`,dir:`desc`}]},fns:{fields:{name:cA(`Name`),system:uA(`System`),kind:uA(`Kind`),available:pA(`Available`),paused:pA(`Paused`),disabled:pA(`Disabled`),runs:dA(`Runs`,`count`),failures:dA(`Failures`,`count`),averageCost:dA(`Avg cost`,`usd`),averageTime:dA(`Avg time`,`ms`),lastRunAt:fA(`Last run`),updatedAt:fA(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},runs:{fields:{fn:uA(`Fn`),system:uA(`System`),status:lA(`Status`,Ww),session:uA(`Session`),actor:uA(`By`),cost:dA(`Cost`,`usd`),duration:dA(`Duration`,`ms`),createdAt:fA(`Started`),endedAt:fA(`Ended`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},modelCalls:{fields:{modality:lA(`Modality`,XT),model:uA(`Model`),provider:uA(`Provider`),system:uA(`System`),status:lA(`Status`,aE.options),session:uA(`Session`),cost:dA(`Cost`,`usd`),tokens:dA(`Tokens`,`tokens`),duration:dA(`Duration`,`ms`),createdAt:fA(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},llmCalls:{fields:{model:uA(`Model`),system:uA(`System`),status:lA(`Status`,Uk.options),session:uA(`Session`),cost:dA(`Cost`,`usd`),tokens:dA(`Tokens`,`tokens`),duration:dA(`Duration`,`ms`),createdAt:fA(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},sessions:{fields:{title:cA(`Title`),agent:uA(`Agent`),status:lA(`Status`,[`idle`,`running`,`paused`]),archived:pA(`Archived`),createdAt:fA(`Created`),updatedAt:fA(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},contexts:{fields:{name:cA(`Name`),system:uA(`System`),origin:lA(`Origin`,Xx),tags:uA(`Tag`),disabled:pA(`Off`),stale:pA(`Stale`),tokens:dA(`Tokens`,`tokens`),updatedAt:fA(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},notifications:{fields:{kind:uA(`Kind`),read:pA(`Read`),createdAt:fA(`Received`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},systems:{fields:{name:cA(`Name`),status:uA(`Status`),version:cA(`Version`),instances:dA(`Instances`,`count`),fns:dA(`Fns`,`count`),context:dA(`Context`,`count`),types:dA(`Types`,`count`),parts:dA(`Other parts`,`count`),pending:dA(`Pending changes`,`count`),refusals:dA(`Refusals`,`count`),lastSeenAt:fA(`Last seen`)},defaultSort:[{field:`name`,dir:`asc`}]},types:{fields:{name:cA(`Name`),system:uA(`System`),instance:uA(`Instance`),references:dA(`Refers to`,`count`),updatedAt:fA(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},graph:{fields:{name:mA(cA(`Name`)),system:mA(uA(`System`)),nodeKind:mA(lA(`Item`,Jk)),edgeKind:mA(lA(`Link`,Xk)),fnKind:mA(uA(`Fn kind`)),mode:mA(uA(`Mode`)),effect:mA(uA(`Effect on`)),visibility:mA(lA(`Visible to`,Il.options)),stage:mA(lA(`Stage`,Qk)),on:pA(`On`)},defaultSort:[]},users:{fields:{name:cA(`Name`),email:cA(`Email`),role:lA(`Role`,[`admin`,`member`]),disabled:pA(`Disabled`),createdAt:fA(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]},groups:{fields:{name:cA(`Name`),createdAt:fA(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]}};function vA(e,t){return t.sort!==void 0&&t.sort.length>0?t.sort:_A[e].defaultSort}var yA=S({value:nA,label:v().optional(),count:y().int().min(0)}),bA=S({list:gA,field:iA,prefix:v().optional(),limit:y().int().min(1).max(50).optional()}),xA=S({list:gA,query:sA.default({})}),SA=Rl(Zc()).extend({sort:x(oA),total:y().int().min(0).optional(),partial:D(!0).optional().describe(`More rows than the hub reads at once: more may match; narrow the filters for a full answer.`)}),CA=il.record,wA=S({shape:E([`table`,`value`]),owner:E([`shared`,`person`]),writers:D(`admins`).optional(),search:S({text:x(v().min(1)),embed:b()})}),TA=S({id:CA,type:I,value:O,owner:M.optional(),title:v(),version:y().int().min(1),createdAt:N,updatedAt:N,updatedBy:M.optional(),updatedBySystem:F.optional(),run:A.optional()}),EA=S({id:v().min(1),record:CA,type:I,number:y().int().min(1),change:E([`created`,`updated`,`removed`]),value:O,by:M.optional(),bySystem:F.optional(),run:A.optional(),at:N}),DA=S({type:I,query:sA.optional(),search:v().min(1).optional(),run:A.optional()}),OA=Rl(TA),kA=DA.extend({query:sA.omit({cursor:!0,limit:!0}).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(500).optional()}),AA=S({type:I,id:CA,run:A.optional()}),jA=S({type:I,id:CA.optional(),value:O,expect:y().int().min(1).optional(),run:A.optional(),owner:M.optional()}),MA=S({type:I,id:CA,set:T(v().min(1),O).refine(e=>Object.keys(e).length>0,`set at least one field`),expect:y().int().min(1).optional(),run:A.optional()}),NA=S({type:I,id:CA,run:A.optional()}),PA=zl.extend({type:I,id:CA}),FA=Rl(EA),IA=S({type:I,system:F,description:v(),storage:wA,records:y().int().min(0),updatedAt:N.optional()}),LA=zl.extend({text:v().optional(),system:F.optional()}),RA=Rl(IA),zA=`general`,BA=S({name:k,title:v().min(1),description:v().min(1)});function VA(e){for(let t of e.matchAll(uw)){let n=(t[1]??``).trim();if(!n.startsWith(`args.`))return`the claim "${e}" uses {${n}}: a claim reads only its call's args ({args.path})`}}var HA=v().min(1).max(500).superRefine((e,t)=>{let n=VA(e);n!==void 0&&t.addIssue({code:`custom`,message:n})}),UA=S({fn:k,args:O,user:ww,caller:A,session:j.optional()}),WA=S({claims:x(v().min(1))});function GA(e){return e==null||e===``?[]:typeof e==`string`?[e]:typeof e==`number`||typeof e==`boolean`?[String(e)]:Array.isArray(e)?e.flatMap(e=>Array.isArray(e)?[JSON.stringify(e)]:GA(e)):[JSON.stringify(e)]}function KA(e,t){let n=[],r=[],i=0;for(let a of e.matchAll(uw)){n.push(e.slice(i,a.index)),i=a.index+a[0].length;let[o,...s]=(a[1]??``).trim().split(`.`),c=o===`args`?GA(hw(t,s)):[],l=a[2],u=c.length>0?c:l===void 0?[]:[l];if(u.length===0)return[];r.push(u)}n.push(e.slice(i));let a=[n[0]??``];return r.forEach((e,t)=>{let r=n[t+1]??``;a=a.flatMap(t=>e.map(e=>`${t}${e}${r}`))}),a}function qA(e,t){return[...new Set(e.flatMap(e=>KA(e,t)))]}var JA=S({label:v(),plural:v().optional(),icon:v().optional(),color:v().optional(),title:v().optional(),subtitle:v().optional()}),YA=S({name:k,description:v(),def:Z,display:JA,methods:x(k),instance:L.optional(),audience:BE.optional(),meta:T(v(),O).optional(),records:wA.optional()}),XA=E([`user-wins`,`union`,`intersect`,`most-restrictive`]),ZA=E([`self`,`fns`]),QA=S({name:k,description:v(),type:Z,appliesTo:x(Ll),merge:XA,editableBy:x(ZA)}),$A=S({name:k,description:v(),data:Z}),ej=S({name:k,description:v(),applicability:v(),payload:Z,approveChanges:b(),status:iw.optional(),estimates:b().optional(),approval:FO.optional()}),tj=S({description:v(),args:Z,returns:Z,required:b()}),nj=w(`to`,[S({to:D(`instance`),instance:L}),S({to:D(`any`)})]),rj=S({args:O,result:O.optional(),note:v().optional()}),ij=E([`read`,`write`,`delete`]),aj=E([`fns`,`types`,`context`,`resources`,`kinds`,`components`,`examples`,`approvals`,`secrets`,`connections`,`records`]),oj=[`create`,`update`,`remove`],sj=E(oj),cj=S({thing:aj,action:sj,kind:jl.optional()}).refine(e=>e.kind===void 0||e.thing===`fns`,{message:`only fns have a kind`,path:[`kind`]}),lj=E([`resources`]),uj=S({mode:ij.optional(),reads:x(I).optional(),writes:x(I).optional(),free:b().optional(),registry:x(cj).optional(),keeps:x(lj).min(1).optional()}),dj=S({language:v().min(1),code:v()}),fj=S({every:kl.min(1e3)}),pj=E([`developer`,`admin`,`reference`]),mj=S({deps:x(I)}),hj=S({name:k,description:v(),instructions:v().optional(),kind:jl,payload:O.optional(),readable:dj.optional(),args:Z,returns:Z,deps:x(I),handlers:T(v(),tj),progress:Nw,status:iw.optional(),operations:Aw,undo:Z.optional(),resume:Z.optional(),state:Z.optional(),form:Z.optional(),display:kw,limits:Mw,visibility:Il,tags:x(v()),niche:pj.optional(),examples:x(rj).optional(),validate:ID.optional(),approval:FO.optional(),routing:nj.optional(),connectKey:cD.optional(),effects:uj.optional(),promptExamples:y().int().min(0).max(20).optional(),group:k.optional(),flags:b().optional(),roles:x(pE).optional(),live:fj.optional(),parallelClaims:x(HA).optional(),dynamicClaims:b().optional(),check:mj.optional()}),gj=S({name:v(),hint:v(),required:b()}),_j=S({to:I,when:v().min(1).max(200)}),vj=S({name:k,title:v().min(1).optional(),description:v(),content:v().optional(),command:S({name:v(),args:x(gj)}).optional(),imports:x(I),fns:x(I),suggestFns:x(I),suggest:Il,visible:Il,inject:Sb.optional(),tags:x(v()),niche:pj.optional(),weight:y().min(0).max(2).optional(),summary:v().optional(),parent:I.optional(),next:I.optional(),choices:x(_j).optional(),links:x(rS).optional()}),yj=S({name:k,description:v(),explains:v().min(1).max(2e3).optional(),order:y(),timeout:kl}),bj=S({name:k,title:v(),description:v(),target:Z,of:I.optional()}),xj=S({name:k,description:v(),match:Rx}),Sj=S({name:k,description:v(),input:Z,returns:Z,state:Z.optional(),expires:kl.optional()}),Cj=[`message`,`run`,`resources`,`system`,`fns`],wj=E(Cj),Tj=S({entry:v(),hash:v(),files:x(S({path:v(),size:y().int().min(0),hash:v()}))}),Ej=E([`types`,`settings`,`attachments`,`kinds`,`fns`,`context`,`hooks`,`mentions`,`sectioners`,`actions`]),Dj={types:x(YA),settings:x(QA),attachments:x($A),kinds:x(ej),fns:x(hj),context:x(vj),hooks:x(yj),mentions:x(bj),sectioners:x(xj),actions:x(Sj)},Oj=S({name:F,version:v(),description:v(),about:v().optional(),hash:v(),...Dj,events:x(wj),resources:b(),client:Tj.optional(),config:Z,requires:x(F),providers:x(CD).optional(),connect:lD.optional(),registries:x(pO).optional(),contributes:x(mO).optional(),configSecrets:KO.optional(),runtime:bc(Ej,x(k)).optional(),grants:QD.optional(),configComponent:$D.optional(),pages:$O.optional(),groups:x(BA).optional()}),kj=S({hash:v(),upsert:S(Dj).partial(),remove:bc(Ej,x(k)),lists:Oj.pick({providers:!0,registries:!0,contributes:!0}).optional(),roots:D(!0).optional()}),Aj=S({added:x(I),updated:x(I),removed:x(I),refused:x(S({name:v(),problems:x(v())}))}),jj=S({args:Z,returns:Z,description:v(),mode:ij}),Mj=S({args:Z,returns:Z,deps:x(I),types:x(I).optional(),refs:x(v()).optional(),operations:Aw,handlers:T(v(),tj).optional(),progress:Nw.optional(),status:iw.optional(),limits:Mw.optional(),display:kw.optional(),approval:FO.optional(),effects:uj.optional(),readable:dj.optional(),connectKey:sD.optional(),parallelClaims:x(HA).optional(),examples:x(rj).min(1)});function Nj(e){return e===`native`||e.startsWith(`hub/`)}function Pj(e){return Nj(e.kind)&&(e.examples??[]).length===0}var Fj=S({session:j,turn:al,text:v(),user:ww,time:Tw}),Ij=y(),Lj=S({label:v(),mode:ij,blocked:v().optional(),args:v().optional(),returns:v().optional(),instructions:v().optional(),examples:x(rj).optional(),moreExamples:y().int().positive().optional()}),Rj={toolset:Rb.optional()},zj=w(`type`,[S({type:D(`text`),tag:v(),text:v()}),S({type:D(`suggest-context`),...Rj,items:x(S({context:I,title:v().optional(),why:v().optional(),score:Ij.optional()}))}),S({type:D(`suggest-fns`),...Rj,items:x(S({fn:I,why:v().optional(),score:Ij.optional(),card:Lj.optional()}))}),S({type:D(`load`),context:x(I).optional(),fns:x(I).optional()})]),Bj=S({label:v(),hint:v().optional(),icon:v().optional(),target:O}),Vj=S({title:v(),subtitle:v().optional(),fields:x(S({label:v(),value:v()})).optional(),body:v().optional(),open:zx.optional(),value:O.optional()});vj.omit({name:!0,content:!0}).extend({key:k,summary:v().min(1).max(300),imports:x(I).default([]),fns:x(I).default([]),suggestFns:x(I).default([]),suggest:Il.default(`both`),visible:Il.default(`both`),tags:x(v()).default([])}).strict();var Hj=E([`header`,`duplicate-key`,`broken-link`,`cycle`,`missing-summary`]);S({file:v().min(1),line:y().int().min(1),column:y().int().min(1),code:Hj,message:v().min(1)});var Uj=S({loaded:x(I),fns:x(I),fnsRefused:x(Sw),refused:x(S({context:v(),reason:v().min(1),closest:x(I)})),cards:v()}),Wj=S({context:x(v().min(1)).min(1),guidance:v().min(1).max(4e3),maxDepth:y().int().min(0).max(10).default(fS.maxDepth),maxDecisions:y().int().min(1).max(4096).default(fS.maxDecisions),maxTokens:y().int().min(1).max(1e6).default(fS.maxTokens),metadataOnly:b().default(!1)}),Gj=E([`start`,`import`,`choice`]),Kj=S({name:I,title:v().optional(),description:v(),depth:y().int().min(0),via:Gj,from:I.optional(),probability:y().min(0).max(1).optional(),tokens:y().int().min(0),content:v().optional()}),qj=E([`declined`,`max-tokens`,`max-decisions`,`max-depth`,`unavailable`,`failed`]),Jj=S({context:v(),from:I.optional(),depth:y().int().min(0),reason:qj,probability:y().min(0).max(1).optional()}),Yj=E([`complete`,`max-depth`,`max-decisions`,`max-tokens`,`failed`]),Xj=Uj.extend({crawled:x(Kj),skipped:x(Jj),stop:S({reason:Yj,detail:v().optional()}),depth:y().int().min(0),decisions:y().int().min(0),tokens:y().int().min(0),calls:x(Tl),metadataOnly:b()}),Zj=S({loaded:x(I),refused:x(Sw),cards:v()});C([Zj.strict(),Uj.strict(),Xj.strict()]);var Qj=S({expiresIn:kl.nullable().optional()}),$j=S({id:Dl,secret:v().min(32),expiresAt:N.optional()}),eM=$j.pick({id:!0,secret:!0}),tM=S({id:Dl,system:F,instance:L,secretHash:v(),previousHash:v().optional(),createdBy:M,createdAt:N,expiresAt:N.optional(),lastUsedAt:N.optional(),uses:y().int().min(0),revokedAt:N.optional()}).omit({secretHash:!0,previousHash:!0}),nM=E([`pairing`,`needs-config`,`connected`,`disconnected`,`removed`]),rM=C([S({path:v()}),S({package:v(),version:v()}),S({git:v(),ref:v()}),S({zip:v().regex(Ex),file:v()})]),iM=S({policy:E([`always`,`on-failure`,`never`]),backoff:kl,maxPerHour:y().int().min(1)}),aM=E([`installing`,`stopped`,`starting`,`running`,`crashed`,`disabled`]),oM=S({name:F,instance:L,source:rM,dir:v(),command:S({run:v(),args:x(v()),env:T(v(),v()),cwd:v().optional()}),version:v(),goodVersion:v().optional(),autoStart:b(),restart:iM,status:aM,pid:y().int().optional(),lastExit:S({code:y().int(),at:N,output:v()}).optional(),installedBy:M,installedAt:N}),sM=S({functions:b(),renderers:b(),context:b().optional()}),cM=S({value:O,version:y().int().min(1),setBy:M,setAt:N}),lM=S({keyFingerprint:v().optional(),publicKey:v().optional(),config:cM.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional()}),uM=E([`one`,`many`]),dM=S({name:F,description:v(),about:v().optional(),status:nM,enabled:sM,version:v(),manifestHash:v(),defaultInstance:L.optional(),actor:M,stage:tO.optional(),instances:uM.optional()}).extend(lM.shape),fM=S({id:ul,name:F,keyFingerprint:v(),publicKey:v(),version:v(),address:v(),method:E([`code`,`token`]),code:v().optional(),replaces:F.optional(),description:v().optional(),instance:L.optional(),configType:Z.optional(),configSecrets:KO.optional(),status:E([`pending`,`approved`,`rejected`,`expired`]),createdAt:N,expiresAt:N});S({id:dl,name:F.optional(),tokenHash:v(),createdBy:M,expiresAt:N,usedAt:N.optional(),autoPair:Qj.optional(),boundTo:S({instance:L,manifestHash:v().min(1),host:Wl,run:A}).optional()}),S({system:F,manifest:Oj,importedAt:N});var pM=jE.pick({averageCost:!0,averageQueued:!0,p95:!0,lastRunAt:!0}).extend({outcomes:wE.default(TE),averageTime:kl,tokens:jE.shape.tokens.default(0)}),mM=E([`contract`,`runtime`]),hM=S({name:I,system:F,decl:hj,version:v(),origin:mM,addedBy:M.optional(),available:bw,paused:b(),disabled:b(),stats:pM,updatedAt:N});S({name:I,system:F,decl:ej});var gM=YA.omit({name:!0,methods:!0}).extend({name:I,system:F,references:x(I),declaredBy:mM.optional(),version:v().optional(),updatedAt:N}),_M=S({types:x(gM),missing:x(I)}),vM=vj.extend({alwaysFor:x(I).optional()}),yM=S({name:I,system:F,origin:Yx.optional(),declaredBy:mM.optional(),version:v().optional(),decl:vM,tokens:Zx.optional(),disabled:b().optional(),systemOff:b().optional(),mentions:S({context:x(I),fns:x(I)}),stale:b(),updatedAt:N});function bM(e){return e.disabled===!0||e.systemOff===!0}var xM=[`kinds`,`commands`,`mentions`,`hooks`,`actions`,`settings`,`attachments`,`embedders`,`sectioners`,`providers`,`registries`,`components`,`examples`],SM=E(xM),CM=S({section:SM,name:v().min(1),about:v(),origin:mM,version:v(),visibility:Il.optional(),owner:I.optional(),decl:O,on:b().optional()}),wM=S({system:F}),TM=S({parts:x(CM),more:bc(SM,y().int().min(0))});function EM(e){return wC(e?.name??`otel`,{requires:e?.requires??[]})}var DM=v().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/),OM=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,kM=e=>e!==``&&e!==`.`&&e!==`..`&&!OM.test(e),AM=v().min(1).refine(e=>!e.includes(`\\`)&&!e.includes(`:`)&&e.split(`/`).every(kM),`A package path is relative, uses forward slashes and stays inside the package.`),jM=S({childProcess:b(),workers:b()});S({format:D(1),name:F,version:DM,description:v(),protocol:y().int().min(1),server:S({entry:AM,external:T(v(),v()).default({}),node:v().optional()}),client:S({entry:AM}).optional(),instances:uM.default(`one`),files:T(AM,v().regex(Ex)).optional(),permissions:jM.partial().optional()});var MM=S({state:v(),data:v(),cache:v()}),NM=S({host:Wl,path:v().min(1),bundleHash:v().min(1),approval:pl}),PM=S({system:F,instance:L,description:v(),status:nM,keyFingerprint:v(),publicKey:v(),version:v(),manifestHash:v(),config:cM.optional(),installed:oM.optional(),host:NM.optional(),dirs:MM.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional(),connect:oD.optional()}),FM=S({instance:L,description:v(),online:b(),config:O,types:x(S({name:I,description:v()}))}),IM=S({pairing:ul,description:v(),instance:L,configType:Z.optional(),configSecrets:KO.optional()});S({format:D(1),system:F,instance:L,version:v(),exportedAt:N,exportedBy:M,withSecrets:b()});var LM=S({system:F,instance:L,description:v().optional(),config:O}),RM=S({at:N,stream:E([`stdout`,`stderr`,`hub`]),text:v()}),zM=S({meaning:b(),items:y().int().min(0),pending:y().int().min(0),embedding:b(),retrying:b(),lastError:S({at:N,message:v()}).optional()}),BM=C([ik,I]),VM=S({id:v(),provider:BM,name:v(),contextWindow:y().int().min(0).optional(),pricing:S({input:P,output:P}).optional(),capabilities:x(v()),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}),HM=VM.extend({tier:E([`flagship`,`efficient`,`legacy`,`experimental`]),maxOutputTokens:y().int().min(1).optional(),roles:x(pE)}),UM=lk.extend({spent:P}),WM=S({setting:I,system:F,decl:QA}),GM=Gk.omit({request:!0,response:!0}),KM=w(`kind`,[S({kind:D(`budget`),id:ml}),S({kind:D(`priority`),id:hl}),S({kind:D(`policy`),id:fl}),S({kind:D(`category`),id:xl}),S({kind:D(`provider`),id:Sl})]),qM=S({uri:Cx,system:F,stat:kx,links:x(Ax),indexedVersion:v().optional(),sectioner:I.optional(),source:sT.optional(),raw:Dx.optional(),forms:x(Fx).optional(),primary:Fx.optional(),seenAt:N});S({id:Cl,match:Rx,sectioner:I,setBy:M}),S({uri:Cx,from:v(),to:v(),added:x(wx),changed:x(wx),removed:x(wx)});var JM=E([`fn`,`context`,`section`,`message`,`type`,`example`,`record`,`contextSection`,`image`]);S({kind:JM,key:v(),system:F.optional(),text:v(),hash:v(),vectorHash:v().optional(),embedder:I,updatedAt:N,parent:v().optional(),image:v().optional()});var YM=E([`words`,`meaning`,`both`]);S({kind:JM,key:v(),rank:y().min(0).max(1),similarity:y().min(-1).max(1).optional(),matched:YM.optional(),parent:v().optional(),text:v()});var XM=E([`approval-needed`,`input-needed`,`config-needed`,`message`,`replied`,`turn-finished`,`turn-failed`,`pairing-requested`,`system-disconnected`,`spend-limit`,`system-paused`,`system-notice`,`system-message`]),ZM=S({system:F,segment:v().min(1),path:x(v().min(1)).optional(),query:T(v(),v()).optional()}).strict(),QM=C([S({session:j}),S({approval:pl}),S({pairing:ul}),S({run:A}),S({system:F}),S({page:ZM})]),$M=E([`ok`,`failed`,`info`]),eN=S({label:v().min(1).max(24),link:QM}),tN=S({id:vl,user:M,reason:XM,title:v(),body:v(),link:QM,read:b(),pushed:b(),resolved:v().optional(),tone:$M.optional(),also:eN.optional(),key:v().min(1).max(200).optional(),createdAt:N}),nN=S({id:yl,user:M,endpoint:Ls(),keys:S({p256dh:v(),auth:v()}),device:v(),createdAt:N}),rN=il.fnExample;rj.extend({id:rN,fn:I,system:F,source:E([`decl`,`added`,`runtime`]),key:v().min(1).max(200).optional(),order:y().int().min(0),text:v(),addedBy:M.optional(),createdAt:N});var iN=S({fn:k,upsert:x(rj.extend({key:v().min(1).max(200)})),remove:x(v().min(1).max(200))}),aN=S({fn:cb,query:v().optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(50).optional()}),oN=S({fn:I,items:x(rj.extend({id:rN,rank:y().optional()})),total:y().int().min(0),next:y().int().min(0).optional()}),sN=E([`text`,`semantic`,`hybrid`]),cN=[`session`,`user`,`everyone`],lN=E([`fn`,`context`]),uN=S({text:v().optional(),match:sN.optional(),items:x(lN).min(1).optional(),kinds:x(C([D(`native`),I])).min(1).optional(),systems:x(F).min(1).optional(),instance:L.optional(),visibility:E([`mine`,`shared`,`public`]).optional(),types:S({reads:x(lb).optional(),writes:x(lb).optional()}).optional(),modes:x(ij).min(1).optional(),effects:x(S({thing:aj,action:sj.optional(),kind:v().min(1).optional()})).min(1).optional(),names:x(I).min(1).max(100).optional(),filters:x(aA).max(20).optional(),off:b().optional(),scopes:x(E(cN)).min(1).optional(),available:b().optional(),niches:x(pj).min(1).optional(),order:E([`rank`,`name`]).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(100).optional()}),dN=uN.omit({items:!0,match:!0,filters:!0,off:!0,scopes:!0}).extend({kinds:uN.shape.kinds.describe("Leave `kinds` out unless the person asks for a kind of fn by name: you can't know how a fn was made, and a search by what it does finds every kind."),names:x(cb).min(1).max(100).optional().describe(`Only these fns, by name, spelled as your tools and search hits spell them: to look up fns whose names you know. Leave it out to search by what a fn does.`),types:S({reads:x(lb).optional(),writes:x(lb).optional()}).optional().describe("Only fns that read (`reads`) or write (`writes`) any of these types: a table's name (`tasks`), or a type's name exactly as a result gave it. Leave it out unless you know the type.")}),fN=S({text:uN.shape.text,systems:uN.shape.systems,origins:x(E(Xx)).min(1).optional(),scopes:uN.shape.scopes,tags:x(v().min(1)).min(1).max(20).optional(),names:uN.shape.names,niches:uN.shape.niches,order:uN.shape.order,offset:uN.shape.offset,limit:uN.shape.limit}),pN=S({key:wx,path:x(v()),title:v()}),mN=S({item:lN,name:I,system:F,description:v(),kind:v().optional(),mode:ij.optional(),signature:v().optional(),effects:v().optional(),instance:L.optional(),rank:y().optional(),similarity:y().optional(),matched:YM.optional(),section:pN.optional(),niche:pj.optional(),available:b(),blocked:xw.optional(),inPrompt:E([`injected`,`loaded`]).optional(),exact:D(!0).optional()}),hN=mN.pick({rank:!0,similarity:!0,matched:!0,section:!0}),gN=yM.extend({found:hN.optional()}),_N=S({item:lN,by:E([`decision`,`llm`]),dropped:x(S({name:I,note:v().optional()})),calls:x(Tl).min(1).optional(),failed:v().optional(),action:D(`load`).optional()}),vN=S({fns:x(I),context:x(I),note:v()}),yN=S({items:x(mN),next:y().int().min(0).optional(),filtered:x(_N).optional(),loaded:vN.optional(),missing:S({names:x(I).min(1),note:v()}).optional()}),bN=S({min:P,typical:P,max:P,basis:E([`free`,`history`,`payload`,`unknown`]),runs:y().int().min(0)}),xN=S({runs:y().int().min(0),typical:kl,slow:kl,longest:kl}),SN=S({fn:I,kind:v(),mode:ij,reads:x(I),writes:x(I),uses:x(I),free:b(),registry:x(cj),cost:bN,times:xN.optional(),longRunning:b(),notice:v().optional()}),CN=S({kind:v().min(1),payload:O,args:O.optional(),history:bN.optional()}),wN=S({estimate:bN.optional()}),TN=S({model:hE.optional(),messages:y().int().min(0).max(20).default(4)}),EN=S({value:TN,setBy:M.optional(),updatedAt:N.optional()}),DN=S({entries:x(w(`type`,[S({type:D(`log`),at:N,level:E([`debug`,`info`,`warn`,`error`]),message:v().max(4e3),fields:T(v(),O).optional()}),S({type:D(`traffic`),at:N,method:v().max(16),endpoint:v().max(300),status:y().int(),duration:kl})])).min(1).max(500),page:v().max(300).optional()}),ON=S({uri:Cx,written:y().int().min(0)});SN.pick({fn:!0,kind:!0,mode:!0,reads:!0,writes:!0,uses:!0,free:!0}).extend({registry:x(cj).optional(),system:F,instance:L.optional(),updatedAt:N}),S({fn:I,type:I,use:E([`read`,`write`])}),S({fn:I,type:I,kind:jl,system:F}),S({fn:I,to:I,link:E([`dep`,`kind`,`role`]),system:F}),S({fn:I,uses:I}),S({id:v(),fn:I,number:y().int().min(1),decl:hj,savedBy:M.optional(),savedAt:N}),S({id:v(),type:I,number:y().int().min(1),decl:YA,instance:L.optional(),savedAt:N});var kN={fns:`fns`,types:`types`,context:`context`,resources:`resources`,kinds:`kinds`,components:`components`,examples:`examples`,approvals:`runs awaiting approval`,secrets:`secrets`,connections:`connections`,records:`records`},AN={create:`Creates`,update:`Updates`,remove:`Removes`};function jN(e){let t=[];for(let n of oj){let r=new Map;for(let t of e){if(t.action!==n)continue;let e=r.has(t.thing)?r.get(t.thing):new Set;e===void 0||t.kind===void 0?r.set(t.thing,void 0):(e.add(t.kind),r.set(t.thing,e))}if(r.size===0)continue;let i=[...r.entries()].map(([e,t])=>t===void 0||t.size===0?kN[e]:`${kN[e]} (${[...t].sort().join(`, `)})`);t.push(`${AN[n]} ${i.join(`, `)}.`)}return t.length===0?void 0:t.join(` `)}var MN=il.refusal,NN=[`fns`,`context`,`types`,`roots`,...xM],PN=E(NN),FN=S({section:PN,name:v().min(1)});FN.extend({system:F,by:M,at:N});var IN=S({version:v(),hash:v().min(1),grants:QD,runtime:x(FN),by:M,at:N}),LN=S({section:C([PN,E([`grants`,`config`])]),name:v().min(1),change:E([`added`,`changed`,`removed`]),origin:mM,before:O.optional(),after:O.optional()}),RN=LN.pick({section:!0,name:!0}),zN=RN.extend({change:LN.shape.change,origin:mM,version:v(),by:M,at:N}),BN=S({version:v(),hash:v().min(1),by:mM,changes:x(LN),since:N});S({system:F,live:IN.optional(),pending:BN.optional(),checks:JD.optional(),declined:x(zN).optional(),updatedAt:N});var VN=S({mode:ij,effects:v().optional(),reads:x(I),writes:x(I),deps:x(I),cost:P.optional(),free:b().optional()}),HN=S({name:v().min(1),before:VN.optional(),after:VN.optional()}),UN=BN.extend({summary:CO,fns:x(HN),injections:x(Eb).default([])}),WN=[`stage`,`effects`,`mode`,`types`,`capability`,`models`,`budget`,`secrets`,`calls`,`network`,`files`,`visibility`],GN=E(WN),KN=S({id:MN,system:F,instance:L,rule:GN,attempt:v().min(1),detail:v().min(1),run:A.optional(),fn:I.optional(),at:N}),qN=S({instance:Wl,rule:GN.extract([`network`,`files`]),attempt:v().min(1).max(1e3),detail:v().min(1).max(2e3)}),JN=S({system:F.optional(),rule:GN.optional(),cursor:v().optional(),limit:y().int().min(1).max(200).optional()}),YN=S({items:x(KN),next:v().optional()}),XN=S({system:F,stage:tO,manifest:Oj,facts:x(SN),checks:JD.optional(),live:IN.optional(),pending:UN.optional(),declined:x(zN).default([]),off:x(FN),refusals:S({total:y().int().min(0),last:x(KN).max(10)}),previewUrls:T(v(),v()).optional(),clientApproved:b().optional()}),ZN=S({system:F,hash:v().min(1),off:x(FN).default([])}),QN=S({system:F,hash:v().min(1),approve:x(RN).default([]),decline:x(RN).default([]),off:x(FN).default([])}).refine(e=>e.approve.length+e.decline.length>0,{message:`approve or decline at least one change`,path:[`approve`]}),$N=S({hash:v(),waiting:y().int().min(0)}),eP=C([S({preview:NO,contract:Oj.optional(),ask:zO.optional()}),S({refused:v().min(1)})]),tP=S({fn:I,args:O,instance:L.optional()}),nP=il.mentionRequest,rP=S({request:nP,query:v(),roots:x(Cx).max(20).optional(),limit:y().int().min(1).max(50)}),iP=S({hits:x(Bx)}),aP=2e3,oP=S({kind:I,changedSince:N.optional(),cursor:v().optional(),limit:y().int().min(1).max(100).optional()}),sP=S({items:x(S({fn:I,kind:I,owner:M,title:v(),version:y().int().min(1),payload:O,removed:b(),updatedAt:N})),cursor:v().optional()}),cP=S({fn:I,args:O,key:v().min(1).max(200),priority:Fl.extract([`background`,`interactive`]).optional(),maxSpend:P.positive().optional()}),lP=S({run:A,turn:al,status:Gw}),uP=S({title:v().min(1).max(120),body:v().max(aP),tone:$M.optional(),link:QM.optional(),also:eN.optional(),key:v().min(1).max(136).optional()}),dP=`Harness`,fP=`hub.name`,pP=v().trim().min(1).max(40).refine(e=>!/[\r\n]/.test(e),{message:`One line only.`}),mP=S({name:pP,source:E([`setting`,`env`,`default`]),version:v()}),hP=S({name:pP.nullable()}),gP=[`off`,`text`,`model`];E(gP);var _P=w(`use`,[S({use:D(`off`)}),S({use:D(`text`)}),S({use:D(`model`),embedder:I})]),vP={use:`text`},yP=S({text:b(),images:b(),crossModal:b()}).extend({embedder:I,name:v(),dimensions:y().int().min(1)}),bP=w(`space`,[S({space:D(`none`),reason:v()}),S({space:D(`shared`),embedder:I}),S({space:D(`own`),embedder:I,crossModal:b()})]),xP=S({value:_P,setBy:M.optional(),updatedAt:N.optional(),text:I,options:x(yP),state:bP}),SP={id:M,name:v(),about:v(),createdAt:N,disabled:b()},CP=E([`admin`,`member`]),wP=S({...SP,kind:D(`user`),email:v(),role:CP,timeZone:v().optional()}),TP=w(`kind`,[wP,S({...SP,kind:D(`group`)}),S({...SP,kind:D(`agent`),fn:I}),S({...SP,kind:D(`system`),system:F}),S({...SP,kind:D(`mcp`),mcp:El})]),EP=wP.pick({id:!0,kind:!0,name:!0,email:!0,role:!0,timeZone:!0});S({group:M,user:M,addedBy:M,addedAt:N,provider:v().optional()}),S({user:M,kind:E([`password`,`passkey`]),secretHash:v(),createdAt:N}),S({id:wl,user:M,version:y().int().min(1),refreshHash:v(),rotatedHashes:x(v()).optional(),device:v(),createdAt:N,lastSeenAt:N,actingAs:M.optional()}),S({actor:M,session:wl,version:y().int().min(1)});var DP=S({setting:I,actor:M,value:O,setBy:M,run:A.optional(),updatedAt:N}),OP=C([S({actor:M}),S({group:M}),S({kind:Ll}),S({everyone:D(!0)})]),kP=S({fn:v().optional(),system:F.optional(),kind:jl.optional(),tags:x(v()).optional(),when:UC.optional(),via:I.optional()}),AP=w(`by`,[S({by:D(`turn-user`)}),S({by:D(`actor`),actor:M}),S({by:D(`group`),group:M,quorum:y().int().min(1).optional()}),S({by:D(`admins`)}),S({by:D(`judge`),fn:I}),S({by:D(`hub`)})]);S({fn:I,args:O,actor:M}),S({approve:b(),reason:v()});var jP=w(`effect`,[S({effect:D(`allow`)}),S({effect:D(`deny`),reason:v()}),S({effect:D(`ask`),approver:AP})]),MP=S({id:fl,description:v(),subject:OP,target:kP,decision:jP,priority:y().int(),expiresAt:N.optional(),createdBy:M,createdAt:N,yields:b().optional()}),NP=E([`once`,`session`,`always`]),PP=S({id:pl,run:A,fn:I,policy:fl.optional(),approver:AP,status:E([`pending`,`approved`,`denied`,`expired`]),decisions:x(S({by:M,approve:b(),remember:NP,reason:v().optional(),at:N})),createdAt:N,preview:NO.optional(),proposed:b().optional(),ask:zO.optional(),variant:Ok.optional()}),FP=v().regex(/^[a-z0-9][a-z0-9-]{0,31}$/,`lower case letters, digits and dashes, starting with a letter or digit`),IP=S({role:v().min(1).default(`groups`).describe(`The claim whose values pick the role (default "groups").`),admin:x(v().min(1)).default([]).describe(`Values of the role claim that make an admin.`),member:x(v().min(1)).optional().describe(`When given, values of the role claim one of which (or an admin value) is needed to sign in.`),groups:v().min(1).optional().describe(`The claim whose values are hub group names to sync the person into.`)}),LP=S({id:FP,label:v().min(1).max(60),issuer:Ls(),clientId:v().min(1),clientSecret:v().min(1).optional(),scope:v().min(1).default(`openid email profile`),userinfo:b().default(!0),claims:IP.prefault({})});x(LP).refine(e=>new Set(e.map(e=>e.id)).size===e.length,`each provider needs its own id`);var RP=v().trim().toLowerCase().regex(/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,`a domain such as example.com`),zP=w(`mode`,[S({mode:D(`invite`)}),S({mode:D(`domains`),domains:x(RP).min(1).max(50)}),S({mode:D(`anyone`)})]),BP=`signInPolicy`,VP=S({limit:y().int().min(1).max(1e5),window:y().int().min(1e3).max(864e5)}),HP=S({account:VP,address:VP}),UP=`signInLimits`,WP=S({proxies:y().int().min(0).max(5)}),GP=`proxyTrust`;S({issuer:v(),sub:v(),provider:FP,user:M,email:v().optional(),linkedAt:N,lastSignInAt:N});var KP=LP.pick({id:!0,label:!0}),qP=S({providers:x(LP.omit({clientSecret:!0}).extend({confidential:b()})),policy:zP,breakGlass:EP.optional(),callbackUrl:v(),limits:HP,proxy:WP}),JP=S({ok:b(),detail:v()}),YP=S({provider:FP,ok:b(),discovery:JP,keys:JP,checkedAt:N}),XP=E([`linked`,`email`,`new`,`none`]),ZP=S({allowed:b(),reason:v(),link:XP,user:EP.optional(),role:CP.optional(),groups:x(v()),unknownGroups:x(v())}),QP=S({id:v(),provider:FP,at:N,problem:v().optional(),subject:v().optional(),email:v().optional(),emailVerified:b(),claims:T(v(),O),outcome:ZP.optional()}),$P=S({provider:FP,label:v(),email:v().optional(),lastSignInAt:N}),eF=EP.extend({disabled:b(),createdAt:N,breakGlass:b(),password:b(),identities:x($P),groups:x(S({id:M,name:v(),synced:b()}))}),tF=S({id:M,name:v(),about:v(),createdAt:N,members:y().int().min(0)}),nF=S({user:M,name:v().trim().min(1).max(120).optional(),role:CP.optional(),disabled:b().optional()}),rF=S({group:M,user:M,member:b()});function iF(e){return`/auth/sso/${encodeURIComponent(e)}/start`}var aF=`harness_sso_handoff`,oF=E([`score`,`decision`,`graph`]),sF=E([`below-threshold`,`top-n`,`declined`,`budget`,`rule`,`failed`]),cF={"below-threshold":`Score under the threshold`,"top-n":`Others scored higher`,declined:`The decision model declined it`,budget:`No room in the token budget`,rule:`Hidden by a rule`,failed:`Decision model failed; the score decided`},lF=[`suggest`,`load`],uF=E(lF);function dF(e){return e.by===`none`?`suggest`:e.action??`suggest`}var fF=E([`loaded`,`budget`,`blocked`]),pF={loaded:`Loaded for the turn`,budget:`No room to load it, so suggested`,blocked:`Can't be loaded now, so suggested`},mF=w(`used`,[S({used:D(!0),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),note:v().optional(),load:fF.optional()}),S({used:D(!1),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),reason:sF,note:v().optional()})]),hF=S({by:oF,threshold:y().optional(),calls:x(Tl).min(1).optional(),action:D(`load`).optional(),items:x(mF)}),gF=S({messages:y().int().min(1).max(20).default(3),candidates:y().int().min(1).max(50).default(20),cap:y().int().min(0).max(20).default(6),floor:y().min(0).max(1).default(.2)}),_F=[`decision`,`llm`,`none`];E(_F);var vF=w(`by`,[S({by:D(`none`)}),gF.extend({by:D(`decision`),model:hE.optional(),action:uF.optional()}),gF.extend({by:D(`llm`),model:hE,action:uF.optional()})]),yF={by:`none`},bF=gF.extend({enabled:b(),model:hE.optional()});function xF(e){let{enabled:t,model:n,...r}=e;return t&&n!==void 0?{by:`llm`,model:n,...r}:yF}var SF=C([vF,bF.transform(xF)]),CF=S({value:vF,setBy:M.optional(),updatedAt:N.optional()}),wF=[`none`,`decision`,`llm`];E(wF);var TF=w(`by`,[S({by:D(`none`)}),S({by:D(`decision`),model:hE.optional(),action:uF.optional()}),S({by:D(`llm`),model:hE,action:uF.optional()})]),EF={by:`none`},DF={fn:`fnsSearchDecision`,context:`contextSearchDecision`},OF=S({value:TF,setBy:M.optional(),updatedAt:N.optional()}),kF=S({fn:OF,context:OF}),AF=S({item:lN,value:TF});w(`key`,[S({key:D(`suggestDecision`),value:SF,setBy:M,updatedAt:N}),S({key:D(`autoClassifier`),value:TN,setBy:M,updatedAt:N}),S({key:D(DF.fn),value:TF,setBy:M,updatedAt:N}),S({key:D(DF.context),value:TF,setBy:M,updatedAt:N}),S({key:D(fP),value:pP,setBy:M,updatedAt:N}),S({key:D(`imageEmbedding`),value:_P,setBy:M,updatedAt:N}),S({key:D(BP),value:zP,setBy:M,updatedAt:N}),S({key:D(mb),value:hb,setBy:M,updatedAt:N}),S({key:D(UP),value:HP,setBy:M,updatedAt:N}),S({key:D(GP),value:WP,setBy:M,updatedAt:N}),S({key:D(_b),value:b(),setBy:M,updatedAt:N})]);var jF=E([`all`,`replies`,`none`]),MF=S({actor:M,role:E([`owner`,`member`,`agent`]),notify:jF,joinedAt:N}),NF=E([`idle`,`running`,`paused`]),PF=S({hash:v(),injected:x(I),at:al}),FF=S({id:j,title:v(),owner:M,...Tk.shape,selection:cx.optional(),participants:x(MF),forkOf:j.optional(),fork:Ok.optional(),tools:x(I),context:x(I),suggested:x(I).optional(),announcedSystems:pk.optional(),citationsTold:Ck.optional(),fixed:PF.optional(),status:NF,transcript:x(OT),createdAt:N,updatedAt:N,archived:b()}),IF=FF.pick({id:!0,title:!0,owner:!0,agent:!0,status:!0,createdAt:!0,updatedAt:!0,archived:!0}),LF=E([`local-time`,`suggested-context`,`suggested-fns`]),RF=S({type:D(`text`),text:v()}),zF=S({type:D(`mention`),provider:I,label:v(),target:O,text:v()}),BF=S({type:D(`command`),context:I,args:T(v(),v())}),VF=S({type:D(`file`),ref:Dx,name:v(),uri:Cx.optional(),text:v().optional(),truncated:b().optional()}),HF=S({type:D(`input-answer`),run:A,title:v(),value:O,text:v()}),UF=`input-answer`,WF=S({type:D(`loaded-for-you`),by:E([`decision`,`llm`,`recall`]),toolset:Rb.optional(),fns:x(S({fn:I,label:v(),why:v().optional(),broughtBy:I.optional()})),context:x(S({context:I,title:v().optional(),why:v().optional(),text:v(),fns:x(I).optional()}))}),GF=w(`type`,[RF,S({type:D(`reasoning`),text:v()}),zF,BF,S({type:D(`invocation`),run:A,fn:I}),S({type:D(`call`),run:A,fn:I}),VF,HF,S({type:D(`extra`),extra:LF,blocks:x(zj)}),S({type:D(`hook`),hook:I,blocks:x(zj)}),S({type:D(`attachment`),attachment:I,data:O,title:v()}),S({type:D(`link`),link:zx}),S({type:D(`systems-changed`),on:x(mk),off:x(mk)}),S({type:D(`kept-effects`),variants:x(Mk)}),WF]),KF=new Set([`extra`,`hook`,`input-answer`,`systems-changed`,`loaded-for-you`]);function qF(e){return KF.has(e.type)}var JF=w(`type`,[RF,zF.omit({text:!0}),BF,VF,HF]),YF=S({id:ol,session:j,turn:al,author:M,role:E([`user`,`assistant`,`note`]),parts:x(GF),runs:x(A),status:E([`streaming`,`done`,`failed`]),replyTo:ol.optional(),replyAll:b(),answerers:x(M),suggestions:hF.optional(),compared:D(!0).optional(),cacheMiss:S({call:Tl,at:N}).optional(),citations:x(Sk).optional(),createdAt:N}),XF=E([`pause`,`resume`,`cancel`]),ZF=S({run:A,fn:I,status:Gw,pause:b(),resume:b(),cancel:b()}),QF=S({pause:b(),cancel:b(),uncancellable:x(A),undoLastTurn:b(),continueLastTurn:b().optional(),runs:x(ZF).optional()}),$F=S({session:j,user:M,focused:b(),typing:b(),lastActiveAt:N}),eI=S({voiceInput:b(),voiceOutput:b(),dictation:S({engine:E(_E),language:v().optional()}).optional(),uploads:b(),meaning:b(),mentions:x(S({provider:I,title:v(),of:I.optional()})),commands:x(S({name:v(),context:I,args:x(gj),description:v(),unavailable:v().optional()})),agents:x(S({fn:I,description:v()})),display:T(v(),kw),invocations:x(S({fn:I,description:v(),args:Z})),methods:x(S({type:I,method:v(),fn:I,description:v(),args:Z})),clients:x(S({system:F,url:v(),hash:v()})),systems:x(S({name:F,status:nM,enabled:b()})),models:x(VM)}),tI=YF.pick({id:!0,session:!0,author:!0,role:!0,replyTo:!0,replyAll:!0,createdAt:!0}).extend({text:v()}),nI=nM.extract([`connected`,`disconnected`,`removed`]),rI=w(`type`,[S({type:D(`message`),message:tI}),S({type:D(`run`),run:A,fn:I,update:Qw,notified:b().optional()}),S({type:D(`resources`),changes:x(Lx)}),S({type:D(`system`),system:F,status:nI}),S({type:D(`fns`),added:x(I),removed:x(I),changed:x(I).default([])})]),iI=S({protocol:D(1),name:F,version:v(),instance:L.default(Ul),instances:uM.optional(),boot:v(),publicKey:v(),manifestHash:v(),contractHash:v().optional(),pairingToken:v().optional(),autoPair:eM.optional()}),aI=w(`kind`,[S({kind:D(`challenge`),nonce:v()}),S({kind:D(`pairing`),pairing:ul,code:v().optional(),url:v(),expiresAt:N})]),oI=S({signature:v()}),sI=S({maxFrame:y().int().min(1024),maxChunk:y().int().min(1024),heartbeat:kl}),cI=S({value:O,version:y().int().min(1)}),lI=S({instance:L,config:cI.optional(),start:S({first:b(),upgradedFrom:v().optional()}),token:v(),sendManifest:b(),limits:sI,autoPair:$j.optional()});S({system:F,instance:L,boot:v()});var uI=wC(`linkSession`,{provides:vC()}),dI=EM({name:`linkTel`}),fI=S({state:O,calls:T(v(),eT),reason:E([`resumed`,`restart`])}),pI=S({run:Dw,fn:v(),kind:jl,payload:O.optional(),args:O,budget:rT,handlers:x(v()),resume:fI.optional(),deadline:N,configVersion:y().int().min(0),connection:mD.optional(),approved:VO.optional()}),mI=C([S({run:A}),S({delivery:sl})]),hI=S({session:j,actor:M,user:ww,time:Tw}),gI=S({level:E([`debug`,`info`,`warn`,`error`]),key:v(),fields:Qc}),_I=S({run:A,action:E([`cancel`,`pause`])}),vI=S({accepted:b(),reason:v().optional()}),yI=E([`restart`,`upgrade`,`shutdown`,`removed`]),bI=S({title:v().min(1).max(120),body:v().max(2e3)}),xI=X(dI,uI).group({manifest:{body:Oj,response:Aj,ws:`mf`},patch:{body:kj,response:Aj,ws:`mp`},call:{body:S({parent:A,fn:I,args:O,key:v(),budget:S({cost:P.optional(),time:kl.optional()}).optional(),handlers:x(v()),background:b(),on:L.optional()}),response:eT,ws:`call`},handle:{body:S({run:A,handler:v(),args:O}),response:nT,ws:`ha`},control:{body:_I,response:vI,ws:`cl`},progress:{body:S({run:A,progress:Iw}),ws:`pg`},allow:{body:S({run:A,operations:jw.partial()}),ws:`al`},undoWith:{body:S({run:A,undo:O}),ws:`uw`},attach:{body:S({run:A,item:C([S({attachment:I,data:O,title:v()}),S({link:zx})])}),ws:`at`},types:{body:S({names:x(I).min(1),run:A.optional()}),response:_M,ws:`ty`},fnShape:{body:S({name:I}),response:S({fn:jj.optional()}),ws:`fsh`},resourcesChanged:{body:S({changes:x(Lx)}),ws:`rc`},llm:{body:RT,streamOut:zT,ws:`llm`},model:{body:dE,response:fE,ws:`mdl`},resource:{body:S({uri:Cx,want:x(jx),run:A.optional(),sections:x(wx).min(1).optional()}),response:Nx,ws:`rs`},resourceSections:{body:S({uri:Cx,run:A.optional()}),response:x(Ix),ws:`rsc`},content:{body:S({ref:Dx,offset:y().int().min(0),length:y().int().min(1),run:A.optional()}),response:S({chunk:v()}),ws:`ct`},upload:{body:S({upload:v(),chunk:v(),last:b(),mime:v()}),response:S({ref:Dx.optional()}),ws:`up`},setting:{body:S({run:A,setting:I}),response:S({value:O.optional()}),ws:`st`},stateGet:{body:S({owner:mI}),response:S({values:Qc,version:y().int()}),ws:`sg`},stateSet:{body:S({owner:mI,patch:Qc,clear:x(v()),version:y().int().optional()}),response:C([S({version:y().int()}),S({conflict:D(!0)})]),ws:`ss`},log:{body:gI,ws:`lg`},connectionUpdate:{body:vD,ws:`cu`},instanceConnect:{body:oD,ws:`ic`},shareFn:{body:VE,ws:`sh`},usableFns:{body:HE,response:S({fns:x(k)}),ws:`uf`},propose:{body:BO,response:WO,ws:`po`},decide:{body:VT,response:HT,ws:`de`},fleet:{body:S({}),response:x(FM),ws:`fl`},searchFns:{body:uN.extend({run:A.optional()}),response:yN,ws:`sf`},fnExamples:{body:aN,response:oN,ws:`fx`},examples:{body:iN,response:S({added:y().int().min(0),removed:y().int().min(0)}),ws:`xp`},models:{body:S({}),response:x(HM),ws:`mo`},grantPairing:{body:HO,response:UO,ws:`gp`},notifyAdmins:{body:bI,ws:`na`},notify:{body:S({run:A,notice:uP}),ws:`nf`},kindFns:{body:oP,response:sP,ws:`kf`},startRun:{body:cP,response:lP,ws:`sru`},notifyOwner:{body:S({fn:I,notice:uP}),ws:`nfo`},reportRefusal:{body:qN,ws:`rx`},mentionResources:{body:rP,response:iP,ws:`mr`},records:{body:DA,response:OA,ws:`rq`},record:{body:AA,response:S({record:TA.optional()}),ws:`rg`},recordTable:{body:kA,response:yO,ws:`rtb`},saveRecord:{body:jA,response:TA,ws:`rsv`},removeRecord:{body:NA,response:S({removed:b()}),ws:`rrm`}});Y({endpoints:{...X(dI).group({hello:{body:iI,response:aI,ws:`hi`},prove:{body:oI,response:lI,ws:`pr`},pairingInfo:{body:IM,ws:`pi`}}),...xI}}),Y({endpoints:{paired:pC({body:S({pairing:ul}),ws:`pd`}),run:pC({body:pI,response:$w,ws:`run`}),control:pC({body:_I,response:vI,ws:`ctl`}),undo:pC({body:S({run:Dw,fn:v(),kind:jl,fnPayload:O.optional(),payload:O}),response:tT,ws:`un`}),handler:pC({body:S({call:cl,run:A,key:v(),handler:v(),args:O}),response:nT,ws:`hd`}),child:pC({body:S({parent:A,key:v(),run:A,update:Qw.optional()}),ws:`ch`}),check:pC({body:S({kind:v(),payload:O}),response:S({problems:x(v()),description:Mj.optional()}),ws:`ck`}),context:pC({body:hI.partial({session:!0}).extend({name:v(),args:T(v(),v())}),response:S({text:v()}),ws:`cx`}),roots:pC({response:x(Ox),ws:`ro`}),list:pC({body:S({uri:Cx,cursor:v().optional()}),response:Rl(kx),ws:`ls`}),stat:pC({body:S({uri:Cx}),response:S({stat:kx.optional()}),ws:`sa`}),read:pC({body:S({uri:Cx,want:x(jx)}),response:Nx,ws:`rd`}),sections:pC({body:S({sectioner:v(),uri:Cx,version:v()}),response:x(Ix),ws:`sc`}),watch:pC({body:S({uris:x(Cx),on:b()}),ws:`wa`}),content:pC({body:S({ref:Dx,offset:y().int().min(0),length:y().int().min(1)}),response:S({chunk:v()}),ws:`ct`}),hook:pC({body:S({hook:v(),message:Fj}),response:x(zj),ws:`hk`}),mentions:pC({body:hI.extend({provider:v(),query:v(),request:nP}),response:x(Bj),ws:`mn`}),mentionHover:pC({body:hI.extend({provider:v(),target:O}),response:S({hover:Vj.optional()}),ws:`mh`}),mentionText:pC({body:hI.extend({provider:v(),target:O}),response:S({text:v()}),ws:`mt`}),event:pC({body:rI,ws:`ev`}),action:pC({body:hI.extend({delivery:sl,action:v(),input:O,run:A.optional()}),response:S({result:O}),ws:`ac`}),form:pC({body:S({delivery:sl,run:A,value:O}),ws:`fm`}),restart:pC({body:S({reason:v()}),ws:`rt`}),stop:pC({body:S({reason:yI,timeout:kl}),ws:`sp`}),configure:pC({body:cI.extend({previous:O.optional()}),ws:`cf`}),export:pC({body:S({timeout:kl}),response:S({data:v()}),ws:`ex`}),validate:pC({body:zD,response:BD,ws:`vl`}),preview:pC({body:IO,response:eP,ws:`pv`}),estimate:pC({body:CN,response:wN,ws:`es`}),providerChat:pC({body:wD,streamOut:TD,ws:`pc`}),providerEmbed:pC({body:ND,response:PD,ws:`pe`}),providerDecide:pC({body:kD,response:AD,ws:`pdc`}),providerModels:pC({body:DD,response:OD,ws:`pml`}),connectStart:pC({body:hD,response:S({url:fb}),ws:`cs`}),connectFinish:pC({body:gD,response:_D,ws:`cn`}),disconnect:pC({body:mD.pick({id:!0,owner:!0,credentials:!0}),ws:`dc`}),flags:pC({body:IO,response:kO,ws:`fg`}),claims:pC({body:UA,response:WA,ws:`pcl`}),checkArgs:pC({body:LO,response:RO,ws:`cka`})}});var SI=S({session:j,parts:x(JF).min(1),variants:Dk,client:Ow}),CI=kk.extend({status:Vk,spent:P,tokens:y().int().min(0),startedAt:N,endedAt:N.optional(),time:kl,messages:x(YF),approvals:x(PP)}),wI=Nk.omit({variants:!0}).extend({turn:al,session:j,message:ol,status:Vk,variants:x(CI)}),TI=S({turn:al,variant:wk,adopt:b().optional()}),EI=v().regex(Al).max(64).brand(),DI=S({uri:v(),system:F.optional(),instance:L.optional()}),OI=S({systems:x(F).optional(),fns:x(kP).optional(),types:x(Gl).optional(),context:x(Gl).optional(),resources:x(DI).optional()}),kI=S({include:OI,exclude:OI}),AI=E([`each`,`static`]),jI=S({id:El,slug:EI,name:v().min(1),instructions:v(),rules:kI,toolMode:AI,user:M,actor:M,secretDigest:v(),grantees:x(F),origins:x(v()),enabled:b(),createdBy:M,createdAt:N,updatedAt:N}),MI=jI.pick({slug:!0,name:!0,instructions:!0,rules:!0,toolMode:!0,user:!0,grantees:!0,origins:!0,enabled:!0});S({mcp:El,label:v().min(1),exp:y().int()});var NI=S({mcp:El,label:v().min(1),ttl:y().int().min(1e3).optional()}),PI=S({fns:x(I),types:x(I),closure:x(I),context:x(I),resources:x(DI),reach:x(I),warnings:x(v())}),FI=S({mcp:El,session:v(),label:v(),client:S({name:v(),version:v()}).optional(),since:N,lastCallAt:N.optional(),calls:y().int().min(0)}),II=jI.omit({secretDigest:!0}).extend({url:v(),sessions:y().int().min(0),callsToday:y().int().min(0)}),LI=E([`added`,`changed`,`removed`]),RI=S({id:v().min(1),system:F,section:PN,name:v().min(1),number:y().int().min(1),change:LI,decl:O,hash:v().min(1),declaredBy:mM.optional(),instance:L.optional(),savedBy:M.optional(),savedAt:N}),zI=zl.extend({system:F,section:PN,name:v().min(1)}),BI=Rl(RI);Ix.extend({uri:Cx,version:v(),hash:v()});var VI=(...e)=>e.join(`\0`),HI=`bearerAuth`,UI={security:{[HI]:{type:`http`,scheme:`bearer`,bearerFormat:`JWT`}}};function WI(e){let t=e?.name??HI,n=e?.doc??UI;return wC(t,{provides:vC(),requires:e?.requires??[],doc:n})}var GI=v().regex(/^[a-z]+:.+$/),KI=S({fnKind:jl.optional(),mode:ij.optional(),effects:x(cj).optional(),reads:x(I).optional(),writes:x(I).optional(),visibility:Il.optional(),on:b(),stage:tO.optional(),pending:b().optional(),examples:y().int().min(0).optional()}),qI=S({id:GI,kind:Yk,name:v().min(1),about:v(),system:F.optional(),external:b(),collapsed:y().int().min(0).optional(),facts:KI}),JI=S({from:GI,to:GI,kind:Zk,label:v().min(1),weight:y().min(0).max(1).optional()}),YI=S({node:GI,kind:Yk,count:y().int().min(1)}),XI=sA.pick({text:!0,filters:!0}).extend({systems:x(F).min(1).optional(),external:b().optional(),focus:S({node:GI,hops:y().int().min(1).max(4).optional()}).optional(),collapse:x(F).min(1).optional(),limit:y().int().min(1).max(1e3).optional()}),ZI=S({nodes:x(qI),edges:x(JI),more:x(YI),total:S({nodes:y().int().min(0),edges:y().int().min(0)})}),QI=`hub/visuals`,$I=S({columns:x(S({name:v().min(1),kind:rO,role:iO,numeric:b(),temporal:b(),day:b(),categorical:b(),key:b(),opaque:b(),distinct:y().int().min(0),nulls:y().min(0).max(1),nonNegative:b(),min:C([y(),v()]).optional(),max:C([y(),v()]).optional(),bound:S({min:y(),max:y()}).optional(),members:x(v()).optional()})),rows:y().int().min(0),whole:b()}),eL=new Set([`integer`,`number`]),tL=new Set([`date`,`datetime`]),nL=new Set([`text`,`boolean`]),rL=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function iL(e){return eL.has(e)?`measure`:tL.has(e)||nL.has(e)?`group`:`attribute`}function aL(e,t,n){return e===void 0||typeof e==typeof t&&(n===`min`?t<e:t>e)?t:e}function oL(e,t){return{columns:e.columns.map((n,r)=>{let i=new Set,a=0,o=0,s=0,c=!0,l,u;for(let t of e.rows){let e=t[r];e==null?a+=1:(s+=1,i.add(typeof e==`object`?JSON.stringify(e):String(e)),typeof e==`string`&&rL.test(e)&&(o+=1),(typeof e==`number`||typeof e==`string`)&&(l=aL(l,e,`min`),u=aL(u,e,`max`)),(typeof e!=`number`||e<0)&&(c=!1))}let d=n.kind,f=n.key===!0,p=d===`uuid`||s>0&&o===s||n.ref!==void 0||d===`binary`;return{name:n.name,kind:d,role:n.role??iL(d),numeric:eL.has(d),temporal:tL.has(d),day:d===`date`,categorical:nL.has(d),key:f,opaque:p,distinct:i.size,nulls:e.rows.length===0?0:a/e.rows.length,nonNegative:c&&s>0,...l===void 0?{}:{min:l},...u===void 0?{}:{max:u},...t?.(n)??{}}}),rows:e.rows.length,whole:e.offset===0&&!e.truncated}}var sL=T(k,x(v().min(1)).min(1));S({visual:k,coverage:y().int().min(0),priority:y(),bind:sL,styles:x(k).min(1),because:x(v())});var cL={floor:0,structural:10,encoded:20,"time-encoded":30},lL={"temporal-key":15,"low-cardinality":10,"enum-key":8,"high-null":-10,"many-categories":-10},uL=.5;function dL(e){return e.columns.filter(e=>!e.opaque)}function fL(e,t){return e.accepts.includes(t.kind)&&(e.role===void 0||e.role===t.role)}function pL(e,t,n){return!e.required&&e.role===`group`&&n>1&&t.distinct>=n}function mL(e,t,n){let r={},i=new Set;for(let a of e.channels){let e=t.filter(e=>!i.has(e.name)&&fL(a,e)&&!pL(a,e,n)).map(e=>e.name),o=a.many?e:e.slice(0,1);if(o.length<(a.many?a.min??1:1)){if(a.required)return`No column fits ${a.label} (${a.accepts.join(`, `)}).`;continue}let[s,...c]=o;if(s!==void 0){r[a.name]=[s,...c];for(let e of o)i.add(e)}}return r}function hL(e,t,n){return(e[t]??[]).flatMap(e=>n.columns.filter(t=>t.name===e))}function gL(e,t,n,r,i){switch(e.rule){case`distinct`:return hL(t,e.channel,n).some(t=>t.distinct>e.max)?`${e.channel} has more than ${String(e.max)} values.`:void 0;case`non-negative`:return hL(t,e.channel,n).every(e=>e.nonNegative)?void 0:`${e.channel} has values below 0.`;case`bounded`:return hL(t,e.channel,n).every(e=>e.bound!==void 0)||t.max!==void 0?void 0:`${e.channel} has no known range.`;case`distinct-columns`:{let n=e.channels.flatMap(e=>t[e]??[]);return new Set(n).size===n.length?void 0:`${e.channels.join(` and `)} need different columns.`}case`links`:{if(r===void 0||i===void 0)return;let n=e=>i.findIndex(n=>n.name===t[e]?.[0]),a=n(e.from),o=n(e.to);if(a<0||o<0)return`${e.to} must name values of ${e.from}.`;let s=new Set(r.map(e=>JSON.stringify(e[a]??null)));return r.every(e=>e[o]===null||s.has(JSON.stringify(e[o]??null)))?void 0:`${e.to} names values that are not ${e.from} values.`}}}function _L(e,t,n){let r=Object.values(t).flat().flatMap(e=>n.columns.filter(t=>t.name===e)),i=r.filter(e=>e.role===`group`),a={"temporal-key":i.some(e=>e.temporal),"low-cardinality":i.length>0&&i.every(e=>e.distinct<=8),"enum-key":i.some(e=>e.members!==void 0),"high-null":r.some(e=>e.nulls>uL),"many-categories":i.some(e=>e.distinct>5)},o=e.priority.terms.filter(e=>a[e]);return{priority:cL[e.priority.band]+o.reduce((e,t)=>e+lL[t],0),because:o.map(e=>`${e} (${String(lL[e])})`)}}function vL(e,t,n){return e.styles.filter(e=>(e.whole!==!0||n)&&(e.needs??[]).every(e=>t[e]!==void 0)).map(e=>e.name)}function yL(e,t,n,r){let i=[];for(let r of e.channels){let e=t[r.name]??[];if(e.length===0)r.required&&i.push(`${r.label} is not bound.`);else{!r.many&&e.length>1&&i.push(`${r.label} takes one column.`),r.many&&e.length<(r.min??1)&&i.push(`${r.label} needs at least ${String(r.min??1)} columns.`);for(let t of e){let e=n.columns.find(e=>e.name===t);e===void 0?i.push(`${r.label}: there is no column ${t}.`):(e.opaque&&i.push(`${r.label}: ${t} holds nothing a person reads.`),r.accepts.includes(e.kind)||i.push(`${r.label}: ${t} is ${e.kind}, not ${r.accepts.join(` or `)}.`))}}}n.rows<e.rows.min&&i.push(`Needs at least ${String(e.rows.min)} rows.`),e.rows.max!==void 0&&n.rows>e.rows.max&&e.size===void 0&&i.push(`Draws at most ${String(e.rows.max)} rows.`),e.whole&&!n.whole&&i.push(`Only draws a whole result, and this is one page of it.`);for(let a of e.rules){let e=gL(a,t,n,r?.rows,r?.columns);e!==void 0&&i.push(e)}return i}function bL(e,t,n){let r=dL(t);return e.flatMap((e,i)=>{let a=mL(e.shape,r.length>0?r:t.columns,t.rows);if(typeof a==`string`||yL(e.shape,a,t,n).length>0)return[];let[o,...s]=vL(e.shape,a,t.whole);if(o===void 0)return[];let{priority:c,because:l}=_L(e.shape,a,t),u=new Set(Object.values(a).flat().filter(e=>r.some(t=>t.name===e))).size;return[{rank:{visual:e.name,coverage:u,priority:c,bind:a,styles:[o,...s],because:[`covers ${String(u)}`,...l]},index:i}]}).sort((e,t)=>t.rank.coverage-e.rank.coverage||t.rank.priority-e.rank.priority||e.index-t.index).map(e=>e.rank)}var xL=[`integer`,`number`],SL=[`date`,`datetime`],CL=[`text`,`boolean`],wL=[`text`,`boolean`,`date`,`datetime`];function TL(e,t,n,r={}){return{name:e,label:t,accepts:[...n],required:r.required??!0,many:r.many??!1,...r.min===void 0?{}:{min:r.min},...r.role===void 0?{}:{role:r.role}}}var EL=[`table`,`value`,`part`,`category`,`time`,`distribution`,`crosstab`,`calendar`,`timeline`,`network`,`hierarchy`,`gauge`,`finance`];E(EL);var DL={table:{label:`Table`,icon:`table`,description:`Every readable column and row, sortable and paged; cards on a phone.`,shape:fO.parse({channels:[TL(`columns`,`Columns`,nO,{required:!1,many:!0})],rows:{min:0},whole:!1,size:`window`,pageSize:10,styles:[{name:`table`,label:`Table`},{name:`compact`,label:`Compact`},{name:`cards`,label:`Cards`}],priority:{band:`floor`,terms:[]}})},value:{label:`Value`,icon:`hash`,description:`One to four rows of numbers as cards, each titled by a text column or named by its column.`,shape:fO.parse({channels:[TL(`value`,`Values`,xL,{many:!0,role:`measure`}),TL(`title`,`Title`,[`text`],{required:!1})],rows:{min:1,max:4},whole:!0,styles:[{name:`cards`,label:`Cards`},{name:`single`,label:`Single`}],priority:{band:`encoded`,terms:[]}})},part:{label:`Part of a whole`,icon:`chart`,description:`Slices of a whole: one per category, sized by a measure.`,shape:fO.parse({channels:[TL(`itemName`,`Slice`,wL,{role:`group`}),TL(`value`,`Size`,xL,{role:`measure`})],rows:{min:1,max:100},whole:!0,size:`partition`,rules:[{rule:`non-negative`,channel:`value`}],styles:[{name:`pie`,label:`Pie`},{name:`doughnut`,label:`Doughnut`},{name:`rose`,label:`Rose`},{name:`half`,label:`Half doughnut`},{name:`funnel`,label:`Funnel`}],priority:{band:`encoded`,terms:[`low-cardinality`,`enum-key`,`many-categories`]}})},category:{label:`Bars`,icon:`chart`,description:`Measures per category, with an optional second key as series.`,shape:fO.parse({channels:[TL(`x`,`Category`,wL,{role:`group`}),TL(`y`,`Values`,xL,{many:!0,role:`measure`}),TL(`series`,`Series`,CL,{required:!1,role:`group`})],rows:{min:1,max:50},whole:!1,size:`top-n`,styles:[{name:`bar`,label:`Bars`},{name:`stacked`,label:`Stacked`},{name:`percent`,label:`100%`,whole:!0},{name:`horizontal`,label:`Horizontal`},{name:`line`,label:`Line`},{name:`area`,label:`Area`},{name:`radar`,label:`Radar`},{name:`polar`,label:`Polar bars`},{name:`pictorial`,label:`Pictorial`}],priority:{band:`encoded`,terms:[`low-cardinality`,`enum-key`,`high-null`]}})},time:{label:`Over time`,icon:`chart`,description:`Measures along a date axis, zoomable; zooming can set the from/to args.`,shape:fO.parse({channels:[TL(`x`,`Date`,SL,{role:`group`}),TL(`y`,`Values`,xL,{many:!0,role:`measure`}),TL(`series`,`Series`,CL,{required:!1,role:`group`})],rows:{min:2},whole:!1,size:`window`,claims:[{claim:`range`,channel:`x`}],styles:[{name:`line`,label:`Line`},{name:`smooth`,label:`Smooth`},{name:`area`,label:`Area`},{name:`stacked`,label:`Stacked area`},{name:`step`,label:`Step`},{name:`bar`,label:`Bars`},{name:`river`,label:`Stream`,needs:[`series`]}],priority:{band:`time-encoded`,terms:[`temporal-key`,`high-null`]}})},distribution:{label:`Distribution`,icon:`chart`,description:`How numbers spread: points, bubbles, bins, boxes or parallel axes.`,shape:fO.parse({channels:[TL(`x`,`X`,xL),TL(`y`,`Y`,xL,{required:!1}),TL(`size`,`Size`,xL,{required:!1}),TL(`group`,`Group`,CL,{required:!1}),TL(`dims`,`More axes`,xL,{required:!1,many:!0,min:1})],rows:{min:2,max:5e3},whole:!1,styles:[{name:`scatter`,label:`Points`,needs:[`y`]},{name:`bubble`,label:`Bubbles`,needs:[`y`,`size`]},{name:`pulse`,label:`Rippling points`,needs:[`y`]},{name:`histogram`,label:`Histogram`,whole:!0},{name:`boxplot`,label:`Box plot`,whole:!0},{name:`parallel`,label:`Parallel axes`,needs:[`y`,`dims`]}],priority:{band:`structural`,terms:[`high-null`]}})},crosstab:{label:`Cross-tab`,icon:`grid`,description:`A measure for each pair of two keys: a heatmap, value cells or small charts.`,shape:fO.parse({channels:[TL(`x`,`Columns`,wL,{role:`group`}),TL(`y`,`Rows`,wL,{role:`group`}),TL(`value`,`Value`,xL,{role:`measure`})],rows:{min:2},whole:!1,size:`top-n`,rules:[{rule:`distinct-columns`,channels:[`x`,`y`]},{rule:`distinct`,channel:`x`,max:50},{rule:`distinct`,channel:`y`,max:50}],styles:[{name:`heatmap`,label:`Heatmap`},{name:`cells`,label:`Value cells`},{name:`multiples`,label:`Small charts`}],priority:{band:`encoded`,terms:[`low-cardinality`]}})},calendar:{label:`Calendar`,icon:`calendar`,description:`Days on a calendar, shaded by a measure; the month shown can set the from/to args.`,shape:fO.parse({channels:[TL(`time`,`Date`,SL,{role:`group`}),TL(`value`,`Intensity`,xL,{required:!1,role:`measure`}),TL(`label`,`Label`,CL,{required:!1})],rows:{min:1},whole:!1,claims:[{claim:`range`,channel:`time`}],styles:[{name:`month`,label:`Month`},{name:`year`,label:`Year`}],priority:{band:`structural`,terms:[`temporal-key`]}})},timeline:{label:`Timeline`,icon:`calendar`,description:`Bars from a start to an end date, one row each: a gantt chart.`,shape:fO.parse({channels:[TL(`start`,`Start`,SL),TL(`end`,`End`,SL),TL(`label`,`Label`,CL),TL(`series`,`Lane`,CL,{required:!1})],rows:{min:1,max:500},whole:!1,size:`window`,rules:[{rule:`distinct-columns`,channels:[`start`,`end`]}],claims:[{claim:`range`,channel:`start`}],styles:[{name:`gantt`,label:`Gantt`},{name:`timeline`,label:`Timeline`}],priority:{band:`time-encoded`,terms:[]}})},network:{label:`Network`,icon:`graph`,description:`Links between things: each row is an edge from a source to a target.`,shape:fO.parse({channels:[TL(`source`,`From`,CL),TL(`target`,`To`,CL),TL(`value`,`Weight`,xL,{required:!1,role:`measure`})],rows:{min:1,max:2e3},whole:!0,rules:[{rule:`distinct-columns`,channels:[`source`,`target`]}],styles:[{name:`force`,label:`Graph`},{name:`circular`,label:`Circle`},{name:`sankey`,label:`Flow`},{name:`chord`,label:`Chord`}],priority:{band:`structural`,terms:[]}})},hierarchy:{label:`Hierarchy`,icon:`tree`,description:`A tree from a name and its parent column, sized by a measure.`,shape:fO.parse({channels:[TL(`name`,`Name`,CL),TL(`parent`,`Parent`,CL),TL(`value`,`Size`,xL,{required:!1,role:`measure`})],rows:{min:2,max:5e3},whole:!0,rules:[{rule:`distinct-columns`,channels:[`name`,`parent`]},{rule:`links`,from:`name`,to:`parent`}],styles:[{name:`tree`,label:`Tree`},{name:`radial`,label:`Radial tree`},{name:`treemap`,label:`Treemap`},{name:`sunburst`,label:`Sunburst`}],priority:{band:`structural`,terms:[]}})},gauge:{label:`Gauge`,icon:`gauge`,description:`One value against its known range.`,shape:fO.parse({channels:[TL(`value`,`Value`,xL,{role:`measure`}),TL(`max`,`Maximum`,xL,{required:!1})],rows:{min:1,max:1},whole:!0,rules:[{rule:`bounded`,channel:`value`}],styles:[{name:`gauge`,label:`Gauge`},{name:`progress`,label:`Progress ring`}],priority:{band:`encoded`,terms:[]}})},finance:{label:`Candlestick`,icon:`chart`,description:`Open, high, low and close per period, with optional volume.`,shape:fO.parse({channels:[TL(`x`,`Period`,wL,{role:`group`}),TL(`open`,`Open`,xL),TL(`close`,`Close`,xL),TL(`low`,`Low`,xL),TL(`high`,`High`,xL),TL(`volume`,`Volume`,xL,{required:!1})],rows:{min:2},whole:!1,size:`window`,claims:[{claim:`range`,channel:`x`}],styles:[{name:`candlestick`,label:`Candles`},{name:`volume`,label:`Candles and volume`,needs:[`volume`]}],priority:{band:`time-encoded`,terms:[`temporal-key`]}})}};EL.map(e=>({name:e,shape:DL[e].shape}));var OL=`widgets`,kL=`widgets/widget`,AL=[`today`,`today-1d`,`today+1d`,`today-7d`,`today-30d`,`today+7d`,`startOf(week)`,`endOf(week)`,`startOf(month)`,`endOf(month)`,`startOf(month,today-1mo)`,`startOf(quarter)`,`startOf(year)`,`now`,`now-1h`,`now-24h`],jL=E(AL),ML={today:{label:`Today`,yields:`day`},"today-1d":{label:`Yesterday`,yields:`day`},"today+1d":{label:`Tomorrow`,yields:`day`},"today-7d":{label:`7 days ago`,yields:`day`},"today-30d":{label:`30 days ago`,yields:`day`},"today+7d":{label:`In 7 days`,yields:`day`},"startOf(week)":{label:`Start of this week`,yields:`day`},"endOf(week)":{label:`End of this week`,yields:`day`},"startOf(month)":{label:`Start of this month`,yields:`day`},"endOf(month)":{label:`End of this month`,yields:`day`},"startOf(month,today-1mo)":{label:`Start of last month`,yields:`day`},"startOf(quarter)":{label:`Start of this quarter`,yields:`day`},"startOf(year)":{label:`Start of this year`,yields:`day`},now:{label:`Now`,yields:`instant`},"now-1h":{label:`An hour ago`,yields:`instant`},"now-24h":{label:`24 hours ago`,yields:`instant`}},NL=C([S({literal:O}),S({relative:jL})]),PL=S({label:v().min(1),value:NL.optional()}),FL=w(`show`,[S({show:D(`control`),label:v().min(1).optional(),choices:x(PL).min(1).optional(),custom:b().optional(),default:NL.optional()}),S({show:D(`pinned`),value:NL}),S({show:D(`hidden`)})]),IL=S({label:v().min(1),sets:T(k,NL)}),LL=S({from:k,to:k}),RL=S({offset:k,limit:k}),zL=S({visual:k,style:k,label:v().min(1).optional(),bind:sL}),BL=E([`open`,`refresh`,`status`]),VL=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:BL.optional()}),HL=S({fn:I,label:v().min(1),bind:T(k,v().min(1))}),UL=S({title:v().min(1),source:I,visuals:x(zL).min(1),args:T(k,FL),presets:x(IL),range:LL.optional(),paging:RL.optional(),actions:x(VL).optional(),drill:HL.optional(),live:D(!0).optional()}),WL=S({arg:k,label:v().min(1),argType:Z,optional:b(),defaulted:b().optional(),choices:x(PL).min(1).optional(),custom:b(),relative:b(),value:NL.optional()}),GL=S({offset:k,limit:k,window:y().int().min(1),more:b()}),KL=S({fn:I,label:v().min(1),mode:ij,confirm:b(),bind:T(k,v().min(1)),form:Z.optional(),then:BL}),qL=S({title:v().min(1),table:yO,facts:$I,source:S({fn:I,run:A,args:T(v(),O)}),visuals:x(zL).min(1),problems:x(v()),controls:x(WL),presets:x(IL),range:LL.optional(),paging:GL.optional(),actions:x(KL),drill:HL.optional(),readOnly:b(),live:S({every:y().int().min(1)}).optional(),summary:v().min(1)}),JL=S({types:x(I).max(20),narrow:x(VL).optional()}).refine(e=>e.types.length>0||(e.narrow?.length??0)>0,{message:`name a row type or an action to offer`}),YL=S({fn:I,args:T(v(),O)}),XL=YL.extend({on:L.optional()});S({source:cb,request:v().min(1),args:T(v(),O).optional(),fns:x(cb).max(10).optional(),widget:cb.optional(),show:b()});var ZL=S({name:k,description:v().min(1),spec:UL,preview:qL,replaces:cb.optional(),show:b()});S({name:k,description:v().min(1),spec:UL,replace:I.optional()});var QL=S({fn:I,args:v(),offset:k,limit:k,format:D(`csv`)});S({summary:v(),columns:x(v()),rows:x(x(O)),more:y().int().min(0),partial:v().optional()});function $L(e,t){return e!==`read`||t===!0}function eR(e,t){return t?`open`:e===`read`?`status`:`refresh`}function tR(e){return qC(e.split(/[/.]/).pop()??e)||e}var Q=EM(),$=WI(),nR=wC(`adminOnly`,{requires:[$]}),rR=S({access:v(),refresh:v(),expiresIn:kl,user:EP}),iR=mP.pick({name:!0,version:!0}).extend({needsAdmin:b(),sso:x(KP)}),aR=S({kind:E([`fn`,`context`]),name:I,description:v(),score:Ij,why:v().optional()}),oR=nk(v().min(1)),sR=S({approvals:x(PP),handlers:x(Bk)}),cR=PM.omit({publicKey:!0}),lR=S({fns:y().int().min(0),context:y().int().min(0),types:y().int().min(0),parts:y().int().min(0),instances:y().int().min(0),pending:y().int().min(0),refusals:y().int().min(0)}),uR=dM.omit({keyFingerprint:!0,publicKey:!0,config:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0,instances:!0}).extend(PM.pick({keyFingerprint:!0,config:!0,installed:!0,host:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0}).shape).extend({counts:lR,instanceMode:uM,needsConfig:b(),configType:O.optional(),configSecrets:KO.optional(),instances:x(cR)}),dR=w(`type`,[S({type:D(`message`),message:YF}),S({type:D(`token`),message:ol,text:v()}),S({type:D(`reasoning`),message:ol,text:v()}),S({type:D(`cite`),message:ol,cite:bk}),S({type:D(`controls`),controls:QF}),S({type:D(`run`),run:A,fn:I,update:Qw}),S({type:D(`state`),system:F,fields:x(Lk)}),S({type:D(`delivery`),delivery:zk}),S({type:D(`handler`),call:Bk}),S({type:D(`approval`),approval:PP}),S({type:D(`budget`),run:A,budget:lk,reason:v()}),S({type:D(`presence`),presence:$F}),S({type:D(`session`),session:IF}),S({type:D(`compare`),turn:al})]),fR=w(`type`,[S({type:D(`notification`),notification:tN}),S({type:D(`approval`),approval:PP}),S({type:D(`system`),system:F,status:nM}),S({type:D(`pairing`),pairing:fM}),S({type:D(`capabilities`)}),S({type:D(`session`),session:IF}),S({type:D(`session-deleted`),session:j}),S({type:D(`fn`),fn:I,system:F,stats:pM}),S({type:D(`resource`),uri:Cx,forms:x(Fx)}),S({type:D(`context`),name:I}),S({type:D(`identity`),identity:mP})]),pR=EC(Y({endpoints:X(Q).group({setup:{method:`GET`,response:iR,ws:`setup`},createAdmin:{body:S({email:Ns(),name:v().min(1),password:v().min(8),setup:v().trim().min(1)}),response:rR,ws:`createAdmin`},signIn:{body:S({email:Ns(),password:v()}),response:rR,errors:{401:S({reason:v()})},ws:`signIn`},refresh:{body:S({refresh:v()}),response:rR,ws:`refresh`},redeemSso:{body:S({code:v().min(1)}),cookies:S({[aF]:v().optional()}),response:rR,ws:`redeemSso`,httpOnly:!0}})}),Y({endpoints:X(Q,$).group({signOut:{ws:`signOut`},me:{method:`GET`,response:EP,ws:`me`},account:{method:`GET`,response:eF,ws:`account`}})})),mR=zl.extend({query:sA.optional()}),hR=zl.extend({session:j}),gR=zl.extend({unread:b().optional(),query:sA.optional()}),_R=FF.pick({title:!0,systems:!0,agent:!0,archived:!0}).partial().extend({priority:Fl.optional(),notify:jF.optional(),model:FF.shape.model.unwrap().nullable().optional(),mode:FF.shape.mode.unwrap().nullable().optional(),contextor:FF.shape.contextor.unwrap().nullable().optional(),fnMode:FF.shape.fnMode.unwrap().nullable().optional(),instructions:FF.shape.instructions.unwrap().nullable().optional(),citations:FF.shape.citations}),vR=Y({endpoints:X(Q,$).group({capabilities:{body:S({session:j.optional()}),response:eI,ws:`capabilities`},types:{body:S({names:x(I).min(1)}),response:_M,ws:`types`},sessions:{body:mR,response:Rl(IF),ws:`sessions`},session:{body:S({session:j}),response:FF,ws:`session`},createSession:{body:FF.pick({agent:!0,systems:!0,title:!0}).partial(),response:FF,ws:`createSession`},updateSession:{body:_R.extend({session:j}),response:FF,ws:`updateSession`},deleteSession:{body:S({session:j}),response:S({deleted:b()}),ws:`deleteSession`},limits:{body:S({session:j}),response:dk,ws:`limits`},messages:{body:hR,response:Rl(YF),ws:`messages`},send:{body:S({session:j,parts:x(JF).min(1),replyTo:ol.optional(),replyAll:b().optional(),client:Ow}),response:S({turn:al,message:YF}),ws:`send`},compare:{body:SI,response:S({turn:al,message:YF}),ws:`compare`},compareView:{body:S({turn:al}),response:wI,ws:`compareView`},chooseVariant:{body:TI,response:wI,ws:`chooseVariant`},invoke:{body:S({session:j,fn:I,args:O,on:L.optional(),client:Ow}),response:S({turn:al,run:A}),ws:`invoke`},control:{body:S({session:j,action:XF,runs:x(A).min(1).optional()}),response:QF,ws:`control`},controls:{body:S({session:j}),response:QF,ws:`controls`},presence:{body:$F.omit({user:!0,lastActiveAt:!0}),ws:`presence`}})}),yR=Y({endpoints:X(Q,$).group({background:{body:S({run:A}),response:S({accepted:b()}),ws:`background`},undoTurn:{body:S({turn:al}),response:qk,ws:`undoTurn`},continueTurn:{body:S({turn:al}),response:S({turn:al,run:A}),ws:`continueTurn`},tree:{body:S({turn:al}),response:Kk,ws:`tree`},run:{body:S({run:A}),response:Fk,ws:`run`},llmCall:{body:S({id:ll}),response:Gk,ws:`llmCall`},waiting:{body:S({session:j}),response:sR,ws:`waiting`},approve:{body:S({approval:pl,approve:b(),remember:NP,reason:v().optional(),answer:O.optional()}),response:PP,ws:`approve`},answer:{body:S({call:cl,value:O}),ws:`answer`},act:{body:S({session:j,system:F,action:v(),input:O,run:A.optional(),client:Ow}),response:S({delivery:sl}),ws:`act`},submit:{body:S({run:A,value:O}),response:S({delivery:sl}),ws:`submit`},state:{body:S({run:A}),response:S({system:F,fields:x(Lk)}),ws:`state`}})}),bR=Y({endpoints:X(Q,$).group({suggest:{body:S({session:j,text:v(),limit:y().int().min(1).max(20).optional()}),response:x(aR),ws:`suggest`},mentions:{body:S({session:j,provider:I,query:v()}),response:x(Bj),ws:`mentions`},mentionHover:{body:S({session:j,provider:I,target:O}),response:S({hover:Vj.optional()}),ws:`mentionHover`},resource:{body:S({uri:Cx,want:x(jx)}),response:Nx,ws:`resource`}})}),xR=Y({endpoints:X(Q,$).group({notifications:{body:gR,response:Rl(tN),ws:`notifications`},readNotifications:{body:S({ids:x(tN.shape.id)}),ws:`readNotifications`},pushKey:{method:`GET`,response:S({publicKey:v()}),ws:`pushKey`},subscribePush:{body:nN.pick({endpoint:!0,keys:!0,device:!0}),response:nN.pick({id:!0}),ws:`subscribePush`}})}),SR=Y({endpoints:X(Q,$).group({upload:{body:S({name:v(),mime:v(),size:y().int().min(0)}),response:S({url:v(),upload:v()}),ws:`upload`},uploaded:{body:S({upload:v()}),response:Dx,ws:`uploaded`},transcribe:{body:S({audio:Dx}),response:S({text:v()}),ws:`transcribe`}})}),CR=S({section:E([`fns`,`context`]),name:I,on:b()}),wR=S({system:F,section:PN.exclude([`fns`,`context`]),name:v().min(1),on:b()}),TR=Y({endpoints:X(Q,$,nR).group({systems:{body:S({query:sA.optional()}),response:x(uR),ws:`systems`},system:{body:S({system:F}),response:uR,ws:`system`},pairings:{body:S({status:fM.shape.status.optional()}),response:x(fM),ws:`pairings`},approvePairing:{body:S({pairing:ul,approve:b(),instance:L.optional(),config:O.optional(),autoPair:Qj.optional()}),response:S({system:F.optional()}),ws:`approvePairing`},createPairingToken:{body:S({name:F.optional(),expiresIn:kl,autoPair:Qj.optional()}),response:S({token:v(),expiresAt:N}),ws:`createPairingToken`},configureSystem:{body:S({system:F,config:O,instance:L.optional()}),response:C([S({version:y().int()}),S({problems:x(v())})]),ws:`configureSystem`},enableSystem:{body:S({system:F,functions:b().optional(),renderers:b().optional(),context:b().optional()}),response:S({enabled:sM}),ws:`enableSystem`},switchItem:{body:CR,response:S({on:b()}),ws:`switchItem`},switchPart:{body:wR,response:S({on:b()}),ws:`switchPart`},removeSystem:{body:S({system:F}),response:S({fnsUnavailable:y().int()}),ws:`removeSystem`},installSystem:{body:S({source:rM,config:O.optional(),autoStart:b().optional()}),response:S({name:F}),ws:`installSystem`},startSystem:{body:S({system:F,instance:L.optional()}),response:S({ok:b()}),ws:`startSystem`},stopSystem:{body:S({system:F,instance:L.optional()}),response:S({ok:b()}),ws:`stopSystem`},restartSystem:{body:S({system:F,instance:L.optional(),reason:v().min(1).max(200)}),response:S({ok:b()}),ws:`restartSystem`},upgradeSystem:{body:S({system:F,version:v().optional()}),response:S({from:v(),to:v()}),ws:`upgradeSystem`},reimport:{body:S({system:F}),response:Aj,ws:`reimport`}})}),ER=Y({endpoints:X(Q,$,nR).group({configureProvider:{body:oR,response:S({models:y().int()}),ws:`configureProvider`},providers:{body:S({}),response:x(S({id:Sl,provider:ik,models:y().int()})),ws:`providers`},setModelCategory:{body:ak.partial({id:!0}),response:ak.pick({id:!0}),ws:`setModelCategory`},setBudget:{body:lk.omit({setBy:!0}).partial({id:!0}),response:lk.pick({id:!0}),ws:`setBudget`},setPriority:{body:uk.omit({setBy:!0}).partial({id:!0}),response:uk.pick({id:!0}),ws:`setPriority`},setPolicy:{body:MP.omit({createdBy:!0,createdAt:!0}).partial({id:!0}),response:MP.pick({id:!0}),ws:`setPolicy`},setActorSetting:{body:S({setting:I,actor:M,value:O}),response:S({ok:b()}),ws:`setActorSetting`},addUser:{body:S({email:Ns(),name:v(),role:CP,groups:x(M).optional()}),response:S({id:M}),ws:`addUser`},addGroup:{body:S({name:v(),about:v(),members:x(M).optional()}),response:S({id:M}),ws:`addGroup`},updateUser:{body:nF,response:S({id:M}),ws:`updateUser`},setMembership:{body:rF,response:S({ok:b()}),ws:`setMembership`},setSignInPolicy:{body:zP,response:zP,ws:`setSignInPolicy`},setSignInLimits:{body:HP,response:HP,ws:`setSignInLimits`},setProxyTrust:{body:WP,response:WP,ws:`setProxyTrust`}})}),DR=Y({endpoints:X(Q,$,nR).group({systemFns:{body:S({system:F}),response:x(hM),ws:`systemFns`},systemParts:{body:wM,response:TM,ws:`systemParts`},systemLogs:{body:S({system:F,limit:y().int().min(1).max(2e3).optional()}),response:x(RM),ws:`systemLogs`},models:{body:S({provider:Sl.optional()}),response:x(VM),ws:`models`},modelCategories:{body:S({}),response:x(ak),ws:`modelCategories`},budgets:{body:S({}),response:x(UM),ws:`budgets`},priorityRules:{body:S({}),response:x(uk),ws:`priorityRules`},resolveLimits:{body:S({user:M,session:j.optional()}),response:dk,ws:`resolveLimits`},policies:{body:S({}),response:x(MP),ws:`policies`},actors:{body:S({kind:Ll.optional()}),response:x(TP),ws:`actors`},actorSettings:{body:S({}),response:S({declared:x(WM),values:x(DP)}),ws:`actorSettings`},runs:{body:zl.extend({query:sA.optional()}),response:Rl(Fk),ws:`runs`},llmCalls:{body:zl.extend({query:sA.optional()}),response:Rl(GM),ws:`llmCalls`},resources:{body:zl.extend({query:sA.optional()}),response:Rl(qM),ws:`resources`},removeRule:{body:KM,response:S({ok:b()}),ws:`removeRule`},indexStatus:{body:S({}),response:zM,ws:`indexStatus`}}),events:{systemLog:{params:S({system:F}),data:RM,guard:[$,nR],ws:`on.systemLog`}}}),OR=wC(`ownEvents`,{requires:[$]}),kR=wC(`sessionWatch`,{requires:[$]}),AR=S({user:M}),jR=Y({endpoints:{},events:{session:{params:S({session:j}),data:dR,guard:[$,kR],ws:`on.session`},user:{params:AR,data:fR,guard:[$,OR],ws:`on.user`}}}),MR=Rl(qM).extend({facets:x(gT)}),NR=S({record:qM,forms:x(aT),offers:x(oT)}),PR=Y({endpoints:X(Q,$).group({browseResources:{body:_T.extend({query:sA.optional()}),response:MR,ws:`browseResources`},resourceForms:{body:S({uri:Cx}),response:NR,ws:`resourceForms`},readResource:{body:ST,response:CT,ws:`readResource`},convertResource:{body:S({uri:Cx,kind:Fx}),response:aT,ws:`convertResource`},downloadResource:{body:S({uri:Cx,form:Fx.optional()}),response:S({url:v(),mime:v(),size:y().int().min(0)}),ws:`downloadResource`},importResource:{body:wT,response:qM,ws:`importResource`},renameResource:{body:S({uri:Cx,name:v().min(1)}),response:qM,ws:`renameResource`},deleteResource:{body:S({uri:Cx}),response:S({deleted:b(),referencedBy:y().int().min(0)}),ws:`deleteResource`},contextFromResource:{body:uS,response:dS,ws:`contextFromResource`}})}),FR=zl.extend({query:sA.optional()}),IR=S({record:yM,links:x(aS),backlinks:x(aS),text:v().optional()}),LR=Y({endpoints:X(Q,$).group({contexts:{body:FR,response:Rl(gN),ws:`contexts`},contextItem:{body:S({name:I}),response:IR,ws:`contextItem`},remember:{body:sS,response:S({name:I}),ws:`remember`},updateMemory:{body:lS,response:S({name:I}),ws:`updateMemory`},forget:{body:S({name:I}),response:S({ok:b()}),ws:`forget`},linkContext:{body:S({from:I,to:tS,relation:eS,weight:y().min(0).max(1)}),response:aS,ws:`linkContext`},unlinkContext:{body:aS.pick({from:!0,toKey:!0,relation:!0}),response:S({ok:b()}),ws:`unlinkContext`}})}),RR=EC(Y({endpoints:X(Q,$).group({modelLimits:{body:S({model:v().optional()}),response:x(ex),ws:`modelLimits`},previewSelection:{body:S({session:j,text:v()}),response:ax,ws:`previewSelection`}})}),Y({endpoints:X(Q,$,nR).group({setModelLimits:{body:S({model:v().min(1),limits:Xb}),response:ex,ws:`setModelLimits`},previewPrompt:{body:ox,response:sx,ws:`previewPrompt`}})})),zR=Y({endpoints:X(Q,$,nR).group({modelRoles:{body:S({}),response:x(SE),ws:`modelRoles`},setModelRole:{body:bE,response:SE,ws:`setModelRole`},clearModelRole:{body:S({role:pE}),response:SE,ws:`clearModelRole`}})}),BR=zl.extend({run:A.optional(),query:sA.optional()}),VR=Y({endpoints:X(Q,$,nR).group({modelCalls:{body:BR,response:Rl(uE),ws:`modelCalls`},modelCall:{body:S({id:Tl}),response:uE,ws:`modelCall`},fnMetrics:{body:ME,response:x(jE),ws:`fnMetrics`},fnMetricsDays:{body:S({fn:I,days:y().int().min(1).max(365).optional()}),response:x(AE),ws:`fnMetricsDays`}})}),HR=Y({endpoints:X(Q,$,nR).group({mcps:{body:S({}),response:x(II),ws:`mcps`},mcp:{body:S({mcp:El}),response:II,ws:`mcp`},createMcp:{body:MI,response:S({mcp:II,secret:v()}),ws:`createMcp`},updateMcp:{body:MI.partial().extend({mcp:El}),response:II,ws:`updateMcp`},rotateMcpSecret:{body:S({mcp:El}),response:S({secret:v()}),ws:`rotateMcpSecret`},deleteMcp:{body:S({mcp:El}),response:S({ok:b()}),ws:`deleteMcp`},previewMcp:{body:S({rules:kI}),response:PI,ws:`previewMcp`},mcpSessions:{body:S({mcp:El}),response:x(FI),ws:`mcpSessions`}})}),UR=Y({endpoints:X(Q,$,nR).group({pairing:{body:S({pairing:ul}),response:fM,ws:`pairing`},instances:{body:S({system:F}),response:x(cR),ws:`instances`},installPackage:{body:S({zip:Dx,instance:L.optional(),config:O.optional(),data:Dx.optional(),autoStart:b().optional()}),response:Wl,ws:`installPackage`},removeInstance:{body:Wl,response:S({ok:b()}),ws:`removeInstance`},addInstance:{body:LM,response:Wl,ws:`addInstance`},exportSystemData:{body:Wl.extend({withSecrets:b().optional()}),response:Dx.extend({url:v()}),ws:`exportSystemData`}})}),WR=EC(Y({endpoints:X(Q,$).group({query:{body:xA,response:SA,ws:`query`},listValues:{body:bA,response:x(yA),ws:`listValues`}})}),Y({endpoints:X(Q,$,nR).group({fns:{body:sA,response:Rl(hM),ws:`fns`}})})),GR=Y({endpoints:X(Q,$,nR).group({suggestDecision:{body:S({}),response:CF,ws:`suggestDecision`},setSuggestDecision:{body:vF,response:CF,ws:`setSuggestDecision`},searchDecisions:{body:S({}),response:kF,ws:`searchDecisions`},setSearchDecision:{body:AF,response:kF,ws:`setSearchDecision`},previewSuggestions:{body:S({session:j,text:v().min(1)}),response:hF,ws:`previewSuggestions`}})}),KR=Y({endpoints:X(Q,$,nR).group({imageEmbedding:{body:S({}),response:xP,ws:`imageEmbedding`},setImageEmbedding:{body:_P,response:xP,ws:`setImageEmbedding`}})}),qR=EC(Y({endpoints:X(Q,$).group({outsideImages:{body:S({}),response:gb,ws:`outsideImages`}})}),Y({endpoints:X(Q,$,nR).group({setOutsideImages:{body:S({value:hb}),response:gb,ws:`setOutsideImages`}})})),JR=EC(Y({endpoints:X(Q,$).group({https:{body:S({}),response:bb,ws:`https`}})}),Y({endpoints:X(Q,$,nR).group({setHttps:{body:S({on:b()}),response:bb,ws:`setHttps`}})})),YR=Y({endpoints:X(Q,$,nR).group({autoPairs:{body:S({system:F.optional()}),response:x(tM),ws:`autoPairs`},revokeAutoPair:{body:S({id:Dl}),response:S({ok:b()}),ws:`revokeAutoPair`}})}),XR=Y({endpoints:X(Q,$).group({accessInfo:{body:S({}),response:zE,ws:`accessInfo`},access:{body:S({targets:x(IE).min(1).max(200)}),response:x(RE),ws:`access`},setAccess:{body:S({target:IE,sharing:FE.omit({owner:!0})}),response:RE,ws:`setAccess`}})}),ZR=Y({endpoints:X(Q,$).group({connectPages:{body:S({}),response:x(pD),ws:`connectPages`},connect:{body:S({system:F,instance:L.optional(),key:sD.optional(),form:O.optional()}),response:C([S({url:fb}),S({connection:fD})]),ws:`connect`,httpOnly:!0},updateConnection:{body:yD,response:fD,ws:`updateConnection`},disconnect:{body:S({connection:Ol}),response:S({ok:b()}),ws:`disconnect`}})}),QR=Y({endpoints:X(Q,$).group({pick:{body:UE,response:x(WE),ws:`pick`}})}),$R=Y({endpoints:X(Q,$).group({approvals:{body:S({runs:x(A).min(1).max(200)}),response:x(PP),ws:`approvals`}})}),ez=Y({endpoints:X(Q,$).group({contributions:{body:S({registry:I}),response:x(hO),ws:`contributions`},systemPages:{body:S({}),response:x(ek),ws:`systemPages`}})}),tz=EC(Y({endpoints:X(Q,$).group({searchFns:{body:uN,response:yN,ws:`searchFns`},fnExamples:{body:aN,response:oN,ws:`fnExamples`},fnFacts:{body:S({fn:I,args:O.optional()}),response:SN,ws:`fnFacts`},fnsOfModelNames:{body:S({names:x(v().min(1).max(64)).min(1).max(200)}),response:T(v(),I),ws:`fnsOfModelNames`},clientLogs:{body:DN,response:ON,ws:`clientLogs`}})}),Y({endpoints:X(Q,$,nR).group({autoClassifier:{body:S({}),response:EN,ws:`autoClassifier`},setAutoClassifier:{body:TN,response:EN,ws:`setAutoClassifier`}})})),nz=Y({endpoints:X(Q,$).group({exploreRoots:{body:S({system:F,instance:L.optional()}),response:x(Ox),ws:`exploreRoots`},exploreList:{body:S({uri:Cx,cursor:v().optional()}),response:Rl(kx),ws:`exploreList`},exploreRead:{body:S({uri:Cx,want:x(jx).min(1)}),response:Nx,ws:`exploreRead`}})}),rz=Y({endpoints:X(Q,$,nR).group({systemReview:{body:S({system:F}),response:XN,ws:`systemReview`},goLive:{body:ZN,response:S({stage:tO,hash:v()}),ws:`goLive`},approveReview:{body:ZN,response:S({hash:v()}),ws:`approveReview`},rejectReview:{body:S({system:F,hash:v().min(1)}),response:S({ok:b()}),ws:`rejectReview`},decideReview:{body:QN,response:$N,ws:`decideReview`},testCall:{body:tP,response:S({run:A}),ws:`testCall`},refusals:{body:JN,response:YN,ws:`refusals`}})}),iz=Y({endpoints:X(Q,$).group({graph:{body:XI,response:ZI,ws:`graph`}})}),az=S({agent:I.optional(),context:I.optional(),mode:Rb.optional(),fnMode:ux.optional()}),oz=Y({endpoints:X(Q,$,nR).group({injections:{body:az,response:kb,ws:`injections`},setInjection:{body:Ab,response:Ob,ws:`setInjection`}})}),sz=EC(Y({endpoints:X(Q).group({identity:{method:`GET`,response:mP,ws:`identity`}})}),Y({endpoints:X(Q,$,nR).group({setHubName:{body:hP,response:mP,ws:`setHubName`}})})),cz=Y({endpoints:X(Q,$,nR).group({people:{body:sA,response:Rl(eF),ws:`people`},groups:{body:sA,response:Rl(tF),ws:`groups`},groupMembers:{body:zl.extend({group:M}),response:Rl(EP).extend({group:tF}),ws:`groupMembers`},signInSettings:{body:S({}),response:qP,ws:`signInSettings`},checkSsoProvider:{body:S({provider:FP}),response:YP,ws:`checkSsoProvider`},testSsoSignIn:{body:S({provider:FP}),response:S({url:fb,test:v()}),ws:`testSsoSignIn`,httpOnly:!0},ssoTestResult:{body:S({test:v()}),response:QP,ws:`ssoTestResult`}})}),lz=Y({endpoints:X(Q,$).group({itemVersions:{body:zI,response:BI,ws:`itemVersions`}})}),uz=Y({endpoints:X(Q,$).group({dataSets:{body:LA,response:RA,ws:`dataSets`},records:{body:DA,response:OA,ws:`records`},record:{body:AA,response:S({record:TA.optional()}),ws:`record`},recordTable:{body:kA,response:yO,ws:`recordTable`},saveRecord:{body:jA,response:TA,ws:`saveRecord`},updateRecord:{body:MA,response:TA,ws:`updateRecord`},removeRecord:{body:NA,response:S({removed:b()}),ws:`removeRecord`},recordVersions:{body:PA,response:FA,ws:`recordVersions`}})}),dz=EC(pR,vR,yR,bR,xR,SR,TR,ER,DR,jR,PR,LR,RR,zR,VR,HR,UR,WR,GR,YR,KR,qR,JR,XR,ZR,QR,$R,ez,tz,nz,rz,iz,oz,sz,lz,uz,Y({endpoints:X(Q,$).group({rowActions:{body:JL,response:x(KL),ws:`rowActions`},readFn:{body:XL,response:O,ws:`readFn`}})}),Y({endpoints:X(Q,$).group({export:{method:`GET`,query:QL,streamOut:`text/csv`,download:`export.csv`}})}),cz),fz={load_fns:`fns_load`,drop_fns:`fns_drop`,fn_examples:`fns_examples`,fn_get:`fns_get`,save_fn:`fns_save`,fn_metrics:`fns_metrics`,load_context:`ctx_load`,context_get:`ctx_get`,context_crawl:`ctx_crawl`,context_from_resource:`ctx_from_resource`,context_link:`ctx_link`,context_unlink:`ctx_unlink`};new Map(Object.entries(fz).map(([e,t])=>[`hub/${e}`,`hub/${t}`])),new Map(Object.entries(fz));var pz=E([`added`,`modified`,`deleted`,`renamed`]),mz=E([`binary`,`large`,`sensitive`,`not-in-git`]),hz=S({path:v().min(1),root:v().min(1),status:pz,from:v().min(1).optional(),size:y().int().min(0).optional(),diff:v().optional(),added:y().int().min(0).optional(),removed:y().int().min(0).optional(),noDiff:mz.optional(),sensitive:wO.optional(),certain:b()}),gz=S({source:E([`git`,`watcher`]),cwd:v().min(1),files:x(hz),ignored:y().int().min(0),truncated:b()}),_z=S({arg:k,label:v().min(1).optional(),choices:x(O).min(1).optional(),custom:b().optional(),pinned:O.optional(),hidden:b().optional()}),vz=S({offset:k.optional(),limit:k.optional(),size:y().int().min(1).max(500)}),yz=S({visual:k,label:v().min(1).optional(),bind:T(k,x(v().min(1)).min(1))}),bz=E([`refresh`,`show`,`none`]),xz=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:bz});S({title:v().min(1),source:I,visuals:x(yz).min(1),controls:x(_z),paging:vz.optional(),actions:x(xz).optional()});var Sz=v().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),Cz=w(`type`,[S({type:D(`stdio`),command:v().min(1),args:x(v()).default([]),env:T(Sz,v()).optional(),cwd:v().min(1).optional()}),S({type:D(`http`),url:Ls()}),S({type:D(`sse`),url:Ls()})]),wz=E([`always`,`writes`,`never`]),Tz=S({label:v().min(1),description:v().optional(),transport:Cz,auth:ZE.default({kind:`none`}),trusted:b().default(!1),approval:wz.default(`writes`),prompts:b().default(!0),resources:b().default(!0),maxTools:y().int().min(1).max(1e3).default(200),timeout:y().int().min(1e3).default(12e4)}),Ez=[`transport.env`,...tD],Dz=S({instance:L,state:E([`connecting`,`connected`,`needs-auth`,`unreachable`,`failed`]),server:S({name:v(),version:v(),protocol:v(),instructions:v().optional()}).optional(),tools:y().int().min(0),prompts:y().int().min(0),resources:y().int().min(0),degraded:x(v()),leftOut:y().int().min(0),problem:v().optional(),checkedAt:N}),Oz=S({title:v().optional(),readOnlyHint:b().optional(),destructiveHint:b().optional(),idempotentHint:b().optional(),openWorldHint:b().optional()});S({tool:v().min(1),description:v(),inputSchema:O,outputSchema:O.optional(),args:Z,returns:Z.optional(),annotations:Oz.optional(),degraded:v().optional()});function kz(e,t){let n=`${e}_${t.replace(/[^A-Za-z0-9_.-]/g,`_`)}`.replace(/-/g,`_`);return eb.parse(n.split(`.`).map(e=>e.replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||`x`).join(`.`))}function Az(e){return`mcp://${e}/`}S({args:Z,returns:Z,program:UC}),S({service:sD,args:Z,returns:Z,request:UC,responseType:Z.optional(),output:UC.optional()});var jz=E([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`]),Mz=sD,Nz=`api/Service`,Pz=S({name:Mz,label:v().min(1),description:v().optional(),baseUrl:Ls(),allowPrivate:b().default(!1),privateTo:M.optional(),auth:$E.default({kind:`none`}),headers:qE.optional(),openapi:Ls().optional(),timeout:y().int().min(1e3).default(6e4),maxBody:y().int().min(1024).default(2097152)});S({label:v().min(1),description:v().optional(),baseUrl:Ls(),auth:QE.default({kind:`none`}),headers:qE.optional(),openapi:Ls().optional(),timeout:y().int().min(1e3).default(6e4),maxBody:y().int().min(1024).default(2097152)}),[...eD],S({method:jz,url:v(),headers:x(S({key:v(),value:v()})),body:v().optional(),response:S({status:y().int(),headers:x(S({key:v(),value:v()})),body:O.optional(),ms:y().int().min(0)}).optional()});var Fz=tN.pick({id:!0,title:!0,body:!0,link:!0,reason:!0,also:!0,key:!0,tone:!0}),Iz=`open`,Lz=E([`link`,`also`]),Rz=`also`;function zz(e,t=`link`){return`/inbox?${Iz}=${encodeURIComponent(e.id)}${t===`also`?`&via=also`:``}`}function Bz(e){return e.key??e.id}function Vz(e){return e.also===void 0?{link:zz(e)}:{link:zz(e),also:zz(e,`also`)}}function Hz(e,t){let n=e=>typeof e==`string`&&e.startsWith(`/`)&&!e.startsWith(`//`);if(n(e))return e;if(typeof e==`object`&&e){let r=Reflect.get(e,`also`),i=Reflect.get(e,`link`);if(t===`also`&&n(r))return r;if(n(i))return i}return`/inbox`}export{UL as $,Bl as $a,vg as $i,OE as $n,lS as $r,xM as $t,HR as A,M as Aa,fv as Ai,gk as An,Zc as Ao,ew as Ar,dF as At,lz as B,Tl as Ba,cv as Bi,_O as Bn,zC as Br,pP as Bt,LR as C,Ef as Ca,My as Ci,hA as Cn,ws as Co,Sw as Cr,EF as Ct,iz as D,gf as Da,Wy as Di,Jk as Dn,ic as Do,fw as Dr,yF as Dt,nz as E,tf as Ea,Uy as Ei,vA as En,E as Eo,tw as Er,_F as Et,PR as F,O as Fa,uv as Fi,GO as Fn,T as Fo,XC as Fr,kP as Ft,YL as G,I as Ga,Mg as Gi,SD as Gn,dC as Gr,oN as Gt,QL as H,vl as Ha,iv as Hi,$D as Hn,MC as Hr,WN as Ht,yR as I,ll as Ia,Eg as Ii,qO as In,v as Io,ZC as Ir,vP as It,kL as J,j as Ja,Ev as Ji,rD as Jn,$x as Jr,mN as Jt,JL as K,Vl as Ka,vv as Ki,lD as Kn,uS as Kr,aN as Kt,ER as L,k as La,Dg as Li,mO as Ln,vc as Lo,UC as Lr,gP as Lt,zR as M,Il as Ma,rv as Mi,ik as Mn,y as Mo,YC as Mr,WP as Mt,UR as N,El as Na,wg as Ni,ZO as Nn,S as No,qC as Nr,HP as Nt,dz as O,R as Oa,Sg as Oi,Rk as On,x as Oo,sw as Or,vF as Ot,WR as P,L as Pa,Tg as Pi,QO as Pn,Ec as Po,JC as Pr,iF as Pt,qL as Q,$c as Qa,Vg as Qi,LE as Qn,sS as Qr,eN as Qt,GR as R,Ul as Ra,gg as Ri,hO as Rn,C as Ro,VC as Rr,_P as Rt,ZR as S,pf as Sa,Ny as Si,_A as Sn,Uc as So,xw as Sr,pF as St,uz as T,Of as Ta,Xy as Ti,tA as Tn,oc as To,ow as Tr,cF as Tt,ML as U,Pl as Ua,bv as Ui,QD as Un,_S as Ur,TN as Ut,BL as V,Gl as Va,gv as Vi,yO as Vn,AC as Vr,NN as Vt,AL as W,ul as Wa,Ng as Wi,GD as Wn,cC as Wr,fN as Wt,RL as X,N as Xa,zg as Xi,BE as Xn,nS as Xr,lN as Xt,KL as Y,F as Ya,W_ as Yi,nD as Yn,rS as Yr,yN as Yt,ZL as Z,al as Za,Bg as Zi,PE as Zn,tS as Zr,jN as Zt,rR as _,_f as _a,vb as _i,zA as _n,zc as _o,qw as _r,UF as _t,Hz as a,wv as aa,Ix as ai,Xj as an,Lc as ao,DT as ar,EL as at,YR as b,Df as ba,ob as bi,wA as bn,yc as bo,Yw as br,qF as bt,Nz as c,qg as ca,Gb as ci,rj as cn,xc as co,bT as cr,bL as ct,Tz as d,jy as da,Jb as di,Oj as dn,Fc as do,vT as dr,VI as dt,Hg as ea,Gx as ei,yM as en,Ml as eo,EE as er,tR as et,Dz as f,am as fa,jb as fi,Cj as fn,rc as fo,yT as fr,MI as ft,oR as g,sf as ga,Sb as gi,BA as gn,Tc as go,Ww as gr,DI as gt,gz as h,Tf as ha,Cb as hi,qA as hn,dc as ho,Lw as hr,NI as ht,Fz as i,_v as ia,Cx as ii,Wj as in,nc as io,YT as ir,QI as it,VR as j,Ll as ja,Cg as ji,yk as jn,D as jo,QC as jr,RP as jt,oz as k,Hl as ka,_g as ki,Ek as kn,b as ko,dw as kr,gF as kt,Pz as l,U as la,lx as li,fj as ln,Gc as lo,xT as lr,GI as lt,kz as m,df as ma,zb as mi,Pj as mn,$s as mo,Zw as mr,EI as mt,Lz as n,nv as na,Tx as ni,gM as nn,ac as no,mE as nr,eR as nt,Bz as o,Wg as oa,wx as oi,Uj as on,qc as oo,iT as or,yL as ot,Az as p,hh as pa,Xb as pi,Nj as pn,kc as po,mT as pr,OI as pt,OL as q,A as qa,Lg as qi,sD as qn,oS as qr,dN as qt,Iz as r,lv as ra,Fx as ri,bM as rn,uc as ro,bE as rr,DL as rt,Vz as s,Gg as sa,Sx as si,Zj as sn,jc as so,uT as sr,oL as st,Rz as t,Ug as ta,Ux as ti,rM as tn,Nl as to,pE as tr,$L as tt,Ez as u,Yg as ua,Lb as ui,nj as un,Sc as uo,hT as ur,XI as ut,XR as v,Xl as va,pb as vi,TA as vn,Nc as vo,Xw as vr,JF as vt,RR as w,mf as wa,Vy as wi,eA as wn,pc as wo,Cw as wr,wF as wt,vR as x,nf as xa,rb as xi,aA as xn,Es as xo,Hw as xr,lF as xt,DR as y,of as ya,tb as yi,CA as yn,Vc as yo,Jw as yr,IF as yt,TR as z,ol as za,pv as zi,gO as zn,sc as zo,Z as zr,dP as zt};
402
- //# sourceMappingURL=push-payload-D5efGCzd.js.map
400
+ `):t;if(n.trim())return d(e,JSON.parse(n))},c=i.body.getReader(),l=new TextDecoder,u=``;try{for(;;){let{done:e,value:t}=await c.read();if(e)break;u+=l.decode(t,{stream:!0});let n;for(;(n=u.indexOf(o))>=0;){let e=u.slice(0,n);u=u.slice(n+o.length);let t=s(e);t!==void 0&&(yield t)}}u+=l.decode();let e=s(u);e!==void 0&&(yield e)}finally{await c.cancel().catch(()=>{})}}function ve(n,...r){let i=t.endpoints[n];if(!i)return Promise.reject(Error(`unknown endpoint "${n}"`));let a=i.p.length>0||i.q.length>0||i.hasBody||i.f.length>0||i.streamIn!==null,o=a?r[0]:void 0,s=a?r[1]:r[0],c=s?.transport??(e.prefer===`ws`&&!i.httpOnly&&e.ws?`ws`:`http`);if(c===`ws`&&i.httpOnly){let e=Error(`endpoint "${n}" is http-only`);if(i.items)throw e;return Promise.reject(e)}return i.items||i.itemsIn?c===`ws`?de(n,i,o,s?.stream,s?.signal):i.items?_e(n,i,o,s):ge(n,i,o,s):c===`ws`?fe(i.ws===null?{type:i.path,method:i.method,data:o}:{type:i.ws,data:o},s?.signal).then(e=>i.multi?e:u(n,e)):ge(n,i,o,s)}function ye(e,...n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);if(r.method!==`GET`)throw Error(`url() requires a GET endpoint; "${e}" is ${r.method}`);let{p:i,q:a}=g(r,n[0]);return pe(r,i,a).toString()}function be(n,...r){let i=t.events[n];if(!i)throw Error(`unknown event "${n}"`);if(!e.ws)throw Error(`no websocket transport configured`);let a=i.hasParams?r[0]:void 0,o=i.hasParams?r[1]:r[0],s=`${i.ws}|${oe(a)}`,c=ee.get(s);return c||ee.set(s,c=new Set),c.add(o),fe({sub:i.ws,params:a}),()=>{c.delete(o),c.size===0&&fe({unsub:i.ws,params:a})}}function xe(e,n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);return nw(e,r,(...t)=>ve(e,...t),i,n??{})}return{call:ve,on:be,url:ye,caller:xe,connection:{get status(){return r.status},subscribe:e=>r.subscribe(e)}}}var xw={initial:500,max:3e4,factor:2,jitter:!0},Sw={interval:3e4,timeout:1e4};function Cw(e,t={}){let n=t.WebSocket??globalThis.WebSocket;if(!n)throw Error(`wsTransport: no WebSocket implementation available; pass opts.WebSocket`);let r=n,i=t.whileDisconnected??`fail`,a={...xw,...t.backoff},o=t.heartbeat===!1?null:{...Sw,...t.heartbeat??{}},s=t.maxRetries??1/0,c=null,l=`closed`,u=null,d=0,f=!1,p=!1,m=null,h=null,ee=null,te=[],ne=new Map,re=new cw,ie=new Set,ae=e=>{if(e!==l){l=e,t.onStateChange?.(e);for(let t of[...ie])t(e)}},oe=e=>u?.(e),se=e=>JSON.stringify(e??{},Object.keys(e??{}).sort());function ce(){re.fail(oe,`connection closed`)}function le(){h&&clearInterval(h),ee&&clearTimeout(ee),h=ee=null}function ue(){o&&(le(),h=setInterval(()=>{l===`open`&&c&&(c.send(JSON.stringify({ping:!0})),ee&&clearTimeout(ee),ee=setTimeout(()=>c?.close(),o.timeout))},o.interval))}function de(e){let t=null;try{t=JSON.parse(e)}catch{oe(e);return}t&&t.pong===!0?ee&&=(clearTimeout(ee),null):(t&&re.settle(t),oe(e))}function fe(){if(p)return;f=!0,d=0,ae(`open`);for(let e of ne.values())c?.send(e);let e=te.splice(0);for(let t of e)c?.send(t);ue()}function g(){le(),c=null,ce(),p?ae(`closed`):pe()}function pe(){if(p)return;if(d>=s){ae(`closed`);return}let e=Math.min(a.max,a.initial*a.factor**+d),t=a.jitter?e/2+e/2*Math.random():e;d++,ae(`connecting`),m=setTimeout(me,t)}function me(){if(p||c)return;m&&=(clearTimeout(m),null),ae(`connecting`);let n;try{n=new r(typeof e==`function`?e():e,typeof t.protocols==`function`?t.protocols():t.protocols)}catch(e){t.onError?.(e),pe();return}c=n;let i=!1,a=()=>{c===n&&g()};n.addEventListener(`open`,()=>{i=!0,fe()}),n.addEventListener(`message`,e=>de(String(e.data))),n.addEventListener(`close`,a),n.addEventListener(`error`,e=>{t.onError?.(e),i||a()})}function he(e){let t={};try{t=JSON.parse(e)}catch{}typeof t.sub==`string`?ne.set(`${t.sub}|${se(t.params)}`,e):typeof t.unsub==`string`&&ne.delete(`${t.unsub}|${se(t.params)}`),typeof t.id==`string`&&typeof t.type==`string`&&re.add(t.id);let n=typeof t.sub==`string`||typeof t.unsub==`string`;l===`open`&&c?c.send(e):`rid`in t||(me(),n||(!f||i===`queue`?te.push(e):typeof t.id==`string`&&oe(ow(t.id,`not connected`))))}return{send:he,onMessage(e){u=e},connect:me,reconnect(){if(p)return;let e=c;c=null,le(),ce(),e?.close(),d=0,me()},close(){p=!0,m&&clearTimeout(m),m=null,le(),ce(),c?.close(),c=null,ae(`closed`)},get state(){return l},onState(e){return ie.add(e),()=>void ie.delete(e)}}}function ww(e,t,n){return{kind:`endpoint`,cfg:e,mws:t,prefixes:n}}function Tw(e){return ww(e,[],[])}function Y(e){for(let[t,n]of Object.entries(e.endpoints)){let e=n.cfg;if(e.streamIn&&(e.body||e.files))throw Error(`endpoint "${t}": streamIn excludes body/files`);if(e.files&&`body`in e.files)throw Error(`endpoint "${t}": "body" is reserved as the multipart JSON field name`);if(e.streamOut&&e.response)throw Error(`endpoint "${t}": streamOut excludes response`);if(e.responses&&e.response)throw Error(`endpoint "${t}": responses (multi-status) excludes response`);if(e.responses&&e.streamOut)throw Error(`endpoint "${t}": responses excludes streamOut`);if(e.streamEncoding&&!(e.streamOut instanceof ws))throw Error(`endpoint "${t}": streamEncoding requires a typed (schema) streamOut`);if(e.bodyEncoding===`urlencoded`&&!(e.body instanceof dc))throw Error(`endpoint "${t}": urlencoded bodies must be z.object(...)`);if(e.download&&typeof e.streamOut!=`string`)throw Error(`endpoint "${t}": download requires a raw (content-type) streamOut`);for(let n of[`params`,`query`,`headers`,`cookies`]){let r=e[n];if(r&&!(r instanceof dc))throw Error(`endpoint "${t}": ${n} must be a z.object(...)`)}kw(t,n)}let t;return Object.defineProperty(e,Ew,{value:()=>t??=Dw(e),enumerable:!1,configurable:!0}),e}var Ew=Symbol.for(`ayepi.manifest`);function Dw(e){let t=Object.entries(e.endpoints).map(([e,t])=>kw(e,t));return{endpoints:Object.fromEntries(t.map(e=>[e.name,{method:e.method,path:e.path,ws:e.ws,httpOnly:e.httpOnly,streamIn:e.streamInCt,itemsIn:e.itemsIn,streamOut:e.streamOutCt,items:e.items,p:e.p,q:e.q,b:e.bRaw?`raw`:e.b,f:e.f,hasBody:!!e.def.cfg.body,hasHeaders:!!e.def.cfg.headers,multi:e.multi,bodyEnc:e.bodyEnc,sideEffects:e.def.cfg.sideEffects}])),events:Object.fromEntries(Object.entries(e.events??{}).map(([e,t])=>[e,{ws:t.ws??e,hasParams:!!t.params}]))}}function Ow(e){return e&&e instanceof dc?Object.keys(e.shape):null}function kw(e,t){let n=t.cfg,r=Lw(t.mws),i=t=>{throw Error(`endpoint "${e}": ${t}`)},a=new Map;for(let e of r)e.paramKey&&e.paramSchema&&a.set(e.paramKey,e.paramSchema);let o=new Map,s=(e,t)=>{for(let n of e.keys)(a.has(n)||o.has(n))&&i(`param ":${n}" is declared more than once (${t})`),o.set(n,e.schemas[n])};for(let e of t.prefixes)typeof e!=`string`&&s(e,`prefix path`);let c=typeof n.path==`object`&&n.path!==null?n.path:null;c&&s(c,`endpoint path`);let l=Ow(n.params)??[];for(let e of l)(a.has(e)||o.has(e))&&i(`param ":${e}" is declared more than once (params schema)`);let u=new Set([...a.keys(),...o.keys(),...l]),d=[];for(let e of t.prefixes)d.push(...typeof e==`string`?TC(e):e.parts);if(c)d.push(...c.parts);else if(typeof n.path==`string`)d.push(...TC(n.path));else{d.push({t:`lit`,v:e});let t=new Set(OC(d));for(let e of u)t.has(e)||d.push({t:`param`,k:e})}let f=OC(d),p=new Set(f);f.length!==p.size&&i(`path positions a param more than once: ${EC(d)}`);for(let e of f)u.has(e)||i(`path references undeclared param ":${e}"`);for(let e of u)p.has(e)||i(`declared param ":${e}" has no position in path ${EC(d)}`);let m=[...u],h=Ow(n.query)??[],ee=n.body?Ow(n.body):null,te=!!n.body&&ee===null,ne=Object.keys(n.files??{}),re=new Map;for(let[e,t]of[[`path`,m],[`query`,h],[`body`,ee??[]],[`files`,ne]])for(let n of t){let t=re.get(n);t&&i(`key "${n}" appears in both ${t} and ${e} — kinds must be disjoint`),re.set(n,e)}te&&(m.length>0||h.length>0||ne.length>0)&&i(`a non-object body is the entire data payload — params/query/files are not allowed alongside it`);let ie=n.streamIn instanceof ws,ae=typeof n.streamIn==`string`?n.streamIn:ie?`application/x-ndjson`:null,oe=n.streamOut instanceof ws,se=oe&&n.streamEncoding===`sse`,ce=typeof n.streamOut==`string`?n.streamOut:oe?se?`text/event-stream`:`application/x-ndjson`:null,le=!!(n.httpOnly||typeof n.streamIn==`string`||typeof n.streamOut==`string`||ne.length>0);return{name:e,def:t,method:n.method??`POST`,parts:d,path:EC(d),ws:n.ws??null,wsEligible:!le,httpOnly:le,streamInCt:ae,itemsIn:ie,streamOutCt:ce,items:oe,sse:se,multi:!!(n.responses&&Object.keys(n.responses).length>0),bodyEnc:n.body?n.bodyEncoding??`json`:null,p:m,q:h,b:ee,bRaw:te,f:ne,loaders:a,tplSchemas:o,chain:r}}function Aw(){return{}}function jw(e){return()=>{throw Error(`middleware "${e}" has no implementation — bind it with implement(api).middleware(def, impl)`)}}function Mw(e,t,n,r,i,a){let o={kind:`middleware`,name:e,requires:t,optional:n,paramKey:r,paramSchema:i,doc:a,run:jw(e),with(...e){return Nw([o,...e],[])},path(e){return Nw([o],[e])},endpoint(e){return Nw([o],[]).endpoint(e)},group(e){return Nw([o],[]).group(e)}};return o}function Nw(e,t){return{kind:`stack`,mws:e,prefixes:t,with(...n){return Nw([...e,...n],t)},path(n){return Nw(e,[...t,n])},endpoint(n){return ww(n,e,t)},group(n){let r={};for(let[i,a]of Object.entries(n))r[i]=ww(a,e,t);return r}}}function X(...e){return Nw([...e],[])}function Pw(e,t){return Mw(e,t?.requires??[],t?.optional??[],void 0,void 0,t?.doc)}function Fw(e,t,n){return Mw(e,n?.requires??[],n?.optional??[],e,t,n?.doc)}var Iw=Object.assign(Pw,{loader:Fw});function Lw(e){let t=new Set,n=[],r=(e,i)=>{if(!t.has(e)){if(i.has(e))throw Error(`middleware cycle involving "${e.name}"`);i.add(e);for(let t of e.requires)r(t,i);i.delete(e),t.add(e),n.push(e)}};for(let t of e)r(t,new Set);let i=new Map(n.map((e,t)=>[e,t]));return[...n].sort((e,t)=>e.optional.includes(t)?1:t.optional.includes(e)?-1:i.get(e)-i.get(t))}function Rw(...e){let t={},n={};for(let r of e){for(let[e,n]of Object.entries(r.endpoints)){if(Object.hasOwn(t,e))throw Error(`mergeSpecs: endpoint "${e}" is in more than one spec`);t[e]=n}for(let[e,t]of Object.entries(r.events??{})){if(Object.hasOwn(n,e))throw Error(`mergeSpecs: event "${e}" is in more than one spec`);n[e]=t}}return Y({endpoints:t,events:n})}var zw=new WeakMap;function Bw(e,t){return zw.set(e._zod.def,{source:t}),e}function Vw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var Hw=class e extends U{static NAME=`record`;name=e.NAME;static optionKeys=[];static genericKeys=[`V`];static from(t,n){let r=t.generic?.V;return new e(n,r===void 0?n.registry.any():n.parse(r))}static toA(){return R.object({name:R.literal(e.NAME),generic:R.object({V:R.ref(`TypeDef`)}).optional()}).describe(`A record: an object with any text keys, each value a V.`)}constructor(e,t){super(e,{},{V:t})}get value(){let e=this.generic.V;if(e===void 0)throw Error(`record has no value type`);return e}valid(e,t){return Vw(e)&&Object.values(e).every(e=>{try{return this.value.parse(e,t),!0}catch{return!1}})}parse(e,t){if(!Vw(e))throw new Fm({path:[],code:`record.invalid`,message:`record.parse: expected an object of values by key`,severity:`error`});for(let[n,r]of Object.entries(e))try{this.value.parse(r,t)}catch(e){throw new Fm({path:[n],code:`record.value`,message:`record.parse: ${n}: ${e instanceof Error?e.message:String(e)}`,severity:`error`})}return new W(this,e)}encode(e){return e}create(){return{}}random(e){return{}}compatibleType(t){return t instanceof e&&this.value.compatibleType(t.value)}or(t){return t instanceof e&&this.value.compatibleType(t.value)?this:t}narrow(){return{}}toJSON(){return{name:e.NAME,generic:{V:this.value.toJSON()}}}clone(){return new e(this.scope,this.value)}toCode(e,t){return`${this.docsPrefix(t)}record<${this.value.toCode(void 0,t)}>`}valueA(e){return R.record(this.value.toA(e))}toNewA(){return R.record(R.ref(`Expr`))}};function Uw(e){return e.typeClass(Hw.NAME)===void 0&&e.define(Hw),e}function Ww(){return Uw(Iv())}var Gw;function Kw(){return Gw??=Ww(),Gw}var qw=Uy.result(`TypeDef`),Jw=Uy.result(`Expr`);function Yw(e){return()=>{let{description:t,...n}=e(Kw()).render(Ql).jsonSchema;return n}}function Xw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Zw(e){return Xw(e)&&`name`in e&&typeof e.name==`string`}var Z=Bw(Jc(Zw,{message:`Expected a gin type definition ({ name, ... }).`}),Yw(e=>qw.bind(e,void 0,{namedRefs:!0})));function Qw(e){return Zw(e)}var $w=Bw(Jc(Qw,{message:`Expected a gin object type definition ({ name: "obj", props: { ... } }).`}),Yw(e=>Ky(e.typ(e.obj({}))).bind(e,void 0,{namedRefs:!0})));function eT(e){return Xw(e)&&`kind`in e&&typeof e.kind==`string`}var tT=Bw(Jc(eT,{message:`Expected a gin expression ({ kind, ... }).`}),Yw(e=>Jw.bind(e,void 0,{namedRefs:!0}))),nT=new Set(`id.uuid.guid.url.uri.api.json.csv.tsv.xml.html.css.yaml.sql.pdf.svg.png.jpg.ip.dns.http.https.ssh.tls.ssl.tcp.udp.vpn.os.cpu.gpu.ram.ui.ux.ai.llm.sku.sms.otp.jwt.utc.iso.gmt.ssn.vat.faq.crm.rgb.db.mime.ttl.oauth.sso.mfa`.split(`.`)),rT=new Map([[`ctx`,`context`]]);function iT(e,t){let n=e.toLowerCase();if(nT.has(n))return n.toUpperCase();let r=rT.get(n);return r===void 0?n.endsWith(`s`)&&nT.has(n.slice(0,-1))?`${n.slice(0,-1).toUpperCase()}s`:t?e:n:t?lT(r):r}function aT(e){return lT((/[\s._/:-]/.test(e)&&!/[a-z]/.test(e)?e.toLowerCase():e).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[\s._/:-]+/).filter(e=>e!==``).map((e,t)=>iT(e,t===0)).join(` `))||e}function oT(e){return e.label??aT(e.name)}function sT(e){return aT(Fl(e).local)}function cT(e){return/^[A-Z][a-z]/.test(e)?`${e.charAt(0).toLowerCase()}${e.slice(1)}`:e}function lT(e){return e===``?e:`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function uT(e,t){let n=e.replace(/\s+/g,` `).trim();if(n.length<=t)return n;let r=n.slice(0,t-1),i=r.lastIndexOf(` `);return`${i>t*.6?r.slice(0,i):r}…`}var dT=[`path`,`file`,`uri`,`query`,`command`,`url`,`name`,`title`,`text`,`pattern`,`message`];function fT(e,t=60){if(e==null)return``;if(typeof e==`string`)return uT(e,t);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e))return e.length===0?``:`${e.length} item${e.length===1?``:`s`}`;let n=dT.map(t=>e[t]).find(e=>typeof e==`string`&&e!==``);if(typeof n==`string`)return uT(n,t);for(let[n,r]of Object.entries(e))if(typeof r==`string`||typeof r==`number`||typeof r==`boolean`)return uT(`${n}: ${String(r)}`,t);return``}var pT=[`active`,`retry`,`done`,`failed`],mT=E(pT),hT=S({one:v().min(1),many:v().min(1)}),gT=S({active:hT,retry:hT,done:hT,failed:hT}),_T=S({phase:mT,one:v(),many:v()}),vT={active:{one:`{fn}…`,many:`{fn} ×{n}…`},retry:{one:`Retrying {fn}…`,many:`Retrying {fn} ×{n}…`},done:{one:`{fn} done`,many:`{fn} ×{n} done`},failed:{one:`{fn} failed`,many:`{fn} ×{n} failed`}};function yT(e,t){switch(e){case`queued`:case`running`:case`waiting`:return t>1?`retry`:`active`;case`invalid-input`:return`retry`;case`done`:return`done`;case`failed`:return`failed`;case`awaiting-approval`:case`paused`:case`cancelled`:case`undone`:return}}var bT=60,xT=3,ST=/\{([^{}|]+)(?:\|([^{}]*))?\}/g;function CT(e,t,n){for(let r of e){if(r===void 0)continue;let e=TT(r[t].one,n,!1),i=TT(r[t].many,n,!0);if(e!==void 0&&i!==void 0)return{phase:t,one:e,many:i}}let r=vT[t];return{phase:t,one:TT(r.one,n,!1)??r.one,many:TT(r.many,n,!0)??r.many}}function wT(e,t){return t===1?e.one:e.many.replaceAll(`{n}`,String(t))}function TT(e,t,n){let r=[],i=e.replace(ST,(e,i,a)=>{let o=ET(i.trim(),t,n);return o===void 0?a===void 0?(r.push(i),e):a:o});return r.length>0?void 0:lT(i.replace(/…{2,}/g,`…`))}function ET(e,t,n){if(e===`fn`)return cT(sT(t.fn));if(e===`n`)return n?`{n}`:void 0;let[r,...i]=e.split(`.`),a=r===`args`?t.args:r===`output`?t.output:void 0;return a===void 0?void 0:OT(DT(a,i))}function DT(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=Array.isArray(n)?n[Number(e)]:n[e]}return n}function OT(e){if(e!=null){if(typeof e==`string`)return e===``?void 0:AT(e);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e)){let t=e.map(OT).filter(e=>e!==void 0);if(t.length===0)return;let n=t.slice(0,xT),r=t.length-n.length;return kT(r>0?[...n,`${r} more`]:n)}for(let t of[`title`,`name`,`id`]){let n=e[t];if(typeof n==`string`&&n!==``)return AT(n)}}}function kT(e){return e.length<=2?e.join(` and `):`${e.slice(0,-1).join(`, `)} and ${e.at(-1)??``}`}function AT(e){let t=e.split(`
401
+ `)[0]??``;return t.length>bT?`${t.slice(0,59)}…`:t}var jT=E([`system-needs-config`,`system-disconnected`,`system-removed`,`kind-missing`,`kind-system-disconnected`,`dep-unavailable`,`disabled`,`held`,`paused`,`role-unset`]),MT=C([D(!0),S({unavailable:jT,detail:v()})]),NT=S({code:E([...jT.options,`no-such-fn`,`not-a-name`,`other-system`,`not-for-model`,`connect-account`]),reason:v().min(1),system:F.optional()}),PT=NT.extend({fn:v()}),FT=NT.extend({name:v()}),IT=S({id:M,name:v(),email:v(),role:E([`admin`,`member`]),groups:x(S({id:M,name:v()})),timeZone:v(),locale:v()}),LT=S({now:N,timeZone:v(),local:v()}),RT=S({name:v(),instance:L,boot:v(),from:S({system:v(),fn:I,run:A}).optional()}),zT=S({id:A,fn:I,parent:A.optional(),turn:sl,session:j.optional(),user:IT,time:LT,system:RT,caller:M,attempt:y().int().min(1),priority:Ll,watched:b().optional(),inChat:b().optional()}),BT=S({timeZone:v(),locale:v(),now:N}),VT=E([`card`,`message`,`hidden`]),HT=S({cancel:b(),pause:b(),undo:b(),background:b()}),UT=HT.pick({cancel:!0,pause:!0,background:!0}),WT=S({timeout:jl.optional(),retries:y().int().min(0).optional(),cost:P.optional()}),GT=w(`type`,[S({type:D(`none`)}),S({type:D(`linear`)}),S({type:D(`steps`),steps:T(v(),v())})]),KT=E([`pending`,`active`,`done`,`failed`,`skipped`]),qT=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({steps:T(v(),S({status:KT,detail:v().optional()}))})]),JT=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({step:v(),status:KT,detail:v().optional()})]),YT=[`retry`,`caller`,`fatal`],XT=S({class:E(YT),message:v(),code:v().optional(),data:O.optional()}),ZT=E([`json`,`schema`,`validation`,`unavailable`,`result`]),QT=S({path:v(),message:v()}),$T=S({path:v(),repair:E([`json-string`])});function eE(e){return e.path===``?e.message:`${e.path}: ${e.message}`}var tE=S({source:ZT,problems:x(QT).min(1),raw:v().optional(),blocked:NT.optional()}),nE=[`awaiting-approval`,`queued`,`running`,`waiting`,`paused`,`done`,`invalid-input`,`failed`,`cancelled`,`undone`],rE=E(nE),iE={"awaiting-approval":!1,queued:!1,running:!1,waiting:!1,paused:!1,done:!0,"invalid-input":!0,failed:!0,cancelled:!0,undone:!0},aE={"awaiting-approval":`Needs approval`,queued:`Queued`,running:`Running`,waiting:`Waiting`,paused:`Paused`,done:`Done`,"invalid-input":`Thinking harder`,failed:`Failed`,cancelled:`Cancelled`,undone:`Undone`};function oE(e){return iE[e]}function sE(e){return!iE[e]}var cE=nE.filter(oE),lE=nE.filter(sE),uE=w(`type`,[S({type:D(`status`),status:rE,text:_T.optional()}),S({type:D(`progress`),progress:qT}),S({type:D(`allowed`),operations:UT}),S({type:D(`cost`),cost:P,total:P}),S({type:D(`background`)}),S({type:D(`result`),revision:y().int().min(1)})]),dE=w(`status`,[S({status:D(`done`),result:O,undo:O.optional(),cost:P.optional(),expose:x(Fb).optional()}),S({status:D(`invalid-input`),invalid:tE,undo:O.optional(),cost:P.optional()}),S({status:D(`paused`),resume:O,cost:P.optional()}),S({status:D(`failed`),error:XT,undo:O.optional(),cost:P.optional()}),S({status:D(`cancelled`),partial:O.optional(),undo:O.optional(),cost:P.optional(),error:XT.optional()})]),fE=w(`status`,[S({status:D(`done`),result:O}),S({status:D(`failed`),error:XT}),S({status:D(`cancelled`),error:XT.optional()}),S({status:D(`background`),run:A})]),pE=w(`status`,[S({status:D(`undone`),summary:v()}),S({status:D(`failed`),error:XT}),S({status:D(`gone`)})]),mE=w(`ok`,[S({ok:D(!0),value:O}),S({ok:D(!1),error:XT})]),hE=S({cost:P,time:jl,limitedBy:v()}),gE=gx,_E=S({hash:v().regex(Ox),kind:Lx,converter:v().min(1),content:kx,chars:y().int().min(0),tokens:y().int().min(0),call:Dl.optional(),createdAt:N}),vE=S({kind:Lx,model:v().optional(),estimate:y().min(0).optional()}),yE=w(`from`,[S({from:D(`system`),system:F,served:E([`bytes`,`text`]).optional()}),S({from:D(`upload`),by:M}),S({from:D(`web`),url:mb,finalUrl:mb.optional(),fetchedAt:N,rendered:b()}),S({from:D(`run`),run:A,fn:I})]),bE=[`system`,`upload`,`web`,`run`],xE=E([`auto`,`always`,`never`]),SE=`hub://resources/`,CE=[`document`,`code`,`image`,`table`,`audio`,`video`,`web`,`data`,`archive`,`folder`,`other`],wE=E(CE),TE={markdown:`document`,text:`document`,pdf:`document`,docx:`document`,pptx:`document`,rtf:`document`,odt:`document`,notebook:`document`,html:`web`,json:`data`,jsonl:`data`,yaml:`data`,toml:`data`,xml:`data`,ini:`data`,csv:`table`,tsv:`table`,excel:`table`,ods:`table`,image:`image`,svg:`image`,mermaid:`image`,audio:`audio`,video:`video`,zip:`archive`,folder:`folder`,...Object.fromEntries(`typescript.javascript.jsx.tsx.vue.python.ruby.go.rust.java.c.cpp.csharp.php.swift.kotlin.scala.css.scss.less.shell.sql.dockerfile.graphql.lua.r.dart`.split(`.`).map(e=>[e,`code`]))};function EE(e,t){let n=e===void 0?void 0:TE[e];if(n!==void 0)return n;let r=t?.split(`/`)[0];return r===`image`||r===`audio`||r===`video`?r:`other`}var DE=E([`type`,`source`,`path`,`date`]),OE=S({value:v(),label:v(),count:y().int().min(0)}),kE=Vl.extend({search:v().optional(),system:F.optional(),family:wE.optional(),source:E(bE).optional(),under:v().optional(),form:Lx.optional(),missing:Lx.optional(),group:DE.optional(),in:v().optional()}),AE=S({uri:Tx}),jE=S({uri:Tx,section:Ex.optional()}),ME=S({image:Tx,question:v().trim().min(1).max(2e3),page:y().int().min(1).optional()}),NE=S({answer:v(),model:v(),image:S({id:Tx,name:v()})}),PE=S({uri:Tx,form:C([Lx,D(`raw`)]).optional(),section:Ex.optional(),offset:y().int().min(0).optional(),maxChars:y().int().min(1).max(2e5).optional(),rows:S({table:v(),from:y().int().min(0),to:y().int().min(0)}).optional()}),FE=S({uri:Tx,form:C([Lx,D(`raw`)]),text:v(),offset:y().int().min(0),total:y().int().min(0),truncated:b(),partial:v().optional(),note:v().optional(),forms:x(Lx),offers:x(vE)}),IE=C([S({url:mb,render:xE.optional(),name:v().optional(),folder:v().min(1).optional()}),S({content:kx,name:v().min(1),path:v().optional()})]),LE=C([S({model:v().min(1)}),S({category:v().min(1)}),S({auto:S({cost:y().min(0).optional(),speed:y().min(0).optional(),accuracy:y().min(0).optional()})})]),RE=S({id:v(),name:v(),arguments:v(),invalid:v().optional()}),zE=S({type:E([`text`,`image`,`file`,`audio`,`video`]),content:v(),format:v().optional(),name:v().optional()}),BE=S({role:E([`system`,`user`,`assistant`,`tool`]),content:C([v(),x(zE)]),name:v().optional(),toolCallId:v().optional(),toolCalls:x(RE).optional(),refusal:v().optional(),tokens:y().int().optional()}),VE=S({input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional()}),HE=E([`stop`,`length`,`tool_calls`,`content_filter`,`refusal`]),UE=S({content:v().optional(),reasoning:v().optional(),toolCallNamed:RE.optional(),toolCallArguments:RE.optional(),toolCallMore:RE.optional(),toolCall:RE.optional(),finishReason:HE.optional(),refusal:v().optional(),usage:VE.optional()}),WE=C([b(),y().positive()]),GE=E([`summary`,`list`,`markers`,`full`]),KE=C([GE,S({detail:GE.optional(),maxErrors:y().int().min(0).optional(),maxChars:y().int().min(0).optional(),suggestions:b().optional(),expected:b().optional(),context:y().int().min(0).optional(),depth:y().int().min(0).optional(),header:b().optional()})]),qE=S({name:v(),description:v().optional(),parameters:O,strict:WE.optional(),errorFormat:KE.optional()}),JE=C([D(`text`),D(`json`),S({schema:O,strict:WE,errorFormat:KE.optional(),schemaDelivery:E([`auto`,`structured`,`json`,`prompt`]).optional()})]),YE=S({messages:x(BE),temperature:y().optional(),maxTokens:y().int().optional(),stop:x(v()).optional(),tools:x(qE).optional(),toolChoice:C([E([`auto`,`none`,`required`]),S({tool:v()})]).optional(),responseFormat:JE.optional(),errorFormat:KE.optional()}),XE=S({run:A.optional(),request:YE,model:LE.optional(),stream:b()}),ZE=w(`type`,[S({type:D(`chunk`),chunk:UE}),S({type:D(`done`),usage:VE,cost:P,interaction:dl,model:v()}),S({type:D(`error`),message:v(),kind:E([`model`,`tool`,`limit`,`provider`])})]),QE=S({id:v().min(1),text:v().min(1),score:y().min(0).max(1)}),$E=S({run:A,question:v().min(1),candidates:x(QE).min(1).max(50),max:y().int().min(1).max(20)}),eD=w(`by`,[S({by:D(`decision`),picked:x(S({id:v(),why:v().optional()})),note:v().optional(),call:Dl.optional()}),S({by:D(`off`)}),S({by:D(`failed`),message:v()})]),tD=w(`type`,[S({type:D(`predicate`),instructions:v().min(1)}),S({type:D(`choice`),instructions:v().min(1),choices:T(v(),v())}),S({type:D(`score`),instructions:v().min(1),levels:x(v()).min(1)})]),nD=C([v().min(1),x(BE).min(1)]),rD=T(v().min(1),tD),iD=y().min(0).max(1),aD=w(`type`,[S({type:D(`predicate`),probability:iD}),S({type:D(`choice`),choice:v(),probabilities:T(v(),iD),confidence:iD}),S({type:D(`score`),score:y(),probabilities:x(iD),confidence:iD}),S({type:D(`refusal`)})]),oD=T(v(),aD),sD=.5,cD=[`chat`,`embed`,`image`,`transcribe`,`speech`,`decide`];E(cD);var lD=E([`yes`,`no`,`unknown`]),uD=S({modality:D(`chat`),input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional(),caching:lD.optional()}),dD=S({modality:D(`embed`),texts:y().int().min(0),characters:y().int().min(0),images:y().int().min(1).optional(),tokens:y().int().min(0).optional(),dimensions:y().int().min(1)}),fD=S({modality:D(`image`),images:y().int().min(0),size:v().optional()}),pD=S({modality:D(`transcribe`),seconds:y().min(0),bytes:y().int().min(0)}),mD=S({modality:D(`speech`),characters:y().int().min(0),seconds:y().min(0).optional()}),hD=S({modality:D(`decide`),questions:y().int().min(0),characters:y().int().min(0),images:y().int().min(0).optional(),tokens:y().int().min(0).optional()});w(`modality`,[uD,dD,fD,pD,mD,hD]);var gD=E([`mp3`,`wav`,`ogg`]),_D=E([`running`,`done`,`failed`,`aborted`]),vD=S({id:Dl,provider:v(),model:v(),run:A.optional(),turn:sl.optional(),session:j.optional(),system:F.optional(),fn:I.optional(),purpose:v().optional(),interaction:dl.optional(),cost:P,status:_D,error:v().optional(),priority:Ll.optional(),sent:y().int().min(0),received:y().int().min(0),queued:jl,firstByte:jl.optional(),total:jl.optional(),startedAt:N,endedAt:N.optional()}),yD=e=>S({modality:e.shape.modality,units:e}),bD=w(`modality`,[yD(uD),yD(dD),yD(fD),yD(pD),yD(mD),yD(hD)]),xD=e=>vD.extend(e.shape),SD=w(`modality`,[xD(bD.options[0]),xD(bD.options[1]),xD(bD.options[2]),xD(bD.options[3]),xD(bD.options[4]),xD(bD.options[5])]),CD=w(`modality`,[S({modality:D(`embed`),texts:x(v()).min(1),model:LE.optional()}),S({modality:D(`image`),prompt:v().min(1),model:LE.optional(),size:v().optional(),count:y().int().min(1).max(10).optional()}),S({modality:D(`transcribe`),audio:kx,model:LE.optional(),language:v().optional()}),S({modality:D(`speech`),text:v().min(1),model:LE.optional(),voice:v().optional(),format:gD.optional()}),S({modality:D(`decide`),input:nD,questions:rD,model:LE.optional()})]).and(S({run:A.optional()})),wD=w(`modality`,[S({modality:D(`embed`),vectors:x(x(y()))}),S({modality:D(`image`),images:x(kx)}),S({modality:D(`transcribe`),text:v(),segments:x(S({start:y().min(0),end:y().min(0),text:v()})).optional()}),S({modality:D(`speech`),audio:kx}),S({modality:D(`decide`),answers:oD})]).and(S({call:Dl,cost:P,model:v()})),TD=E([`chat`,`transcribe`,`dictate`,`speak`,`describe`,`ocr`,`decide`,`metadata`,`plan`]),ED={chat:`chat`,transcribe:`hearing`,dictate:`hearing`,speak:`audio`,describe:`vision`,ocr:`vision`,decide:`decision`,metadata:`chat`,plan:`chat`},DD=S({model:LE,provider:wl.optional()}),OD=w(`engine`,[S({engine:D(`browser`)}),DD.extend({engine:D(`model`)})]),kD=[`browser`,`model`],AD=TD.exclude([`dictate`,`decide`]),jD=DD.extend({role:D(`decide`),threshold:y().min(0).max(1).default(sD)}),MD=w(`role`,[S({role:D(`dictate`),engine:OD,language:v().optional()}),jD,DD.extend({role:AD,language:v().optional()})]);S({choice:MD,setBy:M,updatedAt:N});var ND=C([S({model:v(),provider:v()}),S({problem:v()})]),PD=S({role:TD,choice:MD.optional(),from:E([`setting`,`env`,`none`]),resolved:ND.optional(),fallback:S({role:TD,reason:v()}).optional()}),FD=[`done`,`invalid-input`,`failed`,`cancelled`],ID=T(E(FD),y().int().min(0));function LD(){return{done:0,"invalid-input":0,failed:0,cancelled:0}}function RD(e){return FD.reduce((t,n)=>t+e[n],0)}var zD=v().regex(/^\d{4}-\d{2}-\d{2}$/),BD=[50,100,250,500,1e3,2500,5e3,1e4,3e4,6e4,3e5],VD=S({count:y().int().min(0),sum:jl,max:jl,histogram:x(y().int().min(0)).length(BD.length+1)}),HD=S({fn:I,system:F,day:zD,outcomes:ID,queued:VD,approval:VD,ran:VD,cost:P,tokens:y().int().min(0),retries:y().int().min(0),modelCalls:y().int().min(0),updatedAt:N}),UD=S({fn:I,system:F,from:zD,to:zD,runs:y().int().min(0),outcomes:ID,p50:jl.optional(),p95:jl.optional(),averageQueued:jl.optional(),averageCost:P,cost:P,tokens:y().int().min(0),retries:y().int().min(0),lastRunAt:N.optional()}),WD=S({fn:ub.optional(),system:F.optional(),days:y().int().min(1).max(365).optional()}),GD=E([`private`,`shared`,`public`]),KD={private:`Only me`,shared:`Me and chosen people`,public:`Everyone`},qD=S({owner:M,visibility:GD,with:x(M)});E([`system`,`fn`,`context`,`root`,`connection`]);var JD=w(`kind`,[S({kind:D(`system`),system:F}),S({kind:D(`fn`),fn:I}),S({kind:D(`context`),context:I}),S({kind:D(`root`),uri:v().min(1)}),S({kind:D(`connection`),connection:Al})]);function YD(e){switch(e.kind){case`system`:return`system:${e.system}`;case`fn`:return`fn:${e.fn}`;case`context`:return`context:${e.context}`;case`root`:return`root:${e.uri}`;case`connection`:return`connection:${e.connection}`}}S({key:v(),target:JD,sharing:qD,scoped:b().optional(),setBy:M,updatedAt:N});var XD=S({target:JD,sharing:qD,editable:b()}),ZD=S({multiUser:b()}),QD=qD.omit({owner:!0}),$D=S({run:A,fn:k,share:QD}),eO=S({run:A,fns:x(k).max(1e3)}),tO=S({source:E([`fn`,`context`,`system`,`person`,`group`,`model`,`resource`,`type`,`kind`]),text:v().optional(),values:x(v()).max(200).optional(),limit:y().int().min(1).max(50).optional()}),nO=S({value:v(),label:v(),hint:v().optional(),icon:v().optional(),missing:b().optional()}),rO=E([`shared`,`person`]),iO=v().regex(/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/),aO=T(iO,v()),oO=S({kind:D(`none`)}),sO=S({kind:D(`bearer`),per:rO,token:v().min(1).optional()}),cO=S({kind:D(`headers`),per:rO,names:x(iO).min(1),values:aO.optional()}),lO=w(`kind`,[oO,sO,cO,S({kind:D(`oauth`),per:rO,scopes:x(v().min(1)).optional(),clientId:v().min(1).optional(),clientSecret:v().min(1).optional()})]),uO=w(`kind`,[oO,sO,cO]),dO=w(`kind`,[oO,sO.omit({token:!0}),cO.omit({values:!0})]),fO=[`auth.token`,`auth.values`],pO=[`auth.token`,`auth.values`,`auth.clientSecret`];function mO(e){if(e.kind===`oauth`)return`oauth`;if(e.kind!==`none`&&e.per!==`shared`)return`form`}var hO=C([S({token:v().min(1)}),S({headers:aO}),S({accessToken:v().min(1),refreshToken:v().min(1).optional(),tokenType:v().default(`Bearer`),clientId:v().min(1).optional()})]),gO=S({on:b(),ask:b()}),_O=w(`flow`,[S({flow:D(`oauth`)}),S({flow:D(`form`),form:Z})]),vO=S({flow:_O.optional(),share:b().default(!1),title:v().min(1)}),yO=v().regex(Ml).brand();fc({name:yO,label:v().min(1),auth:lO,baseUrl:Ls().optional(),privateTo:M.optional()});var bO=C([yO,S({arg:k})]),xO=S({title:v(),description:v(),icon:v().optional(),how:_O,settings:Z,fns:T(k,gO),scope:E([`system`,`instance`,`key`]).optional(),keys:S({type:I}).optional(),defaults:gO.optional()}),SO=E([`pending`,`connected`,`expired`,`failed`]),CO=S({label:v(),detail:v().optional(),choices:T(v(),x(nO)).optional()}),wO=S({id:Al,system:F,instance:L.optional(),key:yO.optional(),owner:M,status:SO,account:CO.optional(),credentials:Sl.optional(),expiresAt:N.optional(),settings:O,fns:T(k,gO),share:QD,problem:v().optional(),createdAt:N,updatedAt:N}).omit({credentials:!0}),TO=S({system:F,decl:xO,ready:b(),connections:x(wO),instances:x(S({instance:L,label:v(),connect:vO})).optional(),keys:x(S({key:yO,label:v(),connect:vO,host:v().optional()})).optional()}),EO=S({id:Al,owner:M,credentials:O,settings:O}),DO=S({connection:Al,owner:M,redirect:Ls(),state:v(),instance:L.optional(),key:yO.optional()}),OO=S({connection:Al,owner:M,instance:L.optional(),key:yO.optional(),redirect:Ls(),answer:C([S({params:T(v(),v())}),S({form:O})])}),kO=C([S({account:CO,credentials:O,expiresAt:N.optional()}),S({problem:v()})]),AO=S({connection:Al,update:C([S({credentials:O,expiresAt:N.optional()}),S({expired:v()})])}),jO=S({connection:Al,settings:O.optional(),fns:T(k,gO).optional(),share:QD.optional()}),MO=[`embedding`,`imageEmbedding`],NO=S({input:P,output:P,cached:P.optional(),cacheWrite:P.optional()}),PO=S({id:v().min(1),name:v().optional(),capabilities:x(v()),contextWindow:y().int().min(1),maxOutput:y().int().min(1).optional(),pricing:NO,caching:b(),dimensions:y().int().min(1).optional(),maxInput:y().int().min(1).optional(),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}).refine(e=>!MO.some(t=>e.capabilities.includes(t))||e.dimensions!==void 0,{message:`An embedding model says how many dimensions its vectors have.`,path:[`dimensions`]}),FO=S({name:k,description:v(),models:x(PO),runtime:D(!0).optional(),instance:L.optional()}),IO=S({provider:k,model:v(),request:YE,stream:b(),run:A.optional()}),LO=w(`type`,[S({type:D(`chunk`),chunk:UE}),S({type:D(`done`),usage:VE}),S({type:D(`error`),message:v(),kind:E([`model`,`limit`,`provider`,`auth`])})]),RO=S({id:v().min(1),contextWindow:y().int().min(1).optional(),maxOutput:y().int().min(1).optional(),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}),zO=S({provider:k}),BO=w(`listed`,[S({listed:D(!0),models:x(RO)}),S({listed:D(!1)})]),VO=S({provider:k,model:v(),input:nD,questions:rD}),HO=S({answers:oD,tokens:y().int().min(0).optional()}),UO=S({image:v().regex(/^(https?:|data:)/,`an http(s) or data URL`),mimeType:v().optional()}),WO=C([v(),UO]),GO=S({provider:k,model:v(),inputs:x(WO).min(1)}),KO=S({vectors:x(x(y())),tokens:y().int().min(0).optional()});function qO(e){return S({provider:D(`aws`),region:v().min(1),auth:w(`kind`,[S({kind:D(`keys`),accessKeyId:v().min(1),secretAccessKey:e,sessionToken:e.optional()}),S({kind:D(`apiKey`),apiKey:e})]),profilePrefix:v().optional()})}var JO=S({input:b(),output:b()}),YO=C([S({ok:D(!0)}),S({ok:D(!1),reason:v().min(1)})]),XO=C([S({ok:D(!0)}),S({ok:D(!1),action:E([`retry`,`stop`]),reason:v().min(1)})]),ZO=w(`phase`,[S({phase:D(`input`),run:zT,fn:v(),args:O}),S({phase:D(`output`),run:zT,fn:v(),args:O,result:O,attempt:y().int().min(1)})]),QO=C([XO,YO]),$O=S({kind:E([`builtin`,`dynamic-import`,`dynamic-require`,`eval`,`new-function`]),line:y().int().min(1),detail:v(),code:v()}),ek=S({size:y().int().min(0),builtins:x(v()),concerns:x($O),urls:x(v()),hosts:x(v())}),tk=E([`passed`,`failed`,`skipped`]),nk=S({file:v().min(1),name:v().min(1),status:tk,duration:jl,real:b().optional(),error:v().max(4e3).optional()}),rk=[`phone`,`desktop`],ik=E(rk);E([`empty`,`loading`,`error`,`typical`,`long`]);var ak=S({component:v().min(1),state:v().min(1),viewport:ik,theme:E([`light`,`dark`]),image:kx}),ok=S({scan:ek,tests:S({system:F,version:v().min(1),ranAt:N,duration:jl,passed:y().int().min(0),failed:y().int().min(0),skipped:y().int().min(0),cases:x(nk).max(500),more:y().int().min(0).optional(),previews:x(ak).max(200).optional()}).optional()}),sk=E([`ai`,`embed`,`resources`,`fns`,`search`,`decide`,`approvals`,`connections`,`settings`,`state`,`data`,`runs`]),ck=S({roles:x(TD).optional(),models:x(v().min(1)).optional(),perRun:P.optional(),perDay:P.optional()}),lk=S({read:x(v().min(1)),write:x(v().min(1))}),uk=S({hub:x(sk),models:ck.optional(),secrets:x(v().min(1)).optional(),calls:x(C([I,F])).optional(),network:x(v().min(1)).optional(),files:lk.optional()}),dk=S({component:v().min(1),mode:E([`replace`,`beside`])}),fk=[`installed`,`live`],pk=E(fk),mk=[`text`,`integer`,`number`,`boolean`,`date`,`datetime`,`time`,`uuid`,`json`,`binary`],hk=E(mk),gk=E([`group`,`measure`,`attribute`]),_k=S({name:k,label:v().min(1),accepts:x(hk).min(1),required:b(),many:b(),min:y().int().min(1).optional(),role:E([`group`,`measure`]).optional()}),vk=w(`rule`,[S({rule:D(`distinct`),channel:k,max:y().int().min(1)}),S({rule:D(`non-negative`),channel:k}),S({rule:D(`bounded`),channel:k}),S({rule:D(`distinct-columns`),channels:x(k).min(2)}),S({rule:D(`links`),from:k,to:k})]),yk=E([`window`,`top-n`,`partition`,`aggregate`]),bk=S({name:k,label:v().min(1),whole:D(!0).optional(),needs:x(k).optional()}),xk=S({claim:D(`range`),channel:k}),Sk=E([`floor`,`structural`,`encoded`,`time-encoded`]),Ck=E([`temporal-key`,`low-cardinality`,`enum-key`,`high-null`,`many-categories`]),wk=S({channels:x(_k).min(1),rows:S({min:y().int().min(0),max:y().int().min(1).optional()}),whole:b(),rules:x(vk).default([]),size:yk.optional(),styles:x(bk).min(1).default([{name:`default`,label:`Default`}]),claims:x(xk).default([]),priority:S({band:Sk,terms:x(Ck)}).default({band:`structural`,terms:[]}),pageSize:y().int().min(1).max(500).optional()}),Tk=S({name:k,description:v(),data:Z}),Ek=S({registry:I,name:k,label:v().min(1),description:v().optional(),icon:v().optional(),shape:wk.optional()}),Dk=Ek.extend({system:F}),Ok=S({name:v().min(1),label:v().optional(),kind:hk,nullable:b(),type:Z.optional(),ref:I.optional(),role:gk.optional(),key:b().optional(),editable:b().optional()}),kk=S({column:v().min(1),dir:E([`asc`,`desc`])}),Ak=S({fn:I,args:T(v(),O),keys:x(v().min(1))}),jk=S({columns:x(Ok),rows:x(x(O)),offset:y().int().min(0),limit:y().int().min(1).optional(),total:y().int().min(0).optional(),truncated:b(),sort:x(kk),write:S({affected:y().int().min(0)}).optional(),records:S({type:I,id:v().min(1)}).optional(),drill:Ak.optional()}),Mk=S({flag:E([`delete-fns`,`write-fns`,`runs`,`injects`,`effects`,`capabilities`,`secrets`,`hosts`,`files`,`calls`,`models`]),line:v().min(1),items:x(v().min(1)),lead:v().min(1).optional(),tail:v().min(1).optional()}),Nk=S({section:v().min(1),added:y().int().min(0),changed:y().int().min(0),removed:y().int().min(0)}),Pk=E([`widened`,`narrowed`,`changed`,`added`]),Fk=S({line:v(),counts:x(Nk),flags:x(Mk),grants:Pk.optional(),config:E([`added`,`changed`,`removed`]).optional()}),Ik=E([`gitignored`,`env`,`key`,`credential`,`token`,`secret-content`,`runs-code`,`unknown-path`]),Lk=E([`allow`,`ask`,`refuse`]),Rk=E([`ask`,`refuse`]),zk=w(`type`,[S({type:D(`glob`),glob:v().min(1)}),S({type:D(`content`),pattern:v().min(1)}),S({type:D(`gitignored`)})]);S({name:v().min(1),kind:Ik,match:zk,except:x(v().min(1)).optional(),read:Lk,write:Rk,why:v().min(1)});var Bk=S({path:v().min(1),kind:Ik,rule:v().min(1),access:E([`read`,`write`]),action:E([`allow`,`ask`,`refuse`]),why:v().min(1),certain:b()}),Vk=S({flags:x(Bk)}),Hk=w(`type`,[S({type:D(`text`),text:v()}),S({type:D(`code`),language:v(),code:v(),title:v().optional()}),S({type:D(`table`),title:v(),table:jk}),S({type:D(`type-diff`),name:v(),before:Z.optional(),after:Z.optional(),changes:x(v()),breaks:x(S({fn:v(),why:v()}))}),S({type:D(`flags`),flags:x(Bk).min(1)})]),Uk=S({kind:D(`system-install`),system:F,instance:L,version:v().min(1),manifestHash:v().min(1),bundleHash:v().min(1),sourceHash:v().min(1),host:Kl,source:v().min(1).optional(),grants:uk.optional(),replaces:S({version:v().min(1),manifestHash:v().min(1)}).optional()}),Wk=w(`kind`,[Uk]),Gk=S({title:v().min(1),parts:x(Hk),irreversible:b(),subject:Wk.optional(),checks:ok.optional(),summary:Fk.optional()}),Kk=E([`person`,`admins`]),qk=S({preview:b(),remember:b(),approver:Kk.optional()}),Jk=S({run:A,fn:k,args:O,user:IT,kind:Nl.optional(),payload:O.optional()}),Yk=S({run:A,fn:k,args:O,user:IT,deadline:N}),Xk=S({problems:x(QT)}),Zk=S({type:Z,into:k,label:v().min(1).max(80).optional()}),Qk=S({fn:k,args:O,key:v().min(1),parent:A.optional(),approver:Kk,for:M.optional(),chat:j.optional(),ask:Zk.optional(),preview:Gk}).refine(e=>e.parent!==void 0||e.approver===`admins`||e.for!==void 0,{message:"A run proposed outside a run waits for an admin, or for the person named in `for`.",path:[`approver`]}),$k=S({by:M,preview:Gk}),eA=S({run:A,subject:Uk}),tA=S({token:v().min(1),expiresAt:N}),nA=S({run:A,approval:hl}),rA=v().regex(/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/),iA=x(rA),aA=`•••• kept`,oA=S({$secret:Sl,json:D(!0).optional()}),sA=v().regex(/^[a-z][a-z0-9-]{0,39}$/,`a page segment is lowercase letters, digits and dashes, starting with a letter (at most 40)`),cA=E([`main`,`hidden`]),lA=E([`everyone`,`admin`]),uA=S({segment:sA,title:v().trim().min(1).max(40),description:v().optional(),icon:v().min(1).optional(),nav:cA.default(`main`),access:lA.default(`everyone`),component:v().min(1)});function dA(e){let t=new Set;return e.flatMap(e=>t.has(e.segment)?[`page ${e.segment} is declared twice`]:(t.add(e.segment),[]))}var fA=x(uA).superRefine((e,t)=>{for(let n of dA(e))t.addIssue({code:`custom`,message:n})}),pA=uA.extend({system:F,client:S({url:v().min(1),hash:v().min(1)})}),mA=S({instance:L,description:v(),online:b(),version:v()}),hA=`http://127.0.0.1:11434`;function gA(e){return w(`provider`,[S({provider:D(`openai`),apiKey:e,baseURL:Ls().optional()}),S({provider:D(`openrouter`),apiKey:e}),S({provider:D(`ollama`),baseURL:Ls().default(hA),contextWindow:y().int().min(256).optional(),decisionModels:x(v().min(1)).optional()}),qO(e)])}var _A=gA(Sl),vA=E(_A.options.map(e=>e.shape.provider.value));S({id:wl,config:_A,createdAt:N}),S({id:Sl,name:v(),owner:M,ciphertext:v(),createdAt:N});var yA=S({id:Cl,name:v(),description:v(),models:x(v())}),bA=w(`scope`,[S({scope:D(`hub`)}),S({scope:D(`group`),group:M}),S({scope:D(`user`),user:M}),S({scope:D(`session`),session:j}),S({scope:D(`turn`),turn:sl}),S({scope:D(`system`),system:F}),S({scope:D(`fn`),fn:I}),S({scope:D(`model`),model:v()})]),xA=E([`hub`,`group`,`user`,`session`,`turn`]),SA=w(`scope`,[S({scope:D(`hub`)}),S({scope:D(`group`),group:M}),S({scope:D(`user`),user:M}),S({scope:D(`session`),session:j}),S({scope:D(`turn`),turn:sl})]),CA=S({id:gl,target:bA,period:C([S({window:jl}),D(`all-time`),D(`per-turn`)]),maxCost:P,maxTokens:y().int().optional(),maxCalls:y().int().optional(),maxTime:jl.optional(),share:E([`pooled`,`each`]).optional(),onLimit:E([`wait`,`refuse`,`ask`]),setBy:M}),wA=S({id:_l,target:SA,default:Ll.optional(),max:Ll.optional(),setBy:M}),TA=S({priority:Ll,priorityFrom:S({default:xA,cappedBy:xA.optional()}),turn:S({cost:P,time:jl}),budgets:x(S({rule:gl,scope:bA,remaining:P})),limitedBy:gl.optional()});S({id:vl,budgets:x(gl),estimate:P,createdAt:N,settled:S({cost:P,at:N}).optional()}),S({id:yl,at:N,cost:P,tokens:y().int().min(0),actor:M,system:F.optional(),session:j.optional(),fn:I,model:v().optional(),llmCall:dl.optional(),modelCall:Dl.optional(),run:A});var EA=E([`chat`,`admin`,`disconnected`,`needs-config`,`held`,`removed`]),DA=S({prompt:x(S({name:F,label:v(),description:v(),summary:v().optional()})),on:x(F),off:x(S({name:F,why:EA}))}),OA=S({name:F,reason:v(),label:v().optional(),description:v().optional()}),kA=RegExp(`(\\d+)`,`g`);function AA(e,t=[]){let n=new Map(t.map(e=>[e.index,e.number]));return e.replace(kA,(e,t)=>{let r=n.get(Number(t));return r===void 0?``:`[${r}]`})}function jA(e){let t=e.trim().replace(/^\$\.?/,``);if(t===``)return[];let n=[],r=/\[\s*(?:"([^"]*)"|'([^']*)'|(\d+))\s*\]|([^.[\]]+)/y,i=0;for(;i<t.length;){if(t[i]===`.`){i+=1;continue}r.lastIndex=i;let e=r.exec(t);if(e===null)return;n.push(e[1]??e[2]??e[3]??e[4]??``),i=r.lastIndex}return n}function MA(e){try{return O.parse(JSON.parse(e))}catch{return}}function NA(e,t){let n=jA(t);if(n===void 0)return;let r=e;for(let e of n){let t=typeof r==`string`?MA(r):r;if(Array.isArray(t)){if(!/^\d+$/.test(e))return;let n=t[Number(e)];if(n===void 0)return;r=n}else if(typeof t==`object`&&t){if(!Object.hasOwn(t,e))return;let n=t[e];if(n===void 0)return;r=n}else return}return{value:r}}var PA=S({index:y().int().min(1),number:y().int().min(1),tool:v(),path:v(),note:v()}),FA=E([`result`,`reply`]),IA=PA.extend({run:A.optional(),fn:I.optional(),found:FA.optional(),value:O.optional(),large:D(!0).optional(),problem:v().optional()}),LA=S({prompt:b(),on:b()}),RA=y().int().min(0).max(3),zA=S({agent:I,model:LE.optional(),mode:zb.optional(),contextor:Xb.optional(),fnMode:fx.optional(),systems:C([x(F),D(`all`)]),instructions:v().optional(),citations:b().optional()}),BA=zA.partial(),VA=x(S({label:v().trim().min(1).max(40).optional(),settings:BA})).min(2).max(4),HA=S({turn:sl,variant:RA,label:v()}),UA=S({variant:RA,label:v(),settings:BA,session:j,turn:sl}),WA=S({run:A,fn:I}),GA=S({variant:RA,effects:x(WA)}),KA=S({variant:RA,label:v(),effects:x(WA).min(1)}),qA=S({variants:x(UA).min(2).max(4),reserved:P,chosen:RA.optional(),chosenBy:M.optional(),chosenAt:N.optional(),discarded:x(GA)}),JA=S({field:v(),type:v(),before:O.optional(),after:O.optional()}),YA=S({id:A,fn:I,fnVersion:v(),kind:Nl,system:F,instance:L.optional(),parent:A.optional(),root:A,turn:sl,session:j.optional(),key:v(),actor:M,caller:M,connection:Al.optional(),llmCall:dl.optional(),toolCallId:v().optional(),args:O,repairs:x($T).optional(),test:b().optional(),status:rE,awaitingSystem:b().optional(),text:_T.optional(),outcome:dE.optional(),progress:qT.optional(),allowed:UT,cost:P,totalCost:P,priority:Ll,background:b(),attempt:y().int().min(1),errors:x(S({attempt:y().int(),error:XT,cost:P,at:N})),undo:O.optional(),resume:O.optional(),stateChanges:x(JA),tokens:y().int().min(0).optional(),createdAt:N,approvedAt:N.optional(),startedAt:N.optional(),endedAt:N.optional(),resultRevision:y().int().min(1).optional(),resultUpdatedAt:N.optional(),resultUpdatedBy:M.optional()}),XA=YA.pick({id:!0,fn:!0,status:!0,cost:!0,totalCost:!0,startedAt:!0,endedAt:!0}),ZA=S({session:j,system:F,name:v(),type:v(),def:Z,value:O,version:y().int().min(1),updatedBy:C([S({run:A}),S({delivery:ll})]),updatedAt:N}).pick({name:!0,type:!0}).extend({value:O.optional()}),QA=E([`queued`,`delivered`,`done`,`failed`,`expired`]),$A=S({id:ll,system:F,kind:C([S({action:v(),input:O}),S({form:A,value:O})]),session:j,actor:M,run:A.optional(),status:QA,result:O.optional(),error:XT.optional(),attempts:y().int().min(0),createdAt:N,deliveredAt:N.optional(),doneAt:N.optional(),expiresAt:N.optional()}).pick({id:!0,status:!0,result:!0,error:!0}),ej=S({id:ul,run:A,handler:v(),args:O,decl:S({description:v(),args:Z,returns:Z}),answerer:C([S({user:M}),S({system:F,run:A})]),status:E([`pending`,`answered`,`failed`]),result:O.optional(),createdAt:N}),tj=E([`running`,`done`,`failed`,`cancelled`,`paused`,`undone`]),nj=S({transcript:y().int().min(0),tools:x(I),context:x(I),selection:ux.optional(),suggested:x(I).optional(),announcedSystems:DA.optional(),citationsTold:LA.optional()});S({id:sl,session:j.optional(),message:cl.optional(),actor:M,user:IT,time:LT,client:BT.optional(),root:A.optional(),status:tj,limits:TA,cost:P,errors:C([S({max:y().int().min(1)}),D(`feed-back`)]),start:nj.optional(),compare:qA.optional(),createdAt:N,continuedAt:N.optional(),endedAt:N.optional()});var rj=E([`queued`,`streaming`,`done`,`failed`,`aborted`]),ij=S({content:v(),reasoning:v().optional(),toolCalls:x(UE.shape.toolCall.unwrap()).optional(),finishReason:UE.shape.finishReason.unwrap(),refusal:v().optional()}),aj=S({id:dl,turn:sl,run:A,session:j.optional(),system:F.optional(),iteration:y().int().min(0),provider:v(),model:v(),request:YE,response:ij.optional(),usage:VE.optional(),cost:P,status:rj,error:v().optional(),priority:Ll,selection:sx.optional(),modelCall:Dl.optional(),queuedAt:N,startedAt:N.optional(),firstTokenAt:N.optional(),endedAt:N.optional()}),oj=Kc(()=>S({run:XA,llmCalls:x(aj.pick({id:!0,model:!0,cost:!0,status:!0})),children:x(oj)})),sj=S({turn:sl,undone:x(S({run:A,fn:I,summary:v()})),failed:x(S({run:A,fn:I,error:XT})),notUndoable:x(S({run:A,fn:I})),kept:x(KA).optional(),session:S({messages:y().int().min(0),unloaded:x(I),reloaded:x(I)}).optional()});S({run:A,turn:sl,session:j.optional(),iteration:y().int().min(0),priority:Ll}),S({run:A,priority:Ll});var cj=[`system`,`instance`,`fn`,`context`,`type`,`kind`,`resource`,`root`,`component`,`registry`,`command`,`provider`],lj=E(cj),uj=[`brings`,`names`,`loads`,`next`,`reads`,`writes`,`calls`,`uses`,`kind`,`creates`,`updates`,`removes`,`refers`,`renders`,`contributes`,`belongs`],dj=E(uj),fj=[...fk,`pending`];E(fj);var pj=E([`text`,`enum`,`number`,`date`,`boolean`]);E([`is`,`isNot`,`in`,`notIn`,`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`,`contains`]);var mj={text:[`contains`,`is`,`isNot`,`in`,`notIn`,`empty`,`notEmpty`],enum:[`is`,`isNot`,`in`,`notIn`,`empty`,`notEmpty`],number:[`gt`,`gte`,`lt`,`lte`,`between`,`is`,`isNot`,`empty`,`notEmpty`],date:[`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`],boolean:[`is`]},hj={is:`is`,isNot:`is not`,in:`in`,notIn:`not in`,gt:`>`,gte:`≥`,lt:`<`,lte:`≤`,between:`between`,empty:`is empty`,notEmpty:`is not empty`,contains:`contains`},gj=C([v(),y(),b()]),_j=E([`usd`,`ms`,`tokens`,`bytes`,`count`]);S({label:v(),type:pj,sortable:b(),filterable:b(),values:x(v()).readonly().optional(),dynamic:b().optional(),unit:_j.optional()});var vj=v().min(1),yj=w(`op`,[S({field:vj,op:E([`is`,`isNot`,`gt`,`gte`,`lt`,`lte`,`contains`]),value:gj}),S({field:vj,op:E([`in`,`notIn`]),values:x(gj).min(1)}),S({field:vj,op:D(`between`),from:gj,to:gj}),S({field:vj,op:E([`empty`,`notEmpty`])})]),bj=S({field:vj,dir:E([`asc`,`desc`])}),xj=Vl.extend({text:v().optional(),filters:x(yj).max(20).optional(),sort:x(bj).max(3).optional()}),Sj=(e,t={})=>({label:e,type:`text`,sortable:!0,filterable:!0,...t}),Cj=(e,t)=>({label:e,type:`enum`,sortable:!0,filterable:!0,values:t}),wj=e=>({label:e,type:`enum`,sortable:!0,filterable:!0,dynamic:!0}),Tj=(e,t)=>({label:e,type:`number`,sortable:!0,filterable:!0,unit:t}),Ej=e=>({label:e,type:`date`,sortable:!0,filterable:!0}),Dj=e=>({label:e,type:`boolean`,sortable:!1,filterable:!0}),Oj=e=>({...e,sortable:!1}),kj=[`resources`,`fns`,`runs`,`modelCalls`,`llmCalls`,`sessions`,`contexts`,`notifications`,`systems`,`types`,`graph`,`users`,`groups`],Aj=E(kj),jj={resources:{fields:{name:Sj(`Name`),system:wj(`System`),family:Cj(`Type`,CE),source:Cj(`Source`,bE),forms:{...Cj(`Forms`,Lx.options),sortable:!1},size:Tj(`Size`,`bytes`),seenAt:Ej(`Seen`),modifiedAt:Ej(`Modified`)},defaultSort:[{field:`seenAt`,dir:`desc`}]},fns:{fields:{name:Sj(`Name`),system:wj(`System`),kind:wj(`Kind`),available:Dj(`Available`),paused:Dj(`Paused`),disabled:Dj(`Disabled`),runs:Tj(`Runs`,`count`),failures:Tj(`Failures`,`count`),averageCost:Tj(`Avg cost`,`usd`),averageTime:Tj(`Avg time`,`ms`),lastRunAt:Ej(`Last run`),updatedAt:Ej(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},runs:{fields:{fn:wj(`Fn`),system:wj(`System`),status:Cj(`Status`,nE),session:wj(`Session`),actor:wj(`By`),cost:Tj(`Cost`,`usd`),duration:Tj(`Duration`,`ms`),createdAt:Ej(`Started`),endedAt:Ej(`Ended`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},modelCalls:{fields:{modality:Cj(`Modality`,cD),model:wj(`Model`),provider:wj(`Provider`),system:wj(`System`),status:Cj(`Status`,_D.options),session:wj(`Session`),cost:Tj(`Cost`,`usd`),tokens:Tj(`Tokens`,`tokens`),duration:Tj(`Duration`,`ms`),createdAt:Ej(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},llmCalls:{fields:{model:wj(`Model`),system:wj(`System`),status:Cj(`Status`,rj.options),session:wj(`Session`),cost:Tj(`Cost`,`usd`),tokens:Tj(`Tokens`,`tokens`),duration:Tj(`Duration`,`ms`),createdAt:Ej(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},sessions:{fields:{title:Sj(`Title`),agent:wj(`Agent`),status:Cj(`Status`,[`idle`,`running`,`paused`]),archived:Dj(`Archived`),createdAt:Ej(`Created`),updatedAt:Ej(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},contexts:{fields:{name:Sj(`Name`),system:wj(`System`),origin:Cj(`Origin`,Qx),tags:wj(`Tag`),status:Cj(`Status`,hS),askedBy:Cj(`Asked by`,yS),stale:Dj(`Stale`),tokens:Tj(`Tokens`,`tokens`),lastModified:Ej(`Last modified`),updatedAt:Ej(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},notifications:{fields:{kind:wj(`Kind`),read:Dj(`Read`),createdAt:Ej(`Received`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},systems:{fields:{name:Sj(`Name`),status:wj(`Status`),version:Sj(`Version`),instances:Tj(`Instances`,`count`),fns:Tj(`Fns`,`count`),context:Tj(`Context`,`count`),types:Tj(`Types`,`count`),parts:Tj(`Other parts`,`count`),pending:Tj(`Pending changes`,`count`),refusals:Tj(`Refusals`,`count`),lastSeenAt:Ej(`Last seen`)},defaultSort:[{field:`name`,dir:`asc`}]},types:{fields:{name:Sj(`Name`),system:wj(`System`),instance:wj(`Instance`),references:Tj(`Refers to`,`count`),updatedAt:Ej(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},graph:{fields:{name:Oj(Sj(`Name`)),system:Oj(wj(`System`)),nodeKind:Oj(Cj(`Item`,cj)),edgeKind:Oj(Cj(`Link`,uj)),fnKind:Oj(wj(`Fn kind`)),mode:Oj(wj(`Mode`)),effect:Oj(wj(`Effect on`)),visibility:Oj(Cj(`Visible to`,Rl.options)),stage:Oj(Cj(`Stage`,fj)),on:Dj(`On`)},defaultSort:[]},users:{fields:{name:Sj(`Name`),email:Sj(`Email`),role:Cj(`Role`,[`admin`,`member`]),disabled:Dj(`Disabled`),createdAt:Ej(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]},groups:{fields:{name:Sj(`Name`),createdAt:Ej(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]}};function Mj(e,t){return t.sort!==void 0&&t.sort.length>0?t.sort:jj[e].defaultSort}var Nj=S({value:gj,label:v().optional(),count:y().int().min(0)}),Pj=S({list:Aj,field:vj,prefix:v().optional(),limit:y().int().min(1).max(50).optional()}),Fj=S({list:Aj,query:xj.default({})}),Ij=Bl(Zc()).extend({sort:x(bj),total:y().int().min(0).optional(),partial:D(!0).optional().describe(`More rows than the hub reads at once: more may match; narrow the filters for a full answer.`)}),Lj=ol.record,Rj=S({shape:E([`table`,`value`]),owner:E([`shared`,`person`]),writers:D(`admins`).optional(),search:S({text:x(v().min(1)),embed:b()})}),zj=S({id:Lj,type:I,value:O,owner:M.optional(),title:v(),version:y().int().min(1),createdAt:N,updatedAt:N,updatedBy:M.optional(),updatedBySystem:F.optional(),run:A.optional()}),Bj=S({id:v().min(1),record:Lj,type:I,number:y().int().min(1),change:E([`created`,`updated`,`removed`]),value:O,by:M.optional(),bySystem:F.optional(),run:A.optional(),at:N}),Vj=S({type:I,query:xj.optional(),search:v().min(1).optional(),run:A.optional()}),Hj=Bl(zj),Uj=Vj.extend({query:xj.omit({cursor:!0,limit:!0}).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(500).optional()}),Wj=S({type:I,id:Lj,run:A.optional()}),Gj=S({type:I,id:Lj.optional(),value:O,expect:y().int().min(1).optional(),run:A.optional(),owner:M.optional()}),Kj=S({type:I,id:Lj,set:T(v().min(1),O).refine(e=>Object.keys(e).length>0,`set at least one field`),expect:y().int().min(1).optional(),run:A.optional()}),qj=S({type:I,id:Lj,run:A.optional()}),Jj=Vl.extend({type:I,id:Lj}),Yj=Bl(Bj),Xj=S({type:I,system:F,description:v(),storage:Rj,records:y().int().min(0),updatedAt:N.optional()}),Zj=Vl.extend({text:v().optional(),system:F.optional()}),Qj=Bl(Xj),$j=`general`,eM=S({name:k,title:v().min(1),description:v().min(1)}),tM=E([`sqlite`,`postgres`,`sqlserver`]),nM=tM.options,rM=S({description:v().min(1).max(500),vectors:b().default(!1),engines:x(tM).min(1).default([...nM])}),iM=v().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/,`A migration id is letters, digits, dots, dashes and underscores, starting with a letter or digit.`),aM=v().regex(/^[A-Za-z_][A-Za-z0-9_]{0,62}$/,`A schema name is letters, digits and underscores, starting with a letter or underscore.`),oM=E([`postgres`,`sqlserver`]);E([`system`,`hub`,`external`]);var sM=`system`,cM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:oM,connection:oA,schema:aM})]),lM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:oM,connection:v().min(1).max(4e3),schema:aM})]),uM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:oM,connection:v().min(1),schema:aM})]),dM=[`sqlite`,`postgres`,`sqlserver`],fM={postgres:`Postgres with the pgvector extension installed (CREATE EXTENSION vector)`,sqlserver:`SQL Server 2025 or newer, which has the VECTOR type`};function pM(e){return e.placement===`external`&&e.engine!==void 0?e.engine:`sqlite`}function mM(e,t){let n=pM(t),r=t.placement===`external`?`an external ${n} database`:`the ${t.placement===`hub`?`hub`:`system`} (SQLite)`;return e.engines.includes(n)?e.vectors&&!dM.includes(n)?[`This store keeps vectors, which ${r} can't hold.`]:[]:[`This store runs only on ${e.engines.join(`, `)}, so it can't be kept in ${r}.`]}var hM=E([`preparing`,`migrating`,`ready`,`moving`,`failed`]),gM=S({applied:x(S({id:iM,checksum:v().min(1),at:N})),pending:x(iM)}),_M=S({name:v().min(1).max(200),rows:y().int().min(0)}),vM=S({bytes:y().int().min(0).optional(),tables:x(_M).max(200),at:N,more:b().optional()}),yM=S({state:hM,engine:tM,migrations:gM,error:v().max(4e3).optional(),measure:vM.optional()}),bM=yM.extend({at:N}),xM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:oM,schema:aM})]),SM=v().regex(/^[0-9a-z][0-9a-z_.-]{0,120}$/),CM=S({id:SM,system:v(),instance:v(),where:xM,bytes:y().int().min(0).optional(),at:N,reason:E([`move`,`removed`]),orphaned:b().default(!1)}),wM=v().regex(/^move_[0-9a-z]{8,40}$/),TM=E([`draining`,`waiting`,`copying`,`switching`,`done`,`failed`]),EM=E([`ask`,`cancel`,`wait`]),DM=E([`cancel`,`wait`]),OM=S({step:E([`exporting`,`transferring`,`migrating`,`copying`,`checking`]).optional(),tables:S({done:y().int().min(0),total:y().int().min(0)}),table:v().max(200).optional(),rows:y().int().min(0),bytes:S({done:y().int().min(0),total:y().int().min(0)})}),kM=S({move:wM,system:v(),instance:v(),from:xM,to:xM,phase:TM,runs:EM,running:x(v()),asking:N.optional(),progress:OM,startedAt:N,endedAt:N.optional(),by:v(),backups:x(CM),error:v().max(4e3).optional()}),AM=S({placement:cM,status:bM.optional(),backups:x(CM).optional()}),jM=S({system:v(),instance:v(),decl:rM,placement:xM,status:bM.optional(),holding:b(),measure:vM.optional(),file:S({bytes:y().int().min(0),snapshots:x(S({name:v(),bytes:y().int().min(0),at:N}))}).optional(),backups:x(CM).default([]),move:kM.optional()}),MM=v().regex(/^lease_[0-9a-z]{8,40}$/),NM=S({$bytes:v()}),PM=C([v(),y(),ic(),NM]),FM=S({sql:v().min(1).max(1e6),params:x(PM).max(32766),lease:MM.optional()}),IM=S({rows:x(T(v(),PM)),changes:y().int().min(0).optional(),insertId:y().int().optional()}),LM=S({lease:MM,expiresAt:N}),RM=v().regex(/^[0-9a-z][0-9a-z_.-]{0,120}\.db$/);function zM(e){for(let t of e.matchAll(ST)){let n=(t[1]??``).trim();if(!n.startsWith(`args.`))return`the claim "${e}" uses {${n}}: a claim reads only its call's args ({args.path})`}}var BM=v().min(1).max(500).superRefine((e,t)=>{let n=zM(e);n!==void 0&&t.addIssue({code:`custom`,message:n})}),VM=S({fn:k,args:O,user:IT,caller:A,session:j.optional()}),HM=S({claims:x(v().min(1))});function UM(e){return e==null||e===``?[]:typeof e==`string`?[e]:typeof e==`number`||typeof e==`boolean`?[String(e)]:Array.isArray(e)?e.flatMap(e=>Array.isArray(e)?[JSON.stringify(e)]:UM(e)):[JSON.stringify(e)]}function WM(e,t){let n=[],r=[],i=0;for(let a of e.matchAll(ST)){n.push(e.slice(i,a.index)),i=a.index+a[0].length;let[o,...s]=(a[1]??``).trim().split(`.`),c=o===`args`?UM(DT(t,s)):[],l=a[2],u=c.length>0?c:l===void 0?[]:[l];if(u.length===0)return[];r.push(u)}n.push(e.slice(i));let a=[n[0]??``];return r.forEach((e,t)=>{let r=n[t+1]??``;a=a.flatMap(t=>e.map(e=>`${t}${e}${r}`))}),a}function GM(e,t){return[...new Set(e.flatMap(e=>WM(e,t)))]}var KM=S({label:v(),plural:v().optional(),icon:v().optional(),color:v().optional(),title:v().optional(),subtitle:v().optional()}),qM=S({name:k,description:v(),def:Z,display:KM,methods:x(k),instance:L.optional(),audience:QD.optional(),meta:T(v(),O).optional(),records:Rj.optional()}),JM=E([`user-wins`,`union`,`intersect`,`most-restrictive`]),YM=E([`self`,`fns`]),XM=S({name:k,description:v(),type:Z,appliesTo:x(zl),merge:JM,editableBy:x(YM)}),ZM=S({name:k,description:v(),data:Z}),QM=S({name:k,description:v(),applicability:v(),payload:Z,approveChanges:b(),status:gT.optional(),estimates:b().optional(),approval:qk.optional()}),$M=S({description:v(),args:Z,returns:Z,required:b()}),eN=w(`to`,[S({to:D(`instance`),instance:L}),S({to:D(`any`)})]),tN=S({args:O,result:O.optional(),note:v().optional()}),nN=E([`read`,`write`,`delete`]),rN=E([`fns`,`types`,`context`,`resources`,`kinds`,`components`,`examples`,`approvals`,`secrets`,`connections`,`records`]),iN=[`create`,`update`,`remove`],aN=E(iN),oN=S({thing:rN,action:aN,kind:Nl.optional()}).refine(e=>e.kind===void 0||e.thing===`fns`,{message:`only fns have a kind`,path:[`kind`]}),sN=E([`resources`]),cN=S({mode:nN.optional(),reads:x(I).optional(),writes:x(I).optional(),free:b().optional(),registry:x(oN).optional(),keeps:x(sN).min(1).optional()}),lN=S({language:v().min(1),code:v()}),uN=S({every:jl.min(1e3)}),dN=E([`developer`,`admin`,`reference`]),fN=S({deps:x(I)}),pN=S({name:k,description:v(),instructions:v().optional(),kind:Nl,payload:O.optional(),readable:lN.optional(),args:Z,returns:Z,deps:x(I),handlers:T(v(),$M),progress:GT,status:gT.optional(),operations:HT,undo:Z.optional(),resume:Z.optional(),state:Z.optional(),form:Z.optional(),display:VT,limits:WT,visibility:Rl,tags:x(v()),niche:dN.optional(),examples:x(tN).optional(),validate:JO.optional(),approval:qk.optional(),routing:eN.optional(),connectKey:bO.optional(),effects:cN.optional(),promptExamples:y().int().min(0).max(20).optional(),group:k.optional(),flags:b().optional(),roles:x(TD).optional(),live:uN.optional(),parallelClaims:x(BM).optional(),dynamicClaims:b().optional(),check:fN.optional()}),mN=S({name:v(),hint:v(),required:b()}),hN=S({to:I,when:v().min(1).max(200)}),gN=S({name:k,title:v().min(1).optional(),description:v(),content:v().optional(),command:S({name:v(),args:x(mN)}).optional(),imports:x(I),fns:x(I),suggestFns:x(I),suggest:Rl,visible:Rl,inject:wb.optional(),tags:x(v()),niche:dN.optional(),weight:y().min(0).max(2).optional(),summary:v().optional(),parent:I.optional(),next:I.optional(),choices:x(hN).optional(),links:x(aS).optional(),question:v().min(1).max(500).optional(),when:v().min(1).max(500).optional(),lastModified:N.optional(),askedBy:bS.optional()}),_N=S({name:k,description:v(),explains:v().min(1).max(2e3).optional(),order:y(),timeout:jl}),vN=S({name:k,title:v(),description:v(),target:Z,of:I.optional()}),yN=S({name:k,description:v(),match:Bx}),bN=S({name:k,description:v(),input:Z,returns:Z,state:Z.optional(),expires:jl.optional()}),xN=[`message`,`run`,`resources`,`system`,`fns`],SN=E(xN),CN=S({entry:v(),hash:v(),files:x(S({path:v(),size:y().int().min(0),hash:v()}))}),wN=E([`types`,`settings`,`attachments`,`kinds`,`fns`,`context`,`hooks`,`mentions`,`sectioners`,`actions`]),TN={types:x(qM),settings:x(XM),attachments:x(ZM),kinds:x(QM),fns:x(pN),context:x(gN),hooks:x(_N),mentions:x(vN),sectioners:x(yN),actions:x(bN)},EN=S({name:F,version:v(),description:v(),about:v().optional(),hash:v(),...TN,events:x(SN),resources:b(),client:CN.optional(),config:Z,requires:x(F),providers:x(FO).optional(),connect:xO.optional(),registries:x(Tk).optional(),contributes:x(Ek).optional(),configSecrets:iA.optional(),runtime:bc(wN,x(k)).optional(),grants:uk.optional(),configComponent:dk.optional(),pages:fA.optional(),groups:x(eM).optional(),store:rM.optional()}),DN=S({hash:v(),upsert:S(TN).partial(),remove:bc(wN,x(k)),lists:EN.pick({providers:!0,registries:!0,contributes:!0}).optional(),roots:D(!0).optional()}),ON=S({added:x(I),updated:x(I),removed:x(I),refused:x(S({name:v(),problems:x(v())}))}),kN=S({args:Z,returns:Z,description:v(),mode:nN}),AN=S({args:Z,returns:Z,deps:x(I),types:x(I).optional(),refs:x(v()).optional(),operations:HT,handlers:T(v(),$M).optional(),progress:GT.optional(),status:gT.optional(),limits:WT.optional(),display:VT.optional(),approval:qk.optional(),effects:cN.optional(),readable:lN.optional(),connectKey:yO.optional(),parallelClaims:x(BM).optional(),examples:x(tN).min(1)});function jN(e){return e===`native`||e.startsWith(`hub/`)}function MN(e){return jN(e.kind)&&(e.examples??[]).length===0}var NN=S({session:j,turn:sl,text:v(),user:IT,time:LT}),PN=y(),FN=S({label:v(),mode:nN,blocked:v().optional(),args:v().optional(),returns:v().optional(),instructions:v().optional(),examples:x(tN).optional(),moreExamples:y().int().positive().optional()}),IN={toolset:Bb.optional()},LN=w(`type`,[S({type:D(`text`),tag:v(),text:v()}),S({type:D(`suggest-context`),...IN,items:x(S({context:I,title:v().optional(),why:v().optional(),score:PN.optional()}))}),S({type:D(`suggest-fns`),...IN,items:x(S({fn:I,why:v().optional(),score:PN.optional(),card:FN.optional()}))}),S({type:D(`load`),context:x(I).optional(),fns:x(I).optional()})]),RN=S({label:v(),hint:v().optional(),icon:v().optional(),target:O}),zN=S({title:v(),subtitle:v().optional(),fields:x(S({label:v(),value:v()})).optional(),body:v().optional(),open:Vx.optional(),value:O.optional()});gN.omit({name:!0,content:!0}).extend({key:k,summary:v().min(1).max(300),imports:x(I).default([]),fns:x(I).default([]),suggestFns:x(I).default([]),suggest:Rl.default(`both`),visible:Rl.default(`both`),tags:x(v()).default([]),lastModified:C([N,$c().transform(e=>Date.parse(e)),Qc({offset:!0}).transform(e=>Date.parse(e))]).optional()}).strict();var BN=E([`header`,`duplicate-key`,`broken-link`,`cycle`,`missing-summary`]);S({file:v().min(1),line:y().int().min(1),column:y().int().min(1),code:BN,message:v().min(1)});var VN=S({loaded:x(I),fns:x(I),fnsRefused:x(PT),refused:x(S({context:v(),reason:v().min(1),closest:x(I)})),cards:v()}),HN=S({context:x(v().min(1)).min(1),guidance:v().min(1).max(4e3),maxDepth:y().int().min(0).max(10).default(mS.maxDepth),maxDecisions:y().int().min(1).max(4096).default(mS.maxDecisions),maxTokens:y().int().min(1).max(1e6).default(mS.maxTokens),metadataOnly:b().default(!1)}),UN=E([`start`,`import`,`choice`]),WN=S({name:I,title:v().optional(),description:v(),depth:y().int().min(0),via:UN,from:I.optional(),probability:y().min(0).max(1).optional(),tokens:y().int().min(0),content:v().optional()}),GN=E([`declined`,`max-tokens`,`max-decisions`,`max-depth`,`unavailable`,`failed`]),KN=S({context:v(),from:I.optional(),depth:y().int().min(0),reason:GN,probability:y().min(0).max(1).optional()}),qN=E([`complete`,`max-depth`,`max-decisions`,`max-tokens`,`failed`]),JN=VN.extend({crawled:x(WN),skipped:x(KN),stop:S({reason:qN,detail:v().optional()}),depth:y().int().min(0),decisions:y().int().min(0),tokens:y().int().min(0),calls:x(Dl),metadataOnly:b()}),YN=S({loaded:x(I),refused:x(PT),cards:v()});C([YN.strict(),VN.strict(),JN.strict()]);var XN=S({expiresIn:jl.nullable().optional()}),ZN=S({id:kl,secret:v().min(32),expiresAt:N.optional()}),QN=ZN.pick({id:!0,secret:!0}),$N=S({id:kl,system:F,instance:L,secretHash:v(),previousHash:v().optional(),createdBy:M,createdAt:N,expiresAt:N.optional(),lastUsedAt:N.optional(),uses:y().int().min(0),revokedAt:N.optional()}).omit({secretHash:!0,previousHash:!0}),eP=E([`pairing`,`needs-config`,`connected`,`disconnected`,`removed`]),tP=C([S({path:v()}),S({package:v(),version:v()}),S({git:v(),ref:v()}),S({zip:v().regex(Ox),file:v()})]),nP=S({policy:E([`always`,`on-failure`,`never`]),backoff:jl,maxPerHour:y().int().min(1)}),rP=E([`installing`,`stopped`,`starting`,`running`,`crashed`,`disabled`]),iP=S({name:F,instance:L,source:tP,dir:v(),command:S({run:v(),args:x(v()),env:T(v(),v()),cwd:v().optional()}),version:v(),goodVersion:v().optional(),autoStart:b(),restart:nP,status:rP,pid:y().int().optional(),lastExit:S({code:y().int(),at:N,output:v()}).optional(),installedBy:M,installedAt:N}),aP=S({functions:b(),renderers:b(),context:b().optional()}),oP=S({value:O,version:y().int().min(1),setBy:M,setAt:N}),sP=S({keyFingerprint:v().optional(),publicKey:v().optional(),config:oP.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional()}),cP=E([`one`,`many`]),lP=S({name:F,description:v(),about:v().optional(),status:eP,enabled:aP,version:v(),manifestHash:v(),defaultInstance:L.optional(),actor:M,stage:pk.optional(),instances:cP.optional()}).extend(sP.shape),uP=S({id:fl,name:F,keyFingerprint:v(),publicKey:v(),version:v(),address:v(),method:E([`code`,`token`]),code:v().optional(),replaces:F.optional(),description:v().optional(),instance:L.optional(),configType:Z.optional(),configSecrets:iA.optional(),store:rM.optional(),status:E([`pending`,`approved`,`rejected`,`expired`]),createdAt:N,expiresAt:N});S({id:pl,name:F.optional(),tokenHash:v(),createdBy:M,expiresAt:N,usedAt:N.optional(),autoPair:XN.optional(),boundTo:S({instance:L,manifestHash:v().min(1),host:Kl,run:A}).optional()}),S({system:F,manifest:EN,importedAt:N});var dP=UD.pick({averageCost:!0,averageQueued:!0,p95:!0,lastRunAt:!0}).extend({outcomes:ID.default(LD),averageTime:jl,tokens:UD.shape.tokens.default(0)}),fP=E([`contract`,`runtime`]),pP=S({name:I,system:F,decl:pN,version:v(),origin:fP,addedBy:M.optional(),available:MT,paused:b(),disabled:b(),stats:dP,updatedAt:N});S({name:I,system:F,decl:QM});var mP=qM.omit({name:!0,methods:!0}).extend({name:I,system:F,references:x(I),declaredBy:fP.optional(),version:v().optional(),updatedAt:N}),hP=S({types:x(mP),missing:x(I)}),gP=gN.extend({alwaysFor:x(I).optional()}),_P=S({name:I,system:F,origin:Zx.optional(),declaredBy:fP.optional(),version:v().optional(),decl:gP,tokens:$x.optional(),status:gS.default(`active`),statusReason:v().optional(),statusHistory:x(xS).optional(),disabled:b().optional(),systemOff:b().optional(),lastModified:N.optional(),duplicate:SS.optional(),contradiction:SS.optional(),notDuplicates:x(I).optional(),checked:S({contentHash:v(),at:N}).optional(),metadata:wS.optional(),split:TS.optional(),validUntil:N.optional(),askedBy:bS.optional(),mentions:S({context:x(I),fns:x(I)}),stale:b(),updatedAt:N,wantsMetadata:b().optional(),wantsCheck:b().optional(),inReview:b().optional()});function vP(e){return e.systemOff===!0||!vS(e.status)}function yP(e){return e.lastModified??e.updatedAt}var bP=[`kinds`,`commands`,`mentions`,`hooks`,`actions`,`settings`,`attachments`,`embedders`,`sectioners`,`providers`,`registries`,`components`,`examples`],xP=E(bP),SP=S({section:xP,name:v().min(1),about:v(),origin:fP,version:v(),visibility:Rl.optional(),owner:I.optional(),decl:O,on:b().optional()}),CP=S({system:F}),wP=S({parts:x(SP),more:bc(xP,y().int().min(0))});function TP(e){return Iw(e?.name??`otel`,{requires:e?.requires??[]})}var EP=v().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/),DP=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,OP=e=>e!==``&&e!==`.`&&e!==`..`&&!DP.test(e),kP=v().min(1).refine(e=>!e.includes(`\\`)&&!e.includes(`:`)&&e.split(`/`).every(OP),`A package path is relative, uses forward slashes and stays inside the package.`),AP=S({childProcess:b(),workers:b()});S({format:D(1),name:F,version:EP,description:v(),protocol:y().int().min(1),server:S({entry:kP,external:T(v(),v()).default({}),node:v().optional()}),client:S({entry:kP}).optional(),instances:cP.default(`one`),files:T(kP,v().regex(Ox)).optional(),permissions:AP.partial().optional()});var jP=S({state:v(),data:v(),cache:v()}),MP=S({host:Kl,path:v().min(1),bundleHash:v().min(1),approval:hl}),NP=S({system:F,instance:L,description:v(),status:eP,keyFingerprint:v(),publicKey:v(),version:v(),manifestHash:v(),config:oP.optional(),installed:iP.optional(),host:MP.optional(),dirs:jP.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional(),connect:vO.optional(),store:AM.optional()}),PP=S({instance:L,description:v(),online:b(),config:O,types:x(S({name:I,description:v()}))}),FP=S({pairing:fl,description:v(),instance:L,configType:Z.optional(),configSecrets:iA.optional(),store:rM.optional()});S({format:D(1),system:F,instance:L,version:v(),exportedAt:N,exportedBy:M,withSecrets:b()});var IP=S({system:F,instance:L,description:v().optional(),config:O,store:lM.optional()}),LP=S({at:N,stream:E([`stdout`,`stderr`,`hub`]),text:v()}),RP=S({meaning:b(),items:y().int().min(0),pending:y().int().min(0),embedding:b(),retrying:b(),lastError:S({at:N,message:v()}).optional()}),zP=C([vA,I]),BP=S({id:v(),provider:zP,name:v(),contextWindow:y().int().min(0).optional(),pricing:S({input:P,output:P}).optional(),capabilities:x(v()),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}),VP=BP.extend({tier:E([`flagship`,`efficient`,`legacy`,`experimental`]),maxOutputTokens:y().int().min(1).optional(),roles:x(TD)}),HP=CA.extend({spent:P}),UP=S({setting:I,system:F,decl:XM}),WP=aj.omit({request:!0,response:!0}),GP=w(`kind`,[S({kind:D(`budget`),id:gl}),S({kind:D(`priority`),id:_l}),S({kind:D(`policy`),id:ml}),S({kind:D(`category`),id:Cl}),S({kind:D(`provider`),id:wl})]),KP=S({uri:Tx,system:F,stat:jx,links:x(Mx),indexedVersion:v().optional(),sectioner:I.optional(),source:yE.optional(),raw:kx.optional(),forms:x(Lx).optional(),primary:Lx.optional(),seenAt:N});S({id:Tl,match:Bx,sectioner:I,setBy:M}),S({uri:Tx,from:v(),to:v(),added:x(Ex),changed:x(Ex),removed:x(Ex)});var qP=E([`fn`,`context`,`section`,`message`,`type`,`example`,`record`,`contextSection`,`image`,`contextContent`]);S({kind:qP,key:v(),system:F.optional(),text:v(),embedText:v().optional(),hash:v(),vectorHash:v().optional(),embedder:I,updatedAt:N,parent:v().optional(),image:v().optional()});var JP=E([`words`,`meaning`,`both`]);S({kind:qP,key:v(),rank:y().min(0).max(1),similarity:y().min(-1).max(1).optional(),matched:JP.optional(),parent:v().optional(),text:v()});var YP=E([`approval-needed`,`input-needed`,`config-needed`,`message`,`replied`,`turn-finished`,`turn-failed`,`pairing-requested`,`system-disconnected`,`spend-limit`,`system-paused`,`system-notice`,`system-message`]),XP=S({system:F,segment:v().min(1),path:x(v().min(1)).optional(),query:T(v(),v()).optional()}).strict(),ZP=C([S({session:j}),S({approval:hl}),S({pairing:fl}),S({run:A}),S({system:F}),S({page:XP})]),QP=E([`ok`,`failed`,`info`]),$P=S({label:v().min(1).max(24),link:ZP}),eF=S({id:bl,user:M,reason:YP,title:v(),body:v(),link:ZP,read:b(),pushed:b(),resolved:v().optional(),tone:QP.optional(),also:$P.optional(),key:v().min(1).max(200).optional(),createdAt:N}),tF=S({id:xl,user:M,endpoint:Ls(),keys:S({p256dh:v(),auth:v()}),device:v(),createdAt:N}),nF=ol.fnExample;tN.extend({id:nF,fn:I,system:F,source:E([`decl`,`added`,`runtime`]),key:v().min(1).max(200).optional(),order:y().int().min(0),text:v(),addedBy:M.optional(),createdAt:N});var rF=S({fn:k,upsert:x(tN.extend({key:v().min(1).max(200)})),remove:x(v().min(1).max(200))}),iF=S({fn:ub,query:v().optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(50).optional()}),aF=S({fn:I,items:x(tN.extend({id:nF,rank:y().optional()})),total:y().int().min(0),next:y().int().min(0).optional()}),oF=E([`text`,`semantic`,`hybrid`]),sF=[`session`,`user`,`everyone`],cF=E([`fn`,`context`]),lF=S({text:v().optional(),match:oF.optional(),items:x(cF).min(1).optional(),kinds:x(C([D(`native`),I])).min(1).optional(),systems:x(F).min(1).optional(),instance:L.optional(),visibility:E([`mine`,`shared`,`public`]).optional(),types:S({reads:x(db).optional(),writes:x(db).optional()}).optional(),modes:x(nN).min(1).optional(),effects:x(S({thing:rN,action:aN.optional(),kind:v().min(1).optional()})).min(1).optional(),names:x(I).min(1).max(100).optional(),filters:x(yj).max(20).optional(),off:b().optional(),statuses:AS.shape.statuses,returnNotApplicable:AS.shape.returnNotApplicable,semanticOver:AS.shape.semanticOver,scopes:x(E(sF)).min(1).optional(),available:b().optional(),niches:x(dN).min(1).optional(),order:E([`rank`,`name`]).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(100).optional()}),uF=lF.omit({items:!0,match:!0,filters:!0,off:!0,scopes:!0,statuses:!0,returnNotApplicable:!0,semanticOver:!0}).extend({kinds:lF.shape.kinds.describe("Leave `kinds` out unless the person asks for a kind of fn by name: you can't know how a fn was made, and a search by what it does finds every kind."),names:x(ub).min(1).max(100).optional().describe(`Only these fns, by name, spelled as your tools and search hits spell them: to look up fns whose names you know. Leave it out to search by what a fn does.`),types:S({reads:x(db).optional(),writes:x(db).optional()}).optional().describe("Only fns that read (`reads`) or write (`writes`) any of these types: a table's name (`tasks`), or a type's name exactly as a result gave it. Leave it out unless you know the type.")}),dF=S({text:lF.shape.text,systems:lF.shape.systems,origins:x(E(Qx)).min(1).optional(),scopes:lF.shape.scopes,tags:x(v().min(1)).min(1).max(20).optional(),names:lF.shape.names,niches:lF.shape.niches,returnNotApplicable:b().optional().describe(`Also find questions a plan ruled out (status not_applicable), each with why it was ruled out; only ones that have an answer come back. Leave it out unless you need to know what was decided against.`),semanticOver:lF.shape.semanticOver.describe("What the meaning of `text` is compared with: `question` (the default: each item is worded as the question it answers, so ask in plain words) or `content` (the item's text itself, for a phrase you expect inside it)."),order:lF.shape.order,offset:lF.shape.offset,limit:lF.shape.limit}),fF=S({key:Ex,path:x(v()),title:v()}),pF=S({item:cF,name:I,system:F,description:v(),kind:v().optional(),mode:nN.optional(),signature:v().optional(),effects:v().optional(),instance:L.optional(),rank:y().optional(),similarity:y().optional(),matched:JP.optional(),section:fF.optional(),question:v().optional(),answer:v().optional(),status:gS.optional(),statusReason:v().optional(),niche:dN.optional(),available:b(),blocked:NT.optional(),inPrompt:E([`injected`,`loaded`]).optional(),exact:D(!0).optional()}),mF=pF.pick({rank:!0,similarity:!0,matched:!0,section:!0}),hF=_P.extend({found:mF.optional(),metadataStale:b().optional()}),gF=S({item:cF,by:E([`decision`,`llm`]),dropped:x(S({name:I,note:v().optional()})),calls:x(Dl).min(1).optional(),failed:v().optional(),action:D(`load`).optional()}),_F=S({fns:x(I),context:x(I),note:v()}),vF=S({items:x(pF),next:y().int().min(0).optional(),filtered:x(gF).optional(),loaded:_F.optional(),missing:S({names:x(I).min(1),note:v()}).optional()}),yF=S({min:P,typical:P,max:P,basis:E([`free`,`history`,`payload`,`unknown`]),runs:y().int().min(0)}),bF=S({runs:y().int().min(0),typical:jl,slow:jl,longest:jl}),xF=S({fn:I,kind:v(),mode:nN,reads:x(I),writes:x(I),uses:x(I),free:b(),registry:x(oN),cost:yF,times:bF.optional(),longRunning:b(),notice:v().optional()}),SF=S({kind:v().min(1),payload:O,args:O.optional(),history:yF.optional()}),CF=S({estimate:yF.optional()}),wF=S({model:DD.optional(),messages:y().int().min(0).max(20).default(4)}),TF=S({value:wF,setBy:M.optional(),updatedAt:N.optional()}),EF=S({entries:x(w(`type`,[S({type:D(`log`),at:N,level:E([`debug`,`info`,`warn`,`error`]),message:v().max(4e3),fields:T(v(),O).optional()}),S({type:D(`traffic`),at:N,method:v().max(16),endpoint:v().max(300),status:y().int(),duration:jl})])).min(1).max(500),page:v().max(300).optional()}),DF=S({uri:Tx,written:y().int().min(0)});xF.pick({fn:!0,kind:!0,mode:!0,reads:!0,writes:!0,uses:!0,free:!0}).extend({registry:x(oN).optional(),system:F,instance:L.optional(),updatedAt:N}),S({fn:I,type:I,use:E([`read`,`write`])}),S({fn:I,type:I,kind:Nl,system:F}),S({fn:I,to:I,link:E([`dep`,`kind`,`role`]),system:F}),S({fn:I,uses:I}),S({id:v(),fn:I,number:y().int().min(1),decl:pN,savedBy:M.optional(),savedAt:N}),S({id:v(),type:I,number:y().int().min(1),decl:qM,instance:L.optional(),savedAt:N});var OF={fns:`fns`,types:`types`,context:`context`,resources:`resources`,kinds:`kinds`,components:`components`,examples:`examples`,approvals:`runs awaiting approval`,secrets:`secrets`,connections:`connections`,records:`records`},kF={create:`Creates`,update:`Updates`,remove:`Removes`};function AF(e){let t=[];for(let n of iN){let r=new Map;for(let t of e){if(t.action!==n)continue;let e=r.has(t.thing)?r.get(t.thing):new Set;e===void 0||t.kind===void 0?r.set(t.thing,void 0):(e.add(t.kind),r.set(t.thing,e))}if(r.size===0)continue;let i=[...r.entries()].map(([e,t])=>t===void 0||t.size===0?OF[e]:`${OF[e]} (${[...t].sort().join(`, `)})`);t.push(`${kF[n]} ${i.join(`, `)}.`)}return t.length===0?void 0:t.join(` `)}var jF=ol.refusal,MF=[`fns`,`context`,`types`,`roots`,...bP],NF=E(MF),PF=S({section:NF,name:v().min(1)});PF.extend({system:F,by:M,at:N});var FF=S({version:v(),hash:v().min(1),grants:uk,runtime:x(PF),by:M,at:N}),IF=S({section:C([NF,E([`grants`,`config`])]),name:v().min(1),change:E([`added`,`changed`,`removed`]),origin:fP,before:O.optional(),after:O.optional()}),LF=IF.pick({section:!0,name:!0}),RF=LF.extend({change:IF.shape.change,origin:fP,version:v(),by:M,at:N}),zF=S({version:v(),hash:v().min(1),by:fP,changes:x(IF),since:N});S({system:F,live:FF.optional(),pending:zF.optional(),checks:ok.optional(),declined:x(RF).optional(),updatedAt:N});var BF=S({mode:nN,effects:v().optional(),reads:x(I),writes:x(I),deps:x(I),cost:P.optional(),free:b().optional()}),VF=S({name:v().min(1),before:BF.optional(),after:BF.optional()}),HF=zF.extend({summary:Fk,fns:x(VF),injections:x(Ob).default([])}),UF=[`stage`,`effects`,`mode`,`types`,`capability`,`models`,`budget`,`secrets`,`calls`,`network`,`files`,`visibility`],WF=E(UF),GF=S({id:jF,system:F,instance:L,rule:WF,attempt:v().min(1),detail:v().min(1),run:A.optional(),fn:I.optional(),at:N}),KF=S({instance:Kl,rule:WF.extract([`network`,`files`]),attempt:v().min(1).max(1e3),detail:v().min(1).max(2e3)}),qF=S({system:F.optional(),rule:WF.optional(),cursor:v().optional(),limit:y().int().min(1).max(200).optional()}),JF=S({items:x(GF),next:v().optional()}),YF=S({system:F,stage:pk,manifest:EN,facts:x(xF),checks:ok.optional(),live:FF.optional(),pending:HF.optional(),declined:x(RF).default([]),off:x(PF),refusals:S({total:y().int().min(0),last:x(GF).max(10)}),previewUrls:T(v(),v()).optional(),clientApproved:b().optional()}),XF=S({system:F,hash:v().min(1),off:x(PF).default([])}),ZF=S({system:F,hash:v().min(1),approve:x(LF).default([]),decline:x(LF).default([]),off:x(PF).default([])}).refine(e=>e.approve.length+e.decline.length>0,{message:`approve or decline at least one change`,path:[`approve`]}),QF=S({hash:v(),waiting:y().int().min(0)}),$F=C([S({preview:Gk,contract:EN.optional(),ask:Zk.optional()}),S({refused:v().min(1)})]),eI=S({fn:I,args:O,instance:L.optional()}),tI=ol.mentionRequest,nI=S({request:tI,query:v(),roots:x(Tx).max(20).optional(),limit:y().int().min(1).max(50)}),rI=S({hits:x(Hx)}),iI=2e3,aI=S({kind:I,changedSince:N.optional(),cursor:v().optional(),limit:y().int().min(1).max(100).optional()}),oI=S({items:x(S({fn:I,kind:I,owner:M,title:v(),version:y().int().min(1),payload:O,removed:b(),updatedAt:N})),cursor:v().optional()}),sI=S({fn:I,args:O,key:v().min(1).max(200),priority:Ll.extract([`background`,`interactive`]).optional(),maxSpend:P.positive().optional()}),cI=S({run:A,turn:sl,status:rE}),lI=S({title:v().min(1).max(120),body:v().max(iI),tone:QP.optional(),link:ZP.optional(),also:$P.optional(),key:v().min(1).max(136).optional()}),uI=`fnloom`,dI=`hub.name`,fI=v().trim().min(1).max(40).refine(e=>!/[\r\n]/.test(e),{message:`One line only.`}),pI=S({name:fI,source:E([`setting`,`env`,`default`]),version:v()}),mI=S({name:fI.nullable()}),hI=[`off`,`text`,`model`];E(hI);var gI=w(`use`,[S({use:D(`off`)}),S({use:D(`text`)}),S({use:D(`model`),embedder:I})]),_I={use:`text`},vI=S({text:b(),images:b(),crossModal:b()}).extend({embedder:I,name:v(),dimensions:y().int().min(1)}),yI=w(`space`,[S({space:D(`none`),reason:v()}),S({space:D(`shared`),embedder:I}),S({space:D(`own`),embedder:I,crossModal:b()})]),bI=S({value:gI,setBy:M.optional(),updatedAt:N.optional(),text:I,options:x(vI),state:yI}),xI={id:M,name:v(),about:v(),createdAt:N,disabled:b()},SI=E([`admin`,`member`]),CI=S({...xI,kind:D(`user`),email:v(),role:SI,timeZone:v().optional()}),wI=w(`kind`,[CI,S({...xI,kind:D(`group`)}),S({...xI,kind:D(`agent`),fn:I}),S({...xI,kind:D(`system`),system:F}),S({...xI,kind:D(`mcp`),mcp:Ol})]),TI=CI.pick({id:!0,kind:!0,name:!0,email:!0,role:!0,timeZone:!0});S({group:M,user:M,addedBy:M,addedAt:N,provider:v().optional()}),S({user:M,kind:E([`password`,`passkey`]),secretHash:v(),createdAt:N}),S({id:El,user:M,version:y().int().min(1),refreshHash:v(),rotatedHashes:x(v()).optional(),device:v(),createdAt:N,lastSeenAt:N,actingAs:M.optional()}),S({actor:M,session:El,version:y().int().min(1)});var EI=S({setting:I,actor:M,value:O,setBy:M,run:A.optional(),updatedAt:N}),DI=C([S({actor:M}),S({group:M}),S({kind:zl}),S({everyone:D(!0)})]),OI=S({fn:v().optional(),system:F.optional(),kind:Nl.optional(),tags:x(v()).optional(),when:tT.optional(),via:I.optional()}),kI=w(`by`,[S({by:D(`turn-user`)}),S({by:D(`actor`),actor:M}),S({by:D(`group`),group:M,quorum:y().int().min(1).optional()}),S({by:D(`admins`)}),S({by:D(`judge`),fn:I}),S({by:D(`hub`)})]);S({fn:I,args:O,actor:M}),S({approve:b(),reason:v()});var AI=w(`effect`,[S({effect:D(`allow`)}),S({effect:D(`deny`),reason:v()}),S({effect:D(`ask`),approver:kI})]),jI=S({id:ml,description:v(),subject:DI,target:OI,decision:AI,priority:y().int(),expiresAt:N.optional(),createdBy:M,createdAt:N,yields:b().optional()}),MI=E([`once`,`session`,`always`]),NI=S({id:hl,run:A,fn:I,policy:ml.optional(),approver:kI,status:E([`pending`,`approved`,`denied`,`expired`]),decisions:x(S({by:M,approve:b(),remember:MI,reason:v().optional(),at:N})),createdAt:N,preview:Gk.optional(),proposed:b().optional(),ask:Zk.optional(),variant:HA.optional()}),PI=v().regex(/^[a-z0-9][a-z0-9-]{0,31}$/,`lower case letters, digits and dashes, starting with a letter or digit`),FI=S({role:v().min(1).default(`groups`).describe(`The claim whose values pick the role (default "groups").`),admin:x(v().min(1)).default([]).describe(`Values of the role claim that make an admin.`),member:x(v().min(1)).optional().describe(`When given, values of the role claim one of which (or an admin value) is needed to sign in.`),groups:v().min(1).optional().describe(`The claim whose values are hub group names to sync the person into.`)}),II=S({id:PI,label:v().min(1).max(60),issuer:Ls(),clientId:v().min(1),clientSecret:v().min(1).optional(),scope:v().min(1).default(`openid email profile`),userinfo:b().default(!0),claims:FI.prefault({})});x(II).refine(e=>new Set(e.map(e=>e.id)).size===e.length,`each provider needs its own id`);var LI=v().trim().toLowerCase().regex(/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,`a domain such as example.com`),RI=w(`mode`,[S({mode:D(`invite`)}),S({mode:D(`domains`),domains:x(LI).min(1).max(50)}),S({mode:D(`anyone`)})]),zI=`signInPolicy`,BI=S({limit:y().int().min(1).max(1e5),window:y().int().min(1e3).max(864e5)}),VI=S({account:BI,address:BI}),HI=`signInLimits`,UI=S({proxies:y().int().min(0).max(5)}),WI=`proxyTrust`;S({issuer:v(),sub:v(),provider:PI,user:M,email:v().optional(),linkedAt:N,lastSignInAt:N});var GI=II.pick({id:!0,label:!0}),KI=S({providers:x(II.omit({clientSecret:!0}).extend({confidential:b()})),policy:RI,breakGlass:TI.optional(),callbackUrl:v(),limits:VI,proxy:UI}),qI=S({ok:b(),detail:v()}),JI=S({provider:PI,ok:b(),discovery:qI,keys:qI,checkedAt:N}),YI=E([`linked`,`email`,`new`,`none`]),XI=S({allowed:b(),reason:v(),link:YI,user:TI.optional(),role:SI.optional(),groups:x(v()),unknownGroups:x(v())}),ZI=S({id:v(),provider:PI,at:N,problem:v().optional(),subject:v().optional(),email:v().optional(),emailVerified:b(),claims:T(v(),O),outcome:XI.optional()}),QI=S({provider:PI,label:v(),email:v().optional(),lastSignInAt:N}),$I=TI.extend({disabled:b(),createdAt:N,breakGlass:b(),password:b(),identities:x(QI),groups:x(S({id:M,name:v(),synced:b()}))}),eL=S({id:M,name:v(),about:v(),createdAt:N,members:y().int().min(0)}),tL=S({user:M,name:v().trim().min(1).max(120).optional(),role:SI.optional(),disabled:b().optional()}),nL=S({group:M,user:M,member:b()});function rL(e){return`/auth/sso/${encodeURIComponent(e)}/start`}var iL=`harness_sso_handoff`,aL=E([`score`,`decision`,`graph`]),oL=E([`below-threshold`,`top-n`,`declined`,`budget`,`rule`,`failed`]),sL={"below-threshold":`Score under the threshold`,"top-n":`Others scored higher`,declined:`The decision model declined it`,budget:`No room in the token budget`,rule:`Hidden by a rule`,failed:`Decision model failed; the score decided`},cL=[`suggest`,`load`],lL=E(cL);function uL(e){return e.by===`none`?`suggest`:e.action??`suggest`}var dL=E([`loaded`,`budget`,`blocked`]),fL={loaded:`Loaded for the turn`,budget:`No room to load it, so suggested`,blocked:`Can't be loaded now, so suggested`},pL=w(`used`,[S({used:D(!0),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),note:v().optional(),load:dL.optional()}),S({used:D(!1),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),reason:oL,note:v().optional()})]),mL=S({by:aL,threshold:y().optional(),calls:x(Dl).min(1).optional(),action:D(`load`).optional(),items:x(pL)}),hL=S({messages:y().int().min(1).max(20).default(3),candidates:y().int().min(1).max(50).default(20),cap:y().int().min(0).max(20).default(6),floor:y().min(0).max(1).default(.2)}),gL=[`decision`,`llm`,`none`];E(gL);var _L=w(`by`,[S({by:D(`none`)}),hL.extend({by:D(`decision`),model:DD.optional(),action:lL.optional()}),hL.extend({by:D(`llm`),model:DD,action:lL.optional()})]),vL={by:`none`},yL=hL.extend({enabled:b(),model:DD.optional()});function bL(e){let{enabled:t,model:n,...r}=e;return t&&n!==void 0?{by:`llm`,model:n,...r}:vL}var xL=C([_L,yL.transform(bL)]),SL=S({value:_L,setBy:M.optional(),updatedAt:N.optional()}),CL=[`none`,`decision`,`llm`];E(CL);var wL=w(`by`,[S({by:D(`none`)}),S({by:D(`decision`),model:DD.optional(),action:lL.optional()}),S({by:D(`llm`),model:DD,action:lL.optional()})]),TL={by:`none`},EL={fn:`fnsSearchDecision`,context:`contextSearchDecision`},DL=S({value:wL,setBy:M.optional(),updatedAt:N.optional()}),OL=S({fn:DL,context:DL}),kL=S({item:cF,value:wL});w(`key`,[S({key:D(`suggestDecision`),value:xL,setBy:M,updatedAt:N}),S({key:D(`autoClassifier`),value:wF,setBy:M,updatedAt:N}),S({key:D(EL.fn),value:wL,setBy:M,updatedAt:N}),S({key:D(EL.context),value:wL,setBy:M,updatedAt:N}),S({key:D(dI),value:fI,setBy:M,updatedAt:N}),S({key:D(`imageEmbedding`),value:gI,setBy:M,updatedAt:N}),S({key:D(zI),value:RI,setBy:M,updatedAt:N}),S({key:D(gb),value:_b,setBy:M,updatedAt:N}),S({key:D(HI),value:VI,setBy:M,updatedAt:N}),S({key:D(WI),value:UI,setBy:M,updatedAt:N}),S({key:D(yb),value:b(),setBy:M,updatedAt:N}),S({key:D(ES),value:DS,setBy:M,updatedAt:N})]);var AL=E([`all`,`replies`,`none`]),jL=S({actor:M,role:E([`owner`,`member`,`agent`]),notify:AL,joinedAt:N}),ML=E([`idle`,`running`,`paused`]),NL=S({hash:v(),injected:x(I),at:sl}),PL=S({id:j,title:v(),owner:M,...zA.shape,selection:ux.optional(),participants:x(jL),forkOf:j.optional(),fork:HA.optional(),tools:x(I),context:x(I),suggested:x(I).optional(),announcedSystems:DA.optional(),citationsTold:LA.optional(),fixed:NL.optional(),status:ML,transcript:x(BE),createdAt:N,updatedAt:N,archived:b()}),FL=PL.pick({id:!0,title:!0,owner:!0,agent:!0,status:!0,createdAt:!0,updatedAt:!0,archived:!0}),IL=E([`local-time`,`suggested-context`,`suggested-fns`]),LL=S({type:D(`text`),text:v()}),RL=S({type:D(`mention`),provider:I,label:v(),target:O,text:v()}),zL=S({type:D(`command`),context:I,args:T(v(),v())}),BL=S({type:D(`file`),ref:kx,name:v(),uri:Tx.optional(),text:v().optional(),truncated:b().optional()}),VL=S({type:D(`input-answer`),run:A,title:v(),value:O,text:v()}),HL=`input-answer`,UL=S({type:D(`loaded-for-you`),by:E([`decision`,`llm`,`recall`]),toolset:Bb.optional(),fns:x(S({fn:I,label:v(),why:v().optional(),broughtBy:I.optional()})),context:x(S({context:I,title:v().optional(),why:v().optional(),text:v(),fns:x(I).optional()}))}),WL=w(`type`,[LL,S({type:D(`reasoning`),text:v()}),RL,zL,S({type:D(`invocation`),run:A,fn:I}),S({type:D(`call`),run:A,fn:I}),BL,VL,S({type:D(`extra`),extra:IL,blocks:x(LN)}),S({type:D(`hook`),hook:I,blocks:x(LN)}),S({type:D(`attachment`),attachment:I,data:O,title:v()}),S({type:D(`link`),link:Vx}),S({type:D(`systems-changed`),on:x(OA),off:x(OA)}),S({type:D(`kept-effects`),variants:x(KA)}),UL]),GL=new Set([`extra`,`hook`,`input-answer`,`systems-changed`,`loaded-for-you`]);function KL(e){return GL.has(e.type)}var qL=w(`type`,[LL,RL.omit({text:!0}),zL,BL,VL]),JL=S({id:cl,session:j,turn:sl,author:M,role:E([`user`,`assistant`,`note`]),parts:x(WL),runs:x(A),status:E([`streaming`,`done`,`failed`]),replyTo:cl.optional(),replyAll:b(),answerers:x(M),suggestions:mL.optional(),compared:D(!0).optional(),cacheMiss:S({call:Dl,at:N}).optional(),citations:x(IA).optional(),createdAt:N}),YL=E([`pause`,`resume`,`cancel`]),XL=S({run:A,fn:I,status:rE,pause:b(),resume:b(),cancel:b()}),ZL=S({pause:b(),cancel:b(),uncancellable:x(A),undoLastTurn:b(),continueLastTurn:b().optional(),runs:x(XL).optional()}),QL=S({session:j,user:M,focused:b(),typing:b(),lastActiveAt:N}),$L=S({voiceInput:b(),voiceOutput:b(),dictation:S({engine:E(kD),language:v().optional()}).optional(),uploads:b(),meaning:b(),mentions:x(S({provider:I,title:v(),of:I.optional()})),commands:x(S({name:v(),context:I,args:x(mN),description:v(),unavailable:v().optional()})),agents:x(S({fn:I,description:v()})),display:T(v(),VT),invocations:x(S({fn:I,description:v(),args:Z})),methods:x(S({type:I,method:v(),fn:I,description:v(),args:Z})),clients:x(S({system:F,url:v(),hash:v()})),systems:x(S({name:F,status:eP,enabled:b()})),models:x(BP)}),eR=JL.pick({id:!0,session:!0,author:!0,role:!0,replyTo:!0,replyAll:!0,createdAt:!0}).extend({text:v()}),tR=eP.extract([`connected`,`disconnected`,`removed`]),nR=w(`type`,[S({type:D(`message`),message:eR}),S({type:D(`run`),run:A,fn:I,update:uE,notified:b().optional()}),S({type:D(`resources`),changes:x(zx)}),S({type:D(`system`),system:F,status:tR}),S({type:D(`fns`),added:x(I),removed:x(I),changed:x(I).default([])})]),rR=S({protocol:D(1),name:F,version:v(),instance:L.default(Gl),instances:cP.optional(),boot:v(),publicKey:v(),manifestHash:v(),contractHash:v().optional(),pairingToken:v().optional(),autoPair:QN.optional()}),iR=w(`kind`,[S({kind:D(`challenge`),nonce:v()}),S({kind:D(`pairing`),pairing:fl,code:v().optional(),url:v(),expiresAt:N})]),aR=S({signature:v()}),oR=S({maxFrame:y().int().min(1024),maxChunk:y().int().min(1024),heartbeat:jl}),sR=S({value:O,version:y().int().min(1)}),cR=S({instance:L,config:sR.optional(),start:S({first:b(),upgradedFrom:v().optional()}),token:v(),sendManifest:b(),limits:oR,autoPair:ZN.optional(),store:uM.optional()});S({system:F,instance:L,boot:v()});var lR=Iw(`linkSession`,{provides:Aw()}),uR=TP({name:`linkTel`}),dR=S({state:O,calls:T(v(),fE),reason:E([`resumed`,`restart`])}),fR=S({run:zT,fn:v(),kind:Nl,payload:O.optional(),args:O,budget:hE,handlers:x(v()),resume:dR.optional(),deadline:N,configVersion:y().int().min(0),connection:EO.optional(),approved:$k.optional()}),pR=C([S({run:A}),S({delivery:ll})]),mR=S({session:j,actor:M,user:IT,time:LT}),hR=S({level:E([`debug`,`info`,`warn`,`error`]),key:v(),fields:el}),gR=S({run:A,action:E([`cancel`,`pause`])}),_R=S({accepted:b(),reason:v().optional()}),vR=E([`restart`,`upgrade`,`shutdown`,`removed`]),yR=S({title:v().min(1).max(120),body:v().max(2e3)}),bR=X(uR,lR).group({manifest:{body:EN,response:ON,ws:`mf`},patch:{body:DN,response:ON,ws:`mp`},call:{body:S({parent:A,fn:I,args:O,key:v(),budget:S({cost:P.optional(),time:jl.optional()}).optional(),handlers:x(v()),background:b(),on:L.optional()}),response:fE,ws:`call`},handle:{body:S({run:A,handler:v(),args:O}),response:mE,ws:`ha`},control:{body:gR,response:_R,ws:`cl`},progress:{body:S({run:A,progress:JT}),ws:`pg`},allow:{body:S({run:A,operations:UT.partial()}),ws:`al`},undoWith:{body:S({run:A,undo:O}),ws:`uw`},updateResult:{body:S({run:A,result:O}),response:S({revision:y().int().min(1)}),ws:`ur`},attach:{body:S({run:A,item:C([S({attachment:I,data:O,title:v()}),S({link:Vx})])}),ws:`at`},types:{body:S({names:x(I).min(1),run:A.optional()}),response:hP,ws:`ty`},fnShape:{body:S({name:I}),response:S({fn:kN.optional()}),ws:`fsh`},resourcesChanged:{body:S({changes:x(zx)}),ws:`rc`},llm:{body:XE,streamOut:ZE,ws:`llm`},model:{body:CD,response:wD,ws:`mdl`},resource:{body:S({uri:Tx,want:x(Nx),run:A.optional(),sections:x(Ex).min(1).optional()}),response:Fx,ws:`rs`},resourceSections:{body:S({uri:Tx,run:A.optional()}),response:x(Rx),ws:`rsc`},content:{body:S({ref:kx,offset:y().int().min(0),length:y().int().min(1),run:A.optional()}),response:S({chunk:v()}),ws:`ct`},upload:{body:S({upload:v(),chunk:v(),last:b(),mime:v()}),response:S({ref:kx.optional()}),ws:`up`},setting:{body:S({run:A,setting:I}),response:S({value:O.optional()}),ws:`st`},stateGet:{body:S({owner:pR}),response:S({values:el,version:y().int()}),ws:`sg`},stateSet:{body:S({owner:pR,patch:el,clear:x(v()),version:y().int().optional()}),response:C([S({version:y().int()}),S({conflict:D(!0)})]),ws:`ss`},log:{body:hR,ws:`lg`},connectionUpdate:{body:AO,ws:`cu`},instanceConnect:{body:vO,ws:`ic`},shareFn:{body:$D,ws:`sh`},usableFns:{body:eO,response:S({fns:x(k)}),ws:`uf`},propose:{body:Qk,response:nA,ws:`po`},decide:{body:$E,response:eD,ws:`de`},fleet:{body:S({}),response:x(PP),ws:`fl`},searchFns:{body:lF.extend({run:A.optional()}),response:vF,ws:`sf`},fnExamples:{body:iF,response:aF,ws:`fx`},examples:{body:rF,response:S({added:y().int().min(0),removed:y().int().min(0)}),ws:`xp`},models:{body:S({}),response:x(VP),ws:`mo`},grantPairing:{body:eA,response:tA,ws:`gp`},notifyAdmins:{body:yR,ws:`na`},notify:{body:S({run:A,notice:lI}),ws:`nf`},kindFns:{body:aI,response:oI,ws:`kf`},startRun:{body:sI,response:cI,ws:`sru`},notifyOwner:{body:S({fn:I,notice:lI}),ws:`nfo`},reportRefusal:{body:KF,ws:`rx`},mentionResources:{body:nI,response:rI,ws:`mr`},records:{body:Vj,response:Hj,ws:`rq`},record:{body:Wj,response:S({record:zj.optional()}),ws:`rg`},recordTable:{body:Uj,response:jk,ws:`rtb`},saveRecord:{body:Gj,response:zj,ws:`rsv`},removeRecord:{body:qj,response:S({removed:b()}),ws:`rrm`},storeOpen:{body:S({}),response:S({bytes:y().int().min(0)}),ws:`sto`},storeRun:{body:FM,response:IM,ws:`stq`},storeBegin:{body:S({}),response:LM,ws:`stb`},storeCommit:{body:S({lease:MM}),ws:`stc`},storeRollback:{body:S({lease:MM}),ws:`str`},storeSnapshot:{body:S({}),response:S({snapshot:RM}),ws:`stn`},storeRestore:{body:S({snapshot:RM}),ws:`stx`},storeStatus:{body:yM,ws:`sts`},storeExport:{body:S({move:wM}),response:S({bytes:y().int().min(0),hash:v().regex(/^[0-9a-f]{64}$/)}),ws:`ste`},storeDownload:{body:S({move:wM,offset:y().int().min(0),length:y().int().min(1).max(4e6)}),response:S({chunk:v()}),ws:`std`},storeUpload:{body:S({move:wM,offset:y().int().min(0),chunk:v().max(6e6)}),ws:`stu`},storeUploadDone:{body:S({move:wM,bytes:y().int().min(0),hash:v().regex(/^[0-9a-f]{64}$/)}),ws:`stud`},storeMoveProgress:{body:S({move:wM,progress:OM}),ws:`stmp`}});Y({endpoints:{...X(uR).group({hello:{body:rR,response:iR,ws:`hi`},prove:{body:aR,response:cR,ws:`pr`},pairingInfo:{body:FP,ws:`pi`}}),...bR}}),Y({endpoints:{paired:Tw({body:S({pairing:fl}),ws:`pd`}),run:Tw({body:fR,response:dE,ws:`run`}),control:Tw({body:gR,response:_R,ws:`ctl`}),undo:Tw({body:S({run:zT,fn:v(),kind:Nl,fnPayload:O.optional(),payload:O}),response:pE,ws:`un`}),handler:Tw({body:S({call:ul,run:A,key:v(),handler:v(),args:O}),response:mE,ws:`hd`}),child:Tw({body:S({parent:A,key:v(),run:A,update:uE.optional()}),ws:`ch`}),check:Tw({body:S({kind:v(),payload:O}),response:S({problems:x(v()),description:AN.optional()}),ws:`ck`}),context:Tw({body:mR.partial({session:!0}).extend({name:v(),args:T(v(),v())}),response:S({text:v()}),ws:`cx`}),roots:Tw({response:x(Ax),ws:`ro`}),list:Tw({body:S({uri:Tx,cursor:v().optional()}),response:Bl(jx),ws:`ls`}),stat:Tw({body:S({uri:Tx}),response:S({stat:jx.optional()}),ws:`sa`}),read:Tw({body:S({uri:Tx,want:x(Nx)}),response:Fx,ws:`rd`}),sections:Tw({body:S({sectioner:v(),uri:Tx,version:v()}),response:x(Rx),ws:`sc`}),watch:Tw({body:S({uris:x(Tx),on:b()}),ws:`wa`}),content:Tw({body:S({ref:kx,offset:y().int().min(0),length:y().int().min(1)}),response:S({chunk:v()}),ws:`ct`}),hook:Tw({body:S({hook:v(),message:NN}),response:x(LN),ws:`hk`}),mentions:Tw({body:mR.extend({provider:v(),query:v(),request:tI}),response:x(RN),ws:`mn`}),mentionHover:Tw({body:mR.extend({provider:v(),target:O}),response:S({hover:zN.optional()}),ws:`mh`}),mentionText:Tw({body:mR.extend({provider:v(),target:O}),response:S({text:v()}),ws:`mt`}),event:Tw({body:nR,ws:`ev`}),action:Tw({body:mR.extend({delivery:ll,action:v(),input:O,run:A.optional()}),response:S({result:O}),ws:`ac`}),form:Tw({body:S({delivery:ll,run:A,value:O}),ws:`fm`}),restart:Tw({body:S({reason:v()}),ws:`rt`}),stop:Tw({body:S({reason:vR,timeout:jl}),ws:`sp`}),configure:Tw({body:sR.extend({previous:O.optional()}),ws:`cf`}),export:Tw({body:S({timeout:jl}),response:S({data:v()}),ws:`ex`}),validate:Tw({body:ZO,response:QO,ws:`vl`}),preview:Tw({body:Jk,response:$F,ws:`pv`}),estimate:Tw({body:SF,response:CF,ws:`es`}),providerChat:Tw({body:IO,streamOut:LO,ws:`pc`}),providerEmbed:Tw({body:GO,response:KO,ws:`pe`}),providerDecide:Tw({body:VO,response:HO,ws:`pdc`}),providerModels:Tw({body:zO,response:BO,ws:`pml`}),connectStart:Tw({body:DO,response:S({url:mb}),ws:`cs`}),connectFinish:Tw({body:OO,response:kO,ws:`cn`}),disconnect:Tw({body:EO.pick({id:!0,owner:!0,credentials:!0}),ws:`dc`}),flags:Tw({body:Jk,response:Vk,ws:`fg`}),claims:Tw({body:VM,response:HM,ws:`pcl`}),checkArgs:Tw({body:Yk,response:Xk,ws:`cka`}),storeProbe:Tw({body:S({to:uM}),response:S({problems:x(v())}),ws:`spb`}),storeMove:Tw({body:S({move:wM,from:uM,to:uM}),response:S({tables:y().int().min(0),rows:y().int().min(0),bytes:y().int().min(0)}),ws:`smv`}),storeMoveEnd:Tw({body:S({move:wM,outcome:E([`switched`,`aborted`]),from:uM,to:uM}),response:S({backups:x(S({id:SM,bytes:y().int().min(0)}))}),ws:`sme`}),storeDiscard:Tw({body:w(`what`,[S({what:D(`store`)}),S({what:D(`backup`),backup:SM})]),ws:`sdc`})}});var xR=S({session:j,parts:x(qL).min(1),variants:VA,client:BT}),SR=UA.extend({status:tj,spent:P,tokens:y().int().min(0),startedAt:N,endedAt:N.optional(),time:jl,messages:x(JL),approvals:x(NI)}),CR=qA.omit({variants:!0}).extend({turn:sl,session:j,message:cl,status:tj,variants:x(SR)}),wR=S({turn:sl,variant:RA,adopt:b().optional()}),TR=v().regex(Ml).max(64).brand(),ER=S({uri:v(),system:F.optional(),instance:L.optional()}),DR=S({systems:x(F).optional(),fns:x(OI).optional(),types:x(ql).optional(),context:x(ql).optional(),resources:x(ER).optional()}),OR=S({include:DR,exclude:DR}),kR=E([`each`,`static`]),AR=S({id:Ol,slug:TR,name:v().min(1),instructions:v(),rules:OR,toolMode:kR,user:M,actor:M,secretDigest:v(),grantees:x(F),origins:x(v()),enabled:b(),createdBy:M,createdAt:N,updatedAt:N}),jR=AR.pick({slug:!0,name:!0,instructions:!0,rules:!0,toolMode:!0,user:!0,grantees:!0,origins:!0,enabled:!0});S({mcp:Ol,label:v().min(1),exp:y().int()});var MR=S({mcp:Ol,label:v().min(1),ttl:y().int().min(1e3).optional()}),NR=S({fns:x(I),types:x(I),closure:x(I),context:x(I),resources:x(ER),reach:x(I),warnings:x(v())}),PR=S({mcp:Ol,session:v(),label:v(),client:S({name:v(),version:v()}).optional(),since:N,lastCallAt:N.optional(),calls:y().int().min(0)}),FR=AR.omit({secretDigest:!0}).extend({url:v(),sessions:y().int().min(0),callsToday:y().int().min(0)}),IR=E([`added`,`changed`,`removed`]),LR=S({id:v().min(1),system:F,section:NF,name:v().min(1),number:y().int().min(1),change:IR,decl:O,hash:v().min(1),declaredBy:fP.optional(),instance:L.optional(),savedBy:M.optional(),savedAt:N}),RR=Vl.extend({system:F,section:NF,name:v().min(1)}),zR=Bl(LR);Rx.extend({uri:Tx,version:v(),hash:v()});var BR=(...e)=>e.join(`\0`),VR=`bearerAuth`,HR={security:{[VR]:{type:`http`,scheme:`bearer`,bearerFormat:`JWT`}}};function UR(e){let t=e?.name??VR,n=e?.doc??HR;return Iw(t,{provides:Aw(),requires:e?.requires??[],doc:n})}var WR=v().regex(/^[a-z]+:.+$/),GR=S({fnKind:Nl.optional(),mode:nN.optional(),effects:x(oN).optional(),reads:x(I).optional(),writes:x(I).optional(),visibility:Rl.optional(),on:b(),stage:pk.optional(),pending:b().optional(),examples:y().int().min(0).optional()}),KR=S({id:WR,kind:lj,name:v().min(1),about:v(),system:F.optional(),external:b(),collapsed:y().int().min(0).optional(),facts:GR}),qR=S({from:WR,to:WR,kind:dj,label:v().min(1),weight:y().min(0).max(1).optional()}),JR=S({node:WR,kind:lj,count:y().int().min(1)}),YR=xj.pick({text:!0,filters:!0}).extend({systems:x(F).min(1).optional(),external:b().optional(),focus:S({node:WR,hops:y().int().min(1).max(4).optional()}).optional(),collapse:x(F).min(1).optional(),limit:y().int().min(1).max(1e3).optional()}),XR=S({nodes:x(KR),edges:x(qR),more:x(JR),total:S({nodes:y().int().min(0),edges:y().int().min(0)})}),ZR=`hub/visuals`,QR=S({columns:x(S({name:v().min(1),kind:hk,role:gk,numeric:b(),temporal:b(),day:b(),categorical:b(),key:b(),opaque:b(),distinct:y().int().min(0),nulls:y().min(0).max(1),nonNegative:b(),min:C([y(),v()]).optional(),max:C([y(),v()]).optional(),bound:S({min:y(),max:y()}).optional(),members:x(v()).optional()})),rows:y().int().min(0),whole:b()}),$R=new Set([`integer`,`number`]),ez=new Set([`date`,`datetime`]),tz=new Set([`text`,`boolean`]),nz=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rz(e){return $R.has(e)?`measure`:ez.has(e)||tz.has(e)?`group`:`attribute`}function iz(e,t,n){return e===void 0||typeof e==typeof t&&(n===`min`?t<e:t>e)?t:e}function az(e,t){return{columns:e.columns.map((n,r)=>{let i=new Set,a=0,o=0,s=0,c=!0,l,u;for(let t of e.rows){let e=t[r];e==null?a+=1:(s+=1,i.add(typeof e==`object`?JSON.stringify(e):String(e)),typeof e==`string`&&nz.test(e)&&(o+=1),(typeof e==`number`||typeof e==`string`)&&(l=iz(l,e,`min`),u=iz(u,e,`max`)),(typeof e!=`number`||e<0)&&(c=!1))}let d=n.kind,f=n.key===!0,p=d===`uuid`||s>0&&o===s||n.ref!==void 0||d===`binary`;return{name:n.name,kind:d,role:n.role??rz(d),numeric:$R.has(d),temporal:ez.has(d),day:d===`date`,categorical:tz.has(d),key:f,opaque:p,distinct:i.size,nulls:e.rows.length===0?0:a/e.rows.length,nonNegative:c&&s>0,...l===void 0?{}:{min:l},...u===void 0?{}:{max:u},...t?.(n)??{}}}),rows:e.rows.length,whole:e.offset===0&&!e.truncated}}var oz=T(k,x(v().min(1)).min(1));S({visual:k,coverage:y().int().min(0),priority:y(),bind:oz,styles:x(k).min(1),because:x(v())});var sz={floor:0,structural:10,encoded:20,"time-encoded":30},cz={"temporal-key":15,"low-cardinality":10,"enum-key":8,"high-null":-10,"many-categories":-10},lz=.5;function uz(e){return e.columns.filter(e=>!e.opaque)}function dz(e,t){return e.accepts.includes(t.kind)&&(e.role===void 0||e.role===t.role)}function fz(e,t,n){return!e.required&&e.role===`group`&&n>1&&t.distinct>=n}function pz(e,t,n){let r={},i=new Set;for(let a of e.channels){let e=t.filter(e=>!i.has(e.name)&&dz(a,e)&&!fz(a,e,n)).map(e=>e.name),o=a.many?e:e.slice(0,1);if(o.length<(a.many?a.min??1:1)){if(a.required)return`No column fits ${a.label} (${a.accepts.join(`, `)}).`;continue}let[s,...c]=o;if(s!==void 0){r[a.name]=[s,...c];for(let e of o)i.add(e)}}return r}function mz(e,t,n){return(e[t]??[]).flatMap(e=>n.columns.filter(t=>t.name===e))}function hz(e,t,n,r,i){switch(e.rule){case`distinct`:return mz(t,e.channel,n).some(t=>t.distinct>e.max)?`${e.channel} has more than ${String(e.max)} values.`:void 0;case`non-negative`:return mz(t,e.channel,n).every(e=>e.nonNegative)?void 0:`${e.channel} has values below 0.`;case`bounded`:return mz(t,e.channel,n).every(e=>e.bound!==void 0)||t.max!==void 0?void 0:`${e.channel} has no known range.`;case`distinct-columns`:{let n=e.channels.flatMap(e=>t[e]??[]);return new Set(n).size===n.length?void 0:`${e.channels.join(` and `)} need different columns.`}case`links`:{if(r===void 0||i===void 0)return;let n=e=>i.findIndex(n=>n.name===t[e]?.[0]),a=n(e.from),o=n(e.to);if(a<0||o<0)return`${e.to} must name values of ${e.from}.`;let s=new Set(r.map(e=>JSON.stringify(e[a]??null)));return r.every(e=>e[o]===null||s.has(JSON.stringify(e[o]??null)))?void 0:`${e.to} names values that are not ${e.from} values.`}}}function gz(e,t,n){let r=Object.values(t).flat().flatMap(e=>n.columns.filter(t=>t.name===e)),i=r.filter(e=>e.role===`group`),a={"temporal-key":i.some(e=>e.temporal),"low-cardinality":i.length>0&&i.every(e=>e.distinct<=8),"enum-key":i.some(e=>e.members!==void 0),"high-null":r.some(e=>e.nulls>lz),"many-categories":i.some(e=>e.distinct>5)},o=e.priority.terms.filter(e=>a[e]);return{priority:sz[e.priority.band]+o.reduce((e,t)=>e+cz[t],0),because:o.map(e=>`${e} (${String(cz[e])})`)}}function _z(e,t,n){return e.styles.filter(e=>(e.whole!==!0||n)&&(e.needs??[]).every(e=>t[e]!==void 0)).map(e=>e.name)}function vz(e,t,n,r){let i=[];for(let r of e.channels){let e=t[r.name]??[];if(e.length===0)r.required&&i.push(`${r.label} is not bound.`);else{!r.many&&e.length>1&&i.push(`${r.label} takes one column.`),r.many&&e.length<(r.min??1)&&i.push(`${r.label} needs at least ${String(r.min??1)} columns.`);for(let t of e){let e=n.columns.find(e=>e.name===t);e===void 0?i.push(`${r.label}: there is no column ${t}.`):(e.opaque&&i.push(`${r.label}: ${t} holds nothing a person reads.`),r.accepts.includes(e.kind)||i.push(`${r.label}: ${t} is ${e.kind}, not ${r.accepts.join(` or `)}.`))}}}n.rows<e.rows.min&&i.push(`Needs at least ${String(e.rows.min)} rows.`),e.rows.max!==void 0&&n.rows>e.rows.max&&e.size===void 0&&i.push(`Draws at most ${String(e.rows.max)} rows.`),e.whole&&!n.whole&&i.push(`Only draws a whole result, and this is one page of it.`);for(let a of e.rules){let e=hz(a,t,n,r?.rows,r?.columns);e!==void 0&&i.push(e)}return i}function yz(e,t,n){let r=uz(t);return e.flatMap((e,i)=>{let a=pz(e.shape,r.length>0?r:t.columns,t.rows);if(typeof a==`string`||vz(e.shape,a,t,n).length>0)return[];let[o,...s]=_z(e.shape,a,t.whole);if(o===void 0)return[];let{priority:c,because:l}=gz(e.shape,a,t),u=new Set(Object.values(a).flat().filter(e=>r.some(t=>t.name===e))).size;return[{rank:{visual:e.name,coverage:u,priority:c,bind:a,styles:[o,...s],because:[`covers ${String(u)}`,...l]},index:i}]}).sort((e,t)=>t.rank.coverage-e.rank.coverage||t.rank.priority-e.rank.priority||e.index-t.index).map(e=>e.rank)}var bz=[`integer`,`number`],xz=[`date`,`datetime`],Sz=[`text`,`boolean`],Cz=[`text`,`boolean`,`date`,`datetime`];function wz(e,t,n,r={}){return{name:e,label:t,accepts:[...n],required:r.required??!0,many:r.many??!1,...r.min===void 0?{}:{min:r.min},...r.role===void 0?{}:{role:r.role}}}var Tz=[`table`,`value`,`part`,`category`,`time`,`distribution`,`crosstab`,`calendar`,`timeline`,`network`,`hierarchy`,`gauge`,`finance`];E(Tz);var Ez={table:{label:`Table`,icon:`table`,description:`Every readable column and row, sortable and paged; cards on a phone.`,shape:wk.parse({channels:[wz(`columns`,`Columns`,mk,{required:!1,many:!0})],rows:{min:0},whole:!1,size:`window`,pageSize:10,styles:[{name:`table`,label:`Table`},{name:`compact`,label:`Compact`},{name:`cards`,label:`Cards`}],priority:{band:`floor`,terms:[]}})},value:{label:`Value`,icon:`hash`,description:`One to four rows of numbers as cards, each titled by a text column or named by its column.`,shape:wk.parse({channels:[wz(`value`,`Values`,bz,{many:!0,role:`measure`}),wz(`title`,`Title`,[`text`],{required:!1})],rows:{min:1,max:4},whole:!0,styles:[{name:`cards`,label:`Cards`},{name:`single`,label:`Single`}],priority:{band:`encoded`,terms:[]}})},part:{label:`Part of a whole`,icon:`chart`,description:`Slices of a whole: one per category, sized by a measure.`,shape:wk.parse({channels:[wz(`itemName`,`Slice`,Cz,{role:`group`}),wz(`value`,`Size`,bz,{role:`measure`})],rows:{min:1,max:100},whole:!0,size:`partition`,rules:[{rule:`non-negative`,channel:`value`}],styles:[{name:`pie`,label:`Pie`},{name:`doughnut`,label:`Doughnut`},{name:`rose`,label:`Rose`},{name:`half`,label:`Half doughnut`},{name:`funnel`,label:`Funnel`}],priority:{band:`encoded`,terms:[`low-cardinality`,`enum-key`,`many-categories`]}})},category:{label:`Bars`,icon:`chart`,description:`Measures per category, with an optional second key as series.`,shape:wk.parse({channels:[wz(`x`,`Category`,Cz,{role:`group`}),wz(`y`,`Values`,bz,{many:!0,role:`measure`}),wz(`series`,`Series`,Sz,{required:!1,role:`group`})],rows:{min:1,max:50},whole:!1,size:`top-n`,styles:[{name:`bar`,label:`Bars`},{name:`stacked`,label:`Stacked`},{name:`percent`,label:`100%`,whole:!0},{name:`horizontal`,label:`Horizontal`},{name:`line`,label:`Line`},{name:`area`,label:`Area`},{name:`radar`,label:`Radar`},{name:`polar`,label:`Polar bars`},{name:`pictorial`,label:`Pictorial`}],priority:{band:`encoded`,terms:[`low-cardinality`,`enum-key`,`high-null`]}})},time:{label:`Over time`,icon:`chart`,description:`Measures along a date axis, zoomable; zooming can set the from/to args.`,shape:wk.parse({channels:[wz(`x`,`Date`,xz,{role:`group`}),wz(`y`,`Values`,bz,{many:!0,role:`measure`}),wz(`series`,`Series`,Sz,{required:!1,role:`group`})],rows:{min:2},whole:!1,size:`window`,claims:[{claim:`range`,channel:`x`}],styles:[{name:`line`,label:`Line`},{name:`smooth`,label:`Smooth`},{name:`area`,label:`Area`},{name:`stacked`,label:`Stacked area`},{name:`step`,label:`Step`},{name:`bar`,label:`Bars`},{name:`river`,label:`Stream`,needs:[`series`]}],priority:{band:`time-encoded`,terms:[`temporal-key`,`high-null`]}})},distribution:{label:`Distribution`,icon:`chart`,description:`How numbers spread: points, bubbles, bins, boxes or parallel axes.`,shape:wk.parse({channels:[wz(`x`,`X`,bz),wz(`y`,`Y`,bz,{required:!1}),wz(`size`,`Size`,bz,{required:!1}),wz(`group`,`Group`,Sz,{required:!1}),wz(`dims`,`More axes`,bz,{required:!1,many:!0,min:1})],rows:{min:2,max:5e3},whole:!1,styles:[{name:`scatter`,label:`Points`,needs:[`y`]},{name:`bubble`,label:`Bubbles`,needs:[`y`,`size`]},{name:`pulse`,label:`Rippling points`,needs:[`y`]},{name:`histogram`,label:`Histogram`,whole:!0},{name:`boxplot`,label:`Box plot`,whole:!0},{name:`parallel`,label:`Parallel axes`,needs:[`y`,`dims`]}],priority:{band:`structural`,terms:[`high-null`]}})},crosstab:{label:`Cross-tab`,icon:`grid`,description:`A measure for each pair of two keys: a heatmap, value cells or small charts.`,shape:wk.parse({channels:[wz(`x`,`Columns`,Cz,{role:`group`}),wz(`y`,`Rows`,Cz,{role:`group`}),wz(`value`,`Value`,bz,{role:`measure`})],rows:{min:2},whole:!1,size:`top-n`,rules:[{rule:`distinct-columns`,channels:[`x`,`y`]},{rule:`distinct`,channel:`x`,max:50},{rule:`distinct`,channel:`y`,max:50}],styles:[{name:`heatmap`,label:`Heatmap`},{name:`cells`,label:`Value cells`},{name:`multiples`,label:`Small charts`}],priority:{band:`encoded`,terms:[`low-cardinality`]}})},calendar:{label:`Calendar`,icon:`calendar`,description:`Days on a calendar, shaded by a measure; the month shown can set the from/to args.`,shape:wk.parse({channels:[wz(`time`,`Date`,xz,{role:`group`}),wz(`value`,`Intensity`,bz,{required:!1,role:`measure`}),wz(`label`,`Label`,Sz,{required:!1})],rows:{min:1},whole:!1,claims:[{claim:`range`,channel:`time`}],styles:[{name:`month`,label:`Month`},{name:`year`,label:`Year`}],priority:{band:`structural`,terms:[`temporal-key`]}})},timeline:{label:`Timeline`,icon:`calendar`,description:`Bars from a start to an end date, one row each: a gantt chart.`,shape:wk.parse({channels:[wz(`start`,`Start`,xz),wz(`end`,`End`,xz),wz(`label`,`Label`,Sz),wz(`series`,`Lane`,Sz,{required:!1})],rows:{min:1,max:500},whole:!1,size:`window`,rules:[{rule:`distinct-columns`,channels:[`start`,`end`]}],claims:[{claim:`range`,channel:`start`}],styles:[{name:`gantt`,label:`Gantt`},{name:`timeline`,label:`Timeline`}],priority:{band:`time-encoded`,terms:[]}})},network:{label:`Network`,icon:`graph`,description:`Links between things: each row is an edge from a source to a target.`,shape:wk.parse({channels:[wz(`source`,`From`,Sz),wz(`target`,`To`,Sz),wz(`value`,`Weight`,bz,{required:!1,role:`measure`})],rows:{min:1,max:2e3},whole:!0,rules:[{rule:`distinct-columns`,channels:[`source`,`target`]}],styles:[{name:`force`,label:`Graph`},{name:`circular`,label:`Circle`},{name:`sankey`,label:`Flow`},{name:`chord`,label:`Chord`}],priority:{band:`structural`,terms:[]}})},hierarchy:{label:`Hierarchy`,icon:`tree`,description:`A tree from a name and its parent column, sized by a measure.`,shape:wk.parse({channels:[wz(`name`,`Name`,Sz),wz(`parent`,`Parent`,Sz),wz(`value`,`Size`,bz,{required:!1,role:`measure`})],rows:{min:2,max:5e3},whole:!0,rules:[{rule:`distinct-columns`,channels:[`name`,`parent`]},{rule:`links`,from:`name`,to:`parent`}],styles:[{name:`tree`,label:`Tree`},{name:`radial`,label:`Radial tree`},{name:`treemap`,label:`Treemap`},{name:`sunburst`,label:`Sunburst`}],priority:{band:`structural`,terms:[]}})},gauge:{label:`Gauge`,icon:`gauge`,description:`One value against its known range.`,shape:wk.parse({channels:[wz(`value`,`Value`,bz,{role:`measure`}),wz(`max`,`Maximum`,bz,{required:!1})],rows:{min:1,max:1},whole:!0,rules:[{rule:`bounded`,channel:`value`}],styles:[{name:`gauge`,label:`Gauge`},{name:`progress`,label:`Progress ring`}],priority:{band:`encoded`,terms:[]}})},finance:{label:`Candlestick`,icon:`chart`,description:`Open, high, low and close per period, with optional volume.`,shape:wk.parse({channels:[wz(`x`,`Period`,Cz,{role:`group`}),wz(`open`,`Open`,bz),wz(`close`,`Close`,bz),wz(`low`,`Low`,bz),wz(`high`,`High`,bz),wz(`volume`,`Volume`,bz,{required:!1})],rows:{min:2},whole:!1,size:`window`,claims:[{claim:`range`,channel:`x`}],styles:[{name:`candlestick`,label:`Candles`},{name:`volume`,label:`Candles and volume`,needs:[`volume`]}],priority:{band:`time-encoded`,terms:[`temporal-key`]}})}};Tz.map(e=>({name:e,shape:Ez[e].shape}));var Dz=`widgets`,Oz=`widgets/widget`,kz=[`today`,`today-1d`,`today+1d`,`today-7d`,`today-30d`,`today+7d`,`startOf(week)`,`endOf(week)`,`startOf(month)`,`endOf(month)`,`startOf(month,today-1mo)`,`startOf(quarter)`,`startOf(year)`,`now`,`now-1h`,`now-24h`],Az=E(kz),jz={today:{label:`Today`,yields:`day`},"today-1d":{label:`Yesterday`,yields:`day`},"today+1d":{label:`Tomorrow`,yields:`day`},"today-7d":{label:`7 days ago`,yields:`day`},"today-30d":{label:`30 days ago`,yields:`day`},"today+7d":{label:`In 7 days`,yields:`day`},"startOf(week)":{label:`Start of this week`,yields:`day`},"endOf(week)":{label:`End of this week`,yields:`day`},"startOf(month)":{label:`Start of this month`,yields:`day`},"endOf(month)":{label:`End of this month`,yields:`day`},"startOf(month,today-1mo)":{label:`Start of last month`,yields:`day`},"startOf(quarter)":{label:`Start of this quarter`,yields:`day`},"startOf(year)":{label:`Start of this year`,yields:`day`},now:{label:`Now`,yields:`instant`},"now-1h":{label:`An hour ago`,yields:`instant`},"now-24h":{label:`24 hours ago`,yields:`instant`}},Mz=C([S({literal:O}),S({relative:Az})]),Nz=S({label:v().min(1),value:Mz.optional()}),Pz=w(`show`,[S({show:D(`control`),label:v().min(1).optional(),choices:x(Nz).min(1).optional(),custom:b().optional(),default:Mz.optional()}),S({show:D(`pinned`),value:Mz}),S({show:D(`hidden`)})]),Fz=S({label:v().min(1),sets:T(k,Mz)}),Iz=S({from:k,to:k}),Lz=S({offset:k,limit:k}),Rz=S({visual:k,style:k,label:v().min(1).optional(),bind:oz}),zz=E([`open`,`refresh`,`status`]),Bz=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:zz.optional()}),Vz=S({fn:I,label:v().min(1),bind:T(k,v().min(1))}),Hz=S({title:v().min(1),source:I,visuals:x(Rz).min(1),args:T(k,Pz),presets:x(Fz),range:Iz.optional(),paging:Lz.optional(),actions:x(Bz).optional(),drill:Vz.optional(),live:D(!0).optional()}),Uz=S({arg:k,label:v().min(1),argType:Z,optional:b(),defaulted:b().optional(),choices:x(Nz).min(1).optional(),custom:b(),relative:b(),value:Mz.optional()}),Wz=S({offset:k,limit:k,window:y().int().min(1),more:b()}),Gz=S({fn:I,label:v().min(1),mode:nN,confirm:b(),bind:T(k,v().min(1)),form:Z.optional(),then:zz}),Kz=S({title:v().min(1),table:jk,facts:QR,source:S({fn:I,run:A,args:T(v(),O)}),visuals:x(Rz).min(1),problems:x(v()),controls:x(Uz),presets:x(Fz),range:Iz.optional(),paging:Wz.optional(),actions:x(Gz),drill:Vz.optional(),readOnly:b(),live:S({every:y().int().min(1)}).optional(),summary:v().min(1)}),qz=S({types:x(I).max(20),narrow:x(Bz).optional()}).refine(e=>e.types.length>0||(e.narrow?.length??0)>0,{message:`name a row type or an action to offer`}),Jz=S({fn:I,args:T(v(),O)}),Yz=Jz.extend({on:L.optional()});S({source:ub,request:v().min(1),args:T(v(),O).optional(),fns:x(ub).max(10).optional(),widget:ub.optional(),show:b()});var Xz=S({name:k,description:v().min(1),spec:Hz,preview:Kz,replaces:ub.optional(),show:b()});S({name:k,description:v().min(1),spec:Hz,replace:I.optional()});var Zz=S({fn:I,args:v(),offset:k,limit:k,format:D(`csv`)});S({summary:v(),columns:x(v()),rows:x(x(O)),more:y().int().min(0),partial:v().optional()});function Qz(e,t){return e!==`read`||t===!0}function $z(e,t){return t?`open`:e===`read`?`status`:`refresh`}function eB(e){return aT(e.split(/[/.]/).pop()??e)||e}var Q=TP(),$=UR(),tB=Iw(`adminOnly`,{requires:[$]}),nB=S({access:v(),refresh:v(),expiresIn:jl,user:TI}),rB=pI.pick({name:!0,version:!0}).extend({needsAdmin:b(),sso:x(GI)}),iB=S({kind:E([`fn`,`context`]),name:I,description:v(),score:PN,why:v().optional()}),aB=gA(v().min(1)),oB=S({approvals:x(NI),handlers:x(ej)}),sB=NP.omit({publicKey:!0}),cB=S({fns:y().int().min(0),context:y().int().min(0),types:y().int().min(0),parts:y().int().min(0),instances:y().int().min(0),pending:y().int().min(0),refusals:y().int().min(0)}),lB=lP.omit({keyFingerprint:!0,publicKey:!0,config:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0,instances:!0}).extend(NP.pick({keyFingerprint:!0,config:!0,installed:!0,host:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0}).shape).extend({counts:cB,instanceMode:cP,needsConfig:b(),configType:O.optional(),configSecrets:iA.optional(),store:rM.optional(),instances:x(sB)}),uB=w(`type`,[S({type:D(`message`),message:JL}),S({type:D(`token`),message:cl,text:v()}),S({type:D(`reasoning`),message:cl,text:v()}),S({type:D(`cite`),message:cl,cite:PA}),S({type:D(`controls`),controls:ZL}),S({type:D(`run`),run:A,fn:I,update:uE}),S({type:D(`state`),system:F,fields:x(ZA)}),S({type:D(`delivery`),delivery:$A}),S({type:D(`handler`),call:ej}),S({type:D(`approval`),approval:NI}),S({type:D(`budget`),run:A,budget:CA,reason:v()}),S({type:D(`presence`),presence:QL}),S({type:D(`session`),session:FL}),S({type:D(`compare`),turn:sl})]),dB=w(`type`,[S({type:D(`notification`),notification:eF}),S({type:D(`approval`),approval:NI}),S({type:D(`system`),system:F,status:eP}),S({type:D(`pairing`),pairing:uP}),S({type:D(`capabilities`)}),S({type:D(`session`),session:FL}),S({type:D(`session-deleted`),session:j}),S({type:D(`fn`),fn:I,system:F,stats:dP}),S({type:D(`resource`),uri:Tx,forms:x(Lx)}),S({type:D(`context`),name:I}),S({type:D(`identity`),identity:pI})]),fB=Rw(Y({endpoints:X(Q).group({setup:{method:`GET`,response:rB,ws:`setup`},createAdmin:{body:S({email:Ns(),name:v().min(1),password:v().min(8),setup:v().trim().min(1)}),response:nB,ws:`createAdmin`},signIn:{body:S({email:Ns(),password:v()}),response:nB,errors:{401:S({reason:v()})},ws:`signIn`},refresh:{body:S({refresh:v()}),response:nB,ws:`refresh`},redeemSso:{body:S({code:v().min(1)}),cookies:S({[iL]:v().optional()}),response:nB,ws:`redeemSso`,httpOnly:!0}})}),Y({endpoints:X(Q,$).group({signOut:{ws:`signOut`},me:{method:`GET`,response:TI,ws:`me`},account:{method:`GET`,response:$I,ws:`account`}})})),pB=Vl.extend({query:xj.optional()}),mB=Vl.extend({session:j}),hB=Vl.extend({unread:b().optional(),query:xj.optional()}),gB=PL.pick({title:!0,systems:!0,agent:!0,archived:!0}).partial().extend({priority:Ll.optional(),notify:AL.optional(),model:PL.shape.model.unwrap().nullable().optional(),mode:PL.shape.mode.unwrap().nullable().optional(),contextor:PL.shape.contextor.unwrap().nullable().optional(),fnMode:PL.shape.fnMode.unwrap().nullable().optional(),instructions:PL.shape.instructions.unwrap().nullable().optional(),citations:PL.shape.citations}),_B=Y({endpoints:X(Q,$).group({capabilities:{body:S({session:j.optional()}),response:$L,ws:`capabilities`},types:{body:S({names:x(I).min(1)}),response:hP,ws:`types`},sessions:{body:pB,response:Bl(FL),ws:`sessions`},session:{body:S({session:j}),response:PL,ws:`session`},createSession:{body:PL.pick({agent:!0,systems:!0,title:!0}).partial(),response:PL,ws:`createSession`},updateSession:{body:gB.extend({session:j}),response:PL,ws:`updateSession`},deleteSession:{body:S({session:j}),response:S({deleted:b()}),ws:`deleteSession`},limits:{body:S({session:j}),response:TA,ws:`limits`},messages:{body:mB,response:Bl(JL),ws:`messages`},send:{body:S({session:j,parts:x(qL).min(1),replyTo:cl.optional(),replyAll:b().optional(),client:BT}),response:S({turn:sl,message:JL}),ws:`send`},compare:{body:xR,response:S({turn:sl,message:JL}),ws:`compare`},compareView:{body:S({turn:sl}),response:CR,ws:`compareView`},chooseVariant:{body:wR,response:CR,ws:`chooseVariant`},invoke:{body:S({session:j,fn:I,args:O,on:L.optional(),client:BT}),response:S({turn:sl,run:A}),ws:`invoke`},control:{body:S({session:j,action:YL,runs:x(A).min(1).optional()}),response:ZL,ws:`control`},controls:{body:S({session:j}),response:ZL,ws:`controls`},presence:{body:QL.omit({user:!0,lastActiveAt:!0}),ws:`presence`}})}),vB=Y({endpoints:X(Q,$).group({background:{body:S({run:A}),response:S({accepted:b()}),ws:`background`},undoTurn:{body:S({turn:sl}),response:sj,ws:`undoTurn`},continueTurn:{body:S({turn:sl}),response:S({turn:sl,run:A}),ws:`continueTurn`},tree:{body:S({turn:sl}),response:oj,ws:`tree`},run:{body:S({run:A}),response:YA,ws:`run`},llmCall:{body:S({id:dl}),response:aj,ws:`llmCall`},waiting:{body:S({session:j}),response:oB,ws:`waiting`},approve:{body:S({approval:hl,approve:b(),remember:MI,reason:v().optional(),answer:O.optional()}),response:NI,ws:`approve`},answer:{body:S({call:ul,value:O}),ws:`answer`},act:{body:S({session:j,system:F,action:v(),input:O,run:A.optional(),client:BT}),response:S({delivery:ll}),ws:`act`},submit:{body:S({run:A,value:O}),response:S({delivery:ll}),ws:`submit`},state:{body:S({run:A}),response:S({system:F,fields:x(ZA)}),ws:`state`}})}),yB=Y({endpoints:X(Q,$).group({suggest:{body:S({session:j,text:v(),limit:y().int().min(1).max(20).optional()}),response:x(iB),ws:`suggest`},mentions:{body:S({session:j,provider:I,query:v()}),response:x(RN),ws:`mentions`},mentionHover:{body:S({session:j,provider:I,target:O}),response:S({hover:zN.optional()}),ws:`mentionHover`},resource:{body:S({uri:Tx,want:x(Nx)}),response:Fx,ws:`resource`}})}),bB=Y({endpoints:X(Q,$).group({notifications:{body:hB,response:Bl(eF),ws:`notifications`},readNotifications:{body:S({ids:x(eF.shape.id)}),ws:`readNotifications`},pushKey:{method:`GET`,response:S({publicKey:v()}),ws:`pushKey`},subscribePush:{body:tF.pick({endpoint:!0,keys:!0,device:!0}),response:tF.pick({id:!0}),ws:`subscribePush`}})}),xB=Y({endpoints:X(Q,$).group({upload:{body:S({name:v(),mime:v(),size:y().int().min(0)}),response:S({url:v(),upload:v()}),ws:`upload`},uploaded:{body:S({upload:v()}),response:kx,ws:`uploaded`},transcribe:{body:S({audio:kx}),response:S({text:v()}),ws:`transcribe`}})}),SB=S({section:E([`fns`,`context`]),name:I,on:b()}),CB=S({system:F,section:NF.exclude([`fns`,`context`]),name:v().min(1),on:b()}),wB=Y({endpoints:X(Q,$,tB).group({systems:{body:S({query:xj.optional()}),response:x(lB),ws:`systems`},system:{body:S({system:F}),response:lB,ws:`system`},pairings:{body:S({status:uP.shape.status.optional()}),response:x(uP),ws:`pairings`},approvePairing:{body:S({pairing:fl,approve:b(),instance:L.optional(),config:O.optional(),autoPair:XN.optional(),store:lM.optional()}),response:S({system:F.optional()}),ws:`approvePairing`},createPairingToken:{body:S({name:F.optional(),expiresIn:jl,autoPair:XN.optional()}),response:S({token:v(),expiresAt:N}),ws:`createPairingToken`},configureSystem:{body:S({system:F,config:O,instance:L.optional()}),response:C([S({version:y().int()}),S({problems:x(v())})]),ws:`configureSystem`},enableSystem:{body:S({system:F,functions:b().optional(),renderers:b().optional(),context:b().optional()}),response:S({enabled:aP}),ws:`enableSystem`},switchItem:{body:SB,response:S({on:b()}),ws:`switchItem`},switchPart:{body:CB,response:S({on:b()}),ws:`switchPart`},removeSystem:{body:S({system:F,keepStore:b().optional()}),response:S({fnsUnavailable:y().int()}),ws:`removeSystem`},installSystem:{body:S({source:tP,config:O.optional(),autoStart:b().optional(),store:lM.optional()}),response:S({name:F}),ws:`installSystem`},systemStore:{body:S({system:F,instance:L.optional()}),response:jM,ws:`systemStore`},systemStoreMove:{body:S({system:F,instance:L.optional(),to:lM,runs:EM.optional()}),response:kM,ws:`systemStoreMove`},systemStoreMoveState:{body:S({system:F,instance:L.optional()}),response:S({move:kM.optional()}),ws:`systemStoreMoveState`},systemStoreMoveAnswer:{body:S({system:F,instance:L.optional(),answer:DM}),response:kM,ws:`systemStoreMoveAnswer`},systemStoreBackups:{body:S({system:F,instance:L.optional()}),response:x(CM),ws:`systemStoreBackups`},systemStoreBackupDelete:{body:S({system:F,instance:L.optional(),backup:SM}),response:S({deleted:D(!0),note:v().optional()}),ws:`systemStoreBackupDelete`},startSystem:{body:S({system:F,instance:L.optional()}),response:S({ok:b()}),ws:`startSystem`},stopSystem:{body:S({system:F,instance:L.optional()}),response:S({ok:b()}),ws:`stopSystem`},restartSystem:{body:S({system:F,instance:L.optional(),reason:v().min(1).max(200)}),response:S({ok:b()}),ws:`restartSystem`},upgradeSystem:{body:S({system:F,version:v().optional()}),response:S({from:v(),to:v()}),ws:`upgradeSystem`},reimport:{body:S({system:F}),response:ON,ws:`reimport`}})}),TB=Y({endpoints:X(Q,$,tB).group({configureProvider:{body:aB,response:S({models:y().int()}),ws:`configureProvider`},providers:{body:S({}),response:x(S({id:wl,provider:vA,models:y().int()})),ws:`providers`},setModelCategory:{body:yA.partial({id:!0}),response:yA.pick({id:!0}),ws:`setModelCategory`},setBudget:{body:CA.omit({setBy:!0}).partial({id:!0}),response:CA.pick({id:!0}),ws:`setBudget`},setPriority:{body:wA.omit({setBy:!0}).partial({id:!0}),response:wA.pick({id:!0}),ws:`setPriority`},setPolicy:{body:jI.omit({createdBy:!0,createdAt:!0}).partial({id:!0}),response:jI.pick({id:!0}),ws:`setPolicy`},setActorSetting:{body:S({setting:I,actor:M,value:O}),response:S({ok:b()}),ws:`setActorSetting`},addUser:{body:S({email:Ns(),name:v(),role:SI,groups:x(M).optional()}),response:S({id:M}),ws:`addUser`},addGroup:{body:S({name:v(),about:v(),members:x(M).optional()}),response:S({id:M}),ws:`addGroup`},updateUser:{body:tL,response:S({id:M}),ws:`updateUser`},setMembership:{body:nL,response:S({ok:b()}),ws:`setMembership`},setSignInPolicy:{body:RI,response:RI,ws:`setSignInPolicy`},setSignInLimits:{body:VI,response:VI,ws:`setSignInLimits`},setProxyTrust:{body:UI,response:UI,ws:`setProxyTrust`}})}),EB=Y({endpoints:X(Q,$,tB).group({systemFns:{body:S({system:F}),response:x(pP),ws:`systemFns`},systemParts:{body:CP,response:wP,ws:`systemParts`},systemLogs:{body:S({system:F,limit:y().int().min(1).max(2e3).optional()}),response:x(LP),ws:`systemLogs`},models:{body:S({provider:wl.optional()}),response:x(BP),ws:`models`},modelCategories:{body:S({}),response:x(yA),ws:`modelCategories`},budgets:{body:S({}),response:x(HP),ws:`budgets`},priorityRules:{body:S({}),response:x(wA),ws:`priorityRules`},resolveLimits:{body:S({user:M,session:j.optional()}),response:TA,ws:`resolveLimits`},policies:{body:S({}),response:x(jI),ws:`policies`},actors:{body:S({kind:zl.optional()}),response:x(wI),ws:`actors`},actorSettings:{body:S({}),response:S({declared:x(UP),values:x(EI)}),ws:`actorSettings`},runs:{body:Vl.extend({query:xj.optional()}),response:Bl(YA),ws:`runs`},llmCalls:{body:Vl.extend({query:xj.optional()}),response:Bl(WP),ws:`llmCalls`},resources:{body:Vl.extend({query:xj.optional()}),response:Bl(KP),ws:`resources`},removeRule:{body:GP,response:S({ok:b()}),ws:`removeRule`},indexStatus:{body:S({}),response:RP,ws:`indexStatus`}}),events:{systemLog:{params:S({system:F}),data:LP,guard:[$,tB],ws:`on.systemLog`}}}),DB=Iw(`ownEvents`,{requires:[$]}),OB=Iw(`sessionWatch`,{requires:[$]}),kB=S({user:M}),AB=Y({endpoints:{},events:{session:{params:S({session:j}),data:uB,guard:[$,OB],ws:`on.session`},user:{params:kB,data:dB,guard:[$,DB],ws:`on.user`}}}),jB=Bl(KP).extend({facets:x(OE)}),MB=S({record:KP,forms:x(_E),offers:x(vE)}),NB=Y({endpoints:X(Q,$).group({browseResources:{body:kE.extend({query:xj.optional()}),response:jB,ws:`browseResources`},resourceForms:{body:S({uri:Tx}),response:MB,ws:`resourceForms`},readResource:{body:PE,response:FE,ws:`readResource`},convertResource:{body:S({uri:Tx,kind:Lx}),response:_E,ws:`convertResource`},downloadResource:{body:S({uri:Tx,form:Lx.optional()}),response:S({url:v(),mime:v(),size:y().int().min(0)}),ws:`downloadResource`},importResource:{body:IE,response:KP,ws:`importResource`},renameResource:{body:S({uri:Tx,name:v().min(1)}),response:KP,ws:`renameResource`},deleteResource:{body:S({uri:Tx}),response:S({deleted:b(),referencedBy:y().int().min(0)}),ws:`deleteResource`},contextFromResource:{body:fS,response:pS,ws:`contextFromResource`}})}),PB=Vl.extend({query:xj.optional()}),FB=S({record:_P,links:x(sS),backlinks:x(sS),text:v().optional()}),IB=Y({endpoints:X(Q,$).group({contexts:{body:PB,response:Bl(hF),ws:`contexts`},contextItem:{body:S({name:I}),response:FB,ws:`contextItem`},remember:{body:lS,response:S({name:I}),ws:`remember`},updateMemory:{body:dS,response:S({name:I}),ws:`updateMemory`},forget:{body:S({name:I}),response:S({ok:b()}),ws:`forget`},linkContext:{body:S({from:I,to:rS,relation:nS,weight:y().min(0).max(1)}),response:sS,ws:`linkContext`},unlinkContext:{body:sS.pick({from:!0,toKey:!0,relation:!0}),response:S({ok:b()}),ws:`unlinkContext`}})}),LB=Rw(Y({endpoints:X(Q,$).group({contextMetadata:{body:S({name:I}),response:GS,ws:`contextMetadata`},setContextStatus:{body:NS,response:PS,ws:`setContextStatus`}})}),Y({endpoints:X(Q,$,tB).group({contextReview:{body:LS,response:zS,ws:`contextReview`},mergeContext:{body:BS,response:VS,ws:`mergeContext`},notDuplicate:{body:HS,response:S({ok:b()}),ws:`notDuplicate`},reextractContext:{body:US,response:WS,ws:`reextractContext`},newContextStatus:{body:S({}),response:OS,ws:`newContextStatus`},setNewContextStatus:{body:S({value:DS}),response:OS,ws:`setNewContextStatus`}})})),RB=Y({endpoints:X(Q,$).group({contextPlans:{body:pC,response:mC,ws:`contextPlans`},contextPlan:{body:aC,response:oC,ws:`contextPlan`},answerPlan:{body:lC,response:uC,ws:`answerPlan`}})}),zB=Rw(Y({endpoints:X(Q,$).group({modelLimits:{body:S({model:v().optional()}),response:x(nx),ws:`modelLimits`},previewSelection:{body:S({session:j,text:v()}),response:sx,ws:`previewSelection`}})}),Y({endpoints:X(Q,$,tB).group({setModelLimits:{body:S({model:v().min(1),limits:Qb}),response:nx,ws:`setModelLimits`},previewPrompt:{body:cx,response:lx,ws:`previewPrompt`}})})),BB=Y({endpoints:X(Q,$,tB).group({modelRoles:{body:S({}),response:x(PD),ws:`modelRoles`},setModelRole:{body:MD,response:PD,ws:`setModelRole`},clearModelRole:{body:S({role:TD}),response:PD,ws:`clearModelRole`}})}),VB=Vl.extend({run:A.optional(),query:xj.optional()}),HB=Y({endpoints:X(Q,$,tB).group({modelCalls:{body:VB,response:Bl(SD),ws:`modelCalls`},modelCall:{body:S({id:Dl}),response:SD,ws:`modelCall`},fnMetrics:{body:WD,response:x(UD),ws:`fnMetrics`},fnMetricsDays:{body:S({fn:I,days:y().int().min(1).max(365).optional()}),response:x(HD),ws:`fnMetricsDays`}})}),UB=Y({endpoints:X(Q,$,tB).group({mcps:{body:S({}),response:x(FR),ws:`mcps`},mcp:{body:S({mcp:Ol}),response:FR,ws:`mcp`},createMcp:{body:jR,response:S({mcp:FR,secret:v()}),ws:`createMcp`},updateMcp:{body:jR.partial().extend({mcp:Ol}),response:FR,ws:`updateMcp`},rotateMcpSecret:{body:S({mcp:Ol}),response:S({secret:v()}),ws:`rotateMcpSecret`},deleteMcp:{body:S({mcp:Ol}),response:S({ok:b()}),ws:`deleteMcp`},previewMcp:{body:S({rules:OR}),response:NR,ws:`previewMcp`},mcpSessions:{body:S({mcp:Ol}),response:x(PR),ws:`mcpSessions`}})}),WB=Y({endpoints:X(Q,$,tB).group({pairing:{body:S({pairing:fl}),response:uP,ws:`pairing`},instances:{body:S({system:F}),response:x(sB),ws:`instances`},installPackage:{body:S({zip:kx,instance:L.optional(),config:O.optional(),data:kx.optional(),autoStart:b().optional(),store:lM.optional()}),response:Kl,ws:`installPackage`},removeInstance:{body:Kl.extend({keepStore:b().optional()}),response:S({ok:b()}),ws:`removeInstance`},addInstance:{body:IP,response:Kl,ws:`addInstance`},exportSystemData:{body:Kl.extend({withSecrets:b().optional()}),response:kx.extend({url:v()}),ws:`exportSystemData`}})}),GB=Rw(Y({endpoints:X(Q,$).group({query:{body:Fj,response:Ij,ws:`query`},listValues:{body:Pj,response:x(Nj),ws:`listValues`}})}),Y({endpoints:X(Q,$,tB).group({fns:{body:xj,response:Bl(pP),ws:`fns`}})})),KB=Y({endpoints:X(Q,$,tB).group({suggestDecision:{body:S({}),response:SL,ws:`suggestDecision`},setSuggestDecision:{body:_L,response:SL,ws:`setSuggestDecision`},searchDecisions:{body:S({}),response:OL,ws:`searchDecisions`},setSearchDecision:{body:kL,response:OL,ws:`setSearchDecision`},previewSuggestions:{body:S({session:j,text:v().min(1)}),response:mL,ws:`previewSuggestions`}})}),qB=Y({endpoints:X(Q,$,tB).group({imageEmbedding:{body:S({}),response:bI,ws:`imageEmbedding`},setImageEmbedding:{body:gI,response:bI,ws:`setImageEmbedding`}})}),JB=Rw(Y({endpoints:X(Q,$).group({outsideImages:{body:S({}),response:vb,ws:`outsideImages`}})}),Y({endpoints:X(Q,$,tB).group({setOutsideImages:{body:S({value:_b}),response:vb,ws:`setOutsideImages`}})})),YB=Rw(Y({endpoints:X(Q,$).group({https:{body:S({}),response:Sb,ws:`https`}})}),Y({endpoints:X(Q,$,tB).group({setHttps:{body:S({on:b()}),response:Sb,ws:`setHttps`}})})),XB=Y({endpoints:X(Q,$,tB).group({autoPairs:{body:S({system:F.optional()}),response:x($N),ws:`autoPairs`},revokeAutoPair:{body:S({id:kl}),response:S({ok:b()}),ws:`revokeAutoPair`}})}),ZB=Y({endpoints:X(Q,$).group({accessInfo:{body:S({}),response:ZD,ws:`accessInfo`},access:{body:S({targets:x(JD).min(1).max(200)}),response:x(XD),ws:`access`},setAccess:{body:S({target:JD,sharing:qD.omit({owner:!0})}),response:XD,ws:`setAccess`}})}),QB=Y({endpoints:X(Q,$).group({connectPages:{body:S({}),response:x(TO),ws:`connectPages`},connect:{body:S({system:F,instance:L.optional(),key:yO.optional(),form:O.optional()}),response:C([S({url:mb}),S({connection:wO})]),ws:`connect`,httpOnly:!0},updateConnection:{body:jO,response:wO,ws:`updateConnection`},disconnect:{body:S({connection:Al}),response:S({ok:b()}),ws:`disconnect`}})}),$B=Y({endpoints:X(Q,$).group({pick:{body:tO,response:x(nO),ws:`pick`}})}),eV=Y({endpoints:X(Q,$).group({approvals:{body:S({runs:x(A).min(1).max(200)}),response:x(NI),ws:`approvals`}})}),tV=Y({endpoints:X(Q,$).group({contributions:{body:S({registry:I}),response:x(Dk),ws:`contributions`},systemPages:{body:S({}),response:x(pA),ws:`systemPages`},systemInstances:{body:S({system:F}),response:x(mA),ws:`systemInstances`}})}),nV=Rw(Y({endpoints:X(Q,$).group({searchFns:{body:lF,response:vF,ws:`searchFns`},fnExamples:{body:iF,response:aF,ws:`fnExamples`},fnFacts:{body:S({fn:I,args:O.optional()}),response:xF,ws:`fnFacts`},fnsOfModelNames:{body:S({names:x(v().min(1).max(64)).min(1).max(200)}),response:T(v(),I),ws:`fnsOfModelNames`},clientLogs:{body:EF,response:DF,ws:`clientLogs`}})}),Y({endpoints:X(Q,$,tB).group({autoClassifier:{body:S({}),response:TF,ws:`autoClassifier`},setAutoClassifier:{body:wF,response:TF,ws:`setAutoClassifier`}})})),rV=Y({endpoints:X(Q,$).group({exploreRoots:{body:S({system:F,instance:L.optional()}),response:x(Ax),ws:`exploreRoots`},exploreList:{body:S({uri:Tx,cursor:v().optional()}),response:Bl(jx),ws:`exploreList`},exploreRead:{body:S({uri:Tx,want:x(Nx).min(1)}),response:Fx,ws:`exploreRead`}})}),iV=Y({endpoints:X(Q,$,tB).group({systemReview:{body:S({system:F}),response:YF,ws:`systemReview`},goLive:{body:XF,response:S({stage:pk,hash:v()}),ws:`goLive`},approveReview:{body:XF,response:S({hash:v()}),ws:`approveReview`},rejectReview:{body:S({system:F,hash:v().min(1)}),response:S({ok:b()}),ws:`rejectReview`},decideReview:{body:ZF,response:QF,ws:`decideReview`},testCall:{body:eI,response:S({run:A}),ws:`testCall`},refusals:{body:qF,response:JF,ws:`refusals`}})}),aV=Y({endpoints:X(Q,$).group({graph:{body:YR,response:XR,ws:`graph`}})}),oV=S({agent:I.optional(),context:I.optional(),mode:Bb.optional(),fnMode:fx.optional()}),sV=Y({endpoints:X(Q,$,tB).group({injections:{body:oV,response:jb,ws:`injections`},setInjection:{body:Mb,response:Ab,ws:`setInjection`}})}),cV=Rw(Y({endpoints:X(Q).group({identity:{method:`GET`,response:pI,ws:`identity`}})}),Y({endpoints:X(Q,$,tB).group({setHubName:{body:mI,response:pI,ws:`setHubName`}})})),lV=Y({endpoints:X(Q,$,tB).group({people:{body:xj,response:Bl($I),ws:`people`},groups:{body:xj,response:Bl(eL),ws:`groups`},groupMembers:{body:Vl.extend({group:M}),response:Bl(TI).extend({group:eL}),ws:`groupMembers`},signInSettings:{body:S({}),response:KI,ws:`signInSettings`},checkSsoProvider:{body:S({provider:PI}),response:JI,ws:`checkSsoProvider`},testSsoSignIn:{body:S({provider:PI}),response:S({url:mb,test:v()}),ws:`testSsoSignIn`,httpOnly:!0},ssoTestResult:{body:S({test:v()}),response:ZI,ws:`ssoTestResult`}})}),uV=Y({endpoints:X(Q,$).group({itemVersions:{body:RR,response:zR,ws:`itemVersions`}})}),dV=Y({endpoints:X(Q,$).group({dataSets:{body:Zj,response:Qj,ws:`dataSets`},records:{body:Vj,response:Hj,ws:`records`},record:{body:Wj,response:S({record:zj.optional()}),ws:`record`},recordTable:{body:Uj,response:jk,ws:`recordTable`},saveRecord:{body:Gj,response:zj,ws:`saveRecord`},updateRecord:{body:Kj,response:zj,ws:`updateRecord`},removeRecord:{body:qj,response:S({removed:b()}),ws:`removeRecord`},recordVersions:{body:Jj,response:Yj,ws:`recordVersions`}})}),fV=Rw(fB,_B,vB,yB,bB,xB,wB,TB,EB,AB,NB,IB,LB,RB,zB,BB,HB,UB,WB,GB,KB,XB,qB,JB,YB,ZB,QB,$B,eV,tV,nV,rV,iV,aV,sV,cV,uV,dV,Y({endpoints:X(Q,$).group({rowActions:{body:qz,response:x(Gz),ws:`rowActions`},readFn:{body:Yz,response:O,ws:`readFn`}})}),Y({endpoints:X(Q,$).group({export:{method:`GET`,query:Zz,streamOut:`text/csv`,download:`export.csv`}})}),lV),pV={load_fns:`fns_load`,drop_fns:`fns_drop`,fn_examples:`fns_examples`,fn_get:`fns_get`,save_fn:`fns_save`,fn_metrics:`fns_metrics`,load_context:`ctx_load`,context_get:`ctx_get`,context_crawl:`ctx_crawl`,context_from_resource:`ctx_from_resource`,context_link:`ctx_link`,context_unlink:`ctx_unlink`};new Map(Object.entries(pV).map(([e,t])=>[`hub/${e}`,`hub/${t}`])),new Map(Object.entries(pV));var mV=E([`added`,`modified`,`deleted`,`renamed`]),hV=E([`binary`,`large`,`sensitive`,`not-in-git`]),gV=S({path:v().min(1),root:v().min(1),status:mV,from:v().min(1).optional(),size:y().int().min(0).optional(),diff:v().optional(),added:y().int().min(0).optional(),removed:y().int().min(0).optional(),noDiff:hV.optional(),sensitive:Ik.optional(),certain:b()}),_V=S({source:E([`git`,`watcher`]),cwd:v().min(1),files:x(gV),ignored:y().int().min(0),truncated:b()}),vV=S({arg:k,label:v().min(1).optional(),choices:x(O).min(1).optional(),custom:b().optional(),pinned:O.optional(),hidden:b().optional()}),yV=S({offset:k.optional(),limit:k.optional(),size:y().int().min(1).max(500)}),bV=S({visual:k,label:v().min(1).optional(),bind:T(k,x(v().min(1)).min(1))}),xV=E([`refresh`,`show`,`none`]),SV=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:xV});S({title:v().min(1),source:I,visuals:x(bV).min(1),controls:x(vV),paging:yV.optional(),actions:x(SV).optional()});var CV=v().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),wV=w(`type`,[S({type:D(`stdio`),command:v().min(1),args:x(v()).default([]),env:T(CV,v()).optional(),cwd:v().min(1).optional()}),S({type:D(`http`),url:Ls()}),S({type:D(`sse`),url:Ls()})]),TV=E([`always`,`writes`,`never`]),EV=S({label:v().min(1),description:v().optional(),transport:wV,auth:lO.default({kind:`none`}),trusted:b().default(!1),approval:TV.default(`writes`),prompts:b().default(!0),resources:b().default(!0),maxTools:y().int().min(1).max(1e3).default(200),timeout:y().int().min(1e3).default(12e4)}),DV=[`transport.env`,...pO],OV=S({instance:L,state:E([`connecting`,`connected`,`needs-auth`,`unreachable`,`failed`]),server:S({name:v(),version:v(),protocol:v(),instructions:v().optional()}).optional(),tools:y().int().min(0),prompts:y().int().min(0),resources:y().int().min(0),degraded:x(v()),leftOut:y().int().min(0),problem:v().optional(),checkedAt:N}),kV=S({title:v().optional(),readOnlyHint:b().optional(),destructiveHint:b().optional(),idempotentHint:b().optional(),openWorldHint:b().optional()});S({tool:v().min(1),description:v(),inputSchema:O,outputSchema:O.optional(),args:Z,returns:Z.optional(),annotations:kV.optional(),degraded:v().optional()});function AV(e,t){let n=`${e}_${t.replace(/[^A-Za-z0-9_.-]/g,`_`)}`.replace(/-/g,`_`);return nb.parse(n.split(`.`).map(e=>e.replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||`x`).join(`.`))}function jV(e){return`mcp://${e}/`}S({args:Z,returns:Z,program:tT}),S({service:yO,args:Z,returns:Z,request:tT,responseType:Z.optional(),output:tT.optional()});var MV=E([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`]),NV=yO,PV=`api/Service`,FV=S({name:NV,label:v().min(1),description:v().optional(),baseUrl:Ls(),allowPrivate:b().default(!1),privateTo:M.optional(),auth:dO.default({kind:`none`}),headers:aO.optional(),openapi:Ls().optional(),timeout:y().int().min(1e3).default(6e4),maxBody:y().int().min(1024).default(2097152)});S({label:v().min(1),description:v().optional(),baseUrl:Ls(),auth:uO.default({kind:`none`}),headers:aO.optional(),openapi:Ls().optional(),timeout:y().int().min(1e3).default(6e4),maxBody:y().int().min(1024).default(2097152)}),[...fO],S({method:MV,url:v(),headers:x(S({key:v(),value:v()})),body:v().optional(),response:S({status:y().int(),headers:x(S({key:v(),value:v()})),body:O.optional(),ms:y().int().min(0)}).optional()});var IV=eF.pick({id:!0,title:!0,body:!0,link:!0,reason:!0,also:!0,key:!0,tone:!0}),LV=`open`,RV=E([`link`,`also`]),zV=`also`;function BV(e,t=`link`){return`/inbox?${LV}=${encodeURIComponent(e.id)}${t===`also`?`&via=also`:``}`}function VV(e){return e.key??e.id}function HV(e){return e.also===void 0?{link:BV(e)}:{link:BV(e),also:BV(e,`also`)}}function UV(e,t){let n=e=>typeof e==`string`&&e.startsWith(`/`)&&!e.startsWith(`//`);if(n(e))return e;if(typeof e==`object`&&e){let r=Reflect.get(e,`also`),i=Reflect.get(e,`link`);if(t===`also`&&n(r))return r;if(n(i))return i}return`/inbox`}export{Kz as $,zl as $a,Tg as $i,PO as $n,D as $o,Cw as $r,$P as $t,sV as A,Yg as Aa,qb as Ai,jj as An,xc as Ao,NT as Ar,hL as At,wB as B,Ql as Ba,hb as Bi,vA as Bn,Nc as Bo,sT as Br,uI as Bt,LB as C,Gg as Ca,Gx as Ci,mM as Cn,Fl as Co,YT as Cr,fL as Ct,rV as D,Ev as Da,Rx as Di,Lj as Dn,Lc as Do,oE as Dr,gL as Dt,dV as E,yv as Ea,Tx as Ei,zj as En,nc as Eo,cE as Er,sL as Et,GB as F,_h as Fa,Qb as Fi,cj as Fn,kc as Fo,wT as Fr,rL as Ft,kz as G,Of as Ga,Py as Gi,Ek as Gn,ws as Go,tT as Gr,dF as Gt,zz as H,kf as Ha,cb as Hi,dA as Hn,yc as Ho,oT as Hr,MF as Ht,NB as I,pf as Ia,Vb as Ii,QA as In,$s as Io,yT as Ir,OI as It,Dz as J,rf as Ja,Gy as Ji,kk as Jn,E as Jo,Zw as Jr,uF as Jt,Jz as K,gf as Ka,Uy as Ki,Dk as Kn,pc as Ko,$w as Kr,aF as Kt,vB as L,Df as La,Tb as Li,BA as Ln,dc as Lo,CT as Lr,_I as Lt,HB as M,Zg as Ma,zb as Mi,mj as Mn,Sc as Mo,FT as Mr,LI as Mt,BB as N,Ny as Na,Xb as Ni,hj as Nn,Fc as No,vT as Nr,UI as Nt,aV as O,Kg as Oa,Ex as Oi,Rj as On,qc as Oo,sE as Or,vL as Ot,WB as P,sm as Pa,Nb as Pi,Mj as Pn,rc as Po,pT as Pr,VI as Pt,Xz as Q,M as Qa,mv as Qi,rk as Qn,Zc as Qo,bw as Qr,AF as Qt,TB as R,lf as Ra,wb as Ri,AA as Rn,Tc as Ro,fT as Rr,hI as Rt,QB as S,Wg as Sa,qx as Si,fM as Sn,Pl as So,lE as Sr,cL as St,zB as T,dv as Ta,Lx as Ti,$j as Tn,uc as To,aE as Tr,CL as Tt,Zz as U,af as Ua,ab as Ui,rA as Un,Es as Uo,cT as Ur,UF as Ut,uV as V,cf as Va,rb as Vi,uA as Vn,Vc as Vo,aT as Vr,fI as Vt,jz as W,hf as Wa,Fy as Wi,aA as Wn,Uc as Wo,lT as Wr,wF as Wt,Gz as X,R as Xa,wg as Xi,dk as Xn,x as Xo,Ww as Xr,vF as Xt,Oz as Y,vf as Ya,Ky as Yi,jk as Yn,ic as Yo,Hw as Yr,pF as Yt,Lz as Z,Wl as Za,yg as Zi,uk as Zn,b as Zo,kC as Zr,cF as Zt,nB as _,K_ as _a,aS as _i,GM as _n,F as _o,NE as _r,ER as _t,UV as a,kg as aa,aC as ai,yP as an,k as ao,KD as ar,vc as as,ZR as at,XB as b,Ug as ba,lS as bi,lM as bn,tl as bo,jE as br,FL as bt,PV as c,uv as ca,XS as ci,VN as cn,Dl as co,RD as cr,az as ct,EV as d,Sv as da,CC as di,uN as dn,Il as do,MD as dr,YR as dt,av as ea,lC as ei,bP as en,Rl as eo,xO as er,y as es,Hz as et,OV as f,Fg as fa,FS as fi,eN as fn,fl as fo,sD as fr,BR as ft,aB as g,Ov as ga,tS as gi,MN as gn,j as go,ME as gr,MR as gt,_V as h,zg as ha,cS as hi,jN as hn,A as ho,SE as hr,TR as ht,IV as i,Og as ia,dC as ii,vP as in,dl as io,QD as ir,v as is,Ez as it,UB as j,U as ja,dx as ji,kj as jn,Gc as jo,PT as jr,uL as jt,fV as k,qg as ka,wx as ki,yj as kn,jc as ko,eE as kr,_L as kt,FV as l,vv as la,wC as li,YN as ln,ql as lo,TD as lr,yz as lt,AV as m,bv as ma,fS as mi,xN as mn,Ul as mo,gE as mr,DR as mt,RV as n,Dg as na,nC as ni,tP as nn,L as no,hO as nr,Ec as ns,Qz as nt,VV as o,vg as oa,oC as oi,HN as on,Gl as oo,YD as or,C as os,Tz as ot,jV as p,Pg as pa,jS as pi,EN as pn,I as po,zE as pr,jR as pt,qz as q,Af as qa,Qy as qi,Ok as qn,oc as qo,Z as qr,iF as qt,LV as r,fv as ra,rC as ri,mP as rn,O as ro,mO as rr,T as rs,$z as rt,HV as s,hv as sa,KS as si,JN as sn,cl as so,BD as sr,sc as ss,vz as st,zV as t,Eg as ta,uC as ti,_P as tn,Ol as to,yO as tr,S as ts,eB as tt,DV as u,ov as ua,hC as ui,tN as un,bl as uo,ED as ur,WR as ut,ZB as v,Vg as va,iS as vi,sM as vn,N as vo,DE as vr,HL as vt,IB as w,iv as wa,Dx as wi,eM as wn,ac as wo,nE as wr,TL as wt,_B as x,bg as xa,dS as xi,aM as xn,Hl as xo,EE as xr,KL as xt,EB as y,Hg as ya,rS as yi,rM as yn,sl as yo,AE as yr,qL as yt,KB as z,yf as za,bb as zi,NA as zn,zc as zo,uT as zr,gI as zt};
402
+ //# sourceMappingURL=push-payload-BeU1ADYt.js.map