fnloom 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (587) hide show
  1. package/README.md +27 -20
  2. package/package.json +14 -11
  3. package/packages/build/package.json +2 -2
  4. package/packages/build/src/tests.ts +2 -2
  5. package/packages/cli/package.json +1 -1
  6. package/packages/cli/src/cli.ts +2 -2
  7. package/packages/cli/src/command.ts +2 -2
  8. package/packages/cli/src/commands/install.ts +1 -1
  9. package/packages/cli/src/commands/mcp.ts +6 -6
  10. package/packages/cli/src/commands/store.ts +3 -3
  11. package/packages/cli/src/hub.ts +25 -25
  12. package/packages/cli/src/index.ts +1 -1
  13. package/packages/cli/src/io.ts +2 -2
  14. package/packages/cli/src/local.ts +7 -7
  15. package/packages/cli/src/premade.ts +1 -1
  16. package/packages/core/package.json +4 -4
  17. package/packages/core/src/auto-pair.ts +1 -1
  18. package/packages/core/src/connections.ts +1 -14
  19. package/packages/core/src/context-graph.ts +1 -1
  20. package/packages/core/src/data.ts +1 -1
  21. package/packages/core/src/https.ts +2 -2
  22. package/packages/core/src/identity.ts +1 -1
  23. package/packages/core/src/image-embeddings.ts +1 -1
  24. package/packages/core/src/index.ts +5 -7
  25. package/packages/core/src/link.ts +1 -1
  26. package/packages/core/src/manifest.ts +2 -2
  27. package/packages/core/src/mention-search.ts +1 -1
  28. package/packages/core/src/model-calls.ts +1 -1
  29. package/packages/core/src/package.ts +1 -1
  30. package/packages/core/src/ports.ts +2 -2
  31. package/packages/core/src/query.ts +1 -1
  32. package/packages/core/src/records/chat.ts +1 -1
  33. package/packages/core/src/records/runs.ts +1 -1
  34. package/packages/core/src/records/spend.ts +4 -0
  35. package/packages/core/src/registries.ts +9 -3
  36. package/packages/core/src/sso.ts +2 -2
  37. package/packages/core/src/stores.ts +1 -1
  38. package/packages/core/src/suggestions.ts +2 -2
  39. package/packages/core/src/system-pages.ts +32 -6
  40. package/packages/core/src/tables.ts +233 -0
  41. package/packages/core/src/visuals.ts +47 -139
  42. package/packages/core/src/web.ts +2 -2
  43. package/packages/core/src/widgets-v1.ts +78 -1
  44. package/packages/hub/package.json +13 -11
  45. package/packages/hub/src/api/admin-ops.ts +5 -5
  46. package/packages/hub/src/api/auth.ts +2 -2
  47. package/packages/hub/src/api/https.ts +6 -6
  48. package/packages/hub/src/api/identities.ts +1 -1
  49. package/packages/hub/src/api/reads.ts +1 -1
  50. package/packages/hub/src/api/secrets.ts +1 -1
  51. package/packages/hub/src/api/serve.ts +2 -2
  52. package/packages/hub/src/api/sso-route.ts +2 -2
  53. package/packages/hub/src/api/sso.ts +6 -6
  54. package/packages/hub/src/api/testing/rig.ts +1 -1
  55. package/packages/hub/src/api/tls.ts +2 -2
  56. package/packages/hub/src/api/web/auth.ts +1 -1
  57. package/packages/hub/src/api/web/find.ts +1 -1
  58. package/packages/hub/src/api/web/pages.ts +4 -3
  59. package/packages/hub/src/api/web/pickers.ts +4 -4
  60. package/packages/hub/src/boot/env.ts +82 -78
  61. package/packages/hub/src/boot/hub-fns.ts +1 -1
  62. package/packages/hub/src/boot/identity.ts +2 -2
  63. package/packages/hub/src/boot/index.ts +1 -1
  64. package/packages/hub/src/boot/info.ts +1 -1
  65. package/packages/hub/src/boot/keys.ts +6 -6
  66. package/packages/hub/src/boot/log.ts +4 -4
  67. package/packages/hub/src/boot/modules.ts +4 -4
  68. package/packages/hub/src/boot/services.ts +9 -9
  69. package/packages/hub/src/boot/start.ts +23 -23
  70. package/packages/hub/src/chat/cache.ts +1 -1
  71. package/packages/hub/src/chat/chat.ts +1 -1
  72. package/packages/hub/src/chat/compare.ts +2 -2
  73. package/packages/hub/src/chat/deliveries.ts +1 -1
  74. package/packages/hub/src/chat/deps.ts +3 -3
  75. package/packages/hub/src/chat/enrich.ts +7 -7
  76. package/packages/hub/src/chat/env.ts +20 -20
  77. package/packages/hub/src/chat/mention-requests.ts +1 -1
  78. package/packages/hub/src/chat/mention-search.ts +1 -1
  79. package/packages/hub/src/chat/mentions.ts +3 -3
  80. package/packages/hub/src/chat/notifications.ts +2 -2
  81. package/packages/hub/src/chat/presence.ts +2 -2
  82. package/packages/hub/src/chat/sessions.ts +2 -2
  83. package/packages/hub/src/chat/suggestions.ts +8 -8
  84. package/packages/hub/src/chat/testing.ts +1 -1
  85. package/packages/hub/src/chat/turns.ts +6 -6
  86. package/packages/hub/src/chat/undo.ts +1 -1
  87. package/packages/hub/src/connections/create.ts +1 -1
  88. package/packages/hub/src/connections/env.ts +2 -2
  89. package/packages/hub/src/connections/service.ts +5 -9
  90. package/packages/hub/src/contextor/contextors.ts +9 -9
  91. package/packages/hub/src/contextor/crawl.ts +1 -1
  92. package/packages/hub/src/contextor/create.ts +5 -5
  93. package/packages/hub/src/contextor/dynamic.ts +5 -5
  94. package/packages/hub/src/contextor/env.ts +46 -46
  95. package/packages/hub/src/contextor/injected.ts +1 -1
  96. package/packages/hub/src/contextor/limits.ts +9 -9
  97. package/packages/hub/src/contextor/planner.ts +11 -11
  98. package/packages/hub/src/contextor/testing.ts +1 -1
  99. package/packages/hub/src/data/env.ts +3 -3
  100. package/packages/hub/src/data/service.ts +5 -5
  101. package/packages/hub/src/execution/agent.ts +8 -8
  102. package/packages/hub/src/execution/ai.ts +7 -7
  103. package/packages/hub/src/execution/create.ts +11 -6
  104. package/packages/hub/src/execution/env.ts +16 -16
  105. package/packages/hub/src/execution/executors.ts +2 -2
  106. package/packages/hub/src/execution/gateway.ts +1 -1
  107. package/packages/hub/src/execution/index.ts +1 -1
  108. package/packages/hub/src/execution/ledger.ts +2 -2
  109. package/packages/hub/src/execution/limits.ts +2 -2
  110. package/packages/hub/src/execution/models.ts +2 -2
  111. package/packages/hub/src/execution/ports.ts +1 -1
  112. package/packages/hub/src/execution/providers.ts +55 -11
  113. package/packages/hub/src/execution/queues.ts +6 -6
  114. package/packages/hub/src/execution/runs.ts +10 -10
  115. package/packages/hub/src/execution/stream-guard.ts +2 -2
  116. package/packages/hub/src/execution/testing.ts +5 -5
  117. package/packages/hub/src/execution/wire.ts +3 -3
  118. package/packages/hub/src/fns/auto.ts +2 -2
  119. package/packages/hub/src/fns/client-logs.ts +2 -2
  120. package/packages/hub/src/fns/create.ts +2 -2
  121. package/packages/hub/src/fns/decided.ts +2 -2
  122. package/packages/hub/src/fns/env.ts +14 -14
  123. package/packages/hub/src/fns/examples.ts +3 -3
  124. package/packages/hub/src/fns/facts.ts +5 -5
  125. package/packages/hub/src/fns/search.ts +5 -5
  126. package/packages/hub/src/graph/graph.ts +1 -1
  127. package/packages/hub/src/index/context-sections.ts +1 -1
  128. package/packages/hub/src/index/embedders.ts +3 -3
  129. package/packages/hub/src/index/env.ts +12 -12
  130. package/packages/hub/src/index/index.ts +1 -1
  131. package/packages/hub/src/index/indexer.ts +4 -4
  132. package/packages/hub/src/index/search.ts +1 -1
  133. package/packages/hub/src/index/testing.ts +2 -2
  134. package/packages/hub/src/link/build.ts +32 -32
  135. package/packages/hub/src/link/env.ts +14 -14
  136. package/packages/hub/src/link/grants.ts +10 -10
  137. package/packages/hub/src/link/lifecycle.ts +4 -4
  138. package/packages/hub/src/link/migrate-api.ts +55 -15
  139. package/packages/hub/src/link/pairing.ts +1 -1
  140. package/packages/hub/src/link/process.ts +1 -1
  141. package/packages/hub/src/link/rig.ts +12 -12
  142. package/packages/hub/src/link/supervisor.ts +1 -1
  143. package/packages/hub/src/mcp/calls.ts +6 -6
  144. package/packages/hub/src/mcp/create.ts +5 -5
  145. package/packages/hub/src/mcp/env.ts +6 -6
  146. package/packages/hub/src/mcp/fns.ts +2 -2
  147. package/packages/hub/src/mcp/index.ts +2 -2
  148. package/packages/hub/src/mcp/sources.ts +3 -3
  149. package/packages/hub/src/mcp/tokens.ts +1 -1
  150. package/packages/hub/src/models/create.ts +1 -1
  151. package/packages/hub/src/models/decide.ts +2 -2
  152. package/packages/hub/src/models/index.ts +1 -1
  153. package/packages/hub/src/models/roles.ts +12 -12
  154. package/packages/hub/src/query/env.ts +5 -5
  155. package/packages/hub/src/query/sources.ts +3 -3
  156. package/packages/hub/src/questions/plans.ts +1 -1
  157. package/packages/hub/src/questions/worker.ts +2 -2
  158. package/packages/hub/src/resources/context.ts +3 -3
  159. package/packages/hub/src/resources/converters.ts +2 -2
  160. package/packages/hub/src/resources/create.ts +6 -6
  161. package/packages/hub/src/resources/env.ts +15 -15
  162. package/packages/hub/src/resources/fetch.ts +5 -5
  163. package/packages/hub/src/resources/forms.ts +5 -5
  164. package/packages/hub/src/resources/index.ts +1 -1
  165. package/packages/hub/src/resources/library.ts +2 -2
  166. package/packages/hub/src/resources/raw.ts +1 -1
  167. package/packages/hub/src/resources/reader.ts +2 -2
  168. package/packages/hub/src/resources/sqlite-files.ts +1 -1
  169. package/packages/hub/src/resources/storage.ts +5 -5
  170. package/packages/hub/src/resources/testing.ts +6 -6
  171. package/packages/hub/src/store/env.ts +4 -4
  172. package/packages/hub/src/store/hybrid.ts +4 -4
  173. package/packages/hub/src/store/sqlite.ts +3 -3
  174. package/packages/hub/src/stores/drivers.ts +2 -2
  175. package/packages/hub/src/stores/host.ts +3 -3
  176. package/packages/hub/src/stores/moves.ts +2 -2
  177. package/packages/hub/src/stores/service.ts +2 -2
  178. package/packages/hub/src/tables/env.ts +3 -3
  179. package/packages/hub/src/tables/index.ts +5 -5
  180. package/packages/hub/src/tables/service.ts +7 -7
  181. package/packages/sdk/AUTHORING.md +1206 -881
  182. package/packages/sdk/package.json +11 -8
  183. package/packages/sdk/src/agent.ts +1 -1
  184. package/packages/sdk/src/app-parts.ts +95 -0
  185. package/packages/sdk/src/authored.ts +26 -0
  186. package/packages/sdk/src/authoring.ts +13 -30
  187. package/packages/sdk/src/client-runtime.ts +24 -1
  188. package/packages/sdk/src/client-ui/AddServiceDialog.vue +43 -0
  189. package/packages/sdk/src/client-ui/InstanceNameField.vue +29 -0
  190. package/packages/sdk/src/client-ui/PairRowsEditor.vue +74 -0
  191. package/packages/sdk/src/client-ui/RemoteAuthFields.vue +95 -0
  192. package/packages/sdk/src/client-ui/ServiceRows.vue +57 -0
  193. package/packages/sdk/src/client-ui/draft.ts +10 -0
  194. package/packages/sdk/src/client-ui/host.ts +37 -0
  195. package/packages/sdk/src/client-ui/index.ts +19 -0
  196. package/packages/sdk/src/client-ui/loaded.ts +69 -0
  197. package/packages/sdk/src/client-ui/problems.ts +98 -0
  198. package/packages/sdk/src/client-ui/remote-config.ts +199 -0
  199. package/packages/sdk/src/client-ui/service-rows.ts +25 -0
  200. package/packages/sdk/src/client-ui/state.ts +14 -0
  201. package/packages/sdk/src/client-ui/testing.ts +147 -0
  202. package/packages/sdk/src/client-ui/vue-shim.d.ts +13 -0
  203. package/packages/sdk/src/client.ts +82 -11
  204. package/packages/sdk/src/hub.ts +4 -4
  205. package/packages/sdk/src/index.ts +13 -9
  206. package/packages/sdk/src/page-parts.ts +4 -0
  207. package/packages/sdk/src/program/env.ts +7 -7
  208. package/packages/sdk/src/program/runtime.ts +5 -5
  209. package/packages/sdk/src/program/tools.ts +3 -3
  210. package/packages/sdk/src/remote-auth.ts +128 -7
  211. package/packages/sdk/src/server/context-files.ts +1 -1
  212. package/packages/sdk/src/server/env.ts +36 -36
  213. package/packages/sdk/src/server/fake-hub-widgets.ts +7 -6
  214. package/packages/sdk/src/server/host.ts +28 -28
  215. package/packages/sdk/src/server/index.ts +2 -2
  216. package/packages/sdk/src/server/live.ts +4 -4
  217. package/packages/sdk/src/server/llm-wire.ts +4 -4
  218. package/packages/sdk/src/server/pairing.ts +1 -1
  219. package/packages/sdk/src/server/results.ts +4 -4
  220. package/packages/sdk/src/server/socket-guard.ts +1 -1
  221. package/packages/sdk/src/server/start-gate.ts +2 -2
  222. package/packages/sdk/src/server/store/engines.ts +2 -2
  223. package/packages/sdk/src/server/store/keeper.ts +2 -2
  224. package/packages/sdk/src/server/supervise.ts +4 -4
  225. package/packages/sdk/src/testing/env.ts +6 -6
  226. package/packages/sdk/src/testing/hub.ts +3 -1
  227. package/packages/sdk/src/testing/models.ts +3 -3
  228. package/packages/sdk/src/testing/openrouter.ts +3 -2
  229. package/packages/sdk/src/testing/preview.ts +7 -7
  230. package/packages/sdk/src/widgets.ts +21 -136
  231. package/packages/sdk/tsconfig.json +2 -2
  232. package/packages/web/dist/assets/{ActorSettingsView-v2k7v454.js → ActorSettingsView-CDszUbHz.js} +2 -2
  233. package/packages/web/dist/assets/AdminLayout-CFIz4GsQ.js +2 -0
  234. package/packages/web/dist/assets/{AdminLayout-1hbRPV3d.css → AdminLayout-ggcdQGlQ.css} +1 -1
  235. package/packages/web/dist/assets/{AppPage-CFmKZS8G.js → AppPage-BvoVTk6h.js} +2 -2
  236. package/packages/web/dist/assets/{AutoPairPicker-C61gihmh.js → AutoPairPicker-CLjD-muP.js} +2 -2
  237. package/packages/web/dist/assets/{BrowserFrame-Sq9EmQRT.js → BrowserFrame-BcN-A76X.js} +2 -2
  238. package/packages/web/dist/assets/ChatPage-DhTpAyM2.js +4 -0
  239. package/packages/web/dist/assets/{ChatPage-CbsRmktV.css → ChatPage-DjPv238m.css} +1 -1
  240. package/packages/web/dist/assets/{CodeViewer-tUNXZB77.js → CodeViewer-K9jrTmFO.js} +2 -2
  241. package/packages/web/dist/assets/ConfigWithCustom-BvrvSVIp.js +3 -0
  242. package/packages/web/dist/assets/{ConfirmDialog-Dd3E4sJt.js → ConfirmDialog-BDvLleYf.js} +2 -2
  243. package/packages/web/dist/assets/{ConnectPage-CX9acyQH.js → ConnectPage-Dg6IPNNh.js} +2 -2
  244. package/packages/web/dist/assets/ContextItemPage-qisBQetR.js +2 -0
  245. package/packages/web/dist/assets/ContextPage-DXa6Yqk-.js +3 -0
  246. package/packages/web/dist/assets/{ContextRow-DrtPumZ5.js → ContextRow-DDYnYRaL.js} +2 -2
  247. package/packages/web/dist/assets/{DataPage-DDSsxHro.js → DataPage-DOE_pKAY.js} +2 -2
  248. package/packages/web/dist/assets/DataTypePage-BnP_JELT.js +2 -0
  249. package/packages/web/dist/assets/{DataTypePage-Cr238Hx_.css → DataTypePage-CWrWvUPs.css} +1 -1
  250. package/packages/web/dist/assets/{DesignPage-6e0XbOFC.js → DesignPage-B9MJbF10.js} +3 -3
  251. package/packages/web/dist/assets/{ExplorePage-B7ND0W0l.js → ExplorePage-cRDQZRea.js} +2 -2
  252. package/packages/web/dist/assets/{FnPill-Cp3KuLmP.js → FnPill-CbLZCXYM.js} +2 -2
  253. package/packages/web/dist/assets/{FnView-C0XZdnsS.js → FnView-CG_wBKTP.js} +2 -2
  254. package/packages/web/dist/assets/{FnsView-GTH3p7a0.js → FnsView-BybyK12w.js} +2 -2
  255. package/packages/web/dist/assets/{GinExprView-DGxns6lH.js → GinExprView-BYCKSD_n.js} +2 -2
  256. package/packages/web/dist/assets/{GinForm-BDBUzuDP.js → GinForm-CXjYVf2_.js} +2 -2
  257. package/packages/web/dist/assets/{GinTypeView-CUsymbVf.js → GinTypeView-Bmbmx9e_.js} +2 -2
  258. package/packages/web/dist/assets/{GinValueView-jsKIfiEA.js → GinValueView-CWUzS7ti.js} +2 -2
  259. package/packages/web/dist/assets/{GraphPage-BCcPPsHu.js → GraphPage-D6OhckfJ.js} +2 -2
  260. package/packages/web/dist/assets/GraphPanel-BTitgA-K.js +2 -0
  261. package/packages/web/dist/assets/{HubPicker-EoOErgmk.js → HubPicker-DVly8dLD.js} +2 -2
  262. package/packages/web/dist/assets/{InboxApprovals-Dkq7DFp_.js → InboxApprovals-BF84edZU.js} +2 -2
  263. package/packages/web/dist/assets/{InboxPage-CHhslePq.js → InboxPage-DohZ9EDP.js} +2 -2
  264. package/packages/web/dist/assets/InjectedList-e6qr1kdU.js +2 -0
  265. package/packages/web/dist/assets/{InstallDialog-D-VwfZYF.js → InstallDialog-JJCKYs2s.js} +2 -2
  266. package/packages/web/dist/assets/InstanceTypes-BqUzx87o.js +2 -0
  267. package/packages/web/dist/assets/InstanceView-C73pev7A.js +2 -0
  268. package/packages/web/dist/assets/{ItemHistory-NQAP69ma.js → ItemHistory-dbGgOZsw.js} +2 -2
  269. package/packages/web/dist/assets/LimitsView-Ddp5WakY.js +2 -0
  270. package/packages/web/dist/assets/{ListSearch-BunVrDO0.js → ListSearch-CYNNAuMB.js} +2 -2
  271. package/packages/web/dist/assets/{LlmCallDetails-BoVNDTVs.js → LlmCallDetails-C9H5Hc2J.js} +2 -2
  272. package/packages/web/dist/assets/{LlmCallsView-BGpV92RC.js → LlmCallsView-CBqyZ8Cj.js} +2 -2
  273. package/packages/web/dist/assets/{LoadState-h-K9bTYc.js → LoadState-B2YhZlyC.js} +2 -2
  274. package/packages/web/dist/assets/McpDialog-DhlLklIq.js +2 -0
  275. package/packages/web/dist/assets/{McpView-GPXdCMne.js → McpView-D_ZmNO56.js} +2 -2
  276. package/packages/web/dist/assets/{McpsView-DJIR2JX5.js → McpsView-9_gwBuzw.js} +2 -2
  277. package/packages/web/dist/assets/{MemoryDialog-BTeIHQyA.js → MemoryDialog-pTHIxKEX.js} +2 -2
  278. package/packages/web/dist/assets/{ModelCallsView-DMcnwF2S.js → ModelCallsView-FHv2XWRX.js} +2 -2
  279. package/packages/web/dist/assets/{ModelPicker-CgkMFxSO.js → ModelPicker-EqOuvVnE.js} +2 -2
  280. package/packages/web/dist/assets/ModelsView-D9UaL4PX.js +2 -0
  281. package/packages/web/dist/assets/{NotFoundPage-Tk92K7HN.js → NotFoundPage-BsuJysan.js} +2 -2
  282. package/packages/web/dist/assets/{PairPage-D0BK8CCw.js → PairPage-B_ZXsbL4.js} +2 -2
  283. package/packages/web/dist/assets/{PanelHost-C-gKrxAk.js → PanelHost-Dx-vNNl5.js} +2 -2
  284. package/packages/web/dist/assets/PeopleView-D6dmEgMs.js +2 -0
  285. package/packages/web/dist/assets/{PeopleView-CJ8yArTh.css → PeopleView-DBxdbT1C.css} +1 -1
  286. package/packages/web/dist/assets/{PoliciesView-BRi-QAuo.js → PoliciesView-Bn4rm-ao.js} +2 -2
  287. package/packages/web/dist/assets/{RefusalList-DVO0bmeB.js → RefusalList-aosRD1ie.js} +2 -2
  288. package/packages/web/dist/assets/RendererHost-Ym_SMkhp.css +1 -0
  289. package/packages/web/dist/assets/RendererHost-rjnpSgyQ.js +2 -0
  290. package/packages/web/dist/assets/{ResourceViewer-Do0chYxU.js → ResourceViewer-C4tRColf.js} +2 -2
  291. package/packages/web/dist/assets/ResourcesPage-7mCLBORZ.js +2 -0
  292. package/packages/web/dist/assets/ResultGrid-CL2WSYQH.css +1 -0
  293. package/packages/web/dist/assets/ResultGrid-GIMoQUAr.js +2 -0
  294. package/packages/web/dist/assets/{ReviewSummaryStrip-DO3p64Qj.js → ReviewSummaryStrip-Bvjn3Iq8.js} +2 -2
  295. package/packages/web/dist/assets/ReviewView-DIqsUedT.js +3 -0
  296. package/packages/web/dist/assets/{RuleRow-DX9v4iGP.js → RuleRow-zRg-e8Vj.js} +2 -2
  297. package/packages/web/dist/assets/RunCard-C7wOGaw8.js +2 -0
  298. package/packages/web/dist/assets/RunCard-CSDiz-Nt.css +1 -0
  299. package/packages/web/dist/assets/{RunDetails-DjR206q6.js → RunDetails-W4GbE6AE.js} +2 -2
  300. package/packages/web/dist/assets/{RunDot-lHRICdM5.js → RunDot-C46uzzNM.js} +2 -2
  301. package/packages/web/dist/assets/{RunPage-CbAQ_WPR.js → RunPage-DPLtZpeB.js} +2 -2
  302. package/packages/web/dist/assets/{RunProgress-C3-B4tQf.js → RunProgress-Cr_6TBaF.js} +2 -2
  303. package/packages/web/dist/assets/{RunsView-DMkPmkqX.js → RunsView-tU350TPK.js} +2 -2
  304. package/packages/web/dist/assets/SettingsPage-B8QmmMN3.js +3 -0
  305. package/packages/web/dist/assets/{SettingsPage-t03BqXw8.css → SettingsPage-BTl3Ie4F.css} +1 -1
  306. package/packages/web/dist/assets/SignInPage-CXxLf7Rp.css +1 -0
  307. package/packages/web/dist/assets/{SignInPage-ByqGEZfj.js → SignInPage-DTwdqlnB.js} +2 -2
  308. package/packages/web/dist/assets/{StatusBadge-CXne0sRZ.js → StatusBadge-D7wKMAcD.js} +2 -2
  309. package/packages/web/dist/assets/{StorePlacementStep-B6SwTmdM.js → StorePlacementStep-C04nRU-u.js} +2 -2
  310. package/packages/web/dist/assets/{SystemConfig-vQDL_eUl.js → SystemConfig-CE3keXWq.js} +2 -2
  311. package/packages/web/dist/assets/SystemPageHost-CEhz4li8.js +2 -0
  312. package/packages/web/dist/assets/SystemPageHost-DX7LrFoN.css +1 -0
  313. package/packages/web/dist/assets/SystemView-CBFzEGfm.js +2 -0
  314. package/packages/web/dist/assets/SystemsView-0G8JntMV.js +2 -0
  315. package/packages/web/dist/assets/TableView-BK0uwLHl.js +3 -0
  316. package/packages/web/dist/assets/TableView-B_4MViVb.css +1 -0
  317. package/packages/web/dist/assets/{TableViewer-Boxx86f5.js → TableViewer-nbMInGJJ.js} +3 -3
  318. package/packages/web/dist/assets/{ThemePicker-CIg_oRQX.js → ThemePicker-fZpVSYqG.js} +2 -2
  319. package/packages/web/dist/assets/{TurnTree-Ecm0yA5g.js → TurnTree-Co-iBqhT.js} +2 -2
  320. package/packages/web/dist/assets/{UserMessage-BtECa8ka.css → UserMessage-B63G9sxC.css} +1 -1
  321. package/packages/web/dist/assets/{UserMessage-BlnqZDVU.js → UserMessage-CDjUxKY0.js} +6 -6
  322. package/packages/web/dist/assets/{ValueVisual-C-MWpp7c.js → ValueVisual-EJnCKgSy.js} +2 -2
  323. package/packages/web/dist/assets/{fn-modal-B98MR7JN.js → fn-modal-DtE65mFt.js} +2 -2
  324. package/packages/web/dist/assets/{fn-notices-CfTa1E8y.js → fn-notices-CCZ-DFbi.js} +2 -2
  325. package/packages/web/dist/assets/{formats-JwoKfXIq.js → formats-CyHV2siv.js} +2 -2
  326. package/packages/web/dist/assets/index-BY7M8QUk.css +1 -0
  327. package/packages/web/dist/assets/index-OZS2EluT.js +4 -0
  328. package/packages/web/dist/assets/{labels-BFbk11BE.js → labels-CT7_K0Pt.js} +2 -2
  329. package/packages/web/dist/assets/{layout-D1gf481r.js → layout-B6fBDg80.js} +2 -2
  330. package/packages/web/dist/assets/loaded-LaPjk6mK.js +2 -0
  331. package/packages/web/dist/assets/{metrics-CBPX3W5Y.js → metrics-9n8bKI7u.js} +2 -2
  332. package/packages/web/dist/assets/problems--AW4igVY.js +2 -0
  333. package/packages/web/dist/assets/{push-payload-BeU1ADYt.js → push-payload-B3EcrsVz.js} +64 -64
  334. package/packages/web/dist/assets/record-edits-B-FWAbxR.js +2 -0
  335. package/packages/web/dist/assets/{review-fP-l9D6H.js → review-uLESCEz1.js} +3 -3
  336. package/packages/web/dist/assets/routes-B7Zmt8wh.js +4 -0
  337. package/packages/web/dist/assets/{runs-CveC2kKo.js → runs-CUb2PTFg.js} +2 -2
  338. package/packages/web/dist/assets/{shared-LbaIHjbV.js → shared-Bxhw_9et.js} +2 -2
  339. package/packages/web/dist/assets/{sources-VPrtgLIi.js → sources-YgkjgFLe.js} +2 -2
  340. package/packages/web/dist/assets/src-DY1fSFJS.js +43 -0
  341. package/packages/web/dist/assets/state-ChQDWWj-.js +2 -0
  342. package/packages/web/dist/assets/{systems-BqE3WTSF.js → systems-CjwjRySu.js} +2 -2
  343. package/packages/web/dist/assets/table-host-B_D9dmCz.js +2 -0
  344. package/packages/web/dist/assets/tables-CaxIuHdw.js +2 -0
  345. package/packages/web/dist/assets/{ui-BzgWquIU.js → ui-DWjytmDS.js} +5 -5
  346. package/packages/web/dist/assets/{url-DKGcECT1.js → url-DbGOI14W.js} +2 -2
  347. package/packages/web/dist/index.html +49 -47
  348. package/packages/web/dist/sw.js +1 -1
  349. package/packages/web/package.json +2 -4
  350. package/premade/claude.zip +0 -0
  351. package/premade/database.zip +0 -0
  352. package/premade/web.zip +0 -0
  353. package/scripts/dev-env.ts +9 -9
  354. package/scripts/run-stack.ts +15 -15
  355. package/scripts/stack.ts +3 -3
  356. package/scripts/start.ts +18 -18
  357. package/systems/api/client/ApiServiceForm.vue +55 -0
  358. package/systems/api/client/ServiceList.vue +90 -0
  359. package/systems/api/client/ServicePage.vue +142 -0
  360. package/systems/api/client/ServicesPage.vue +32 -0
  361. package/systems/api/client/index.ts +15 -0
  362. package/systems/api/client/logic.ts +140 -0
  363. package/systems/api/client/state.ts +92 -0
  364. package/systems/api/package.json +9 -6
  365. package/systems/api/server/authoring.ts +2 -1
  366. package/systems/api/server/env.ts +1 -1
  367. package/systems/api/server/guard.ts +1 -1
  368. package/systems/api/server/http.ts +3 -2
  369. package/systems/api/server/impl.ts +3 -2
  370. package/systems/api/server/main.ts +11 -7
  371. package/systems/api/server/openapi.ts +1 -1
  372. package/systems/api/server/program.ts +2 -1
  373. package/systems/api/server/services.ts +2 -1
  374. package/systems/api/shared/http.ts +2 -1
  375. package/systems/api/shared/index.ts +15 -5
  376. package/{packages/core/src/programs.ts → systems/api/shared/services.ts} +7 -51
  377. package/systems/api/system.json +2 -1
  378. package/systems/api/tsconfig.json +2 -2
  379. package/systems/code/package.json +4 -3
  380. package/systems/code/server/authoring.ts +2 -1
  381. package/systems/code/server/impl.ts +2 -1
  382. package/systems/code/server/main.ts +5 -5
  383. package/systems/code/shared/index.ts +2 -3
  384. package/systems/code/shared/program.ts +23 -0
  385. package/systems/embedder/package.json +1 -1
  386. package/systems/embedder/server/env.ts +1 -1
  387. package/systems/embedder/server/main.ts +5 -5
  388. package/systems/embedder/shared/index.ts +1 -1
  389. package/systems/fs/client/machines/fakes.ts +1 -1
  390. package/systems/fs/client/machines/files/fakes.ts +1 -1
  391. package/systems/fs/client/machines/palette.ts +3 -2
  392. package/systems/fs/context/authoring/parts/client.md +23 -5
  393. package/systems/fs/context/authoring/parts/client.reference/client.md +7 -16
  394. package/systems/fs/context/authoring/parts/client.reference/pageinbox.md +524 -0
  395. package/systems/fs/context/authoring/parts/client.reference/{resultview.md → visuals.md} +85 -116
  396. package/systems/fs/context/authoring/parts/client.reference.md +8 -8
  397. package/systems/fs/context/authoring/parts/context.md +1 -1
  398. package/systems/fs/context/authoring/parts/contract.md +1 -1
  399. package/systems/fs/context/authoring/parts/core-types/admin-ts.md +2 -2
  400. package/systems/fs/context/authoring/parts/core-types/connections-ts.md +12 -1
  401. package/systems/fs/context/authoring/parts/core-types/context-files-ts.md +2 -2
  402. package/systems/fs/context/authoring/parts/core-types/context-graph-ts.md +2 -2
  403. package/systems/fs/context/authoring/parts/core-types/contextdecl.md +2 -2
  404. package/systems/fs/context/authoring/parts/core-types/lifecycle-ts.md +27 -2
  405. package/systems/fs/context/authoring/parts/core-types/manifest.md +27 -2
  406. package/systems/fs/context/authoring/parts/core-types/manifestpatch.md +26 -2
  407. package/systems/fs/context/authoring/parts/core-types/modes-ts.md +3 -3
  408. package/systems/fs/context/authoring/parts/core-types/records-systems-ts.md +145 -1
  409. package/systems/fs/context/authoring/parts/core-types/registries-ts.md +98 -2
  410. package/systems/fs/context/authoring/parts/core-types/run-ts.md +2 -2
  411. package/systems/fs/context/authoring/parts/core-types/system-pages-ts.md +4 -2
  412. package/systems/fs/context/authoring/parts/core-types/system-providers-ts.md +2 -2
  413. package/systems/fs/context/authoring/parts/core-types/tables-ts.md +91 -0
  414. package/systems/fs/context/authoring/parts/core-types/web-ts.md +1 -2
  415. package/systems/fs/context/authoring/parts/core-types.md +5 -8
  416. package/systems/fs/context/authoring/parts/examples/server-main-ts.md +4 -4
  417. package/systems/fs/context/authoring/parts/examples/systems-fs-shared-index-ts-lines-568-660.md +1 -1
  418. package/systems/fs/context/authoring/parts/fns.md +1 -1
  419. package/systems/fs/context/authoring/parts/folder.md +6 -6
  420. package/systems/fs/context/authoring/parts/hub/hub-ctx-from-resource.md +2 -2
  421. package/systems/fs/context/authoring/parts/hub/hub-install-package.md +2 -2
  422. package/systems/fs/context/authoring/parts/hub.reference.md +3 -3
  423. package/systems/fs/context/authoring/parts/internals/manifestof.md +2 -2
  424. package/systems/fs/context/authoring/parts/internals/permissionargs.md +4 -4
  425. package/systems/fs/context/authoring/parts/kinds-agents.md +1 -1
  426. package/systems/fs/context/authoring/parts/kinds-agents.reference/authoringsession.md +7 -5
  427. package/systems/fs/context/authoring/parts/kinds-agents.reference/kind.md +4 -4
  428. package/systems/fs/context/authoring/parts/outcomes.md +2 -2
  429. package/systems/fs/context/authoring/parts/outcomes.reference.md +2 -2
  430. package/systems/fs/context/authoring/parts/packaging.md +4 -4
  431. package/systems/fs/context/authoring/parts/remote.md +5 -5
  432. package/systems/fs/context/authoring/parts/remote.reference.md +201 -17
  433. package/systems/fs/context/authoring/parts/server.md +7 -7
  434. package/systems/fs/context/authoring/parts/server.reference.md +15 -15
  435. package/systems/fs/context/authoring/parts/testing.reference/equal.md +3 -3
  436. package/systems/fs/context/authoring/parts/testing.reference/fakehub.md +1 -1
  437. package/systems/fs/context/authoring/parts/testing.reference/kindprops.md +22 -10
  438. package/systems/fs/context/authoring/parts/testing.reference/{openmemorystore.md → storeconnection.md} +7 -19
  439. package/systems/fs/context/authoring/parts/testing.reference.md +5 -5
  440. package/systems/fs/context/authoring/parts/widgets.md +32 -22
  441. package/systems/fs/context/authoring/parts/widgets.reference.md +503 -9
  442. package/systems/fs/package.json +3 -3
  443. package/systems/fs/server/hosting.ts +10 -10
  444. package/systems/fs/server/main.ts +8 -8
  445. package/systems/fs/server/shell.ts +1 -1
  446. package/systems/fs/shared/index.ts +1 -1
  447. package/systems/google-calendar/package.json +1 -1
  448. package/systems/google-calendar/server/main.ts +4 -4
  449. package/systems/input/package.json +3 -3
  450. package/systems/input/server/main.ts +6 -6
  451. package/systems/mcp/client/McpServerForm.vue +99 -0
  452. package/systems/mcp/client/ServerList.vue +78 -0
  453. package/systems/mcp/client/ServerPage.vue +194 -0
  454. package/systems/mcp/client/ServersPage.vue +32 -0
  455. package/systems/mcp/client/index.ts +15 -0
  456. package/systems/mcp/client/logic.ts +224 -0
  457. package/systems/mcp/client/state.ts +128 -0
  458. package/systems/mcp/package.json +9 -6
  459. package/systems/mcp/server/dial.ts +1 -1
  460. package/systems/mcp/server/impl.ts +2 -1
  461. package/systems/mcp/server/instance.ts +3 -5
  462. package/systems/mcp/server/main.ts +10 -6
  463. package/systems/mcp/server/mirror.ts +2 -3
  464. package/systems/mcp/server/oauth.ts +2 -1
  465. package/systems/mcp/server/server-link.ts +2 -1
  466. package/systems/mcp/shared/index.ts +15 -2
  467. package/{packages/core/src/mcp-servers.ts → systems/mcp/shared/servers.ts} +6 -5
  468. package/systems/mcp/system.json +2 -1
  469. package/systems/mcp/tsconfig.json +2 -2
  470. package/systems/ollama/package.json +3 -3
  471. package/systems/ollama/server/main.ts +5 -5
  472. package/systems/schedule/package.json +3 -3
  473. package/systems/schedule/server/main.ts +6 -6
  474. package/systems/template/README.md +2 -2
  475. package/systems/template/package.json +1 -1
  476. package/systems/template/server/main.ts +4 -4
  477. package/systems/widgets/client/ChipRow.vue +22 -0
  478. package/systems/widgets/client/ProposalCard.vue +6 -5
  479. package/systems/widgets/client/SavedWidget.vue +11 -8
  480. package/systems/widgets/client/WidgetChips.vue +137 -0
  481. package/systems/widgets/client/WidgetView.vue +32 -0
  482. package/systems/widgets/client/charts/ChartVisual.vue +157 -0
  483. package/systems/widgets/client/charts/chart-data.ts +230 -0
  484. package/systems/widgets/client/charts/echarts-setup.ts +69 -0
  485. package/systems/widgets/client/charts/export.ts +36 -0
  486. package/systems/widgets/client/charts/families/calendar.ts +105 -0
  487. package/systems/widgets/client/charts/families/category.ts +186 -0
  488. package/systems/widgets/client/charts/families/crosstab.ts +113 -0
  489. package/systems/widgets/client/charts/families/distribution.ts +160 -0
  490. package/systems/widgets/client/charts/families/finance.ts +96 -0
  491. package/systems/widgets/client/charts/families/gauge.ts +75 -0
  492. package/systems/widgets/client/charts/families/hierarchy.ts +166 -0
  493. package/systems/widgets/client/charts/families/index.ts +21 -0
  494. package/systems/widgets/client/charts/families/network.ts +140 -0
  495. package/systems/widgets/client/charts/families/part.ts +61 -0
  496. package/systems/widgets/client/charts/families/profile.ts +30 -0
  497. package/systems/widgets/client/charts/families/progress.ts +76 -0
  498. package/systems/widgets/client/charts/families/range.ts +107 -0
  499. package/systems/widgets/client/charts/families/time.ts +177 -0
  500. package/systems/widgets/client/charts/families/timeline.ts +114 -0
  501. package/systems/widgets/client/charts/families/wide.ts +41 -0
  502. package/systems/widgets/client/charts/index.ts +37 -0
  503. package/systems/widgets/client/charts/maths.ts +139 -0
  504. package/systems/widgets/client/charts/size.ts +39 -0
  505. package/systems/widgets/client/chips.ts +150 -0
  506. package/systems/widgets/client/index.ts +18 -5
  507. package/systems/widgets/client/proposal.ts +2 -1
  508. package/systems/widgets/package.json +7 -4
  509. package/systems/widgets/server/authoring.ts +13 -7
  510. package/systems/widgets/server/env.ts +1 -1
  511. package/systems/widgets/server/impl.ts +10 -6
  512. package/systems/widgets/server/main.ts +6 -6
  513. package/systems/widgets/server/run.ts +16 -9
  514. package/systems/widgets/server/upgrade.ts +34 -0
  515. package/systems/widgets/shared/args.ts +137 -0
  516. package/systems/widgets/shared/charts.ts +243 -0
  517. package/systems/widgets/shared/index.ts +12 -3
  518. package/{packages/sdk/src → systems/widgets/shared}/relative-dates.ts +2 -1
  519. package/systems/widgets/shared/spec.ts +208 -0
  520. package/{packages/sdk/src → systems/widgets/shared}/widget-check.ts +7 -9
  521. package/{packages/sdk/src → systems/widgets/shared}/widget-schema.ts +4 -4
  522. package/packages/core/src/remote-auth.ts +0 -111
  523. package/packages/core/src/widgets.ts +0 -427
  524. package/packages/web/dist/assets/AdminLayout-B6Jrc_4W.js +0 -2
  525. package/packages/web/dist/assets/ApiServiceForm-BxprSaAq.css +0 -1
  526. package/packages/web/dist/assets/ApiServiceForm-CuuQgOJc.js +0 -2
  527. package/packages/web/dist/assets/ApiServiceView-7bTHSO_Z.js +0 -2
  528. package/packages/web/dist/assets/ApiServiceView-BVmdRCjR.css +0 -1
  529. package/packages/web/dist/assets/ApiServicesView-BTLV6c8n.css +0 -1
  530. package/packages/web/dist/assets/ApiServicesView-BXi24n49.js +0 -2
  531. package/packages/web/dist/assets/ChartVisual-BnFG9aFi.css +0 -1
  532. package/packages/web/dist/assets/ChartVisual-C4mgw4wh.js +0 -11
  533. package/packages/web/dist/assets/ChatPage-CAhHE03Z.js +0 -4
  534. package/packages/web/dist/assets/ConfigWithCustom-D_-rY66L.js +0 -3
  535. package/packages/web/dist/assets/ContextItemPage-rUI3-T_L.js +0 -2
  536. package/packages/web/dist/assets/ContextPage-CtefzyKg.js +0 -3
  537. package/packages/web/dist/assets/DataTypePage-BW9fWaz8.js +0 -2
  538. package/packages/web/dist/assets/FnList-BCnb4kOB.css +0 -1
  539. package/packages/web/dist/assets/FnList-Bx6H-kux.js +0 -2
  540. package/packages/web/dist/assets/GraphPanel-9tztGHmu.js +0 -2
  541. package/packages/web/dist/assets/InjectedList-CSWqRiON.js +0 -2
  542. package/packages/web/dist/assets/InstanceTypes-D3rAEiE7.js +0 -2
  543. package/packages/web/dist/assets/InstanceView-DoH8C-1j.js +0 -2
  544. package/packages/web/dist/assets/LimitsView-DY2C9nYS.js +0 -2
  545. package/packages/web/dist/assets/McpDialog-DhOCk6_E.js +0 -2
  546. package/packages/web/dist/assets/McpServerForm-Cor3fI7s.js +0 -2
  547. package/packages/web/dist/assets/McpServerForm-DsHaf5Um.css +0 -1
  548. package/packages/web/dist/assets/McpServerView-7I76EznB.css +0 -1
  549. package/packages/web/dist/assets/McpServerView-ewXRPEmZ.js +0 -2
  550. package/packages/web/dist/assets/McpServersView-Dd0xmfws.js +0 -2
  551. package/packages/web/dist/assets/ModelsView-cMHygeiK.js +0 -2
  552. package/packages/web/dist/assets/PeopleView-DRfeNWK5.js +0 -2
  553. package/packages/web/dist/assets/RemoteAuthFields-CgiufuqQ.js +0 -2
  554. package/packages/web/dist/assets/RemoteAuthFields-Dm44vz2t.css +0 -1
  555. package/packages/web/dist/assets/ResourcesPage-BBx2u2mw.js +0 -2
  556. package/packages/web/dist/assets/ResultGrid-Bj-0I5HY.js +0 -2
  557. package/packages/web/dist/assets/ResultGrid-CuUQyTjW.css +0 -1
  558. package/packages/web/dist/assets/ReviewView-DZF9E1hb.js +0 -3
  559. package/packages/web/dist/assets/RunCard-BnrtK2Yp.js +0 -2
  560. package/packages/web/dist/assets/RunCard-CfyRaDLS.css +0 -1
  561. package/packages/web/dist/assets/ServiceRows-4WythFpF.js +0 -2
  562. package/packages/web/dist/assets/ServiceRows-HPQ0pN6b.css +0 -1
  563. package/packages/web/dist/assets/SettingsPage-BN4oSzoL.js +0 -3
  564. package/packages/web/dist/assets/SignInPage-Djx-M-0U.css +0 -1
  565. package/packages/web/dist/assets/SystemPageHost-BeZ-6N0-.css +0 -1
  566. package/packages/web/dist/assets/SystemPageHost-DrMrEPyh.js +0 -2
  567. package/packages/web/dist/assets/SystemView-Be6TBM4j.js +0 -2
  568. package/packages/web/dist/assets/SystemsView-DZtT3laz.js +0 -2
  569. package/packages/web/dist/assets/WidgetView-DQUDeFkB.css +0 -1
  570. package/packages/web/dist/assets/WidgetView-DX4ejNb6.js +0 -3
  571. package/packages/web/dist/assets/export-BwFkEtcm.js +0 -15
  572. package/packages/web/dist/assets/index-6ScWTFy2.js +0 -4
  573. package/packages/web/dist/assets/index-CEslGcrX.css +0 -1
  574. package/packages/web/dist/assets/problems-t1E_ovSz.js +0 -2
  575. package/packages/web/dist/assets/record-edits-Bfsi4lU3.js +0 -2
  576. package/packages/web/dist/assets/remote-config-BNQhSDzB.js +0 -2
  577. package/packages/web/dist/assets/routes-DV4IJpwe.js +0 -4
  578. package/packages/web/dist/assets/size-Bh__w5aI.js +0 -2
  579. package/packages/web/dist/assets/src-CT3TeFaM.js +0 -43
  580. package/packages/web/dist/assets/state-xfQqaQPX.js +0 -2
  581. package/packages/web/dist/assets/widget-host-B87MTaTn.js +0 -2
  582. package/packages/web/dist/assets/widgets-BBCuSS6E.js +0 -2
  583. package/systems/fs/context/authoring/parts/client.reference/textareaprops.md +0 -195
  584. package/systems/fs/context/authoring/parts/core-types/remote-auth-ts.md +0 -64
  585. package/systems/fs/context/authoring/parts/core-types/widgets-ts.md +0 -303
  586. package/systems/fs/context/authoring/parts/widgets.reference/hub-visuals.md +0 -627
  587. package/systems/fs/context/authoring/parts/widgets.reference/sourcecompatible.md +0 -154
@@ -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}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(`
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 e===void 0?null:O.parse(JSON.parse(JSON.stringify(e)))}function nl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var rl={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`},il=e=>v().regex(RegExp(`^${rl[e]}_.+$`),`expected a ${e} id starting with "${rl[e]}_"`).brand().describe(`${e} id`),al=e=>Object.hasOwn(rl,e);function ol(){return Object.fromEntries(Object.keys(rl).filter(al).map(e=>[e,il(e)]))}var k=v().regex(/^[A-Za-z_][A-Za-z0-9_.-]*$/),sl=ol(),A=sl.run,cl=sl.turn,j=sl.session,M=sl.actor,ll=sl.message,ul=sl.delivery,dl=sl.handlerCall,fl=sl.llmInteraction,pl=sl.pairing,ml=sl.pairingToken,hl=sl.policy,gl=sl.approval,_l=sl.budget,vl=sl.priorityRule,yl=sl.reservation,bl=sl.ledger,xl=sl.notification,Sl=sl.push,Cl=sl.secret,wl=sl.modelCategory,Tl=sl.provider,El=sl.sectionRule,Dl=sl.authSession,Ol=sl.modelCall,kl=sl.mcp,Al=sl.autoPair,jl=sl.connection,Ml=y().int().min(0),N=y().int(),P=y(),Nl=/^[a-z][a-z0-9-]*$/,F=v().regex(Nl).brand(),I=Wc([v().regex(Nl),`/`,v().min(1)]),Pl=C([D(`native`),I]);function Fl(e,t){return`${e}/${t}`}function Il(e){let t=e.indexOf(`/`);return{system:e.slice(0,t),local:e.slice(t+1)}}var Ll=[`urgent`,`interactive`,`normal`,`background`],Rl=E(Ll),zl=E([`user`,`llm`,`both`,`none`]),Bl=E([`user`,`group`,`agent`,`system`,`mcp`]),Vl=e=>S({items:x(e),cursor:v().optional()}),Hl=S({cursor:v().optional(),limit:y().int().min(1).max(200).optional()});function Ul(e){return e instanceof Error?e.message:String(e)}var Wl=`read`,Gl=`admin`,L=v().regex(Nl).brand(),Kl=L.parse(`main`),ql=S({system:F,instance:L}),Jl=v().regex(/^[a-z*][a-z0-9*-]*\/[A-Za-z0-9_.*-]+$/).brand(),Yl=Object.defineProperty,Xl=(e,t)=>{for(var n in t)Yl(e,n,{get:t[n],enumerable:!0})},R={};Xl(R,{array:()=>gp,boolean:()=>cp,codec:()=>Ap,conditional:()=>Cp,declare:()=>Np,default:()=>Ep,define:()=>Mp,dependent:()=>wp,discriminatedUnion:()=>bp,dispatch:()=>jp,enum:()=>dp,fromJSONSchema:()=>rp,int:()=>sp,intersection:()=>xp,json:()=>mp,literal:()=>up,module:()=>Pp,never:()=>fp,not:()=>Sp,null:()=>lp,nullable:()=>Dp,number:()=>op,object:()=>hp,optional:()=>Tp,record:()=>vp,ref:()=>Op,refOf:()=>kp,string:()=>ap,tuple:()=>_p,union:()=>yp,unknown:()=>pp});var Zl=Object.freeze({length:!0,range:!0,items:`all`,pattern:`full`}),Ql=Object.freeze({length:!1,range:!1,items:`none`,pattern:`none`}),$l=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:Zl,formats:`all`,examples:`keyword`,propertyOrdering:!1,rootObject:!1}),eu=Object.freeze({...$l,id:`people`,family:`people`,audience:`people`}),tu=Object.freeze({...$l,id:`openai`,family:`openai`,rootObject:!0,request:Object.freeze({maxTools:128})}),nu=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`ipv4`,`ipv6`,`uuid`]),ru=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:nu,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:tu}),iu=Object.freeze({...ru,id:`openai-finetuned-strict`,constraints:Ql,formats:new Set}),au=Object.freeze({...$l,id:`anthropic`,family:`anthropic`,rootObject:!0}),ou={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,limits:Object.freeze({maxObjectProperties:34}),request:Object.freeze({maxStrictTools:20,totals:Object.freeze({maxOptional:24,maxUnions:16,maxProperties:54})}),loose:au,alwaysStrictOutput:!0},su=Object.freeze({...ou,id:`anthropic-strict-output`,limits:Object.freeze({maxObjectOptional:12})}),cu=Object.freeze({...ou,output:su}),lu=`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.`,uu=Object.freeze({...$l,id:`google`,family:`google`,recursion:`guarded`,maxEnumValues:40,rootObject:!0,jsonInstruction:lu}),du=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:uu,jsonInstruction:lu}),fu=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:uu,jsonInstruction:lu}),pu=new Set([`date`,`time`,`date-time`,`email`,`uuid`,`ipv4`,`ipv6`,`uri`]),mu=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:pu,examples:`description`,propertyOrdering:!1,rootObject:!0}),hu=Object.freeze({...mu,id:`xai`,strict:!1}),gu=Object.freeze({...$l,id:`ollama`,family:`ollama`,rootObject:!0}),_u=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:Ql,formats:new Set,examples:`description`,propertyOrdering:!1,maxDepth:6,maxEnumValues:8,rootObject:!0}),vu=new Map,yu=new Map;function bu(e){vu.set(e.id,e);let t=yu.get(e.family)??{};e.strict?t.strict??=e:t.loose??=e,yu.set(e.family,t)}for(let e of[$l,eu,tu,ru,iu,au,cu,su,uu,du,fu,mu,hu,gu,_u])bu(e);var xu=new WeakMap;function Su(e){let t=xu.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`}),xu.set(e,t)),t}Object.freeze({properties:0,depth:0,stringChars:0,enumValues:0,enums:Object.freeze([]),optional:0,unions:0,objectProperties:0,objectOptional:0});function Cu(e){let t=0,n=0,r=0,i=0,a=0,o=0,s=0,c=[],l=e.$defs??{};for(let e of Object.keys(l))n+=e.length;let u=e=>{if(!e||typeof e!=`object`)return;if(Array.isArray(e)){for(let t of e)u(t);return}let l=e;if(l.properties&&typeof l.properties==`object`){let e=l.properties,r=new Set(Array.isArray(l.required)?l.required:[]),a=Object.keys(e);o=Math.max(o,a.length),s=Math.max(s,a.filter(e=>!r.has(e)).length);for(let[a,o]of Object.entries(e))t++,n+=a.length,r.has(a)||i++,u(o)}if(Array.isArray(l.enum)){let e=0;for(let t of l.enum)typeof t==`string`&&(e+=t.length);r+=l.enum.length,n+=e,c.push({values:l.enum.length,chars:e})}typeof l.const==`string`&&(n+=l.const.length);let d=l.anyOf??l.oneOf;(Array.isArray(d)&&d.length>1||Array.isArray(l.type)&&l.type.length>1)&&a++;for(let e of[`items`,`prefixItems`,`anyOf`,`oneOf`,`allOf`,`additionalProperties`,`not`,`if`,`then`,`else`])e in l&&u(l[e]);if(l.patternProperties&&typeof l.patternProperties==`object`)for(let e of Object.values(l.patternProperties))u(e)},{$defs:d,...f}=e;u(f);for(let e of Object.values(l))u(e);let p=e=>{if(typeof e.$ref==`string`)return/^#\/\$defs\/(.+)$/.exec(e.$ref)?.[1]?.replace(/~1/g,`/`).replace(/~0/g,`~`)},m=wu(l,p),h=new Set,ee=new Map,te=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e;if(typeof t.$ref==`string`){let e=p(t);if(!e||h.has(e)||!l[e])return 0;let n=m.get(e),r=e;if(n){r+=`|`;for(let e of n)r+=h.has(e)?`1`:`0`}let i=ee.get(r);if(i!==void 0)return i;h.add(e);let a=te(l[e]);return h.delete(e),ee.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=te(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},ne=te(f);return{properties:t,depth:ne,stringChars:n,enumValues:r,enums:c,optional:i,unions:a,objectProperties:o,objectOptional:s}}function wu(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 Tu=class extends Error{constructor(e){super(`@aeye/schema: ${e}`),this.name=`SchemaDefinitionError`}},Eu=class extends Error{constructor(e,t=Kd(e)){super(t),this.issues=e,this.name=`SchemaParseError`}issues};function Du(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 Ou(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function ku(e,t,n=Ou(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=Du(r,o.toLowerCase());s<=n&&i.push({candidate:o,index:a,ci:s,exact:Du(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 Au(e,t,n){return ku(e,t,n)[0]}var ju=Object.freeze({detail:`full`,maxErrors:5,maxChars:2e3,suggestions:!0,context:3,depth:6,header:!0});function Mu(...e){let t;for(let n of e)n!==void 0&&(t={...t,...Pu(typeof n==`string`?{detail:n}:n)});return t}function Nu(...e){let t=Mu(...e)??{},n=t.detail??ju.detail;return{...ju,...t,detail:n,expected:t.expected??n===`full`}}function Pu(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Fu(e){let t=typeof e==`string`?e:e?.detail??ju.detail;return t===`markers`||t===`full`}var Iu=new WeakMap;function Lu(e,t){Iu.set(e,t)}function Ru(e,t,n){for(let r=t;r<e.length;r++){let t=Iu.get(e[r]);t&&!t.node&&(t.node=n)}}var zu=/^[A-Za-z_$][\w$]*$/;function Bu(e){let t=``,n=``;for(let r of e)r===`(json)`?(t+=`${n||`(root)`} \u2192 JSON text \u2192 `,n=``):n+=typeof r==`number`?`[${r}]`:zu.test(r)?n?`.${r}`:r:`[${JSON.stringify(r)}]`;return t&&!n?t.slice(0,-3):t+(n||(t?``:`(root)`))}var Vu=Symbol(`absent`);function Hu(e,t){let n=e;for(let e of t)if(e===`(json)`){if(typeof n!=`string`)continue;if(n=Wu(n),n===Vu)return Vu}else{if(typeof n==`string`&&(n=Wu(n)),typeof n!=`object`||!n||!Object.prototype.hasOwnProperty.call(n,e))return Vu;n=n[e]}return n}var Uu;function Wu(e){let t=Uu?.get(e);if(t!==void 0)return t;let n;try{n=JSON.parse(e)}catch{n=Vu}return Uu?.set(e,n),n}function Gu(e,t=160){for(let n of[2,1,0]){let r=qu(e,n,6);if(r.length<=t)return r}let n=qu(e,0,3);return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Ku(e){return e.replace(/^#\/\$defs\//,``).replace(/~1/g,`/`).replace(/~0/g,`~`)}function qu(e,t,n){if(typeof e.$ref==`string`)return Ku(e.$ref);if(`const`in e)return JSON.stringify(e.const);if(Array.isArray(e.enum))return Yu(e.enum.map(e=>JSON.stringify(e)),n,` | `);let r=e.anyOf??e.oneOf;if(Array.isArray(r))return Yu([...new Set(r.map(e=>qu(e,t,n)))],n,` | `,`options`);if(Array.isArray(e.allOf))return e.allOf.map(e=>Ju(qu(e,t,n))).join(` & `);if(Array.isArray(e.type))return e.type.map(r=>qu({...e,type:r},t,n)).join(` | `);if(e.nullable===!0)return`${Ju(qu({...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=>qu(e,t-1,n)).join(`, `)}]`:`${Ju(e.items&&typeof e.items==`object`?qu(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=>`${zu.test(e)?e:JSON.stringify(e)}${o.has(e)?``:`?`}: ${qu(r[e],t-1,n)}`);return i.length>n&&s.push(`\u2026 ${i.length-n} more`),a&&s.push(`[key: string]: ${qu(a,t-1,n)}`),`{ ${s.join(`; `)} }`}default:return`any JSON value`}}function Ju(e){return/ \| | & /.test(e)&&!/^[{[(]/.test(e)?`(${e})`:e}function Yu(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 Xu(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=Gu(n.json());return t.kind===`type`&&/^(string|number|integer|boolean|null)$/.test(e)?void 0:e}catch{return}}function Zu(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=Zu(r),i=n.get(e);if(i){i.paths.push(r.path);continue}let a={issue:r,info:Iu.get(r),paths:[r.path]};n.set(e,a),t.push(a)}return t}function $u(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=ed(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(Bu),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 ed(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=Au(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=ku(r,n)[0];return i!==void 0&&i!==r?` \u2014 did you mean \`${i}\`?`:``}function td(e,t,n,r=`your answer`){if(!e.length)return``;let i=rd(n)?n:Nu(n),a=Qu(i.suggestions?nd(e):e),o=Uu;Uu=new Map;try{for(let e of id(i)){let n=od(a,t,e,r);if(n.length<=i.maxChars)return n}let e=od(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{Uu=o}}function nd(e){let t,n=0;for(let r of e){let e=Iu.get(r);if(e?.kind!==`required`||!e.candidates||++n>50)continue;let i=r.path[r.path.length-1],a=typeof i==`string`?Au(i,e.candidates()):void 0;a!==void 0&&(t??=new Set).add(sd([...r.path.slice(0,-1),a]))}return t?e.filter(e=>!(Iu.get(e)?.kind===`unknown-key`&&t.has(sd(e.path)))):e}function rd(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*id(e){for(let t of ad(e))yield t,yield{...t,terse:!0}}function*ad(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 od(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 ${Bu(e.issue.path)}: ${$u(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?Xu(e.issue,e.info):void 0;l.push(`- at ${Bu(e.issue.path)}: ${$u(e,n)}${t?` (expected: ${t})`:``}`)}else n.header&&l.push(``),l.push(...dd(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 sd=e=>{let t=``;for(let n of e)t+=`${typeof n==`number`?`#`:`$`}${n}\0`;return t};function cd(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 ld(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 ud=e=>e.filter(e=>e!==`(json)`).length;function dd(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):Hu(t,e)===Vu?e.length&&fd(Hu(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)=>cd(e.p.issue.path,t.p.issue.path));let a=[],o=e=>{let t=[];for(let r of e){if(ud(e)-ud(t)<=n.depth)break;t.push(r)}return t};for(let e of r){let t=a[a.length-1];if(t){let r=ld(t.anchor,e.at);if([...t.members,e].every(e=>ud(e.at)-ud(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&&Hu(t,r)===Vu;)r=r.slice(0,-1);let i=new Map,a=new Map;for(let t of e.members){let e=sd(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=sd(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 ${Bu(r)}:`),new md(i,a,n,s,r.length).node(Hu(t,r),r,``,``,``)}for(let e of i)s.push(`- at ${Bu(e.issue.path)}: ${$u(e,n)}`);return s}var fd=e=>typeof e==`object`&&!!e;function pd(e){if(!e.length)return`…`;let t=e[0],n=Bu(e);return t===`(json)`?`\u2026 \u2192 ${n.replace(/^\(root\) → /,``)}`:typeof t==`number`||!zu.test(t)?`\u2026${n}`:`\u2026.${n}`}var md=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=sd(t),o=this.below.has(a);if(typeof e==`string`&&o){let a=Wu(e);if(a!==Vu){let e=[...t,`(json)`],o=sd(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(!(fd(e)&&(o||s.some(e=>e.where===`missing`)))){let t=hd(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(sd(t)),a=r.filter(e=>i?.has(e)),o=r.filter(e=>!a.includes(e)),s=new Set(o.filter(t=>hd(e[t],40).length<=40&&!fd(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(sd(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)||hd(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?pd(e.issue.path.slice(this.from)):Bu(e.issue.path)}: ${$u(e,this.f)}`;this.out.push(`${` `.repeat(t)}${`^`.repeat(r)} ${i}`);let a=this.f.expected?Xu(e.issue,e.info):void 0;a&&this.out.push(`${` `.repeat(t+r+1)}expected: ${a}`)}};function hd(e,t){if(typeof e==`string`){let n=JSON.stringify(e);return n.length<=t?n:`${n.slice(0,t-2)}\u2026"`}if(!fd(e))return e===void 0?`undefined`:JSON.stringify(e);let n=gd(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 gd(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(fd(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 _d=class{constructor(e){this.issues=e}issues};function vd(){return{objects:0,arrays:0,edits:0,parsed:0,repaired:0}}function yd(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 bd=Object.freeze({path:[],codePath:[],message:``}),xd=vd(),Sd=Symbol(`absent`),Cd=Symbol(`order`),wd,Td=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(bd);return}let a={path:this.wire.slice(0,this.wd),codePath:this.code.slice(0,this.cd),message:e};this.errors.push(a),Lu(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(bd);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),Lu(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,xd,this.repair,!0);let n=new e(!1,!0,xd,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++]=Cd,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]:Sd}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===Cd)for(let e of i){let t=n[e];delete n[e],n[e]=t}else i===Sd?delete n[r]:n[r]=i}}keepUndo(){this.undo=wd??[],wd=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&&(wd=e)}}},Ed=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||Ru(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 Dd(this.compiler.env)):`any JSON value`}encode(e,t=vd()){return this.needs?this.impl.encode(e,t):e}child(e){return this.impl?.child?.(e)}},Dd=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}},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(`
60
+ `)}`:t}},Od=new Set([`object`,`array`,`record`,`tuple`]),kd=new WeakMap;function Ad(e){let t=kd.get(e);return t===void 0&&(t=e.kind===`dependent`||e.children().some(Ad),kd.set(e,t)),t}var jd=new WeakMap;function Md(e){let t=jd.get(e);return t===void 0&&(t=+!!Od.has(e.kind)+Math.max(0,...e.children().map(Md)),jd.set(e,t)),t}var Nd=new WeakMap,Pd=new WeakMap;function Fd(e){let t=Pd.get(e);return t||Pd.set(e,t=new Bd(e,Id,Rd,!1,!0)),t}var Id=new Map,Ld;function Rd(){if(!Ld){let e=Fd($l);Ld=new Wd(e,e.node({emit:()=>({}),run:e=>e,encode:e=>e}))}return Ld}var zd=class extends Error{},Bd=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=Su(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 Ed(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=Od.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&&!Ad(e)&&(this.profile.maxDepth===void 0||this.depth+Md(e)<this.profile.maxDepth);if(r){let t=Nd.get(e)?.get(this.profile.id);if(t)return t;if(!this.shared){let t=Fd(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=Nd.get(e);t||Nd.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 Tu(`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 Vd(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 zd;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 Dd(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=Ud(e,t);if(n===Hd)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 Td(!1,!0,vd(),!1);if(this.lenient().nodeFor(n).run(t,r),r.errors.length)throw new Tu(`example ${JSON.stringify(t)} does not fit its schema:
62
+ ${Kd(r.errors)}`)}},Vd=class extends Ed{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=vd()){return this.target.encode(e,t)}child(e){return this.target.child(e)}},Hd=Symbol(`failed`);function Ud(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`),Hd);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`),Hd}}var Wd=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 Dd(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??=Cu(this.jsonSchema)}parse(e,t){return this.decode(e,t,void 0)}decode(e,t,n){let r=vd(),i=t?.inPlace??!0,a=new Td(i,!1,r,t?.repair??!0),o=i&&!n&&Fu(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:td(a.errors,i,Nu(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 Lu(n[0],{kind:`json`}),{ok:!1,issues:n,message:td(n,void 0,Nu(t?.errorFormat),t?.label),stats:vd()}}return this.decode(n,t,()=>JSON.parse(e))}parseOrThrow(e,t){let n=this.parse(e,t);if(!n.ok)throw new Eu(n.issues,n.message);return n.value}encode(e,t=vd()){let n=this.root.encode(e,t);return this.wrapped?(t.objects++,{input:n}):n}encodeAt(e,t,n=vd()){let r=Gd(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 Tu(`no schema at path ${yd(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 Dd(this.compiler.env).full(e)}};function Gd(e){return e===void 0||e===``?[]:typeof e==`string`?e.split(`.`).map(e=>/^\d+$/.test(e)?Number(e):e):[...e]}function Kd(e){return e.map(e=>`- at ${yd(e.path)}: ${e.message}`).join(`
65
+ `)}var qd=class e{constructor(e={}){this.defs=e}defs;define(t){for(let e of Object.keys(t))if(e in this.defs)throw new Tu(`"${e}" is already defined.`);return new e({...this.defs,...t})}declare(){return this}dynamic(e,t={}){return new Jd(this.defs,e,t)}result(e){return new Xd(this.defs,Yd(e))}},Jd=class{constructor(e,t,n){this.defs=e,this.fn=t,this.opts=n}defs;fn;opts;result(e){return new Xd(this.defs,Yd(e),{fn:this.fn,opts:this.opts})}};function Yd(e){return typeof e==`string`?new Nf(e):e}var Xd=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 Zd(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 Tu(`the dynamic step redefined "${e}".`);i.set(e,t)}let a=new Zd(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)}},Zd=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 Tu(`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($l),r=new Bd(e,this.env,n),i;try{i=r.compile(this.root)}catch(t){if(!(t instanceof zd))throw t;r=new Bd(e,this.env,n,!0),i=r.compile(this.root)}r.finish(),t=new Wd(r,i),this.rendered.set(e.id,t)}return t}},Qd=new WeakMap;function $d(e){let t=Qd.get(e);return t||Qd.set(e,t=new Xd({},e)),t}var ef=Object.freeze({}),tf=Object.freeze([]),nf=class{meta=ef;checks=tf;_refNames;refNames(){if(!this._refNames){let e=new Set;this instanceof Nf&&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 jf(this)}nullable(){return new Mf(this)}default(e){return new Af(this,e)}bind(){return $d(this).bind()}render(e){return $d(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}},rf={"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)&&af(`[${e}]`)}};function af(e){try{return new URL(`http://${e}/`),!0}catch{return!1}}function of(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 sf=class extends nf{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:rf[t.format],o=[];return e.node({hint:()=>this.hintOf(o),emit:()=>{let e={type:`string`};Zf(e,o,`minLength`,t.minLength,n.constraints.length,`At least ${t.minLength} characters.`),Zf(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&&of(t.pattern));return Zf(e,o,`pattern`,t.pattern,r,`Must match ${i}.`),Zf(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):zf(n,e,`Expected a string, got ${If(e)}.`),encode:e=>e})}},cf=class extends nf{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 Zf(e,r,`minimum`,t.minimum,n,`At least ${t.minimum}.`),Zf(e,r,`maximum`,t.maximum,n,`At most ${t.maximum}.`),Zf(e,r,`exclusiveMinimum`,t.exclusiveMinimum,n,`Greater than ${t.exclusiveMinimum}.`),Zf(e,r,`exclusiveMaximum`,t.exclusiveMaximum,n,`Less than ${t.exclusiveMaximum}.`),e},run:(e,n)=>typeof e!=`number`||!Number.isFinite(e)?zf(n,e,`Expected a number, got ${If(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})}},lf=class extends nf{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:zf(t,e,`Expected true or false, got ${If(e)}.`),encode:e=>e})}},uf=class extends nf{kind=`null`;children(){return[]}print(){return`null`}compile(e){return e.node({emit:()=>({type:`null`}),run:(e,t)=>e===null?e:zf(t,e,`Expected null, got ${If(e)}.`),encode:e=>e})}},df=class extends nf{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:Rf(t),enum:[t]},run:(e,n)=>e===t?e:zf(n,e,`Expected ${JSON.stringify(t)}.`,`literal`,typeof t==`string`?()=>[t]:void 0),encode:e=>e})}},ff=class extends nf{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 kf(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)?zf(r,e,`Expected one of: ${Bf(t)}.`,`enum`,()=>t):e,encode:e=>e})}},pf=class extends nf{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:hf.map(e=>({...e}))},run:(e,t)=>e===void 0?zf(t,e,`Required.`,`required`):e,encode:e=>e}):mf(e.node({own:!0,hint:()=>this.hintOf([`Write the value as JSON text.`]),emit:()=>({type:`string`}),run:(e,t)=>{let n=Ud(e,t);return n===Hd?e:n},encode:e=>JSON.stringify(e)}))}};function mf(e){return e.jsonText=!0,e}var hf=Object.freeze([{type:`string`},{type:`number`},{type:`boolean`},{type:`null`},{type:`array`},{type:`object`,additionalProperties:!0}]),gf=class extends nf{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=Of(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 Zf(e,i,`minItems`,t.minItems,r===`all`||r===`min-0-1`&&(t.minItems??0)<=1,`At least ${t.minItems} items.`),Zf(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 zf(r,i,`Expected a list, got ${If(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=np(a,i,e,t,r))}return a},encode:(e,t)=>$f(e,e=>n.encode(e,t),t),child:()=>n})}},_f=class extends nf{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=np(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 Dd(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(!Ff(n))return zf(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)):zf(t,a,`Expected a list of ${r} items.`)},encode:(e,r)=>{let i=e;if(n!==`object`)return $f(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)]})}},vf=class e extends nf{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 Tf(n,r,i??new pf);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 jf||n instanceof Af;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 xf(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 Af?s:void 0,l=s instanceof jf||!!c,u=s instanceof jf?s.inner:c?c.inner:s;if(l&&Of(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 Mf,...u instanceof Tf?{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 Dd(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=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(`
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(!Ff(i))return zf(r,i,`Expected an object, got ${If(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=ep(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?ep(d,u,t.key,t.dflt.fresh(r.stats),r):tp(d,u,t.key,r));continue}r.enter(t.key);let a=t.node.run(i,r);r.leave(),a!==i&&!r.dry&&(d=ep(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=tp(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=ep(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))zf(r,t,`Expected a list of {key, value} entries.`);else{r.dry||(d=tp(d,u,p,r));for(let e=0;e<t.length;e++){let n=t[e];if(r.enter(e,null),!Ff(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?zf(r,n.value,`Key "${i}" is not allowed.`,`not-allowed`):n.value;r.leave(),r.dry||(d=ep(d,u,i,o,r)),r.leave(!1)}}r.leave(!1)}else p&&e===null&&!r.dry&&(d=tp(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=ep(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)})}},yf=class extends nf{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??bf),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`],e.profile.closedObjects)};let i={type:`object`,additionalProperties:t.json()};return this.key&&!e.profile.closedObjects&&!(this.key instanceof sf&&!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&&Ff(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=ep(s,r,e,t,a))}return s}return zf(a,r,`Expected a list of {key, value} entries, got ${If(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),!Ff(i)){zf(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(!Ff(o))return zf(a,o,`Expected an object, got ${If(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=ep(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})}},bf=new sf,xf=class extends nf{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??Kf(this.options,e);if(!n)return;let r=new Map,i=[];return this.options.forEach((a,o)=>{let s=t.has(o)?void 0:Hf(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?Yf(this.options[e],t).shape?.[this.tag]:void 0;return n instanceof df&&typeof n.value==`string`?n.value:`option${e+1}`}compile(e){if(this.options.some(t=>Of(t,e.env))){let t=this.options.filter(t=>!Of(t,e.env));return t.length?this.with({options:t}).compile(e):kf(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=>Yf(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),Jf(e,r)):a&&e.profile.records===`pairs`&&i(this.options[o])===`record`?(n.add(o),Jf(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=>Yf(this.options[t],e.env)instanceof uf,f=(t,n)=>{if(c&&Ff(t)){let r=c.get(t[l]);if(r!==void 0){let i=new Set(Wf(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=!Ff(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 Dd(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(!Ff(n))return zf(r,n,`Expected an object with one of: ${u.join(`, `)}.`);let e=u.filter(e=>n[e]!=null);if(e.length!==1)return zf(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:zf(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&&Ff(n)&&n[l]!==void 0){r.enter(l);let e=n[l];return r.fail(`Expected ${l} to be one of: ${Bf([...c.keys()].map(e=>JSON.stringify(e)))}.`,`tag`,e,()=>[...c.keys()].filter(e=>typeof e==`string`)),r.leave(),n}let t=qf(this.options,n,e.env);return t>=0?o[t].run(n,r):zf(r,n,`Did not match any of: ${Vf(this.options.map(e=>e.print(p())).join(` | `),300)}.`,`union`,typeof n==`string`?()=>Uf(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||Xf(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&&Ff(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 Td(!1,!0,vd(),!1,!0);return i.nodeFor(t).run(e,n),n.errors.length===0})}},Sf=class extends nf{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=>Yf(t,e));if(n.every(e=>e instanceof vf)){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 vf(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 Dd(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)})}},Cf=class extends nf{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 Dd(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&&Xf(e,this.excluded,a)&&r.fail(`Must not be: ${this.excluded.print(new Dd(e.env))}.`,`rule`),a},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},wf=class extends nf{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 Dd(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=Xf(e,this.when,o)?this.then:this.otherwise;return s&&!Xf(e,s,o)&&i.fail(r,`rule`),o},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},Tf=class extends nf{constructor(e,t,n=new pf){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)})}},Ef=class extends nf{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 ff(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=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(`
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(!Ff(c))return zf(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: ${Bf(t)}.`,`tool`,u,()=>t),i.leave(),c;let f=l[s];if(a){let e=Qf(f,i,`object`);f=Ff(e)?e[u]:void 0,i.enter(s),i.enter(u,null)}else i.enter(s);let p=f===void 0?zf(i,f,`Required.`,`required`,r[d]):r[d].run(f,i);return a&&i.leave(!1),i.leave(),p!==l[s]&&!i.dry?ep(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}}})}},Df=class extends nf{kind=`never`;children(){return[]}print(){return`never`}compile(e){return kf(e,()=>this.ruleHint())}};function Of(e,t){let n=Yf(e,t);return n?n.kind===`never`?!0:n instanceof ff?n.values.length===0:n instanceof xf&&n.options.every(e=>Of(e,t)):!1}function kf(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)=>zf(t,e,`No value is allowed here.`,`not-allowed`),encode:e=>e})}var Af=class extends nf{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 Mf;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)})}},jf=class extends nf{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 Mf)?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)})}},Mf=class extends nf{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)})}},Nf=class extends nf{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)}},Pf=class extends nf{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 zf(n,e,a.message,`other`);if(a instanceof _d){if(!a.issues.length)return zf(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 Ff(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function If(e){return typeof e==`string`?Lf(e)??`string`:e===null?`null`:Array.isArray(e)?`a list`:typeof e==`object`?`an object`:typeof e}function Lf(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 Rf(e){return typeof e==`string`?`string`:typeof e==`number`?`number`:typeof e==`boolean`?`boolean`:`null`}function zf(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 Bf(e,t=30){return e.length<=t?e.join(`, `):`${e.slice(0,t).join(`, `)}, \u2026 (${e.length-t} more)`}function Vf(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Hf(e,t,n,r=0){let i=Yf(e,n);if(i instanceof vf){let e=Yf(i.shape[t],n);return e instanceof df?[e.value]:e instanceof ff?[...e.values]:void 0}if(i instanceof xf&&r<8){let e=[];for(let a of i.options){let i=Hf(a,t,n,r+1);if(!i)return;e.push(...i)}return e}}function Uf(e,t,n=0){let r=[];for(let i of e){let e=Yf(i,t);e instanceof ff?r.push(...e.values):e instanceof df&&typeof e.value==`string`?r.push(e.value):e instanceof xf&&n<8&&r.push(...Uf(e.options,t,n+1))}return r}function Wf(e,t,n=0){let r=Yf(e,t);return r instanceof vf?Object.keys(r.shape):r instanceof xf&&n<8?Wf(r.options[0],t,n+1):[]}var Gf=new WeakMap;function Kf(e,t){let n=Gf.get(e);n||Gf.set(e,n=new WeakMap);let r=n.get(t);if(r===void 0){if(r=null,e.length>1)for(let n of Wf(e[0],t)){let i=new Set,a=!0;for(let r of e){let e=Hf(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 qf(e,t,n){if(!Ff(t))return-1;let r=t,i=-1,a=0,o=!1;if(e.forEach((e,t)=>{let s=0;for(let t of Wf(e,n)){let i=Hf(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(Wf(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 Jf(e,t,n=`json`){let r=e.node({own:!0,deps:[t],emit:()=>e.object({[n]:t.json()},[n]),run:(e,r)=>{if(!Ff(e)||!(n in e))return zf(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 Yf(e,t){for(let n=0;e instanceof Nf&&n<16;n++)e=t.get(e.name);return e}function Xf(e,t,n){let r=new Td(!1,!0,vd(),!1,!0);return e.lenient().nodeFor(t).run(n,r),r.errors.length===0}function Zf(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):Ff(r))?(t.dry||t.stats.repaired++,r):e}function $f(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 ep(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 tp(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 np(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 rp(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 pf;if(e===!1)return new xf([new uf]).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 Sf(t)}r!==void 0&&(d=new Cf(s(r),d)),i!==void 0&&(d=new wf(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 Nf(o(e.$ref));if(`const`in e)return new df(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 ff(n):new xf(t.filter(e=>e!==null).map(e=>new df(e)));return r?new Mf(i):i}let t=e.anyOf??e.oneOf;if(Array.isArray(t)){let e=t.map(s),n=e.filter(e=>!(e instanceof uf)),r=n.length===1?n[0]:new xf(n);return n.length<e.length?new Mf(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 xf(n):new uf;return t.includes(`null`)&&n.length?new Mf(r):r}let n=e.type??ip(e);switch(n){case`string`:{let t=new sf;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 cf({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 lf;case`null`:return new uf;case`array`:{if(Array.isArray(e.prefixItems)&&e.prefixItems.length)return new _f(e.prefixItems.map(s));let t=new gf(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 pf;if(!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new yf(new pf);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 yf(i===!0?new pf:s(i));let o={};for(let[e,n]of Object.entries(t))o[e]=r.has(e)?s(n):new jf(s(n));for(let e of r)e in o||(o[e]=new pf);let c=new vf(o);return a&&(c=c.patterns(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,s(t)])))),i===!0?c=c.rest(new pf):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 pf);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 pf().describe(`Unknown reference ${e}.`));return new Xd(i,a?new Nf(`__root`):f)}function ip(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 ap=()=>new sf,op=()=>new cf,sp=()=>new cf({int:!0}),cp=()=>new lf,lp=()=>new uf,up=e=>new df(e);function dp(e){return new ff([...e])}var fp=()=>new Df,pp=()=>new pf,mp=()=>new pf,hp=e=>new vf(e),gp=e=>new gf(e),_p=e=>new _f(e);function vp(e,t){return t?new yf(t,e):new yf(e)}function yp(e){return new xf([...e])}function bp(e,t){return new xf([...t],e)}var xp=e=>new Sf(e);function Sp(e,t){return new Cf(e,t??new pf)}function Cp(e,t){return new wf(e,t.if,t.then,t.else)}function wp(e,t,n){return new Tf(e,t,n)}var Tp=e=>new jf(e),Ep=(e,t)=>new Af(e,t),Dp=e=>new Mf(e),Op=e=>new Nf(e),kp=e=>new Nf(e),Ap=(e,t)=>new Pf(e,t),jp=(e,t={})=>new Ef(e,t.tag??`tool`,t.args??`args`),Mp=e=>new qd(e),Np=()=>new qd,Pp=()=>new qd,Fp={optional:[`omit`,`null`],closedObjects:`boolean`,records:[`open`,`pairs`],tuples:[`prefixItems`,`object`,`array`],unions:[`anyOf`,`tagged`],nulls:[`type-array`,`anyOf`,`nullable`],allOf:`boolean`,conditionals:`boolean`,patternProperties:`boolean`,defs:`boolean`,refSiblings:`boolean`,recursion:[!0,!1,`guarded`],any:[`empty`,`flat`,`json-text`],examples:[`keyword`,`description`,`none`],propertyOrdering:`boolean`,rootObject:`boolean`,alwaysStrictOutput:`boolean`,jsonInstruction:`string`,audience:[`model`,`people`]},Ip={properties:`maxProperties`,objectProperties:`maxObjectProperties`,objectOptionals:`maxObjectOptional`,optionals:`maxOptional`,unions:`maxUnions`,depth:`maxDepth`,enumSize:null,enumValues:`maxEnumValues`,stringChars:`maxStringChars`,largeEnumValues:`largeEnumValues`,largeEnumChars:`maxLargeEnumChars`},Lp={tools:[`request`,`maxTools`],strictTools:[`request`,`maxStrictTools`],requestProperties:[`totals`,`maxProperties`],requestOptionals:[`totals`,`maxOptional`],requestUnions:[`totals`,`maxUnions`],requestDepth:[`totals`,`maxDepth`],requestStringChars:[`totals`,`maxStringChars`],requestEnumValues:[`totals`,`maxEnumValues`],requestLargeEnumValues:[`totals`,`largeEnumValues`],requestLargeEnumChars:[`totals`,`maxLargeEnumChars`],requestObjectProperties:[`totals`,`maxObjectProperties`],requestObjectOptionals:[`totals`,`maxObjectOptional`]},Rp={length:`boolean`,range:`boolean`,items:[`all`,`min-0-1`,`none`],pattern:[`full`,`basic`,`none`]},zp=e=>Object.fromEntries(Object.keys(e).map(e=>[e,`number`])),Bp={rules:Fp,limits:zp(Ip),constraints:Rp,formats:`formats`},Vp={strict:`boolean`,dialect:`string`,loose:`string`,...Bp,looseRules:Bp},Hp={base:`string`,tools:Vp,output:Vp,delivery:[`structured`,`prompt`],limits:zp(Lp)},Up=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Wp=e=>JSON.stringify(e)??String(e);function Gp(e,t,n,r){let i=t=>{throw Error(`Schema rules${r}: ${n} is ${Wp(e)}, expected ${t}`)};Array.isArray(t)?t.includes(e)||i(t.map(Wp).join(` | `)):t===`boolean`||t===`string`?typeof e!==t&&i(`a ${t}`):t===`number`?typeof e==`number`&&e>=0||i(`a number of 0 or more`):t===`formats`?e!==`all`&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`))&&i(`"all" or a list of format names`):Kp(e,t,n,r)}function Kp(e,t,n,r){if(!Up(e))throw Error(`Schema rules${r}: ${n||`the rules`} is ${Wp(e)}, expected an object`);for(let[i,a]of Object.entries(e)){let e=n?`${n}.${i}`:i,o=t[i];if(!o)throw Error(`Schema rules${r}: unknown key "${e}" (known: ${Object.keys(t).join(`, `)})`);a!==void 0&&Gp(a,o,e,r)}}var qp=new WeakSet;function Jp(e,t){Up(e)&&qp.has(e)||(Kp(e,Hp,``,t?` of ${t}`:``),qp.add(e))}var Yp=new Map;function Xp(e,t){Jp(t,`base "${e}"`);let n=Object.freeze({...t});qp.add(n),Yp.set(e,n)}var Zp=(e,t)=>({tools:{dialect:e,loose:t},output:{dialect:e,loose:t}});Xp(`lenient`,Zp(`lenient`,`lenient`)),Xp(`openai`,Zp(`openai-strict`,`openai`)),Xp(`openai-finetuned`,{base:`openai`,...Zp(`openai-finetuned-strict`,`openai`)}),Xp(`anthropic`,{tools:{dialect:`anthropic-strict`,loose:`anthropic`},output:{dialect:`anthropic-strict-output`,loose:`anthropic`}}),Xp(`google`,Zp(`google-strict`,`google`)),Xp(`google-openapi`,Zp(`google-openapi`,`google`)),Xp(`xai`,{tools:{strict:!0,dialect:`xai-strict`,loose:`xai`},output:{dialect:`xai-strict`,loose:`xai`}}),Xp(`ollama`,Zp(`ollama`,`ollama`));function Qp(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 $p(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function em(e,t,n){let r=e.toLowerCase(),i=t.map((t,n)=>({candidate:t,index:n,ci:Qp(r,t.toLowerCase()),exact:Qp(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 tm(e,t,n=$p(e.length)){return em(e,t,n)[0]}function nm(e,t,n={}){let r=Math.max(1,n.max??1),i=em(e,t,$p(e.length)).slice(0,r);return i.length===0?``:` \u2014 did you mean ${rm(i.map(e=>`\`${e}\``))}?`}function rm(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 im(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+Qp(s,t[e-1].toLowerCase());a[e]=Math.min(a[e]+n,a[e-1]+n,o),r=i}}return a[i]}function am(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=$p(o.length),c=r.reduce((e,t)=>e+$p(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--,Qp(n.toLowerCase(),o)>s)continue;let e=[...i,n],t=im(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 om=[`name`,`docs`,`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`],sm=[`docs`,`type`,`get`,`default`,`set`],cm=[`docs`,`key`,`value`,`get`,`set`,`loop`,`loopDynamic`],lm=[`docs`,`types`,`args`,`returns`,`throws`,`get`,`set`],um=[`docs`,`args`,`run`];function dm(e,t,n,r){let i=e;for(let n of gm(i))if(!om.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown key '${n}'`+bm(n,i[n],om,t,`top`,r));let a=_m(e.options)?e.options:void 0;if(t?.optionKeys&&a){for(let n of gm(a))if(!t.optionKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown options key '${n}'`+bm(n,a[n],t.optionKeys,t,`options`,r))}let o=_m(e.generic)?e.generic:void 0;if(n&&t?.genericKeys&&o){for(let n of gm(o))if(!t.genericKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown generic parameter '${n}'`+bm(n,o[n],t.genericKeys,t,`generic`,r))}}function fm(e,t,n,r,i){if(_m(t))for(let a of gm(t)){if(n.includes(a))continue;let o=r?.[a],s=typeof o==`function`?o(t[a],i):o,c=tm(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 pm={generic:`a fn declares its type parameters on the TYPE, not the call: {"name":"fn","generic":{"T":{"name":"any"}},"call":{"args":…,"returns":…}}`},mm=[{by:`prop`,keys:[`prop`],example:`{"prop":"name"}`},{by:`args`,keys:[`args`,`generic`,`catch`],example:`{"args":{…}}`},{by:`key`,keys:[`key`],example:`{"key":<expr>}`}];function hm(e){if(!_m(e))return;let t=mm.filter(t=>e[t.by]!==void 0);if(t.length===0){let t=gm(e),n=mm.map(e=>e.by),r=t.map(e=>tm(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 ${mm.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}]`)}fm(`path step`,e,t[0].keys)}function gm(e){return Object.keys(e).filter(t=>e[t]!==void 0)}function _m(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vm(e){return Array.isArray(e)?e.length>0&&vm(e[0]):_m(e)&&typeof e.name==`string`}function ym(e){return _m(e)&&`type`in e}function bm(e,t,n,r,i,a){let o=[],s=tm(e,n);if(s)return` \u2014 did you mean \`${s}\`?`;let c=r?.genericKeys??[],l=i===`options`?Sm(t,r,a):void 0;return l?o.push(l):r&&i!==`generic`&&c.length>0&&vm(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`&&ym(t)&&(r?.consumes??[]).includes(`props`)&&o.push("that value is a PropDef — declare it under `props`"),o.push(Tm(n,r,i)),` \u2014 ${o.join(`; `)}`}var xm=12;function Sm(e,t,n){if(!(!t||t.NAME===`enum`||(t.genericKeys?.length??0)>0))return wm(e,n,"an `enum` in gin, not an option")}var Cm={values:(e,t)=>t?wm(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 wm(e,t,n,r=e=>e){let i=!Array.isArray(e)&&_m(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>xm)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 Tm(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 Em=/^(?:\w[\w-]*\/)*\w+$/;function Dm(e){return typeof e==`string`&&Em.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`},km=()=>R.string().pattern(Em.source).describe(`A type name: an identifier, optionally namespaced as ns/Name.`);function Am(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 jm(){return R.object({name:km()}).strict().describe(`A named type, by its name.`)}function Mm(e){return R.object({name:km(),extends:e.length>0?R.enum([...new Set(e)]):R.never(),docs:R.string().optional(),satisfies:R.array(km()).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 Nm=R.ref(`TypeDef`),z=R.ref(`Expr`),Pm=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."),Fm={Generic:R.record(Nm).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:Nm,get:z.optional(),default:z.optional(),set:z.optional()}),GetSetDef:R.object({docs:R.string().optional(),key:Nm,value:Nm,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(Nm).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:Nm,returns:Nm.optional(),throws:Nm.optional(),get:z.optional(),set:z.optional()}),InitDef:R.object({docs:R.string().optional(),args:Nm,run:z})},Im=[`any`,`void`,`null`,`bool`,`num`,`text`,`list`,`map`,`tuple`,`obj`,`optional`,`nullable`,`not`,`or`,`and`,`enum`,`literal`,`fn`,`interface`,`typ`,`date`,`timestamp`,`duration`,`color`],Lm={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:Nm}).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:Nm,V:Nm}).optional()}),Type_tuple:R.object({name:R.literal(`tuple`),options:R.object({elements:R.array(Nm)})}),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:Nm}).optional()}),Type_nullable:R.object({name:R.literal(`nullable`),generic:R.object({T:Nm}).optional()}),Type_not:R.object({name:R.literal(`not`),options:R.object({excluded:Nm})}),Type_or:R.object({name:R.literal(`or`),options:R.object({types:R.array(Nm)})}),Type_and:R.object({name:R.literal(`and`),options:R.object({types:R.array(Nm)})}),Type_enum:R.object({name:R.literal(`enum`),generic:R.object({V:Nm}).optional(),options:R.object({values:R.record(R.unknown())})}),Type_literal:R.object({name:R.literal(`literal`),generic:R.object({T:Nm}).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:Nm}).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()})},Rm={Expr_block:R.object({kind:R.literal(`block`),comment:Pm,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:Pm,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:Nm.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:Pm,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:Pm,type:Nm.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:Pm,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:Pm,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:Nm.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:Pm,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:Pm,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).")})},zm=[`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:Nm,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()})},Vm=(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.`)}),Hm=Object.fromEntries(Im.map(e=>[`New_${e}`,Vm(e,R.ref(Om[e]),Bm[e])])),Um=R.object({kind:R.literal(`new`),type:Nm.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(Fm),...Object.keys(Lm),...Object.keys(Rm),...Object.keys(Hm),`TypeDef`,`Type_Extension`,`Expr_new`,`Expr`]),Gm=(e,t)=>t.length===0?R.never():t.length===1?t[0]:R.discriminatedUnion(e,t);function Km(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 qm(e,t){let n=Km(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=>Am(e,t.NAME)),R.ref(`Type_Extension`)];t?.namedRefs&&a.push(jm());let o=Mm([...i.map(e=>e.NAME),...r]),s=e.exprClassList().map(e=>zm.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=Um,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=>Om[t.NAME]!==void 0&&Im.includes(t.NAME)?R.ref(`New_${t.NAME}`):Vm(t.NAME,Am(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:Gm(`name`,a),Type_Extension:o,Expr_new:c,Expr:Gm(`kind`,s)}}var Jm=new WeakMap,Ym=0,Xm=e=>{let t=Jm.get(e);return t===void 0&&Jm.set(e,t=++Ym),t},Zm=(e,t)=>`${Xm(e)}:${e.version}|${t?.newStrict?`s`:``}${t?.namedRefs?`r`:``}|${(t?.types??[]).map(e=>e.name).join(`,`)}`,Qm=R.define(Fm).define(Lm).define(Rm).define(Hm).declare(),$m=Qm.dynamic((e,t)=>qm(e,t),{key:Zm,cacheSize:8});$m.result(`TypeDef`),$m.result(`Expr`);var eh=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`)}},th=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 nh(...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 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(`
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 rh(`{}`,n);let o=` `.repeat((r+1)*i),s=` `.repeat(r*i);return rh(H`{\n${ih(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 rh(`[]`,n);let a=` `.repeat((r+1)*i),o=` `.repeat(r*i);return rh(H`[\n${ih(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 lh(this,e.list,t)}formatProblem(e,t={}){return lh(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(!ph(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 rh(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 ih(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 ah(e){return ih(e,`
78
+ `)}var oh={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,cyan:`\x1B[36m`},sh={error:`error`,warning:`warning`,info:`info`},ch={error:oh.red,warning:oh.yellow,info:oh.blue};function lh(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}${oh.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=uh(e,l,r);if(i)u.push(i);else{let e=ch[r.severity],t=`${sh[r.severity]}:`,n=r.path.length>0?` @ ${r.path.join(`.`)}`:``;d.push(`${c(e,t)} ${r.message}${n}`)}}let p=dh(u,l.length,i),m=l.length,h=o?String(m).length:0,ee=p.map(e=>fh(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 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)}
81
+ `)}function uh(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 dh(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 fh(e,t,n){let{color:r,sectionHeaders:i,lineNumbers:a,gutterWidth:o,c:s}=n,c=[],l=e=>a?s(oh.dim,`${String(e).padStart(o)} \u2502 `):``,u=()=>a?s(oh.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(oh.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(ch[t],o))}for(let t of e.problems){if(t.lastLine!==n)continue;let e=t.problem.severity,r=s(ch[e],`${sh[e]}:`);c.push(u()+`${r} ${t.problem.message}`)}}return c.join(`
82
+ `)}function ph(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 mh(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}var hh=new WeakMap,gh=0,_h=e=>{let t=hh.get(e);return t===void 0&&hh.set(e,t=++gh),t},vh=new WeakMap;function yh(e){let t=vh.get(e);return t===void 0&&(t=e instanceof bh?`${yh(e.parent)}/${_h(e.bindingsRecord)}`:String(_h(e)),vh.set(e,t)),t}var bh=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)}},xh=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 eh,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 rh(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
+ ${Sh(n)}
85
85
  }`}return r===`if`||r===`switch`||r===`loop`?`{
86
- ${nh(this.toCode(e,{...t,expectsValue:!1}))}
86
+ ${Sh(this.toCode(e,{...t,expectsValue:!1}))}
87
87
  }`:`{
88
- ${nh(this.toCode(e,{...t,expectsValue:!0}))};
88
+ ${Sh(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 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(`
90
+ `+e)}return rh(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 Sh(e){return e.replace(/\n/g,`
91
+ `)}var Ch=new Set([`args`,`recurse`,`this`,`super`,`key`,`value`,`yield`,`error`]),wh=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 Th(e,t,n){let r=t instanceof xh?t:Eh(e,t);return r?r.typeOf(e,n):e.registry.any()}function Eh(e,t){try{return e.registry.parseExpr(t)}catch{return}}function Dh(e,t,n,r={inLoop:!1,inLambda:!1}){let i=new eh;return Oh(e,t,n,i,r),i}function Oh(e,t,n,r,i){let a;if(t instanceof xh)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 kh(e,t,n){Ch.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 Ah=class{constructor(e){this.action=e}action},jh=class extends Ah{constructor(){super(`break`)}},Mh=class extends Ah{constructor(){super(`continue`)}},Nh=class extends Ah{constructor(e){super(`return`),this.value=e}value},Ph=class extends Ah{constructor(e){super(`exit`),this.value=e}value},Fh=class extends Ah{constructor(e){super(`throw`),this.error=e}error};function Ih(e,t){let n=new Bh(t);n.type(e,zh);let r=new Set(n.defines);return{refs:n.refs.filter(e=>!r.has(e)),defines:n.defines}}function Lh(e,t,n){let r=new Map,i=[],a=[],o=new Map,s=new Set;for(let n of e)for(let e of Ih(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 Ih(l,t).refs)c(e);o.set(e,`done`),a.push(e)}};for(let n of e)for(let e of Ih(n,t).refs)c(e);return{order:a,defs:r,missing:i}}var Rh=new Set([`enum`,`literal`]),zh=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?Uh(t,Object.keys(e.generic)):t;for(let t of Object.values(e.generic??{}))this.type(t,i);n&&Rh.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(Vh(e))for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)Hh(e)&&this.type(e,t);else Hh(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=Uh(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(!Vh(e))return;let n=Hh(e.type)&&this.registry.typeClass(e.type.name)?.valuesAreTypes===!0;for(let[r,i]of Object.entries(e))if(r===`type`&&Hh(i))this.type(i,t);else if(r===`generic`&&Vh(i))for(let e of Object.values(i))Hh(e)&&this.type(e,t);else r===`value`?n&&Hh(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(Vh(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 Vh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Hh(e){return Vh(e)&&typeof e.name==`string`}function Uh(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=Gh(t);r;r=Gh(r))if(e.compatible(r,void 0,n))return!0;return!1}function Gh(e){let t=e.base;return t instanceof U&&t!==e?t:void 0}function Kh(e){if(e.name!==`or`)return;let t=e.variants;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function qh(e){if(e.name!==`and`)return;let t=e.parts;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function Jh(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 Yh(e,t,n,r,i){n instanceof W&&n.raw!==void 0&&(e[t]=Jh(n,r,i))}var Xh={form:`envelope`,typeRefs:`definition`};function Zh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&!(e instanceof W)}function Qh(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 $h=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||fm(r?`prop '${r}'`:`prop`,t,sm,Cm,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 xh?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 mh({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 Nh)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)}},eg=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||fm(`get/set surface`,t,cm);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 xh?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 mh({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))}},tg=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||fm(`call signature`,t,lm,pm);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 bh(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 xh?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 mh({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?``:`{${cg(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}},ng=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||fm(`init constructor`,t,um);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 xh?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 mh({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=ag.depth;ag.active++,ag.depth=this.registry.lookup(this.name)===this?0:1;try{return this.toJSON()}finally{ag.active--,ag.depth=e}}references(){return Ih(this.toDefinitionJSON(),this.registry)}closure(e=this.scope){return Lh([this.toDefinitionJSON()],this.registry,t=>e.lookup(t)?.toDefinitionJSON())}compatibleWithParts(e,t,n){let r=qh(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=rg,i=ig(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=Kh(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?$h.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=Qh(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=Qh(e,this.scope);return r?r.evaluate(t,n):e}toGinCode(e,t,n=[]){return rh(this.toCode(e,t),{path:n,type:this})}toJSONCode(e=[],t=2,n=0){return gg(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?``:`<${cg(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:lg(t)})}>`}static renderGenericArgs(t,n){let r=Object.keys(t);return r.length===0||!r.some(n=>!e.isGenericPlaceholder(n,t[n]))?``:`<${cg(r.map(e=>t[e].toCode(void 0,n)),{indent:lg(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=lg(t);return n===`auto`?cg(i,{indent:a}):i.length<=1?i.join(``):`
92
+ ${i.map(e=>ug(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=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)}
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=lg(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 $h?o:$h.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=>Wh(e,i)).join(`
96
+ ${n.map(e=>ug(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 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(`
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 eh;try{this.registry.parse(this.toDefinitionJSON())}catch(e){t.error(`type.invalid`,e.message)}return dg(this,e,t),t}},rg={depth:0,lowWater:1/0,active:new Map,memo:new Map};function ig(e,t){return`${+!!e?.strict}${+!!e?.value}${+!!e?.exact}:${t?yh(t):``}`}var ag={active:0,depth:0};function og(e,t){if(!e)return``;let n=Object.entries(e).filter(([e,n])=>!(n===void 0||n===``||t&&e in t&&sg(t[e],n)));return n.length===0?``:`{${cg(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 sg(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function cg(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=>Wh(e,s)).join(`${o}
100
+ ${e.map(e=>ug(e,s)).join(`${o}
101
101
  `)}
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?`\${
102
+ `}function lg(e){return e?.indent??` `}function ug(e,t){return t+e.replace(/\n/g,`
103
+ ${t}`)}function dg(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 $h?s:$h.from(s);n.at([`props`,o],()=>{hg(a.get,fg(a,e,r),mg(a),`get`,t,n,i),hg(a.set,pg(a,e,r),r.void(),`set`,t,n,i),hg(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]]);hg(o.get,a,o.value,`get`,t,n,i),hg(o.set,s,r.void(),`set`,t,n,i),hg(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()})]]);hg(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()})]]);hg(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]]);hg(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 fg(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 pg(e,t,n){return new Map([[`this`,t],[`value`,e.type]])}function mg(e){let t=e.type.call?.();return t?t.returns:e.type}function hg(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 gg(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:wg(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:wg(e.options,[...n,`options`],r,o)}),e.generic!==void 0&&Object.keys(e.generic).length>0&&s.push({key:`generic`,value:_g(e.generic,t,[...n,`generic`],r,o)}),e.props!==void 0&&Object.keys(e.props).length>0&&s.push({key:`props`,value:vg(e.props,t,[...n,`props`],r,o)}),e.get!==void 0&&s.push({key:`get`,value:bg(e.get,t,[...n,`get`],r,o)}),e.call!==void 0&&s.push({key:`call`,value:xg(e.call,t,[...n,`call`],r,o)}),e.init!==void 0&&s.push({key:`init`,value:Sg(e.init,t,[...n,`init`],r,o)}),e.constraint!==void 0&&s.push({key:`constraint`,value:Cg(e.constraint,t,[...n,`constraint`],r,o)}),V.jsonObject(s,{path:n,type:a},i,r)}function _g(e,t,n,r,i){let a=Object.entries(e).map(([e,a])=>({key:e,value:gg(a,t,[...n,e],r,i+1,void 0)}));return V.jsonObject(a,{path:n},i,r)}function vg(e,t,n,r,i){let a=Object.entries(e).map(([e,a])=>({key:e,value:yg(a,t,[...n,e],r,i+1)}));return V.jsonObject(a,{path:n},i,r)}function yg(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:gg(e.type,t,[...n,`type`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:Cg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:Cg(e.set,t,[...n,`set`],r,a)}),e.default!==void 0&&o.push({key:`default`,value:Cg(e.default,t,[...n,`default`],r,a)}),V.jsonObject(o,{path:n},i,r)}function bg(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:gg(e.key,t,[...n,`key`],r,a,void 0)}),o.push({key:`value`,value:gg(e.value,t,[...n,`value`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:Cg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:Cg(e.set,t,[...n,`set`],r,a)}),e.loop!==void 0&&o.push({key:`loop`,value:Cg(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 xg(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:_g(e.types,t,[...n,`types`],r,a)}),o.push({key:`args`,value:gg(e.args,t,[...n,`args`],r,a,void 0)}),e.returns!==void 0&&o.push({key:`returns`,value:gg(e.returns,t,[...n,`returns`],r,a,void 0)}),e.throws!==void 0&&o.push({key:`throws`,value:gg(e.throws,t,[...n,`throws`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:Cg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:Cg(e.set,t,[...n,`set`],r,a)}),V.jsonObject(o,{path:n},i,r)}function Sg(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:gg(e.args,t,[...n,`args`],r,a,void 0)}),o.push({key:`run`,value:Cg(e.run,t,[...n,`run`],r,a)}),V.jsonObject(o,{path:n},i,r)}function Cg(e,t,n,r,i){try{return t.parseExpr(e).toJSONCode(n,r,i)}catch{return wg(e,n,r,i)}}function wg(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 rh(i,{path:t})}var W=class{type;raw;constructor(e,t){this.type=e,this.raw=t}toLogical(){return Tg(this.raw)}encode(){return this.type.encode(this.raw)}toJSON(e=Xh){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 Tg(e){if(e instanceof W)return e.toLogical();if(Array.isArray(e))return e.map(Tg);if(e instanceof Map){let t=new Map;for(let n of e.values())Eg(n)&&t.set(n[0].toLogical(),n[1].toLogical());return t}if(Dg(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Tg(r);return t}return e}function Eg(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function Dg(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 kg=class extends Error{constructor(){super(`The run was stopped.`),this.name=`RunStoppedError`}},Ag=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 kg}async checkpoint(){this.check(),Date.now()-this.#e<this.slice||(await new Promise(e=>{setTimeout(e,0)}),this.#e=Date.now(),this.check())}},jg=new Set([`text`,`num`,`bool`,`enum`,`literal`,`date`,`timestamp`,`duration`,`color`,`null`]);function Mg(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 Ng(e){return jg.has(Mg(e).name)}function Pg(e,t){let n=e.isOptional()?e.inner??e:e;return Ng(n)?R.union([n.toA(t),R.ref(`Expr`)]):R.ref(`Expr`)}function Fg(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 Ig(e,t,n){let r=Object.keys(e);return r.length===0?t?$h.toJSONMap(t):void 0:{...n&&Object.keys(n).length===r.length&&r.every(e=>e in n)?n:$h.toJSONMap(e),...t?$h.toJSONMap(t):{}}}function Lg(e,t){return{...e,props:e.props?$h.fromMap(e.props,t):void 0,get:e.get?eg.from(e.get,t):void 0,call:e.call?tg.from(e.call,t):void 0,init:e.init?ng.from(e.init,t):void 0}}var Rg=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&&!Fg(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=Lg(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 $h?n:$h.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||!Zh(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||!Zh(r.raw))return new W(this,r.raw);let a=Zh(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,Xh,t)}encodeAs(e,t,n){let r=this.bindScope(n),i=this.base.encodeAs(e,t,r),a=this.storedLocalProps();if(a.length===0||!Zh(i)||!Zh(e))return i;let o=e,s={...i};for(let[e]of a)Yh(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||!Zh(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||!Zh(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||!Zh(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(ag.active>0&&ag.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}}ag.depth++;try{return this.toJSONInner()}finally{ag.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 mh({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:Ig(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?og(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 bh(this.scope,r))}bindScope(e){return this.bindings?e?new bh(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=>Pg(t.type,e)),e)}mergeLocalPropsA(e,t,n){if(!(e instanceof vf))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)})}},zg=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 th({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=$h.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]=$h.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 th({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,Xh,t)}encodeAs(e,t,n){let r=e,i={};for(let[e]of Object.entries(this.fields))Yh(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(!Vg(e)||Qh(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(!Vg(e)||Qh(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 eg({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:$h.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{${cg(i,{indent:lg(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=Pg(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 Vg(e){return Zh(e)}var Hg=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 th({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 eg({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 tg({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)}},Ug=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)+og(this.options.options)}valueA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(Ug.has(this.options.name))return R.json().describe(`A value of the named type ${this.options.name}.`);Ug.add(this.options.name);try{return t.toA(e)}finally{Ug.delete(this.options.name)}}toNewA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(Ug.has(this.options.name))return R.ref(`Expr`);Ug.add(this.options.name);try{return t.toNewA(e)}finally{Ug.delete(this.options.name)}}},Gg=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 eg({key:e.num({whole:!0,min:0}),value:e.bool(),loopDynamic:!0})}toJSON(){return mh({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`+og(this.options)}valueA(){return R.boolean()}describe(e){return typeof e==`boolean`?this:void 0}},Kg=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 th({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 ng({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 mh({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`+og(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.`)}},qg=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 th({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 th({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 mh({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`+og(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}},Jg=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 ng({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.`)}},Yg=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 th({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 th({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)}>`+Zg(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)))}},Xg=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function Zg(e,t){let n=Object.entries(e);return n.length===0?``:`{${cg(n.map(([e,t])=>{let n=Xg.test(e)?e:JSON.stringify(e);return t===e?n:`${n}=${typeof t==`number`||typeof t==`boolean`?String(t):JSON.stringify(t??null)}`}),{indent:lg(t)})}}`}var Qg=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 bh(n);if(t.generic)for(let[e,n]of Object.entries(t.generic))i[e]=a.parse(n);return t.call?new e(a,tg.from(t.call,a),i):new e(a,new tg({args:r.any(),returns:r.any()}),i)}constructor(e,t,n={}){super(e,{},n),this._call=t instanceof tg?t:new tg(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 mh({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`)])}},$g=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?$h.fromMap(t.props,n):{},get:t.get?eg.from(t.get,n):void 0,call:t.call?tg.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]=$h.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 eg({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 tg({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 mh({name:e.NAME,props:Object.keys(this._props).length>0?$h.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{${cg(r,{indent:lg(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)}},e_=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 th({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 th({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)}>`+og({value:this.literal})}valueA(){return R.literal(this.literal)}},t_=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 th({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 th({path:[],code:`list.constraint`,message:`list.parse: length constraints violated`,severity:`error`});return new W(this,n)}encode(e,t){return this.encodeAs(e,Xh,t)}encodeAs(e,t,n){return e.map(e=>Jh(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 th({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 eg({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 mh({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)}>`+og(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 n_(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function r_(e){if(Array.isArray(e))return[e[0],e[1]];let t=e;return[t?.key,t?.value]}function i_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var a_=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])=>n_(t)?t:[e,t]):this.textKeyed()&&i_(e)?Object.entries(e):e;if(!Array.isArray(n))throw new th({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,Xh,t)}encodeAs(e,t,n){return t.form===`logical`&&this.textKeyed()?Object.fromEntries(Array.from(e,([,[e,r]])=>[String(Jh(e,t,n)),Jh(r,t,n)])):Array.from(e,([,[e,r]])=>({key:Jh(e,t,n),value:Jh(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]=r_(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]=r_(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 eg({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}},o_=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 th({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))}},s_=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 th({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 th({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()}},c_=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,Xh,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 th({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)}},l_=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 th({path:[],code:`num.invalid`,message:`num.parse: not a number \u2014 ${String(e)}`,severity:`error`});if(!this.valid(t))throw new th({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 th({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 eg({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 mh({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`+og(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)})}},u_=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,Xh,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 th({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)}},d_=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 th({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 th({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 th({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 eg({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 tg({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)}},f_=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 th({path:[],code:`text.invalid`,message:`text.parse: expected string, got ${typeof e}`,severity:`error`});if(!this.valid(e))throw new th({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 th({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 eg({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 mh({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`+og(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}},p_=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 th({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 mh({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`+og(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 m_(e){let t,n={};return Object.defineProperty(n,"elements",{enumerable:!0,get:()=>t??=e.map(e=>e.toJSON())}),n}var h_=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,m_(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 th({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,Xh,t)}encodeAs(e,t,n){if(!Array.isArray(e))throw new th({path:[],code:`tuple.invalid`,message:`tuple.encode: expected an array of cells`,severity:`error`});return e.map(e=>Jh(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 eg({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)}},g_=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=>Am(this.registry,e.name));e.push(jm()),e.push(Mm(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)}},__=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 th({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 th({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 v_(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:x_(r)?r.raw:r}function y_(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];if(x_(r))return r}function b_(e){let t=q(e,`epsilon`);return typeof t==`number`?t:0}function x_(e){return!!e&&typeof e==`object`&&`type`in e&&`raw`in e}function S_(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 C_={"type.toAny":(e,t)=>G(t.any(),K(e)),"any.typeOf":(e,t)=>G(t.text(),v_(e).type.name),"any.is":(e,t)=>G(t.bool(),!0),"any.as":(e,t)=>{let n=v_(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`))},w_={"void.toText":(e,t)=>G(t.text(),`void`),"void.toBool":(e,t)=>G(t.bool(),!1)},T_={"null.toText":(e,t)=>G(t.text(),`null`),"null.toBool":(e,t)=>G(t.bool(),!1)},E_={"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)}},D_={"num.eq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))<=b_(e)),"num.neq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))>b_(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))<=b_(e)),"num.isPositive":(e,t)=>G(t.bool(),K(e)>b_(e)),"num.isNegative":(e,t)=>G(t.bool(),K(e)<-b_(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=S_(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=S_(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)}},k_=e=>v_(e).type.item,A_={"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=S_(e,t,r,k_(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(k_(e)),void 0):G(t.optional(k_(e)),r[n].raw)},"list.push":(e,t)=>(K(e).push(y_(e,`value`)),G(t.void(),void 0)),"list.pop":(e,t)=>{let n=K(e).pop();return G(t.optional(k_(e)),n?n.raw:void 0)},"list.shift":(e,t)=>{let n=K(e).shift();return G(t.optional(k_(e)),n?n.raw:void 0)},"list.unshift":(e,t)=>(K(e).unshift(y_(e,`value`)),G(t.void(),void 0)),"list.insert":(e,t)=>(K(e).splice(q(e,`index`),0,y_(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=v_(e).type,n=q(e,`start`),r=q(e,`end`);return G(t,K(e).slice(n,r))},"list.concat":e=>{let t=v_(e).type,n=q(e,`other`);return G(t,K(e).concat(n))},"list.reverse":e=>{let t=v_(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=y_(e,`value`).raw,r=K(e).findIndex(e=>e.raw===n);return G(t.num(),r)},"list.contains":(e,t)=>{let n=y_(e,`value`).raw,r=K(e);return G(t.bool(),r.some(e=>e.raw===n))},"list.unique":e=>{let t=v_(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=v_(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=y_(e,`fn`).raw,i=k_(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=v_(e).type,n=K(e),r=y_(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=y_(e,`fn`).raw,i=k_(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=y_(e,`fn`),i=y_(e,`initial`),a=r.raw,o=k_(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=y_(e,`fn`).raw,i=k_(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=y_(e,`fn`).raw,i=k_(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=v_(e).type,n=[...K(e)],r=y_(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(k_(e)),n.length>0?n[0].raw:void 0)},"list.last":(e,t)=>{let n=K(e);return G(t.optional(k_(e)),n.length>0?n[n.length-1].raw:void 0)}},j_={"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},M_=e=>v_(e).type.value,N_={"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=S_(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(M_(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=v_(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=v_(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)},P_={"map.indexSet":B.STATE,"map.delete":B.STATE,"map.clear":B.STATE},F_=e=>v_(e).type.elements,I_={"tuple.at":e=>{let t=e.get(`key`).raw,n=K(e)[t];return n instanceof W?n:G(F_(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=S_(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=F_(e),r=t[0];return r instanceof W?r:G(n[0],r)},"tuple.last":e=>{let t=K(e),n=F_(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)])},L_={"tuple.setAt":B.STATE},R_=e=>v_(e).type.fields,z_={"object.indexGet":e=>{let t=e.get(`key`).raw,n=R_(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=R_(e),i=t.text(),a=Object.values(r).map(e=>e.type),o=S_(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(R_(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(R_(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(R_(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(R_(e),q(e,`key`))),"object.eq":(e,t)=>G(t.bool(),V_(v_(e),e.get(`args`).raw)),"object.neq":(e,t)=>G(t.bool(),!V_(v_(e),e.get(`args`).raw)),"object.toText":(e,t)=>{let n=K(e),r=R_(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 V_(e,t){let n=t.other,r=n instanceof W?n.raw:n;return H_(e.raw,r)}function H_(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(!H_(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(!H_(e[r],t[r]))return!1;return!0}var U_={"optional.value":e=>{let t=K(e);if(t===void 0)throw Error(`optional.value: value is undefined`);return G(v_(e).type.inner,t)},"optional.has":(e,t)=>G(t.bool(),K(e)!==void 0),"optional.or":e=>{let t=K(e),n=v_(e).type.inner;return t===void 0?y_(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"optional.map":async(e,t)=>{let n=K(e),r=v_(e).type.inner;if(n===void 0)return G(t.optional(t.any()),void 0);let i=y_(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(v_(e).type.inner,t)},"nullable.isNull":(e,t)=>G(t.bool(),K(e)===null),"nullable.or":e=>{let t=K(e),n=v_(e).type.inner;return t===null?y_(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"nullable.map":async(e,t)=>{let n=K(e),r=v_(e).type.inner;if(n===null)return G(t.nullable(t.any()),null);let i=y_(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)}},G_={"not.typeOf":(e,t)=>G(t.text(),v_(e).type.name),"not.toText":(e,t)=>G(t.text(),String(K(e)))},K_={"enum.name":(e,t)=>{let n=K(e),r=v_(e).type,i=Object.entries(r.options.values).find(([,e])=>e===n);return G(t.text(),i?i[0]:``)},"enum.value":e=>{let t=v_(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)))},q_={"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))},J_={"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())},Y_=864e5,X_=36e5,Z_=6e4,Q_=1e3,$_={"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*Y_+r*X_+i*Z_+a*Q_+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)/Y_)),"duration.hours":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/X_)%24),"duration.minutes":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/Z_)%60),"duration.seconds":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/Q_)%60),"duration.ms":(e,t)=>G(t.num({whole:!0}),K(e)%Q_),"duration.toText":(e,t)=>{let n=K(e),r=Math.trunc(n/Y_),i=Math.trunc(n%Y_/X_),a=Math.trunc(n%X_/Z_),o=Math.trunc(n%Z_/Q_),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(` `))}},ev=e=>e>>>24&255,tv=e=>e>>>16&255,nv=e=>e>>>8&255,rv=e=>(e&255)/255,iv=(e,t,n,r)=>(Math.round(e)&255)<<24|(Math.round(t)&255)<<16|(Math.round(n)&255)<<8|Math.round(r*255)&255,av={"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(),iv(n,r,i,a)>>>0)},"color.r":(e,t)=>G(t.num(),ev(K(e))),"color.g":(e,t)=>G(t.num(),tv(K(e))),"color.b":(e,t)=>G(t.num(),nv(K(e))),"color.a":(e,t)=>G(t.num(),rv(K(e))),"color.hue":(e,t)=>G(t.num(),ov(K(e)).h),"color.saturation":(e,t)=>G(t.num(),ov(K(e)).s),"color.lightness":(e,t)=>G(t.num(),ov(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(),cv(K(e),q(e,`amount`))),"color.darken":(e,t)=>G(t.color(),cv(K(e),-q(e,`amount`))),"color.saturate":(e,t)=>G(t.color(),lv(K(e),q(e,`amount`))),"color.desaturate":(e,t)=>G(t.color(),lv(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(),iv(255-ev(n),255-tv(n),255-nv(n),rv(n))>>>0)},"color.mix":(e,t)=>{let n=K(e),r=q(e,`other`),i=q(e,`weight`)??.5;return G(t.color(),iv(ev(n)*(1-i)+ev(r)*i,tv(n)*(1-i)+tv(r)*i,nv(n)*(1-i)+nv(r)*i,rv(n)*(1-i)+rv(r)*i)>>>0)},"color.complement":(e,t)=>G(t.color(),uv(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(${ev(n)},${tv(n)},${nv(n)})`)},"color.toHsl":(e,t)=>{let{h:n,s:r,l:i}=ov(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 ov(e){let t=ev(e)/255,n=tv(e)/255,r=nv(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 sv(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],iv((s+o)*255,(c+o)*255,(l+o)*255,r)}function cv(e,t){let{h:n,s:r,l:i}=ov(e);return sv(n,r,Math.max(0,Math.min(1,i+t)),rv(e))>>>0}function lv(e,t){let{h:n,s:r,l:i}=ov(e);return sv(n,Math.max(0,Math.min(1,r+t)),i,rv(e))>>>0}function uv(e,t){let{h:n,s:r,l:i}=ov(e);return sv((n+t+360)%360,r,i,rv(e))>>>0}function dv(e){let t=[{impls:C_},{impls:w_},{impls:T_},{impls:E_},{impls:D_},{impls:O_},{impls:A_,effects:j_},{impls:N_,effects:P_},{impls:I_,effects:L_},{impls:z_,effects:B_},{impls:U_},{impls:W_},{impls:G_},{impls:K_},{impls:q_},{impls:J_},{impls:$_},{impls:av}];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 fv=class e extends xh{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&&gv(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`:pv(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:rh(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 pv(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=cg(e.map(e=>mv(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=cg(o.map(([e,n])=>`${e}: ${mv(n,t,a?.[e]?.type,r)}`));return s.startsWith(`
107
+ `)?`new ${i} {${s}}`:`new ${i} { ${s} }`}return JSON.stringify(e)}function mv(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):pv(e,t,n,r)}function hv(e){if(e instanceof Bg)return e;let t=e.base;return t?hv(t):void 0}function gv(e){let t=hv(e);if(!t)return!1;for(let e of Object.values(t.fields))if(!e.type.isOptional())return!0;return!1}function _v(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 vv(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 yv(e,t){return t.type instanceof Wg?t.type.simplify(e.scope):t.type}function bv(e,t){let n=e.raw;if(!n||typeof n!=`object`)return;let r=n[t];return r instanceof W?r:void 0}function xv(e){return e instanceof Bg||e instanceof $g||e instanceof Rg&&xv(e.base)}function Sv(e,t,n){let r=[];for(let e=n;e<t.length;e++){let n=t[e];if(n instanceof wv)r.push(n.prop);else break}if(r.length===0)return``;let i=am(e,e=>Object.keys(e.props()),e=>{let t=[];for(let n of Object.keys(e.props())){let r=e.prop(n)?.type;r&&xv(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 wv)a.push(n.prop);else{a.length=0;break}}return` \u2014 did you mean \`${[...a,...i].join(`.`)}\`?`}var Cv=class{static from(e,t){if(hm(e),`prop`in e)return new wv(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 Tv(r,e.generic,e.catch?n.parseExpr(e.catch,t):void 0)}if(`key`in e)return new Ev(n.parseExpr(e.key,t));throw Error(`PathStep.from: unknown step shape`)}},wv=class e extends Cv{constructor(e){super(),this.prop=e}prop;toJSON(){return{prop:this.prop}}clone(){return new e(this.prop)}complexity(){return 1}},Tv=class e extends Cv{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 bh(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)}},Ev=class e extends Cv{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()}},Dv=class e{constructor(e){this.steps=e}steps;static from(t,n){return new e(t.map(e=>Cv.from(e,n)))}toJSON(){return this.steps.map(e=>e.toJSON())}toJSONCode(e=[],t=2,n=0){let r=this.steps.map((r,i)=>kv(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 Tv){for(let n of Object.values(t.args))e(n);t.catch_&&e(t.catch_)}else t instanceof Ev&&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 wv){let e=i===0?a.prop:`.${a.prop}`;r=i===0?rh(e,{path:o}):H`${r}${rh(e,{path:o})}`}else if(a instanceof Tv){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=cg(r.map(e=>e.toString())).startsWith(`
108
+ `)?H`({\n ${ih(r,`,
109
+ `)}\n})`:H`({ ${ih(r,`, `)} })`}if(r=H`${r}${rh(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 Ev){let n=a.key.toGinCode(e,{...t,expectsValue:!0},[...o,`key`]);r=H`${r}${rh(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 Tv))return r();if(s instanceof wv){if(a===null){let t=e.get(s.prop);if(t===void 0)throw Error(`path: unknown variable '${s.prop}'${nm(s.prop,e.names())}`);a=t,o++;continue}let r=a.type.prop(s.prop);if(!r){let e=n.mode===`get`?bv(a,s.prop):void 0;if(e){a=e,o++;continue}throw Error(`path: no prop '${s.prop}' on type '${a.type.name}'${Sv(a.type,this.steps,o)}`)}let l=yv(a.type,r),u=this.steps[o+1],d=u instanceof Tv;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 Fh&&u.catch_){let r=e.child({error:n.error});a=await u.catch_.evaluate(t,r)}else throw n}o+=2;continue}if(!d&&_v(l)){let u=await new Tv({},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 Ev){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 Tv){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 Nh)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 Fh&&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 wv){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=yv(n,a),s=this.steps[r+1];if(s instanceof Tv&&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 Tv)&&_v(o)){n=o.call()?.returns??e.registry.any(),r++;continue}n=o,r++}else if(i instanceof Ev)n=n?.get()?.value??e.registry.any(),r++;else if(i instanceof Tv){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 wv)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 wv){if(a===null){let r=t.get(s.prop);r?a=r:(n.at([`path`,o],()=>n.error(`var.unknown`,`unknown variable '${s.prop}'${nm(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}'${Sv(a,this.steps,o)}`)),a=e.registry.any(),o++;continue}let u=yv(a,l),d=this.steps[o+1];if(d instanceof Tv&&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);vv(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 Tv)&&_v(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&&!_v(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 Ev){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 Tv){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);vv(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 kv(e,t,n,r){if(e instanceof wv)return V.jsonObject([{key:`prop`,value:V.jsonString(e.prop)}],{path:t},r,n);if(e instanceof Tv){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 Ev?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 Av=class e extends xh{constructor(e){super(),this.path=e}path;static KIND=`get`;kind=e.KIND;static from(t,n){return new e(Dv.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 rh(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 Tv&&t.resolvedEffects!==void 0&&e.push(t.resolvedEffects);return nh(...e)}complexity(){return this.path.complexity()}},jv=class e extends xh{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(Dv.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 wv?(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 rh(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 Tv&&t.resolvedEffects!==void 0&&(e|=t.resolvedEffects);return e}complexity(){return this.path.complexity()+this.value.complexity()}},Mv=class e extends xh{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??Th(e,t.value,n);n.set(t.name,r)}return Th(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`],()=>kh(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=Nv(a.type),r=Nv(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=ah([...a,s]);return rh(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 rh(H`${this.commentPrefix(t)}${ah([...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 Nv(e){try{return e.toCode()}catch{return e.name}}var Pv=class e extends xh{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():Th(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 rh(r?`undefined`:``,{path:n,expr:this});if(this.lines.length===1)return rh(this.lines[0].toGinCode(e,t,[...n,0]),{path:n,expr:this});let i=this.commentPrefix(t);return rh(r?H`${i}(() => {\n${ah(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}${ah(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}},Fv=class e extends xh{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 jh;case`continue`:throw new Mh;case`return`:throw new Nh(this.value?await this.value.evaluate(e,t):void 0);case`exit`:throw new Ph(this.value?await this.value.evaluate(e,t):void 0);case`throw`:throw this.error?new Fh(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 rh(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 Iv(e){return e.replace(/\n/g,`
112
+ `)}function Lv(e,t=`inherit`){if(e instanceof Fv)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=Lv(e,r===`inherit`?t:r);i&&(n=i)}),n}var Rv=class e extends xh{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=>Th(e,n.body,t));return this.otherwise&&n.push(Th(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=>!!Lv(e.body))||(this.otherwise?!!Lv(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 rh(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(` `)};`),rh(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 rh(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}},zv=class e extends xh{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=>Th(e,n.body,t));return this.otherwise&&n.push(Th(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=>!!Lv(e.body))||(this.otherwise?!!Lv(this.otherwise):!1),a={...t,expectsValue:!0},o=this.value.toGinCode(e,a,[...n,`value`]),s=this.commentPrefix(t);if(r&&!i){let t=ah(this.cases.map((t,r)=>H`${ah(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(` `)};`),rh(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 Fv?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=ah(this.cases.map((t,r)=>{let i=ah(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 Fv?``:`
114
+ break;`}`})),u=``;return this.otherwise&&(u=H`\n default:\n ${c(this.otherwise,[...n,`else`]).indent(` `)}`),rh(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 xh{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 jh)break;if(!(e instanceof Mh))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 Mh)return;if(e instanceof jh){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 Vv(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 Mh)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 Vv(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 Mh)return;if(e instanceof jh){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`,()=>kh(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`,()=>kh(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
+ ${Iv(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 Vv(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 jh))throw e}}var Hv=class e extends xh{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=Gv(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 Nh)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=`(${Uv(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}`,rh(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 Uv(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 Gv(e,t){let n=new bh(e),r=t.call();if(r?.types)for(let[e,t]of Object.entries(r.types))n.bind(e,t);return n}var Kv=class e extends xh{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 fv&&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 fv&&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?qv(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 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\`. */
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 qv(e,t){if(!(e instanceof fv))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 Jv=class e extends xh{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}},Yv=[`props`,`get`,`call`,`init`],Xv=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 bh(this,{...e})}augment(e,t){this._version++;let n={props:t.props?$h.fromMap(t.props,this):void 0,get:t.get?eg.from(t.get,this):void 0,call:t.call?tg.from(t.call,this):void 0,init:t.init?ng.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 xh)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 xh?e:this.parseExpr(e)).toCode(this,t)}toGinCode(e,t){return(e instanceof xh?e:this.parseExpr(e)).toGinCode(this,t,[])}toJSONCode(e,t=2){return(e instanceof xh?e:this.parseExpr(e)).toJSONCode([],t)}validate(e){let t=new eh,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(!Dm(n.name))throw Error(`registry.parse: type 'name' must match ${Em}, got ${JSON.stringify(n.name)}`);if(n.extends!==void 0&&!Dm(n.extends))throw Error(`registry.parse: type 'extends' must match ${Em}, got ${JSON.stringify(n.extends)}`);if(n.satisfies){for(let e of n.satisfies)if(!Dm(e))throw Error(`registry.parse: 'satisfies' entries must match ${Em}, got ${JSON.stringify(e)}`)}let r=n.extends??n.name;dm(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}'${nm(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 Rg&&(i=i.specialize(t)),n!==void 0&&Object.keys(n).length>0&&!Fg(i.narrow(n),i.options)&&(i=new Rg(this,i,{name:i.name,docs:i.docs,options:n,generic:i instanceof Rg?i.local.generic:void 0,useSite:!0},i instanceof Rg&&i.bindings?i.scope:void 0,r)),i}nearBuiltin(e){return e[0]===e[0]?.toLowerCase()&&nm(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}'${nm(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?Yv.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 Rg(this,i,this.buildLocal(o,t))}return new Rg(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 Rg?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}'${nm(e.name,this.typeNameCandidates())}`)}let i=new Set(r.consumes??[]),a=Yv.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?$h.fromMap(e.props,t):void 0,get:a.includes(`get`)&&e.get?eg.from(e.get,t):void 0,call:a.includes(`call`)&&e.call?tg.from(e.call,t):void 0,init:a.includes(`init`)&&e.init?ng.from(e.init,t):void 0};return new Rg(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?$h.fromMap(e.props,t):void 0,get:e.get?eg.from(e.get,t):void 0,call:e.call?tg.from(e.call,t):void 0,init:e.init?ng.from(e.init,t):void 0,constraint:e.constraint?this.parseExpr(e.constraint,t):void 0}}any(){return new zg(this,{})}void(){return new __(this,{})}null(){return new s_(this,{})}bool(e){return new Gg(this,e??{})}num(e){return new l_(this,e??{})}text(e){return new f_(this,e??{})}list(e,t){return new t_(this,e,t??{})}map(e,t){return new a_(this,e,t)}tuple(e){return new h_(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 u_(this,e)}nullable(e){return new c_(this,e)}not(e){return new o_(this,e)}or(e){return new d_(this,[...e])}and(e){return new Hg(this,[...e])}enum(e,t){return Zv(e)?new Yg(this,this.text(),{values:Object.fromEntries(e.map(e=>[e,e]))}):new Yg(this,t??this.text(),{values:e})}literal(e,t){if(e instanceof U)return new e_(this,e,t);let n=this.primitiveOf(e);return new e_(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 qg(this,e??{})}timestamp(e){return new p_(this,e??{})}duration(){return new Jg(this,{})}color(e){return new Kg(this,e??{})}fn(e){return new Qg(this,{args:e.args,returns:e.returns,throws:e.throws,get:e.call},e.generic??{})}iface(e){return new $g(this,{props:e.props?$h.fromMap(e.props,this):{},get:e.get?eg.from(e.get,this):void 0,call:e.call?tg.from(e.call,this):void 0})}alias(e){return new Wg(this,{name:e})}typ(e){return new g_(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 Rg(this,n,t)}nativeExpr(e){return this.parseExpr({kind:`native`,id:e})}prop(e,t,n){return Qv(new $h({type:e,get:this.nativeExpr(t),docs:n}))}method(e,t,n,r){return Qv(new $h({type:this.fn({args:this.obj(e),returns:t,generic:r?.generic}),get:this.nativeExpr(n),docs:r?.docs}))}};function Zv(e){return Array.isArray(e)}function Qv(e){if(!$v(e))throw Error(`registry: a computed prop must carry a get expression`);return e}function $v(e){return e.get!==void 0}var ey=[zg,__,s_,Gg,l_,f_,t_,a_,h_,Bg,u_,c_,o_,d_,Hg,Yg,e_,Qg,$g,g_,qg,p_,Jg,Kg],ty=[fv,Av,jv,Mv,Pv,Rv,zv,Bv,Hv,Kv,Fv,Jv];function ny(){let e=new Xv;for(let t of ey)e.define(t);for(let t of ty)e.defineExpr(t);return dv(e),e}var ry={$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
- };`}},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`}
369
+ };`}},iy=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 ay(e){return/^[A-Za-z_][\w$]*$/.test(e)&&!iy.has(e)&&!(e in ry)}function oy(e){let t=e.replace(/[^\w]/g,`_`);return/^[A-Za-z_]/.test(t)||(t=`_`+t),ay(t)?t:`${t}_`}var sy=class{taken=new Set;types=new Map;data=new Map;constructor(e,t){let n=e.namedTypeList().filter(e=>e instanceof Rg&&!e.local.useSite).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of n)ay(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,oy(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,oy(e))}},cy=(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`,ly=e=>t=>`(${t.self()} ${e} ${J(t,`other`)})`,uy=(e,...t)=>n=>`${e}(${[n.self(),...t.map(e=>J(n,e))].join(`, `)})`,dy=(e,...t)=>n=>`${n.self()}.${e}(${t.map(e=>J(n,e)).join(`, `)})`,fy=e=>t=>`${t.self()}.${e}`,py=e=>t=>`void ${e(t)}`,my=(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(`, `)},hy=(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(`, `)})`},gy=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)})`},_y={"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":ly(`===`),"any.neq":ly(`!==`),"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":ly(`===`),"bool.neq":ly(`!==`),"bool.and":ly(`&&`),"bool.or":ly(`||`),"bool.xor":ly(`!==`),"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()} ? ${cy(t,`"true"`)} : ${cy(n,`"false"`)})`},"bool.toNum":e=>{let t=e.arg(`trueValue`),n=e.arg(`falseValue`);return`(${e.self()} ? ${cy(t,`1`)} : ${cy(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":ly(`<`),"num.lte":ly(`<=`),"num.gt":ly(`>`),"num.gte":ly(`>=`),"num.add":ly(`+`),"num.sub":ly(`-`),"num.mul":ly(`*`),"num.div":ly(`/`),"num.mod":ly(`%`),"num.pow":ly(`**`),"num.abs":uy(`Math.abs`),"num.neg":e=>`(-${e.self()})`,"num.sign":uy(`Math.sign`),"num.sqrt":uy(`Math.sqrt`),"num.min":uy(`Math.min`,`other`),"num.max":uy(`Math.max`,`other`),"num.clamp":e=>`Math.min(Math.max(${e.self()}, ${J(e,`min`)}), ${J(e,`max`)})`,"num.floor":uy(`Math.floor`),"num.ceil":uy(`Math.ceil`),"num.round":uy(`Math.round`),"num.isZero":e=>`(Math.abs(${e.self()}) <= 0)`,"num.isPositive":e=>`(${e.self()} > 0)`,"num.isNegative":e=>`(${e.self()} < 0)`,"num.isInteger":uy(`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":fy(`length`),"text.eq":ly(`===`),"text.neq":ly(`!==`),"text.contains":dy(`includes`,`search`),"text.startsWith":dy(`startsWith`,`prefix`),"text.endsWith":dy(`endsWith`,`suffix`),"text.trim":dy(`trim`),"text.trimStart":dy(`trimStart`),"text.trimEnd":dy(`trimEnd`),"text.upper":dy(`toUpperCase`),"text.lower":dy(`toLowerCase`),"text.slice":e=>`${e.self()}.slice(${my(e,`start`,`end`)})`,"text.replace":e=>`${e.self()}.split(${J(e,`search`)}).join(${J(e,`replacement`)})`,"text.split":dy(`split`,`separator`),"text.concat":ly(`+`),"text.repeat":dy(`repeat`,`count`),"text.indexOf":e=>`${e.self()}.indexOf(${my(e,`search`,`from`)})`,"text.lastIndexOf":e=>`${e.self()}.lastIndexOf(${my(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":uy(`Number`),"text.toBool":e=>`(${e.self()}.length > 0)`,"list.length":fy(`length`),"list.at":e=>`${e.helper(`$listAt`)}(${e.self()}, ${J(e,`index`)})`,"list.push":py(dy(`push`,`value`)),"list.pop":dy(`pop`),"list.shift":dy(`shift`),"list.unshift":py(dy(`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(${my(e,`start`,`end`)})`,"list.concat":dy(`concat`,`other`),"list.reverse":e=>`[...${e.self()}].reverse()`,"list.join":e=>`${e.self()}.map(String).join(${cy(e.arg(`separator`),`","`)})`,"list.indexOf":dy(`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":hy(`map`),"list.filter":hy(`filter`),"list.find":hy(`find`),"list.reduce":hy(`reduce`,`initial`),"list.some":hy(`some`),"list.every":hy(`every`),"list.sort":e=>e.arg(`fn`)===void 0?`${e.helper(`$sortNatural`)}(${e.self()})`:hy(`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":fy(`size`),"map.at":dy(`get`,`key`),"map.has":dy(`has`,`key`),"map.delete":dy(`delete`,`key`),"map.clear":py(dy(`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=>by(t,e)).join(`, `)}]`},"object.entries":e=>{let t=e.once();return`[${e.fields().map(e=>`[${JSON.stringify(e)}, ${by(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":fy(`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":gy(`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":gy(`null`),"enum.name":e=>{let t=Sy(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":ly(`===`),"enum.neq":ly(`!==`),"enum.toText":e=>`String(${e.self()})`,"date.year":dy(`getUTCFullYear`),"date.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"date.day":dy(`getUTCDate`),"date.dayOfWeek":dy(`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":dy(`getUTCFullYear`),"timestamp.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"timestamp.day":dy(`getUTCDate`),"timestamp.hour":dy(`getUTCHours`),"timestamp.minute":dy(`getUTCMinutes`),"timestamp.second":dy(`getUTCSeconds`),"timestamp.millisecond":dy(`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":dy(`getTime`),"timestamp.toText":dy(`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":ly(`===`),"color.neq":ly(`!==`),"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()}, ${my(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);_y[e]=e=>`${e.helper(`$color`)}.${t}(${e.self()})`}var vy={"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}]`},yy={"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 by(e,t){return xy(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function xy(e){return/^[A-Za-z_$][\w$]*$/.test(e)}function Sy(e){let t=e;for(let e=0;e<10&&t;e++){if(t instanceof Yg)return t;t=t.base}}var Cy=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},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])} */
371
+ - `)}`),this.problems=e,this.name=`TypeScriptExportError`}problems},wy=class{constructor(e){this.ctxAllowed=e}ctxAllowed;awaited=!1;loops=[]},Ty=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(`.`)),Ey=/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false|null|undefined)$/,Dy=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 sy(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 Cy([...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=Ty.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=ry[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 Rg)return this.namedRef(e,t);if(e instanceof zg)return`any`;if(e instanceof __)return`void`;if(e instanceof s_)return`null`;if(e instanceof Gg)return`boolean`;if(e instanceof l_||e instanceof Jg||e instanceof Kg)return`number`;if(e instanceof f_)return`string`;if(e instanceof qg||e instanceof p_)return`Date`;if(e instanceof t_)return Gy(this.ref(e.item,t));if(e instanceof a_)return`Map<${this.ref(e.key,t)}, ${this.ref(e.value,t)}>`;if(e instanceof h_)return`[${e.elements.map(e=>this.ref(e,t)).join(`, `)}]`;if(e instanceof u_)return Wy([this.ref(e.inner,t),`undefined`]);if(e instanceof c_)return Wy([this.ref(e.inner,t),`null`]);if(e instanceof d_)return Wy(e.variants.map(e=>this.ref(e,t)));if(e instanceof Hg)return e.parts.map(e=>Uy(this.ref(e,t))).join(` & `)||`unknown`;if(e instanceof Yg){let t=Object.values(e.options.values).map(e=>JSON.stringify(e));return t.length?t.join(` | `):`never`}if(e instanceof e_)return JSON.stringify(e.literal);if(e instanceof Qg){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 $g){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`)}`),Hy(n)}return e instanceof o_||e instanceof g_?`unknown`:`any`}decl(e){let t=this.registry.lookup(e.name);return t instanceof Rg&&t.name===e.name?t:e}namedRef(e,t,n=!1){if(e.local.useSite)return e.original instanceof Rg?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,$h.from(t)])}definitionCall(e){return e.definitionCall()}splits(e){if(!Ay(e.base))return!1;if(this.definitionCall(e)||this.surface(e).some(([,e])=>ky(e)))return!0;let t=e.original;return t instanceof Rg&&!t.local.useSite&&this.splits(this.decl(t))}carriedMembers(e){let t=new Map,n=new Set;for(let r=e;r instanceof Rg&&!r.local.useSite;r=r.original)for(let[e,i]of this.surface(this.decl(r)))n.has(e)||(n.add(e),ky(i)&&(!i.get||i.get instanceof Jv)&&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 Rg&&!s.local.useSite,l=this.surface(e),u=this.members(l.filter(([,e])=>!ky(e)),i,t),d=this.members(l.filter(([,e])=>ky(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(Hy(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(Hy(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 Rg&&!s.local.useSite,l=Ay(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} & ${Hy(d)}`:e}else l?f=Hy(d):(f=this.ref(e.base,i),d.length&&(f=`${Uy(f)} & ${Hy(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=xy(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 Qg)){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=zy(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 Jv&&!_y[e.get.id]?e.get.effects()&(B.EXTERNAL|B.SYSTEM)?`async`:`sync`:e.get instanceof Jv?`sync`:`unknown`}objLiteralType(e,t){return Hy(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}>`:`${Uy(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 zg||e instanceof __?``:`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?`/** ${qy(t[0])} */
373
373
  `:`/**
374
- ${t.map(e=>` * ${Dy(e)}`).join(`
374
+ ${t.map(e=>` * ${qy(e)}`).join(`
375
375
  `)}
376
376
  */
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} {
377
+ `}docLine(e){return!this.opt.includeComments||e.length===0?``:`/** ${qy(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,$h.from(t)]).filter(([,e])=>e.get&&!(e.get instanceof Jv)),r=e.original instanceof Rg&&!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(!Ay(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 wy(!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(`${by(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?` & ${Hy(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 Rg?`$is${this.tsName(this.decl(e).name)}`:`$is_${Xy(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 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(`
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 Rg)return r?this.checkExpr(e.base,t,n):`${this.guard(e)}(${t})`;if(e instanceof l_||e instanceof Jg||e instanceof Kg)return`typeof ${t} === "number"`;if(e instanceof f_)return`typeof ${t} === "string"`;if(e instanceof Gg)return`typeof ${t} === "boolean"`;if(e instanceof s_)return`${t} === null`;if(e instanceof __)return`${t} === undefined`;if(e instanceof qg||e instanceof p_)return`${t} instanceof Date`;if(e instanceof Qg)return`typeof ${t} === "function"`;if(e instanceof a_)return`${t} instanceof Map`;if(e instanceof t_){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 h_){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 u_)return`(${t} === undefined || ${this.checkExpr(e.inner,t,n)})`;if(e instanceof c_)return`(${t} === null || ${this.checkExpr(e.inner,t,n)})`;if(e instanceof d_)return`(${e.variants.map(e=>this.checkExpr(e,t,n)).join(` || `)})`;if(e instanceof Hg)return`(${e.parts.map(e=>this.checkExpr(e,t,n)).join(` && `)})`;if(e instanceof Yg)return`${JSON.stringify(Object.values(e.options.values))}.includes(${t} as any)`;if(e instanceof e_)return`${t} === ${JSON.stringify(e.literal)}`;if(e instanceof Bg||e instanceof $g){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)${xy(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,(!xy(t)||Ty.has(t))&&this.problem(`'${t}' is not usable as a function name`);let n=t;this.used.add(t);let r=new wy(!0),i=[],a=[],o=``;if(e instanceof Hv){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(`${Yy(t)}Ctx`),n=[...this.ctxVars].map(([e,t])=>{let n=this.engine.getGlobal(e),r=n?.docs?[n.docs]:[];return`${this.docLine(r)}${xy(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} = ${Hy(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 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(`
382
+ `).map(e=>`// ${e}`)),e instanceof Pv){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 Mv){let a=this.defineVars(e,t,n,r);return this.stmt(e.body,a,n,r,i)}if(e instanceof Rv)return this.ifStmt(e,t,n,r,i);if(e instanceof zv)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 Fv)return this.flow(e,t,n,r);if(e instanceof jv)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 ${Ky(e)};`):n.kind===`assign`?t.push(`${n.name} = ${Ky(e)};`):r||t.push(`${Ky(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} = ${Ky(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 (${Ky(c.code)}) {`,...By(l),`}`);let u=[];a(r+1,u),u.length!==0&&(u[0].startsWith(`if (`)&&Vy(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 ${Ky(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`)}(${Ky(i)});`);return}case`throw`:{let i=e.error?this.val(e.error,t,n,r).code:`undefined`;r.push(`throw new ${this.helper(`$Throw`)}(${Ky(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 Jv?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} = ${Ky(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(My(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(My(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 wy(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 fv)return this.newValue(e,t,n,r);if(e instanceof Av)return this.path(e.path.steps,t,n,r);if(e instanceof jv)return this.set(e,t,n,r),{code:`true`,type:this.registry.bool(),pure:!0};if(e instanceof Hv)return this.lambda(e,t,n);if(e instanceof Kv)return this.template(e,t,n,r);if(e instanceof Pv){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 Mv)return this.val(e.body,this.defineVars(e,t,n,r),n,r);if(e instanceof Rv)return this.ifValue(e,t,n,r);if(e instanceof zv||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 Fv?(this.flow(e,t,n,r),{code:`undefined as never`,type:this.registry.void(),pure:!0}):e instanceof Jv?(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} = ${Ky(s.code)};`);return}let n=a[e];t.push(...n.cb,`if (${Ky(n.c.code)}) {`,...By([...n.bb,`${l} = ${Ky(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 fv&&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?Ny(a.type):void 0,l="`",u=0;for(let e of s.matchAll(/\{(\w+)\}/g)){l+=Jy(s.slice(u,e.index)),u=e.index+e[0].length;let r=e[1],i;if(o&&c?.has(r))i={code:by(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+="${"+(Fy(i.type)?i.code:`${this.helper(`$str`)}(${i.code})`)+`}`)}return l+=Jy(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 wy(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} => {`,...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(`
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 Jv?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 xh?e:Qh(e,t.scope??this.registry);if(a){let e=this.val(a,n,r,i);return{code:e.code,pure:e.pure}}if(!Ly(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 u_||t instanceof c_)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 t_&&Array.isArray(e))return{code:`[${o(e.map(e=>[void 0,e,t.item])).map(e=>e.code).join(`, `)}]`,pure:!1};if(t instanceof h_&&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 a_&&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=jy(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=>`${xy(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 Rg&&!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 Rg?t.base:t instanceof u_||t instanceof c_?t.inner:t;if(e instanceof Map){let t=n instanceof a_?n.key:this.registry.any(),r=n instanceof a_?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 h_)return`[${e.map((e,t)=>this.literal(e,n.elements[t]??this.registry.any())).join(`, `)}]`;let t=n instanceof t_?n.item:this.registry.any();return`[${e.map(e=>this.literal(e,t)).join(`, `)}]`}if(typeof e==`object`){let n=new Map(jy(t)??[]);return`{ ${Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${xy(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 wv){let e=i[0].prop,o=this.lookup(e,t,n);if(!o){this.problem(`set: unknown variable '${e}'`);return}r.push(`${o.ts} = ${Ky(a.code)};`);return}let o=Ey.test(a.code)?a.code:this.spill(a,r,`value`),s=i[i.length-1];if(s instanceof Tv){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 wv){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(`${by(c.code,s.prop)} = ${o};`)}else if(s instanceof Ev){let e=this.val(s.key,t,n,r).code,i=c.type.get(),a=i?.set instanceof Jv?i.set.id:void 0,l=a?yy[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:by(`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 wv){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:by(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 Tv&&c.call()){i=this.invoke(i,o.prop,s,c,l,t,n,r),a++;continue}if(!(l instanceof Tv)&&Oy(c)){i=this.invoke(i,o.prop,s,c,new Tv({}),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 Ev){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 Jv?l.get.id:void 0,d=u?vy[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 Tv){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}(${Ry(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 Rg&&!e.local.useSite&&this.define(this.decl(e))}readProp(e,t,n,r,i,a){let o=n.get instanceof Jv?n.get.id:void 0,s=o?_y[o]:void 0;if(s)return{code:s(this.nativeCtx(e,{},void 0,i,a)),type:r,pure:e.pure};let c=by(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 Jv?n.get.id:void 0,f=d?_y[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=`${by(p,t)}(${Ry(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&&Iy(d))}}memberAsync(e,t,n,r){if(n.get&&!(n.get instanceof Jv)){let n=e instanceof Rg?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 Rg;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&&!Ey.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&&!Ey.test(e.r.code)){let n=this.uniq(`slot`);return t.push(`const ${n} = ${Ky(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:()=>(xy(a)||(a=this.spill({...e,code:a},i,`recv`)),a),discard:()=>{e.pure||i.push(`${Ky(a)};`)},arg:e=>o[e],argOnce:e=>{let n=o[e];return n===void 0||xy(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:()=>My(e.type),guard:()=>n?this.guard(n):void 0,staticTypeName:()=>Py(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} = ${Ky(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} = ${Ky(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(xy(e.code)||Ey.test(e.code))return e.code;let r=this.uniq(n);return t.push(`const ${r} = ${Ky(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 Bg?Object.values(t.args.fields).every(e=>e.type.isOptional()):!0:!1}function ky(e){return!!e.get||e.type instanceof Qg}function Ay(e){return e instanceof Bg||e instanceof $g||e instanceof Rg&&Ay(e.base)}function jy(e){if(e instanceof Bg)return Object.entries(e.fields);if(e instanceof $g)return Object.entries(e._props);if(e instanceof Rg){let t=jy(e.base);if(!t)return;let n=new Map(t);for(let[t,r]of Object.entries(e.local.props??{}))n.set(t,$h.from(r));return[...n]}}function My(e){return(jy(e)??[]).filter(([,e])=>!e.get&&!e.type.call()).map(([e])=>e)}function Ny(e){let t=jy(e);if(t)return new Map(t.filter(([,e])=>!e.get).map(([e,t])=>[e,t.type]))}function Py(e){if(!(e instanceof zg||e instanceof d_||e instanceof Hg||e instanceof o_||e instanceof Wg||e instanceof u_||e instanceof c_))return e.name}function Fy(e){let t=e instanceof Rg?e.base:e;return t instanceof f_||t instanceof l_||t instanceof Gg||t instanceof Yg}function Iy(e){return/\.(push|pop|shift|unshift|insert|remove|clear|delete|indexSet|setAt)$/.test(e)}function Ly(e,t){return e instanceof xh?!0:!e||typeof e!=`object`?!1:!Array.isArray(e)&&typeof e.kind==`string`&&t.exprClass(e.kind)?!0:Object.values(e).some(e=>Ly(e,t))}function Ry(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:`${xy(e)?e:JSON.stringify(e)}: ${Ky(t.code)}`).join(`, `)} }`}function zy(e){let t=e.options;if(t&&typeof t==`object`&&Object.keys(t).length!==0&&(e instanceof l_||e instanceof f_||e instanceof t_||e instanceof qg||e instanceof p_))return`gin: ${e.toCode(void 0,{includeComments:!1})}`}function By(e){return e.flatMap(e=>e.split(`
386
+ `)).map(e=>e&&` ${e}`)}function Vy(e){return e[e.length-1]===`}`}function Hy(e){if(e.length===0)return`{}`;let t=`{ ${e.join(`; `)} }`;return t.length<=80&&!t.includes(`
387
387
  `)&&!t.includes(`/**`)?t:`{
388
- ${by(e.map(e=>`${e};`)).join(`
388
+ ${By(e.map(e=>`${e};`)).join(`
389
389
  `)}
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(`
390
+ }`}function Uy(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 Gy(e){return/^[\w$.]+(<.*>)?$/.test(e)&&!e.includes(` `)?`${e}[]`:`Array<${e}>`}function Ky(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 qy(e){return e.replace(/\*\//g,`*\\/`)}function Jy(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function Yy(e){let t=e.replace(/[^\w$]+(.)/g,(e,t)=>t.toUpperCase());return t.charAt(0).toUpperCase()+t.slice(1)}function Xy(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 Zy(e,t,n={}){let r=e.registry.parseExpr(t),i=new Dy(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 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?`
394
+ ${o}`,s.clear()),{code:o,types:new Map(i.types),helpers:s,functions:[a]}}var Qy=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 wh(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 Ag(n):void 0;r?.check();let i=this.createRootScope(t,r);try{return await this.evaluate(e,i)}catch(e){if(e instanceof Ph)return e.value??G(this.registry.void(),void 0);throw e}}typeOf(e,t){let n=t??this.globalTypeScope();return Th(this,e,n)}validate(e,t,n){let r=t??this.globalTypeScope();return Dh(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 Zy(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 xh?e:this.registry.parseExpr(e)).evaluate(this,t)}async validateValue(e,t){let n=new eh,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 $y(e){return new Qy(e)}var eb=`^[a-z]\\S*$`,tb=`A fn's name, as your tools spell it.`;function nb(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 rb=R.string().pattern(eb).describe(tb);function ib(e){return R.codec(rb,{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 ab=new WeakMap,ob=0;function sb(e){if(e===void 0)return 0;let t=ab.get(e);return t===void 0&&ab.set(e,t=++ob),t}var cb=Qm.declare().dynamic((e,t,n)=>({...qm(e,n),FnName:t===void 0?rb:ib(t)}),{key:(e,t,n)=>`${Zm(e,n)}|${sb(t)}`,cacheSize:4}),lb={result:e=>cb.result(e)},ub=e=>nb(e)?R.ref(`FnName`):void 0;function db(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:ub})}function fb(e,t={}){return lb.result(db(e,t))}var pb=new WeakMap,mb=new WeakMap;function hb(e,t){let n=t.unknownKeys??`strip`,r=pb;t.scope!==void 0&&(r=mb.get(t.scope)??new WeakMap,mb.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=fb(e,{...t,includeDocs:`none`});return i.set(n,o),o}function gb(e,t={}){return hb(e,t).bind(e.registry)}function _b(e){return e.map(String).join(`.`)}function vb(e,t,n={}){let r=gb(e,n).render($l).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:_b(e.codePath),message:e.message})),message:r.message}}var yb=v().regex(/^[a-z][A-Za-z0-9_-]{0,63}$/).brand(),bb=`[A-Za-z0-9](?:[A-Za-z0-9-]|_(?![_.]|$))*`,xb=RegExp(`^${bb}(?:\\.${bb})*$`);v().regex(xb,"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 Sb(e){if(!xb.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 Cb(e){let{system:t,local:n}=Il(e);return`${t}__${n.replaceAll(`.`,`__`)}`}function wb(e){return e.length===64&&/_x[0-9a-f]{8}$/.test(e)}function Tb(e){return Cb(e).length>64}function Eb(e){if(wb(e))return;let t=e.indexOf(`__`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+2).split(`__`).join(`.`);if(!Nl.test(n)||!xb.test(r))return;let i=I.safeParse(`${n}/${r}`);return i.success&&!Tb(i.data)&&Cb(i.data)===e?i.data:void 0}function Db(e,t){let n=I.safeParse(e);if(n.success)return n.data;let r=t?.(e);return r===void 0?e.includes(`--`)?Ob(e)??Eb(e):Eb(e)??Ob(e):r}function Ob(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:yb,fn:I,until:N}),S({model:yb,fn:I,system:F});var kb=I.describe(tb),Ab=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 jb=/^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i;function Mb(e){try{let{protocol:t}=new URL(e);return t===`http:`||t===`https:`}catch{return!1}}var Nb=v().regex(jb,`expected an http or https URL`).refine(Mb,`expected an http or https URL`);function Pb(e){return Nb.safeParse(e).success}var Fb=`outsideImages`,Ib=E([`ask`,`always`]),Lb=S({value:Ib,setBy:M.optional(),updatedAt:N.optional()}),Rb=`https`,zb={der:`/harness-ca.crt`,pem:`/harness-ca.pem`},Bb=E([`own`,`files`]),Vb=S({on:b(),source:Bb,setBy:M.optional(),updatedAt:N.optional(),fingerprint:v().optional(),authorityName:v().optional(),host:v(),links:x(v())}),Hb=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 *`),Ub=S({into:x(Hb).min(1),order:y().int().min(0).max(1e3).default(100),requires:x(I).default([]),mode:E([`tools`,`static`]).optional(),replaces:x(I).optional()}),Wb=C([D(`none`),S({detail:E([`full`,`summary`]).default(`full`),maxTokens:y().int().min(1).optional()})]),Gb=S({target:Hb,agents:x(I)}),Kb=E([`approved`,`pending`,`declined`]);S({context:I,system:F,title:v(),inject:Ub,fns:x(I),targets:x(Gb),agents:x(I),review:Kb,off:b(),dynamic:b()}),S({hook:I,system:F,explains:v(),review:Kb});var qb=S({section:E([`context`,`hooks`]),name:I,title:v(),change:E([`added`,`changed`,`removed`]),tokens:y().int().min(0).optional(),targets:x(Gb),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 Jb=E([`off`,`pending`,`declined`,`system-off`,`fns-unusable`,`mode`,`replaced`,`no-fit`]),Yb=S({agent:I,context:I,source:w(`type`,[S({type:D(`context`)}),S({type:D(`hook`),hook:I})]),system:F,via:Hb,title:v(),detail:E([`full`,`summary`]),text:v(),tokens:y().int().min(0),order:y().int(),on:b(),leftOut:S({why:Jb,reason:v()}).optional(),switched:S({by:M,at:N}).optional()}),Xb=S({injections:x(Yb),targets:x(Gb)}),Zb=S({agent:I,context:I,on:b().optional(),order:y().int().min(0).max(1e3).nullable().optional()}),Qb=[`listed`,`signature`,`full`],$b=E(Qb),ex=S({fn:I,detail:$b}),tx=S({type:D(`tools`)}),nx=E([`auto`,`native`,`text`]),rx=E([`system-end`,`tail`]),ix=w(`type`,[tx,S({type:D(`static`),protocol:nx.default(`auto`),placement:rx.default(`system-end`),loadDetail:$b.default(`full`)})]),ax=E(ix.options.map(e=>e.shape.type.value));E([`find`,`find_ctx`,`inspect`,`load`,`unload`,`run`]);var ox=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).`)}),sx=S({type:D(`plain`)}),cx=S({type:D(`suggest`),topN:y().int().min(0).default(6),autoInject:S({tokens:y().int().min(0),items:y().int().min(0)}).optional()}),lx=E([`embedding`,`words`,`turnsAgo`,`age`,`selectedBefore`,`used`]),ux=S({weight:y().min(0),target:y().optional(),k:y().positive().optional()}),dx=E([`perMessage`,`perIteration`]),fx=[`history`,`context`,`fns`],px=E(fx),mx=T(px,y().min(0)),hx=w(`type`,[sx,cx,S({type:D(`graph`),metrics:bc(lx,ux).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:mx.default({history:.45,context:.35,fns:.2}),threshold:y().min(0).default(.15),evaluate:dx.default(`perMessage`)})]),gx=E(hx.options.map(e=>e.shape.type.value)),_x=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()}),vx=_x.keyof();vx.options;var yx=_x.required(),bx=E([`admin`,`probe`,`model-info`,`default`]),xx=S({model:v(),limits:yx,sources:T(vx,bx),ratio:y()});S({model:v(),limits:_x,setBy:M,updatedAt:N}),S({model:v(),ratio:y().min(.5).max(2),samples:y().int().min(0),updatedAt:N});var Sx=S({asked:y().int().min(0),got:y().int().min(0)}),Cx=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(px,Sx),estimate:y().int().min(0),cut:x(S({what:v(),why:v()}))}),wx=S({name:I,detail:$b,activation:y().min(0)}),Tx=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:Jb,reason:v()})),rebuilt:S({added:x(I),dropped:x(I)}).optional()}),Ex=S({contextor:gx,mode:ax,context:x(wx),fns:x(wx),linear:y().int().min(0),earlier:x(y().int().min(0)),budget:Cx,injected:Tx.optional()}),Dx=S({session:j,text:v().min(1),model:v().min(1).optional(),count:x(v()).max(200).optional()}),Ox=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:Ex}),kx=S({turn:cl,items:x(wx),at:N}),Ax=[`none`,`read`,`write`,`delete`,`auto`],jx=E(Ax),Mx=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 Nx=E([`file`,`folder`,`link`,`other`]);S({entries:x(S({name:v(),location:v(),kind:Nx,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()},Fx=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(Mx)})]),Ix=Fx.options.map(e=>e.shape.kind.value),Lx=/^(?:true|false|yes|no)$/i,Rx=/^[-+]?\d{1,15}$/,zx=/^[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)?(?:\.\d+)?(?:e[-+]?\d+)?%?$/i,Bx=/^\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 Vx(e){return Lx.test(e)?`boolean`:Rx.test(e)?`integer`:/\d/.test(e)&&zx.test(e)?`number`:Bx.test(e)&&!Number.isNaN(Date.parse(e))?`date`:`text`}function Hx(e,t){return e===`empty`||e===t?t:e===`integer`&&t===`number`||e===`number`&&t===`integer`?`number`:`text`}function Ux(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=Hx(r,Vx(e)))}return r})}var Wx=Wc([v().regex(/^[a-z][a-z0-9+.-]*$/),`://`,v()]),Gx=v().min(1).brand(),Kx=`^[0-9a-f]{64}$`,qx=new RegExp(Kx),Jx=S({hash:v().regex(qx),size:y().int().min(0),mime:v()});S({content:Jx,mime:v(),finalUrl:v(),status:y().int(),rendered:b(),title:v().optional()});var Yx=S({uri:Wx,name:v(),description:v(),index:E([`all`,`on-read`,`none`]),ignore:x(v()),watch:b()}),Xx=S({uri:Wx,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()}),Zx=S({uri:Wx.optional(),raw:v(),kind:E([`child`,`import`,`link`,`embed`,`external`]),title:v().optional()}),Qx=E([`links`,`text`,`bytes`]),$x=C([S({inline:v()}),S({ref:Jx})]),eS=S({stat:Xx,links:x(Zx).optional(),text:$x.optional(),bytes:Jx.optional()});E(Ix);var tS=[`description`,`ocr`,`transcript`,`thumbnail`];E(tS);var nS=E([...Ix,...tS]),rS=S({key:Gx,path:x(v()),title:v(),start:y().int().min(0),end:y().int().min(0),embedText:v().optional(),form:nS.optional()}),iS=S({uri:Wx,change:E([`added`,`changed`,`removed`]),version:v().optional()}),aS=S({format:v().optional(),mime:v().optional(),glob:v().optional(),form:nS.optional()}),oS=C([S({resource:Wx,section:Gx.optional(),title:v().optional()}),S({url:Nb,title:v()}),S({file:Jx,title:v()}),S({run:A,title:v()})]),sS=S({uri:Wx,section:Gx.optional(),title:v(),preview:v(),rank:y()}),cS=Gi();function lS(e,t){return cS.add(e,{why:t}),e}function uS(e){let t=e;for(;t!==void 0;){if(cS.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 dS(e){let t=e.shape;return Object.entries(t).filter(([,e])=>uS(e)).map(([e])=>e)}var fS=new WeakMap;function pS(e,t){return fS.set(e,{schema:t}),e}var mS=w(`to`,[S({to:D(`session`),session:j}),S({to:D(`user`),user:M}),S({to:D(`everyone`)})]),hS=E([`live`,`snapshot`]),gS=w(`type`,[S({type:D(`system`)}),S({type:D(`memory`),scope:mS,author:M,run:A.optional()}),S({type:D(`resource`),uri:Wx,section:Gx.optional(),version:v(),copy:hS})]),_S=[`system`,`memory`,`resource`],vS=S({full:y().int().min(0),summary:y().int().min(0)}),yS=E([`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`mentions`,`about`,`learned`]),bS=[`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`about`],xS=E(bS),SS=w(`kind`,[S({kind:D(`context`),name:I}),S({kind:D(`fn`),name:kb}),S({kind:D(`type`),name:I}),S({kind:D(`resource`),uri:Wx,section:Gx.optional()})]),CS=[`fn`,`context`,`resource`,`type`],wS=S({to:SS,relation:xS,weight:y().min(0).max(1).default(.5)}),TS=E([`declared`,`mentioned`,`resource`,`learned`,`authored`]),ES=S({from:I,to:SS,toKey:v(),relation:yS,weight:y().min(0).max(1),source:TS,uses:y().min(0).optional(),by:M.optional(),updatedAt:N}),DS=S({weight:y().min(0).max(2).optional(),summary:v().optional(),tags:x(v().min(1)).optional(),fns:x(kb).optional(),suggestFns:x(kb).optional(),inject:lS(Ub.optional(),`a model never writes text that lands in later prompts`),command:v().regex(/^[a-z][a-z0-9-]*$/).optional(),visible:zl.optional(),suggest:zl.optional(),parent:I.optional()}),OS=S({text:v().min(1),title:v().optional(),scope:E([`session`,`user`,`everyone`]).default(`session`),about:x(SS).optional(),question:v().min(1).max(500).optional(),when:v().min(1).max(500).optional()}).extend(DS.shape),kS=DS.keyof().exclude(DS.keyof().options.filter(e=>dS(DS).includes(e))),AS=OS.omit({scope:!0}).partial().extend({name:I,clear:pS(x(DS.keyof()).optional(),x(kS).optional())}),jS=S({uri:Wx,sections:x(Gx).optional(),copy:hS.default(`live`)}).extend(DS.omit({summary:!0,parent:!0}).shape),MS=S({created:x(I),updated:x(I),links:y().int().min(0)}),NS={maxDepth:3,maxDecisions:256,maxTokens:8e3},PS=[`active`,`hidden`,`not_applicable`,`pending_approval`,`pending_removal`,`pending_plan`],FS=E(PS),IS=E([`active`,`hidden`,`not_applicable`,`pending_approval`,`pending_removal`]);function LS(e){return e===`active`||e===`pending_removal`}var RS=[`person`,`system`,`research`],zS=E(RS),BS=S({status:FS,from:FS.optional(),by:M,reason:v().optional(),at:N}),VS=S({of:I,similarity:y().min(0).max(1).optional(),reason:v(),at:N}),HS=E([`question`,`when`,`askedBy`,`validUntil`]),US=S({model:v(),at:N,contentHash:v(),fields:x(HS)}),WS=S({from:I.optional(),into:x(I).optional()}),GS=`newContextStatus`,KS=E([`active`,`pending_approval`,`hidden`]),qS=S({value:KS,setBy:M.optional(),updatedAt:N.optional()}),JS=E([`question`,`content`]),YS=S({statuses:x(IS).min(1).optional(),returnNotApplicable:b().optional(),semanticOver:JS.optional()}),XS=[`approve`,`hide`,`restore`,`confirm_removal`],ZS=E(XS),QS=S({names:x(I).min(1).max(200),action:ZS,reason:v().min(1).max(500).optional()}),$S=S({changed:x(S({name:I,status:C([FS,D(`removed`)])})),skipped:x(S({name:I,reason:v()}))}),eC=[`duplicate`,`contradiction`,`pending_approval`,`pending_removal`],tC=E(eC),nC=S({kinds:x(tC).min(1).optional(),systems:x(v().min(1)).min(1).optional(),limit:y().int().min(1).max(200).optional(),cursor:v().optional()}),rC=S({name:I,system:v(),title:v(),question:v().optional(),status:FS,statusReason:v().optional(),lastModified:N,excerpt:v().optional()}),iC=S({items:x(S({kind:tC,item:rC,other:rC.optional(),flag:VS.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)})}),aC=S({keep:I,drop:I,reason:v().min(1).max(500).optional()}),oC=S({kept:I,hidden:I,links:y().int().min(0),mentions:y().int().min(0)}),sC=S({name:I,of:I}),cC=S({names:x(I).min(1).max(20)}),lC=S({done:x(S({name:I,fields:x(HS),split:x(I).optional()})),failed:x(S({name:I,reason:v()}))}),uC=S({name:I,question:v().optional(),when:v().optional(),askedBy:zS.optional(),validUntil:N.optional(),lastModified:N,status:FS,statusReason:v().optional(),statusHistory:x(BS),metadata:US.optional(),metadataStale:b(),duplicate:VS.optional(),contradiction:VS.optional(),notDuplicates:x(I),split:WS.optional()}),dC={openQuestions:60,depth:6,minutes:10,cost:2},fC=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.`)}),pC=S({openQuestions:y().int().min(1),depth:y().int().min(1),minutes:y().min(0),cost:y().min(0)}),mC=E([`complete`,`open_questions`,`depth`,`time`,`cost`,`stopped`]),hC={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`},gC=v().regex(/^o\d+$/),_C=S({id:gC,label:v().min(1).max(200),detail:v().max(1e3).optional(),raises:x(I),later:x(v().min(1).max(500)).optional()}),vC=S({question:I,option:gC}),yC=S({name:I,question:v().min(1),askedBy:zS.optional(),depth:y().int().min(1),parents:x(vC),options:x(_C),planned:b(),known:b().optional(),picked:x(gC),text:v().max(4e3).optional(),answeredBy:M.optional(),answeredAt:N.optional(),status:FS,statusReason:v().optional(),reasonEdited:b().optional()}),bC=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)}),xC=S({description:v().min(1),limits:pC,stop:mC,cost:P,time:y().min(0),startedAt:N,updatedAt:N,roots:x(I),questions:x(yC),counts:bC,revision:y().int().min(0)}),SC=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:fC.optional()}),CC=S({run:A.describe(`The run of hub/ctx_plan that made the plan (its id, such as run_01HZX3).`)}),wC=CC.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.")}),TC=S({run:A,plan:xC,markdown:v().optional()}),EC=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.`)}),DC=S({question:I,reason:v().trim().min(1).max(500)}),OC=CC.extend({answers:x(EC).max(100).optional(),reasons:x(DC).max(100).optional()}),kC=S({run:A,plan:xC,changed:x(S({name:I,status:FS})),deeper:x(I),skipped:x(S({question:v(),reason:v()}))}),AC=CC.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:fC.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.")}),jC=S({run:A,description:v(),counts:bC,stop:mC.optional(),running:b(),actor:M,session:v().optional(),createdAt:N,updatedAt:N}),MC=S({limit:y().int().min(1).max(100).optional()}),NC=S({items:x(jC)});function PC(e){return e.known===!0||e.picked.length>0||(e.text??``).trim()!==``}function FC(e){return e.options.filter(t=>e.picked.includes(t.id)).map(e=>e.label)}function IC(e){let t=FC(e).map(e=>`"${e}"`);return`${t.length>0?t.join(` and `):`none of the options`} for '${e.question}'`}function LC(e){return`You chose ${IC(e)}`}function RC(e,t){return`'${e.question}' no longer applies${t===void 0?``:`: you chose ${IC(t)}`}`}function zC(e,t){return e.picked.length===0||e.picked.includes(t)}function BC(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(zC(i,t.id))for(let i of t.raises)!n.has(i)&&e.has(i)&&(n.add(i),r.push(i))}}return n}function VC(e,t){return e.picked.length>0&&!e.picked.includes(t)}function HC(e){let t=new Map(e.questions.map(e=>[e.name,e])),n=BC(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&&VC(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=>VC(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:LC(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:RC(s,a(s,new Set([t.name])))})}return o}function UC(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 WC(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 GC(e){return`/`+e.map(e=>e.t===`param`?`:${e.k}`:e.v).join(`/`)}function KC(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 qC(e){return e.filter(e=>e.t===`param`).map(e=>e.k)}var JC=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`}},YC=()=>{let e=globalThis.navigator;return typeof e?.onLine==`boolean`?e.onLine:void 0};function XC(e={}){let t=new Set,n=e.initial??(YC()===!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 ZC=e=>{if(Array.isArray(e))return e.map(ZC);if(e&&typeof e==`object`){let t={};for(let n of Object.keys(e).sort())t[n]=ZC(e[n]);return t}return e},QC=e=>JSON.stringify(ZC(e))??`null`,$C=e=>{try{return JSON.stringify(e)!==void 0}catch{return!1}},ew=(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))}}}),tw=(e,t)=>{if(typeof e==`object`)return e;if(e!==`memory`)try{let n=e===`local`?globalThis.localStorage:globalThis.sessionStorage;if(n)return ew(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 nw(e={}){let t=e.max??500,n=e.ttl??0,r=e.now??Date.now,i=tw(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(!$C(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 rw(e={},t=XC()){let n=new Map,r=t=>{let r=t??e.store??`memory`,i=n.get(r);return i||(i=nw({...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 iw=class extends Error{constructor(e=`caller rate limit exceeded`){super(e),this.name=`CallerRateLimited`}},aw=`\0`,ow=e=>new DOMException(e,`AbortError`),sw=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},cw=(e,t)=>new Promise((n,r)=>{if(t.aborted){r(ow(`aborted`));return}let i=()=>{clearTimeout(a),r(ow(`aborted`))},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e);t.addEventListener(`abort`,i,{once:!0})}),lw=(e,t)=>t.reduceRight((e,t)=>t(e),e),uw=(e,t,n)=>e===void 0?[]:typeof e==`function`?e(t,n):e,dw=(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)}},fw=(e,t,n)=>r=>async(i,a)=>{t!==`success`&&n.invalidateTags(uw(e,i.data,void 0));let o=await r(i,a);return t!==`start`&&n.invalidateTags(uw(e,i.data,o)),o},pw=(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:uw(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},mw=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}},hw=()=>{let e=null;return t=>(n,r)=>{e?.abort(ow(`superseded`));let i=new AbortController;e=i;let a=sw([r,i.signal]);return new Promise((e,r)=>{a.addEventListener(`abort`,()=>r(ow(`superseded`)),{once:!0}),t(n,a).then(e,r)}).finally(()=>{e===i&&(e=null)})}},gw=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 iw;await cw((1-r)*n,o),a()}return--r,e(i,o)}},_w=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 cw(Math.min(i,n*r**(l-1))*(1-a*Math.random()),s)}throw c}},vw=e=>e instanceof JC&&e.status===0&&e.code===`DISCONNECTED`,yw=(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(!vw(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)})}}},bw=(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(ow(`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 xw(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):QC(e),c=t=>`${e}${aw}${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(dw(i,u)),i.invalidates&&m.push(fw(i.invalidates,i.invalidateOn??`success`,r)),l&&m.push(pw(o,l,c)),i.dedupe&&m.push(mw(c)),i.lastOnly&&m.push(hw()),i.debounce!==void 0){let e=typeof i.debounce==`number`?{wait:i.debounce}:i.debounce;m.push(bw(e,d))}i.rateLimit&&m.push(gw(i.rateLimit)),i.retry&&m.push(_w(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(yw(ee,r)),(i.onOnline||i.onOffline)&&r.connectivity.subscribe(e=>e===`online`?i.onOnline?.():i.onOffline?.());let te=lw(p,m);return{call:(...e)=>{let t=a?e[0]:void 0,n=a?e[1]:e[0],r=sw([n?.signal,f.signal]);return te({data:t,opts:n},r)},cancel:()=>{f.abort(ow(`cancelled`)),f=new AbortController;for(let e of d)e()},invalidate:()=>void l?.removeWhere(t=>t.startsWith(`${e}${aw}`)),get pending(){return u.n}}}function Sw(e){try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}}function Cw(e){let{id:t,...n}=e;return JSON.stringify({rid:typeof t==`string`?t:null,...n})}function ww(e){let{rid:t,...n}=e;return JSON.stringify(typeof t==`string`?{id:t,...n}:n)}function Tw(e,t){return JSON.stringify({id:e,$status:0,$code:`DISCONNECTED`,$error:t})}function Ew(e){return`$status`in e||e.end===!0}var Dw=class{#e=new Set;add(e){this.#e.add(e)}settle(e){typeof e.id==`string`&&Ew(e)&&this.#e.delete(e.id)}fail(e,t){let n=[...this.#e];this.#e.clear();for(let r of n)e(Tw(r,t))}},Ow={$status:501,$code:`NOT_SERVED`,$error:`this client serves no spec`};function kw(e,t){let n=e.rid;typeof n==`string`&&typeof e.type==`string`&&t(JSON.stringify({rid:n,...Ow}))}var Aw=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,ww(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=Sw(t);n&&this.#e===e&&this.send(Cw(n))},this.request());return this.#e=e,e}},jw=new Set([101,204,205,304]);function Mw(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=jw.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 Nw(e){return!!e&&typeof e.parse==`function`}function Pw(e){let t=Fw(e);return t?t():e}function Fw(e){let t=e[Symbol.for(`ayepi.manifest`)];return typeof t==`function`?t:void 0}function Iw(e){return typeof e==`number`&&e>=200&&e<300}var Lw={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 Rw(e){let t=Number(e.$status);return new JC(t,typeof e.$code==`string`?e.$code:`ERROR`,typeof e.$error==`string`?e.$error:Lw[t]??`Request failed with status ${t}`,e.data)}function zw(e){let t=Pw(e.manifest),n=e.fetchImpl??(e=>fetch(e)),r=XC(),i=rw(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&&Nw(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 Aw(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=Sw(e);if(!i)return;if(`rid`in i){r?r.receive(i):kw(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&&!Iw(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(Rw(t)))}else if(m.has(e)){let r=m.get(e);m.delete(e),ie(e),n?r.reject(Rw(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=KC(WC(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 Mw(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 JC(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 JC(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 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
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 xw(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 Bw={initial:500,max:3e4,factor:2,jitter:!0},Vw={interval:3e4,timeout:1e4};function Hw(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={...Bw,...t.backoff},o=t.heartbeat===!1?null:{...Vw,...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 Dw,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(Tw(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 Uw(e,t,n){return{kind:`endpoint`,cfg:e,mws:t,prefixes:n}}function Y(e){return Uw(e,[],[])}function X(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(...)`)}qw(t,n)}let t;return Object.defineProperty(e,Ww,{value:()=>t??=Gw(e),enumerable:!1,configurable:!0}),e}var Ww=Symbol.for(`ayepi.manifest`);function Gw(e){let t=Object.entries(e.endpoints).map(([e,t])=>qw(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 Kw(e){return e&&e instanceof dc?Object.keys(e.shape):null}function qw(e,t){let n=t.cfg,r=tT(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=Kw(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`?WC(e):e.parts);if(c)d.push(...c.parts);else if(typeof n.path==`string`)d.push(...WC(n.path));else{d.push({t:`lit`,v:e});let t=new Set(qC(d));for(let e of u)t.has(e)||d.push({t:`param`,k:e})}let f=qC(d),p=new Set(f);f.length!==p.size&&i(`path positions a param more than once: ${GC(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 ${GC(d)}`);let m=[...u],h=Kw(n.query)??[],ee=n.body?Kw(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:GC(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 Jw(){return{}}function Yw(e){return()=>{throw Error(`middleware "${e}" has no implementation — bind it with implement(api).middleware(def, impl)`)}}function Xw(e,t,n,r,i,a){let o={kind:`middleware`,name:e,requires:t,optional:n,paramKey:r,paramSchema:i,doc:a,run:Yw(e),with(...e){return Zw([o,...e],[])},path(e){return Zw([o],[e])},endpoint(e){return Zw([o],[]).endpoint(e)},group(e){return Zw([o],[]).group(e)}};return o}function Zw(e,t){return{kind:`stack`,mws:e,prefixes:t,with(...n){return Zw([...e,...n],t)},path(n){return Zw(e,[...t,n])},endpoint(n){return Uw(n,e,t)},group(n){let r={};for(let[i,a]of Object.entries(n))r[i]=Uw(a,e,t);return r}}}function Z(...e){return Zw([...e],[])}function Qw(e,t){return Xw(e,t?.requires??[],t?.optional??[],void 0,void 0,t?.doc)}function $w(e,t,n){return Xw(e,n?.requires??[],n?.optional??[],e,t,n?.doc)}var eT=Object.assign(Qw,{loader:$w});function tT(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 nT(...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 X({endpoints:t,events:n})}var rT=new WeakMap;function iT(e,t){return rT.set(e._zod.def,{source:t}),e}function aT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var oT=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 aT(e)&&Object.values(e).every(e=>{try{return this.value.parse(e,t),!0}catch{return!1}})}parse(e,t){if(!aT(e))throw new th({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 th({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 sT(e){return e.typeClass(oT.NAME)===void 0&&e.define(oT),e}function cT(){return sT(ny())}var lT;function uT(){return lT??=cT(),lT}var dT=lb.result(`TypeDef`),fT=lb.result(`Expr`);function pT(e){return()=>{let{description:t,...n}=e(uT()).render($l).jsonSchema;return n}}function mT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hT(e){return mT(e)&&`name`in e&&typeof e.name==`string`}var gT=iT(Jc(hT,{message:`Expected a gin type definition ({ name, ... }).`}),pT(e=>dT.bind(e,void 0,{namedRefs:!0})));function _T(e){return hT(e)}var vT=iT(Jc(_T,{message:`Expected a gin object type definition ({ name: "obj", props: { ... } }).`}),pT(e=>fb(e.typ(e.obj({}))).bind(e,void 0,{namedRefs:!0})));function yT(e){return mT(e)&&`kind`in e&&typeof e.kind==`string`}var bT=iT(Jc(yT,{message:`Expected a gin expression ({ kind, ... }).`}),pT(e=>fT.bind(e,void 0,{namedRefs:!0}))),xT=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(`.`)),ST=new Map([[`ctx`,`context`]]);function CT(e,t){let n=e.toLowerCase();if(xT.has(n))return n.toUpperCase();let r=ST.get(n);return r===void 0?n.endsWith(`s`)&&xT.has(n.slice(0,-1))?`${n.slice(0,-1).toUpperCase()}s`:t?e:n:t?OT(r):r}function wT(e){return OT((/[\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)=>CT(e,t===0)).join(` `))||e}function TT(e){return e.label??wT(e.name)}function ET(e){return wT(Il(e).local)}function DT(e){return/^[A-Z][a-z]/.test(e)?`${e.charAt(0).toLowerCase()}${e.slice(1)}`:e}function OT(e){return e===``?e:`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function kT(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 AT=[`path`,`file`,`uri`,`query`,`command`,`url`,`name`,`title`,`text`,`pattern`,`message`];function jT(e,t=60){if(e==null)return``;if(typeof e==`string`)return kT(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=AT.map(t=>e[t]).find(e=>typeof e==`string`&&e!==``);if(typeof n==`string`)return kT(n,t);for(let[n,r]of Object.entries(e))if(typeof r==`string`||typeof r==`number`||typeof r==`boolean`)return kT(`${n}: ${String(r)}`,t);return``}var MT=[`active`,`retry`,`done`,`failed`],NT=E(MT),PT=S({one:v().min(1),many:v().min(1)}),FT=S({active:PT,retry:PT,done:PT,failed:PT}),IT=S({phase:NT,one:v(),many:v()}),LT={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 RT(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 zT=60,BT=3,VT=/\{([^{}|]+)(?:\|([^{}]*))?\}/g;function HT(e,t,n){for(let r of e){if(r===void 0)continue;let e=WT(r[t].one,n,!1),i=WT(r[t].many,n,!0);if(e!==void 0&&i!==void 0)return{phase:t,one:e,many:i}}let r=LT[t];return{phase:t,one:WT(r.one,n,!1)??r.one,many:WT(r.many,n,!0)??r.many}}function UT(e,t){return t===1?e.one:e.many.replaceAll(`{n}`,String(t))}function WT(e,t,n){let r=[],i=e.replace(VT,(e,i,a)=>{let o=GT(i.trim(),t,n);return o===void 0?a===void 0?(r.push(i),e):a:o});return r.length>0?void 0:OT(i.replace(/…{2,}/g,`…`))}function GT(e,t,n){if(e===`fn`)return DT(ET(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:qT(KT(a,i))}function KT(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 qT(e){if(e!=null){if(typeof e==`string`)return e===``?void 0:YT(e);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e)){let t=e.map(qT).filter(e=>e!==void 0);if(t.length===0)return;let n=t.slice(0,BT),r=t.length-n.length;return JT(r>0?[...n,`${r} more`]:n)}for(let t of[`title`,`name`,`id`]){let n=e[t];if(typeof n==`string`&&n!==``)return YT(n)}}}function JT(e){return e.length<=2?e.join(` and `):`${e.slice(0,-1).join(`, `)} and ${e.at(-1)??``}`}function YT(e){let t=e.split(`
401
+ `)[0]??``;return t.length>zT?`${t.slice(0,59)}…`:t}var XT=E([`system-needs-config`,`system-disconnected`,`system-removed`,`kind-missing`,`kind-system-disconnected`,`dep-unavailable`,`disabled`,`held`,`paused`,`role-unset`]),ZT=C([D(!0),S({unavailable:XT,detail:v()})]),QT=S({code:E([...XT.options,`no-such-fn`,`not-a-name`,`other-system`,`not-for-model`,`connect-account`]),reason:v().min(1),system:F.optional()}),$T=QT.extend({fn:v()}),eE=QT.extend({name:v()}),tE=S({id:M,name:v(),email:v(),role:E([`admin`,`member`]),groups:x(S({id:M,name:v()})),timeZone:v(),locale:v()}),nE=S({now:N,timeZone:v(),local:v()}),rE=S({name:v(),instance:L,boot:v(),from:S({system:v(),fn:I,run:A}).optional()}),iE=S({id:A,fn:I,parent:A.optional(),turn:cl,session:j.optional(),user:tE,time:nE,system:rE,caller:M,attempt:y().int().min(1),priority:Rl,watched:b().optional(),inChat:b().optional()}),aE=S({timeZone:v(),locale:v(),now:N}),oE=E([`card`,`message`,`hidden`]),sE=S({cancel:b(),pause:b(),undo:b(),background:b()}),cE=sE.pick({cancel:!0,pause:!0,background:!0}),lE=S({timeout:Ml.optional(),retries:y().int().min(0).optional(),cost:P.optional()}),uE=w(`type`,[S({type:D(`none`)}),S({type:D(`linear`)}),S({type:D(`steps`),steps:T(v(),v())})]),dE=E([`pending`,`active`,`done`,`failed`,`skipped`]),fE=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({steps:T(v(),S({status:dE,detail:v().optional()}))})]),pE=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({step:v(),status:dE,detail:v().optional()})]),mE=[`retry`,`caller`,`fatal`],hE=S({class:E(mE),message:v(),code:v().optional(),data:O.optional()}),gE=E([`json`,`schema`,`validation`,`unavailable`,`result`]),_E=S({path:v(),message:v()}),vE=S({path:v(),repair:E([`json-string`])});function yE(e){return e.path===``?e.message:`${e.path}: ${e.message}`}var bE=S({source:gE,problems:x(_E).min(1),raw:v().optional(),blocked:QT.optional()}),xE=[`awaiting-approval`,`queued`,`running`,`waiting`,`paused`,`done`,`invalid-input`,`failed`,`cancelled`,`undone`],SE=E(xE),CE={"awaiting-approval":!1,queued:!1,running:!1,waiting:!1,paused:!1,done:!0,"invalid-input":!0,failed:!0,cancelled:!0,undone:!0},wE={"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 TE(e){return CE[e]}function EE(e){return!CE[e]}var DE=xE.filter(TE),OE=xE.filter(EE),kE=w(`type`,[S({type:D(`status`),status:SE,text:IT.optional()}),S({type:D(`progress`),progress:fE}),S({type:D(`allowed`),operations:cE}),S({type:D(`cost`),cost:P,total:P}),S({type:D(`background`)}),S({type:D(`result`),revision:y().int().min(1)})]),AE=w(`status`,[S({status:D(`done`),result:O,undo:O.optional(),cost:P.optional(),expose:x(ex).optional()}),S({status:D(`invalid-input`),invalid:bE,undo:O.optional(),cost:P.optional()}),S({status:D(`paused`),resume:O,cost:P.optional()}),S({status:D(`failed`),error:hE,undo:O.optional(),cost:P.optional()}),S({status:D(`cancelled`),partial:O.optional(),undo:O.optional(),cost:P.optional(),error:hE.optional()})]),jE=w(`status`,[S({status:D(`done`),result:O}),S({status:D(`failed`),error:hE}),S({status:D(`cancelled`),error:hE.optional()}),S({status:D(`background`),run:A})]),ME=w(`status`,[S({status:D(`undone`),summary:v()}),S({status:D(`failed`),error:hE}),S({status:D(`gone`)})]),NE=w(`ok`,[S({ok:D(!0),value:O}),S({ok:D(!1),error:hE})]),PE=S({cost:P,time:Ml,limitedBy:v()}),FE=Fx,IE=S({hash:v().regex(qx),kind:nS,converter:v().min(1),content:Jx,chars:y().int().min(0),tokens:y().int().min(0),call:Ol.optional(),createdAt:N}),LE=S({kind:nS,model:v().optional(),estimate:y().min(0).optional()}),RE=w(`from`,[S({from:D(`system`),system:F,served:E([`bytes`,`text`]).optional()}),S({from:D(`upload`),by:M}),S({from:D(`web`),url:Nb,finalUrl:Nb.optional(),fetchedAt:N,rendered:b()}),S({from:D(`run`),run:A,fn:I})]),zE=[`system`,`upload`,`web`,`run`],BE=E([`auto`,`always`,`never`]),VE=`hub://resources/`,HE=[`document`,`code`,`image`,`table`,`audio`,`video`,`web`,`data`,`archive`,`folder`,`other`],UE=E(HE),WE={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 GE(e,t){let n=e===void 0?void 0:WE[e];if(n!==void 0)return n;let r=t?.split(`/`)[0];return r===`image`||r===`audio`||r===`video`?r:`other`}var KE=E([`type`,`source`,`path`,`date`]),qE=S({value:v(),label:v(),count:y().int().min(0)}),JE=Hl.extend({search:v().optional(),system:F.optional(),family:UE.optional(),source:E(zE).optional(),under:v().optional(),form:nS.optional(),missing:nS.optional(),group:KE.optional(),in:v().optional()}),YE=S({uri:Wx}),XE=S({uri:Wx,section:Gx.optional()}),ZE=S({image:Wx,question:v().trim().min(1).max(2e3),page:y().int().min(1).optional()}),QE=S({answer:v(),model:v(),image:S({id:Wx,name:v()})}),$E=S({uri:Wx,form:C([nS,D(`raw`)]).optional(),section:Gx.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()}),eD=S({uri:Wx,form:C([nS,D(`raw`)]),text:v(),offset:y().int().min(0),total:y().int().min(0),truncated:b(),partial:v().optional(),note:v().optional(),forms:x(nS),offers:x(LE)}),tD=C([S({url:Nb,render:BE.optional(),name:v().optional(),folder:v().min(1).optional()}),S({content:Jx,name:v().min(1),path:v().optional()})]),nD=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()})})]),rD=S({id:v(),name:v(),arguments:v(),invalid:v().optional()}),iD=S({type:E([`text`,`image`,`file`,`audio`,`video`]),content:v(),format:v().optional(),name:v().optional()}),aD=S({role:E([`system`,`user`,`assistant`,`tool`]),content:C([v(),x(iD)]),name:v().optional(),toolCallId:v().optional(),toolCalls:x(rD).optional(),refusal:v().optional(),tokens:y().int().optional()}),oD=S({input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional()}),sD=E([`stop`,`length`,`tool_calls`,`content_filter`,`refusal`]),cD=S({content:v().optional(),reasoning:v().optional(),toolCallNamed:rD.optional(),toolCallArguments:rD.optional(),toolCallMore:rD.optional(),toolCall:rD.optional(),finishReason:sD.optional(),refusal:v().optional(),usage:oD.optional()}),lD=C([b(),y().positive()]),uD=E([`summary`,`list`,`markers`,`full`]),dD=C([uD,S({detail:uD.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()})]),fD=S({name:v(),description:v().optional(),parameters:O,strict:lD.optional(),errorFormat:dD.optional()}),pD=C([D(`text`),D(`json`),S({schema:O,strict:lD,errorFormat:dD.optional(),schemaDelivery:E([`auto`,`structured`,`json`,`prompt`]).optional()})]),mD=S({messages:x(aD),temperature:y().optional(),maxTokens:y().int().optional(),stop:x(v()).optional(),tools:x(fD).optional(),toolChoice:C([E([`auto`,`none`,`required`]),S({tool:v()})]).optional(),responseFormat:pD.optional(),errorFormat:dD.optional()}),hD=S({run:A.optional(),request:mD,model:nD.optional(),stream:b()}),gD=w(`type`,[S({type:D(`chunk`),chunk:cD}),S({type:D(`done`),usage:oD,cost:P,interaction:fl,model:v()}),S({type:D(`error`),message:v(),kind:E([`model`,`tool`,`limit`,`provider`])})]),_D=S({id:v().min(1),text:v().min(1),score:y().min(0).max(1)}),vD=S({run:A,question:v().min(1),candidates:x(_D).min(1).max(50),max:y().int().min(1).max(20)}),yD=w(`by`,[S({by:D(`decision`),picked:x(S({id:v(),why:v().optional()})),note:v().optional(),call:Ol.optional()}),S({by:D(`off`)}),S({by:D(`failed`),message:v()})]),bD=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)})]),xD=C([v().min(1),x(aD).min(1)]),SD=T(v().min(1),bD),CD=y().min(0).max(1),wD=w(`type`,[S({type:D(`predicate`),probability:CD}),S({type:D(`choice`),choice:v(),probabilities:T(v(),CD),confidence:CD}),S({type:D(`score`),score:y(),probabilities:x(CD),confidence:CD}),S({type:D(`refusal`)})]),TD=T(v(),wD),ED=.5,DD=[`chat`,`embed`,`image`,`transcribe`,`speech`,`decide`];E(DD);var OD=E([`yes`,`no`,`unknown`]),kD=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:OD.optional()}),AD=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)}),jD=S({modality:D(`image`),images:y().int().min(0),size:v().optional()}),MD=S({modality:D(`transcribe`),seconds:y().min(0),bytes:y().int().min(0)}),ND=S({modality:D(`speech`),characters:y().int().min(0),seconds:y().min(0).optional()}),PD=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`,[kD,AD,jD,MD,ND,PD]);var FD=E([`mp3`,`wav`,`ogg`]),ID=E([`running`,`done`,`failed`,`aborted`]),LD=S({id:Ol,provider:v(),model:v(),run:A.optional(),turn:cl.optional(),session:j.optional(),system:F.optional(),fn:I.optional(),purpose:v().optional(),interaction:fl.optional(),cost:P,status:ID,error:v().optional(),priority:Rl.optional(),sent:y().int().min(0),received:y().int().min(0),queued:Ml,firstByte:Ml.optional(),total:Ml.optional(),startedAt:N,endedAt:N.optional()}),RD=e=>S({modality:e.shape.modality,units:e}),zD=w(`modality`,[RD(kD),RD(AD),RD(jD),RD(MD),RD(ND),RD(PD)]),BD=e=>LD.extend(e.shape),VD=w(`modality`,[BD(zD.options[0]),BD(zD.options[1]),BD(zD.options[2]),BD(zD.options[3]),BD(zD.options[4]),BD(zD.options[5])]),HD=w(`modality`,[S({modality:D(`embed`),texts:x(v()).min(1),model:nD.optional()}),S({modality:D(`image`),prompt:v().min(1),model:nD.optional(),size:v().optional(),count:y().int().min(1).max(10).optional()}),S({modality:D(`transcribe`),audio:Jx,model:nD.optional(),language:v().optional()}),S({modality:D(`speech`),text:v().min(1),model:nD.optional(),voice:v().optional(),format:FD.optional()}),S({modality:D(`decide`),input:xD,questions:SD,model:nD.optional()})]).and(S({run:A.optional()})),UD=w(`modality`,[S({modality:D(`embed`),vectors:x(x(y()))}),S({modality:D(`image`),images:x(Jx)}),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:Jx}),S({modality:D(`decide`),answers:TD})]).and(S({call:Ol,cost:P,model:v()})),WD=E([`chat`,`transcribe`,`dictate`,`speak`,`describe`,`ocr`,`decide`,`metadata`,`plan`]),GD={chat:`chat`,transcribe:`hearing`,dictate:`hearing`,speak:`audio`,describe:`vision`,ocr:`vision`,decide:`decision`,metadata:`chat`,plan:`chat`},KD=S({model:nD,provider:Tl.optional()}),qD=w(`engine`,[S({engine:D(`browser`)}),KD.extend({engine:D(`model`)})]),JD=[`browser`,`model`],YD=WD.exclude([`dictate`,`decide`]),XD=KD.extend({role:D(`decide`),threshold:y().min(0).max(1).default(ED)}),ZD=w(`role`,[S({role:D(`dictate`),engine:qD,language:v().optional()}),XD,KD.extend({role:YD,language:v().optional()})]);S({choice:ZD,setBy:M,updatedAt:N});var QD=C([S({model:v(),provider:v()}),S({problem:v()})]),$D=S({role:WD,choice:ZD.optional(),from:E([`setting`,`env`,`none`]),resolved:QD.optional(),fallback:S({role:WD,reason:v()}).optional()}),eO=[`done`,`invalid-input`,`failed`,`cancelled`],tO=T(E(eO),y().int().min(0));function nO(){return{done:0,"invalid-input":0,failed:0,cancelled:0}}function rO(e){return eO.reduce((t,n)=>t+e[n],0)}var iO=v().regex(/^\d{4}-\d{2}-\d{2}$/),aO=[50,100,250,500,1e3,2500,5e3,1e4,3e4,6e4,3e5],oO=S({count:y().int().min(0),sum:Ml,max:Ml,histogram:x(y().int().min(0)).length(aO.length+1)}),sO=S({fn:I,system:F,day:iO,outcomes:tO,queued:oO,approval:oO,ran:oO,cost:P,tokens:y().int().min(0),retries:y().int().min(0),modelCalls:y().int().min(0),updatedAt:N}),cO=S({fn:I,system:F,from:iO,to:iO,runs:y().int().min(0),outcomes:tO,p50:Ml.optional(),p95:Ml.optional(),averageQueued:Ml.optional(),averageCost:P,cost:P,tokens:y().int().min(0),retries:y().int().min(0),lastRunAt:N.optional()}),lO=S({fn:kb.optional(),system:F.optional(),days:y().int().min(1).max(365).optional()}),uO=E([`private`,`shared`,`public`]),dO={private:`Only me`,shared:`Me and chosen people`,public:`Everyone`},fO=S({owner:M,visibility:uO,with:x(M)});E([`system`,`fn`,`context`,`root`,`connection`]);var pO=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:jl})]);function mO(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:pO,sharing:fO,scoped:b().optional(),setBy:M,updatedAt:N});var hO=S({target:pO,sharing:fO,editable:b()}),gO=S({multiUser:b()}),_O=fO.omit({owner:!0}),vO=S({run:A,fn:k,share:_O}),yO=S({run:A,fns:x(k).max(1e3)}),bO=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()}),xO=S({value:v(),label:v(),hint:v().optional(),icon:v().optional(),missing:b().optional()}),SO=S({on:b(),ask:b()}),CO=w(`flow`,[S({flow:D(`oauth`)}),S({flow:D(`form`),form:gT})]),wO=S({flow:CO.optional(),share:b().default(!1),title:v().min(1)}),TO=v().regex(Nl).brand(),EO=C([TO,S({arg:k})]),DO=S({title:v(),description:v(),icon:v().optional(),how:CO,settings:gT,fns:T(k,SO),scope:E([`system`,`instance`,`key`]).optional(),keys:S({type:I}).optional(),defaults:SO.optional()}),OO=E([`pending`,`connected`,`expired`,`failed`]),kO=S({label:v(),detail:v().optional(),choices:T(v(),x(xO)).optional()}),AO=S({id:jl,system:F,instance:L.optional(),key:TO.optional(),owner:M,status:OO,account:kO.optional(),credentials:Cl.optional(),expiresAt:N.optional(),settings:O,fns:T(k,SO),share:_O,problem:v().optional(),createdAt:N,updatedAt:N}).omit({credentials:!0}),jO=S({system:F,decl:DO,ready:b(),connections:x(AO),instances:x(S({instance:L,label:v(),connect:wO})).optional(),keys:x(S({key:TO,label:v(),connect:wO,host:v().optional()})).optional()}),MO=S({id:jl,owner:M,credentials:O,settings:O}),NO=S({connection:jl,owner:M,redirect:Ls(),state:v(),instance:L.optional(),key:TO.optional()}),PO=S({connection:jl,owner:M,instance:L.optional(),key:TO.optional(),redirect:Ls(),answer:C([S({params:T(v(),v())}),S({form:O})])}),FO=C([S({account:kO,credentials:O,expiresAt:N.optional()}),S({problem:v()})]),IO=S({connection:jl,update:C([S({credentials:O,expiresAt:N.optional()}),S({expired:v()})])}),LO=S({connection:jl,settings:O.optional(),fns:T(k,SO).optional(),share:_O.optional()}),RO=[`embedding`,`imageEmbedding`],zO=S({input:P,output:P,cached:P.optional(),cacheWrite:P.optional()}),BO=S({id:v().min(1),name:v().optional(),capabilities:x(v()),contextWindow:y().int().min(1),maxOutput:y().int().min(1).optional(),pricing:zO,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=>!RO.some(t=>e.capabilities.includes(t))||e.dimensions!==void 0,{message:`An embedding model says how many dimensions its vectors have.`,path:[`dimensions`]}),VO=S({name:k,description:v(),models:x(BO),runtime:D(!0).optional(),instance:L.optional()}),HO=S({provider:k,model:v(),request:mD,stream:b(),run:A.optional()}),UO=w(`type`,[S({type:D(`chunk`),chunk:cD}),S({type:D(`done`),usage:oD}),S({type:D(`error`),message:v(),kind:E([`model`,`limit`,`provider`,`auth`])})]),WO=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()}),GO=S({provider:k}),KO=w(`listed`,[S({listed:D(!0),models:x(WO)}),S({listed:D(!1)})]),qO=S({provider:k,model:v(),input:xD,questions:SD}),JO=S({answers:TD,tokens:y().int().min(0).optional()}),YO=S({image:v().regex(/^(https?:|data:)/,`an http(s) or data URL`),mimeType:v().optional()}),XO=C([v(),YO]),ZO=S({provider:k,model:v(),inputs:x(XO).min(1)}),QO=S({vectors:x(x(y())),tokens:y().int().min(0).optional()});function $O(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 ek=S({input:b(),output:b()}),tk=C([S({ok:D(!0)}),S({ok:D(!1),reason:v().min(1)})]),nk=C([S({ok:D(!0)}),S({ok:D(!1),action:E([`retry`,`stop`]),reason:v().min(1)})]),rk=w(`phase`,[S({phase:D(`input`),run:iE,fn:v(),args:O}),S({phase:D(`output`),run:iE,fn:v(),args:O,result:O,attempt:y().int().min(1)})]),ik=C([nk,tk]),ak=S({kind:E([`builtin`,`dynamic-import`,`dynamic-require`,`eval`,`new-function`]),line:y().int().min(1),detail:v(),code:v()}),ok=S({size:y().int().min(0),builtins:x(v()),concerns:x(ak),urls:x(v()),hosts:x(v())}),sk=E([`passed`,`failed`,`skipped`]),ck=S({file:v().min(1),name:v().min(1),status:sk,duration:Ml,real:b().optional(),error:v().max(4e3).optional()}),lk=[`phone`,`desktop`],uk=E(lk);E([`empty`,`loading`,`error`,`typical`,`long`]);var dk=S({component:v().min(1),state:v().min(1),viewport:uk,theme:E([`light`,`dark`]),image:Jx}),fk=S({scan:ok,tests:S({system:F,version:v().min(1),ranAt:N,duration:Ml,passed:y().int().min(0),failed:y().int().min(0),skipped:y().int().min(0),cases:x(ck).max(500),more:y().int().min(0).optional(),previews:x(dk).max(200).optional()}).optional()}),pk=E([`ai`,`embed`,`resources`,`fns`,`search`,`decide`,`approvals`,`connections`,`settings`,`state`,`data`,`runs`]),mk=S({roles:x(WD).optional(),models:x(v().min(1)).optional(),perRun:P.optional(),perDay:P.optional()}),hk=S({read:x(v().min(1)),write:x(v().min(1))}),gk=S({hub:x(pk),models:mk.optional(),secrets:x(v().min(1)).optional(),calls:x(C([I,F])).optional(),network:x(v().min(1)).optional(),files:hk.optional()}),_k=S({component:v().min(1),mode:E([`replace`,`beside`])}),vk=[`installed`,`live`],yk=E(vk),bk=[`text`,`integer`,`number`,`boolean`,`date`,`datetime`,`time`,`uuid`,`json`,`binary`],xk=E(bk),Sk=E([`group`,`measure`,`attribute`]),Ck=S({name:k,label:v().min(1),accepts:x(xk).min(1),required:b(),many:b(),min:y().int().min(1).optional(),role:E([`group`,`measure`]).optional()}),wk=w(`rule`,[S({rule:D(`distinct`),channel:k,max:y().int().min(1),min:y().int().min(1).optional()}),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})]),Tk=E([`window`,`top-n`,`partition`,`aggregate`]),Ek=S({name:k,label:v().min(1),whole:D(!0).optional(),needs:x(k).optional(),columns:T(k,S({min:y().int().min(0).optional(),max:y().int().min(0).optional()})).optional(),rules:x(wk).optional()}),Dk=S({claim:D(`range`),channel:k}),Ok=E([`floor`,`structural`,`encoded`,`time-encoded`]),kk=E([`temporal-key`,`low-cardinality`,`enum-key`,`high-null`,`many-categories`]),Ak=S({channels:x(Ck).min(1),rows:S({min:y().int().min(0),max:y().int().min(1).optional()}),whole:b(),rules:x(wk).default([]),size:Tk.optional(),styles:x(Ek).min(1).default([{name:`default`,label:`Default`}]),claims:x(Dk).default([]),priority:S({band:Ok,terms:x(kk)}).default({band:`structural`,terms:[]}),pageSize:y().int().min(1).max(500).optional()}),jk=S({name:k,description:v(),data:gT}),Mk=S({registry:I,name:k,label:v().min(1),description:v().optional(),icon:v().optional(),shape:Ak.optional()}),Nk=Mk.extend({system:F}),Pk=S({name:v().min(1),label:v().optional(),kind:xk,nullable:b(),type:gT.optional(),ref:I.optional(),role:Sk.optional(),key:b().optional(),editable:b().optional()}),Fk=S({column:v().min(1),dir:E([`asc`,`desc`])}),Ik=S({fn:I,args:T(v(),O),keys:x(v().min(1))}),Lk=S({columns:x(Pk),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(Fk),write:S({affected:y().int().min(0)}).optional(),records:S({type:I,id:v().min(1)}).optional(),drill:Ik.optional()}),Rk=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()}),zk=S({section:v().min(1),added:y().int().min(0),changed:y().int().min(0),removed:y().int().min(0)}),Bk=E([`widened`,`narrowed`,`changed`,`added`]),Vk=S({line:v(),counts:x(zk),flags:x(Rk),grants:Bk.optional(),config:E([`added`,`changed`,`removed`]).optional()}),Hk=E([`gitignored`,`env`,`key`,`credential`,`token`,`secret-content`,`runs-code`,`unknown-path`]),Uk=E([`allow`,`ask`,`refuse`]),Wk=E([`ask`,`refuse`]),Gk=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:Hk,match:Gk,except:x(v().min(1)).optional(),read:Uk,write:Wk,why:v().min(1)});var Kk=S({path:v().min(1),kind:Hk,rule:v().min(1),access:E([`read`,`write`]),action:E([`allow`,`ask`,`refuse`]),why:v().min(1),certain:b()}),qk=S({flags:x(Kk)}),Jk=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:Lk}),S({type:D(`type-diff`),name:v(),before:gT.optional(),after:gT.optional(),changes:x(v()),breaks:x(S({fn:v(),why:v()}))}),S({type:D(`flags`),flags:x(Kk).min(1)})]),Yk=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:ql,source:v().min(1).optional(),grants:gk.optional(),replaces:S({version:v().min(1),manifestHash:v().min(1)}).optional()}),Xk=w(`kind`,[Yk]),Zk=S({title:v().min(1),parts:x(Jk),irreversible:b(),subject:Xk.optional(),checks:fk.optional(),summary:Vk.optional()}),Qk=E([`person`,`admins`]),$k=S({preview:b(),remember:b(),approver:Qk.optional()}),eA=S({run:A,fn:k,args:O,user:tE,kind:Pl.optional(),payload:O.optional()}),tA=S({run:A,fn:k,args:O,user:tE,deadline:N}),nA=S({problems:x(_E)}),rA=S({type:gT,into:k,label:v().min(1).max(80).optional()}),iA=S({fn:k,args:O,key:v().min(1),parent:A.optional(),approver:Qk,for:M.optional(),chat:j.optional(),ask:rA.optional(),preview:Zk}).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`]}),aA=S({by:M,preview:Zk}),oA=S({run:A,subject:Yk}),sA=S({token:v().min(1),expiresAt:N}),cA=S({run:A,approval:gl}),lA=v().regex(/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/),uA=x(lA),dA=`•••• kept`,fA=S({$secret:Cl,json:D(!0).optional()}),pA=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)`),mA=E([`main`,`hidden`]),hA=E([`app`,`admin`]),gA=E([`everyone`,`admin`]),_A=S({segment:pA,title:v().trim().min(1).max(40),description:v().optional(),icon:v().min(1).optional(),nav:mA.default(`main`),access:gA.default(`everyone`),area:hA.optional(),component:v().min(1)});function vA(e){let t=new Set;return e.flatMap(e=>t.has(e.segment)?[`page ${e.segment} is declared twice`]:(t.add(e.segment),[]))}var yA=x(_A).superRefine((e,t)=>{for(let n of vA(e))t.addIssue({code:`custom`,message:n})}),bA=_A.extend({system:F,client:S({url:v().min(1),hash:v().min(1)})}),xA=S({instance:L,description:v(),online:b(),version:v()}),SA=`http://127.0.0.1:11434`;function CA(e){return w(`provider`,[S({provider:D(`openai`),apiKey:e,baseURL:Ls().optional()}),S({provider:D(`anthropic`),apiKey:e}),S({provider:D(`google`),apiKey:e}),S({provider:D(`openrouter`),apiKey:e}),S({provider:D(`ollama`),baseURL:Ls().default(SA),contextWindow:y().int().min(256).optional(),decisionModels:x(v().min(1)).optional()}),$O(e)])}var wA=CA(Cl),TA=E(wA.options.map(e=>e.shape.provider.value));S({id:Tl,config:wA,createdAt:N}),S({id:Cl,name:v(),owner:M,ciphertext:v(),createdAt:N});var EA=S({id:wl,name:v(),description:v(),models:x(v())}),DA=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:cl}),S({scope:D(`system`),system:F}),S({scope:D(`fn`),fn:I}),S({scope:D(`model`),model:v()})]),OA=E([`hub`,`group`,`user`,`session`,`turn`]),kA=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:cl})]),AA=S({id:_l,target:DA,period:C([S({window:Ml}),D(`all-time`),D(`per-turn`)]),maxCost:P,maxTokens:y().int().optional(),maxCalls:y().int().optional(),maxTime:Ml.optional(),share:E([`pooled`,`each`]).optional(),onLimit:E([`wait`,`refuse`,`ask`]),setBy:M}),jA=S({id:vl,target:kA,default:Rl.optional(),max:Rl.optional(),setBy:M}),MA=S({priority:Rl,priorityFrom:S({default:OA,cappedBy:OA.optional()}),turn:S({cost:P,time:Ml}),budgets:x(S({rule:_l,scope:DA,remaining:P})),limitedBy:_l.optional()});S({id:yl,budgets:x(_l),estimate:P,createdAt:N,settled:S({cost:P,at:N}).optional()}),S({id:bl,at:N,cost:P,tokens:y().int().min(0),actor:M,system:F.optional(),session:j.optional(),fn:I,model:v().optional(),llmCall:fl.optional(),modelCall:Ol.optional(),run:A});var NA=E([`chat`,`admin`,`disconnected`,`needs-config`,`held`,`removed`]),PA=S({prompt:x(S({name:F,label:v(),description:v(),summary:v().optional()})),on:x(F),off:x(S({name:F,why:NA}))}),FA=S({name:F,reason:v(),label:v().optional(),description:v().optional()}),IA=RegExp(`(\\d+)`,`g`);function LA(e,t=[]){let n=new Map(t.map(e=>[e.index,e.number]));return e.replace(IA,(e,t)=>{let r=n.get(Number(t));return r===void 0?``:`[${r}]`})}function RA(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 zA(e){try{return O.parse(JSON.parse(e))}catch{return}}function BA(e,t){let n=RA(t);if(n===void 0)return;let r=e;for(let e of n){let t=typeof r==`string`?zA(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 VA=S({index:y().int().min(1),number:y().int().min(1),tool:v(),path:v(),note:v()}),HA=E([`result`,`reply`]),UA=VA.extend({run:A.optional(),fn:I.optional(),found:HA.optional(),value:O.optional(),large:D(!0).optional(),problem:v().optional()}),WA=S({prompt:b(),on:b()}),GA=y().int().min(0).max(3),KA=S({agent:I,model:nD.optional(),mode:ix.optional(),contextor:hx.optional(),fnMode:jx.optional(),systems:C([x(F),D(`all`)]),instructions:v().optional(),citations:b().optional()}),qA=KA.partial(),JA=x(S({label:v().trim().min(1).max(40).optional(),settings:qA})).min(2).max(4),YA=S({turn:cl,variant:GA,label:v()}),XA=S({variant:GA,label:v(),settings:qA,session:j,turn:cl}),ZA=S({run:A,fn:I}),QA=S({variant:GA,effects:x(ZA)}),$A=S({variant:GA,label:v(),effects:x(ZA).min(1)}),ej=S({variants:x(XA).min(2).max(4),reserved:P,chosen:GA.optional(),chosenBy:M.optional(),chosenAt:N.optional(),discarded:x(QA)}),tj=S({field:v(),type:v(),before:O.optional(),after:O.optional()}),nj=S({id:A,fn:I,fnVersion:v(),kind:Pl,system:F,instance:L.optional(),parent:A.optional(),root:A,turn:cl,session:j.optional(),key:v(),actor:M,caller:M,connection:jl.optional(),llmCall:fl.optional(),toolCallId:v().optional(),args:O,repairs:x(vE).optional(),test:b().optional(),status:SE,awaitingSystem:b().optional(),text:IT.optional(),outcome:AE.optional(),progress:fE.optional(),allowed:cE,cost:P,totalCost:P,priority:Rl,background:b(),attempt:y().int().min(1),errors:x(S({attempt:y().int(),error:hE,cost:P,at:N})),undo:O.optional(),resume:O.optional(),stateChanges:x(tj),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()}),rj=nj.pick({id:!0,fn:!0,status:!0,cost:!0,totalCost:!0,startedAt:!0,endedAt:!0}),ij=S({session:j,system:F,name:v(),type:v(),def:gT,value:O,version:y().int().min(1),updatedBy:C([S({run:A}),S({delivery:ul})]),updatedAt:N}).pick({name:!0,type:!0}).extend({value:O.optional()}),aj=E([`queued`,`delivered`,`done`,`failed`,`expired`]),oj=S({id:ul,system:F,kind:C([S({action:v(),input:O}),S({form:A,value:O})]),session:j,actor:M,run:A.optional(),status:aj,result:O.optional(),error:hE.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}),sj=S({id:dl,run:A,handler:v(),args:O,decl:S({description:v(),args:gT,returns:gT}),answerer:C([S({user:M}),S({system:F,run:A})]),status:E([`pending`,`answered`,`failed`]),result:O.optional(),createdAt:N}),cj=E([`running`,`done`,`failed`,`cancelled`,`paused`,`undone`]),lj=S({transcript:y().int().min(0),tools:x(I),context:x(I),selection:kx.optional(),suggested:x(I).optional(),announcedSystems:PA.optional(),citationsTold:WA.optional()});S({id:cl,session:j.optional(),message:ll.optional(),actor:M,user:tE,time:nE,client:aE.optional(),root:A.optional(),status:cj,limits:MA,cost:P,errors:C([S({max:y().int().min(1)}),D(`feed-back`)]),start:lj.optional(),compare:ej.optional(),createdAt:N,continuedAt:N.optional(),endedAt:N.optional()});var uj=E([`queued`,`streaming`,`done`,`failed`,`aborted`]),dj=S({content:v(),reasoning:v().optional(),toolCalls:x(cD.shape.toolCall.unwrap()).optional(),finishReason:cD.shape.finishReason.unwrap(),refusal:v().optional()}),fj=S({id:fl,turn:cl,run:A,session:j.optional(),system:F.optional(),iteration:y().int().min(0),provider:v(),model:v(),request:mD,response:dj.optional(),usage:oD.optional(),cost:P,status:uj,error:v().optional(),priority:Rl,selection:Ex.optional(),modelCall:Ol.optional(),queuedAt:N,startedAt:N.optional(),firstTokenAt:N.optional(),endedAt:N.optional()}),pj=Kc(()=>S({run:rj,llmCalls:x(fj.pick({id:!0,model:!0,cost:!0,status:!0})),children:x(pj)})),mj=S({turn:cl,undone:x(S({run:A,fn:I,summary:v()})),failed:x(S({run:A,fn:I,error:hE})),notUndoable:x(S({run:A,fn:I})),kept:x($A).optional(),session:S({messages:y().int().min(0),unloaded:x(I),reloaded:x(I)}).optional()});S({run:A,turn:cl,session:j.optional(),iteration:y().int().min(0),priority:Rl}),S({run:A,priority:Rl});var hj=[`system`,`instance`,`fn`,`context`,`type`,`kind`,`resource`,`root`,`component`,`registry`,`command`,`provider`],gj=E(hj),_j=[`brings`,`names`,`loads`,`next`,`reads`,`writes`,`calls`,`uses`,`kind`,`creates`,`updates`,`removes`,`refers`,`renders`,`contributes`,`belongs`],vj=E(_j),yj=[...vk,`pending`];E(yj);var bj=E([`text`,`enum`,`number`,`date`,`boolean`]);E([`is`,`isNot`,`in`,`notIn`,`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`,`contains`]);var xj={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`]},Sj={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`},Cj=C([v(),y(),b()]),wj=E([`usd`,`ms`,`tokens`,`bytes`,`count`]);S({label:v(),type:bj,sortable:b(),filterable:b(),values:x(v()).readonly().optional(),dynamic:b().optional(),unit:wj.optional()});var Tj=v().min(1),Ej=w(`op`,[S({field:Tj,op:E([`is`,`isNot`,`gt`,`gte`,`lt`,`lte`,`contains`]),value:Cj}),S({field:Tj,op:E([`in`,`notIn`]),values:x(Cj).min(1)}),S({field:Tj,op:D(`between`),from:Cj,to:Cj}),S({field:Tj,op:E([`empty`,`notEmpty`])})]),Dj=S({field:Tj,dir:E([`asc`,`desc`])}),Oj=Hl.extend({text:v().optional(),filters:x(Ej).max(20).optional(),sort:x(Dj).max(3).optional()}),kj=(e,t={})=>({label:e,type:`text`,sortable:!0,filterable:!0,...t}),Aj=(e,t)=>({label:e,type:`enum`,sortable:!0,filterable:!0,values:t}),jj=e=>({label:e,type:`enum`,sortable:!0,filterable:!0,dynamic:!0}),Mj=(e,t)=>({label:e,type:`number`,sortable:!0,filterable:!0,unit:t}),Nj=e=>({label:e,type:`date`,sortable:!0,filterable:!0}),Pj=e=>({label:e,type:`boolean`,sortable:!1,filterable:!0}),Fj=e=>({...e,sortable:!1}),Ij=[`resources`,`fns`,`runs`,`modelCalls`,`llmCalls`,`sessions`,`contexts`,`notifications`,`systems`,`types`,`graph`,`users`,`groups`],Lj=E(Ij),Rj={resources:{fields:{name:kj(`Name`),system:jj(`System`),family:Aj(`Type`,HE),source:Aj(`Source`,zE),forms:{...Aj(`Forms`,nS.options),sortable:!1},size:Mj(`Size`,`bytes`),seenAt:Nj(`Seen`),modifiedAt:Nj(`Modified`)},defaultSort:[{field:`seenAt`,dir:`desc`}]},fns:{fields:{name:kj(`Name`),system:jj(`System`),kind:jj(`Kind`),available:Pj(`Available`),paused:Pj(`Paused`),disabled:Pj(`Disabled`),runs:Mj(`Runs`,`count`),failures:Mj(`Failures`,`count`),averageCost:Mj(`Avg cost`,`usd`),averageTime:Mj(`Avg time`,`ms`),lastRunAt:Nj(`Last run`),updatedAt:Nj(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},runs:{fields:{fn:jj(`Fn`),system:jj(`System`),status:Aj(`Status`,xE),session:jj(`Session`),actor:jj(`By`),cost:Mj(`Cost`,`usd`),duration:Mj(`Duration`,`ms`),createdAt:Nj(`Started`),endedAt:Nj(`Ended`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},modelCalls:{fields:{modality:Aj(`Modality`,DD),model:jj(`Model`),provider:jj(`Provider`),system:jj(`System`),status:Aj(`Status`,ID.options),session:jj(`Session`),cost:Mj(`Cost`,`usd`),tokens:Mj(`Tokens`,`tokens`),duration:Mj(`Duration`,`ms`),createdAt:Nj(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},llmCalls:{fields:{model:jj(`Model`),system:jj(`System`),status:Aj(`Status`,uj.options),session:jj(`Session`),cost:Mj(`Cost`,`usd`),tokens:Mj(`Tokens`,`tokens`),duration:Mj(`Duration`,`ms`),createdAt:Nj(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},sessions:{fields:{title:kj(`Title`),agent:jj(`Agent`),status:Aj(`Status`,[`idle`,`running`,`paused`]),archived:Pj(`Archived`),createdAt:Nj(`Created`),updatedAt:Nj(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},contexts:{fields:{name:kj(`Name`),system:jj(`System`),origin:Aj(`Origin`,_S),tags:jj(`Tag`),status:Aj(`Status`,PS),askedBy:Aj(`Asked by`,RS),stale:Pj(`Stale`),tokens:Mj(`Tokens`,`tokens`),lastModified:Nj(`Last modified`),updatedAt:Nj(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},notifications:{fields:{kind:jj(`Kind`),read:Pj(`Read`),createdAt:Nj(`Received`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},systems:{fields:{name:kj(`Name`),status:jj(`Status`),version:kj(`Version`),instances:Mj(`Instances`,`count`),fns:Mj(`Fns`,`count`),context:Mj(`Context`,`count`),types:Mj(`Types`,`count`),parts:Mj(`Other parts`,`count`),pending:Mj(`Pending changes`,`count`),refusals:Mj(`Refusals`,`count`),lastSeenAt:Nj(`Last seen`)},defaultSort:[{field:`name`,dir:`asc`}]},types:{fields:{name:kj(`Name`),system:jj(`System`),instance:jj(`Instance`),references:Mj(`Refers to`,`count`),updatedAt:Nj(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},graph:{fields:{name:Fj(kj(`Name`)),system:Fj(jj(`System`)),nodeKind:Fj(Aj(`Item`,hj)),edgeKind:Fj(Aj(`Link`,_j)),fnKind:Fj(jj(`Fn kind`)),mode:Fj(jj(`Mode`)),effect:Fj(jj(`Effect on`)),visibility:Fj(Aj(`Visible to`,zl.options)),stage:Fj(Aj(`Stage`,yj)),on:Pj(`On`)},defaultSort:[]},users:{fields:{name:kj(`Name`),email:kj(`Email`),role:Aj(`Role`,[`admin`,`member`]),disabled:Pj(`Disabled`),createdAt:Nj(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]},groups:{fields:{name:kj(`Name`),createdAt:Nj(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]}};function zj(e,t){return t.sort!==void 0&&t.sort.length>0?t.sort:Rj[e].defaultSort}var Bj=S({value:Cj,label:v().optional(),count:y().int().min(0)}),Vj=S({list:Lj,field:Tj,prefix:v().optional(),limit:y().int().min(1).max(50).optional()}),Hj=S({list:Lj,query:Oj.default({})}),Uj=Vl(Zc()).extend({sort:x(Dj),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.`)}),Wj=sl.record,Gj=S({shape:E([`table`,`value`]),owner:E([`shared`,`person`]),writers:D(`admins`).optional(),search:S({text:x(v().min(1)),embed:b()})}),Kj=S({id:Wj,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()}),qj=S({id:v().min(1),record:Wj,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}),Jj=S({type:I,query:Oj.optional(),search:v().min(1).optional(),run:A.optional()}),Yj=Vl(Kj),Xj=Jj.extend({query:Oj.omit({cursor:!0,limit:!0}).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(500).optional()}),Zj=S({type:I,id:Wj,run:A.optional()}),Qj=S({type:I,id:Wj.optional(),value:O,expect:y().int().min(1).optional(),run:A.optional(),owner:M.optional()}),$j=S({type:I,id:Wj,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()}),eM=S({type:I,id:Wj,run:A.optional()}),tM=Hl.extend({type:I,id:Wj}),nM=Vl(qj),rM=S({type:I,system:F,description:v(),storage:Gj,records:y().int().min(0),updatedAt:N.optional()}),iM=Hl.extend({text:v().optional(),system:F.optional()}),aM=Vl(rM),oM=`general`,sM=S({name:k,title:v().min(1),description:v().min(1)}),cM=E([`sqlite`,`postgres`,`sqlserver`]),lM=cM.options,uM=S({description:v().min(1).max(500),vectors:b().default(!1),engines:x(cM).min(1).default([...lM])}),dM=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.`),fM=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.`),pM=E([`postgres`,`sqlserver`]);E([`system`,`hub`,`external`]);var mM=`system`,hM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:pM,connection:fA,schema:fM})]),gM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:pM,connection:v().min(1).max(4e3),schema:fM})]),_M=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:pM,connection:v().min(1),schema:fM})]),vM=[`sqlite`,`postgres`,`sqlserver`],yM={postgres:`Postgres with the pgvector extension installed (CREATE EXTENSION vector)`,sqlserver:`SQL Server 2025 or newer, which has the VECTOR type`};function bM(e){return e.placement===`external`&&e.engine!==void 0?e.engine:`sqlite`}function xM(e,t){let n=bM(t),r=t.placement===`external`?`an external ${n} database`:`the ${t.placement===`hub`?`hub`:`system`} (SQLite)`;return e.engines.includes(n)?e.vectors&&!vM.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 SM=E([`preparing`,`migrating`,`ready`,`moving`,`failed`]),CM=S({applied:x(S({id:dM,checksum:v().min(1),at:N})),pending:x(dM)}),wM=S({name:v().min(1).max(200),rows:y().int().min(0)}),TM=S({bytes:y().int().min(0).optional(),tables:x(wM).max(200),at:N,more:b().optional()}),EM=S({state:SM,engine:cM,migrations:CM,error:v().max(4e3).optional(),measure:TM.optional()}),DM=EM.extend({at:N}),OM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:pM,schema:fM})]),kM=v().regex(/^[0-9a-z][0-9a-z_.-]{0,120}$/),AM=S({id:kM,system:v(),instance:v(),where:OM,bytes:y().int().min(0).optional(),at:N,reason:E([`move`,`removed`]),orphaned:b().default(!1)}),jM=v().regex(/^move_[0-9a-z]{8,40}$/),MM=E([`draining`,`waiting`,`copying`,`switching`,`done`,`failed`]),NM=E([`ask`,`cancel`,`wait`]),PM=E([`cancel`,`wait`]),FM=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)})}),IM=S({move:jM,system:v(),instance:v(),from:OM,to:OM,phase:MM,runs:NM,running:x(v()),asking:N.optional(),progress:FM,startedAt:N,endedAt:N.optional(),by:v(),backups:x(AM),error:v().max(4e3).optional()}),LM=S({placement:hM,status:DM.optional(),backups:x(AM).optional()}),RM=S({system:v(),instance:v(),decl:uM,placement:OM,status:DM.optional(),holding:b(),measure:TM.optional(),file:S({bytes:y().int().min(0),snapshots:x(S({name:v(),bytes:y().int().min(0),at:N}))}).optional(),backups:x(AM).default([]),move:IM.optional()}),zM=v().regex(/^lease_[0-9a-z]{8,40}$/),BM=S({$bytes:v()}),VM=C([v(),y(),ic(),BM]),HM=S({sql:v().min(1).max(1e6),params:x(VM).max(32766),lease:zM.optional()}),UM=S({rows:x(T(v(),VM)),changes:y().int().min(0).optional(),insertId:y().int().optional()}),WM=S({lease:zM,expiresAt:N}),GM=v().regex(/^[0-9a-z][0-9a-z_.-]{0,120}\.db$/);function KM(e){for(let t of e.matchAll(VT)){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 qM=v().min(1).max(500).superRefine((e,t)=>{let n=KM(e);n!==void 0&&t.addIssue({code:`custom`,message:n})}),JM=S({fn:k,args:O,user:tE,caller:A,session:j.optional()}),YM=S({claims:x(v().min(1))});function XM(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)]:XM(e)):[JSON.stringify(e)]}function ZM(e,t){let n=[],r=[],i=0;for(let a of e.matchAll(VT)){n.push(e.slice(i,a.index)),i=a.index+a[0].length;let[o,...s]=(a[1]??``).trim().split(`.`),c=o===`args`?XM(KT(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 QM(e,t){return[...new Set(e.flatMap(e=>ZM(e,t)))]}var $M=S({label:v(),plural:v().optional(),icon:v().optional(),color:v().optional(),title:v().optional(),subtitle:v().optional()}),eN=S({name:k,description:v(),def:gT,display:$M,methods:x(k),instance:L.optional(),audience:_O.optional(),meta:T(v(),O).optional(),records:Gj.optional()}),tN=E([`user-wins`,`union`,`intersect`,`most-restrictive`]),nN=E([`self`,`fns`]),rN=S({name:k,description:v(),type:gT,appliesTo:x(Bl),merge:tN,editableBy:x(nN)}),iN=S({name:k,description:v(),data:gT}),aN=S({name:k,description:v(),applicability:v(),payload:gT,approveChanges:b(),status:FT.optional(),estimates:b().optional(),approval:$k.optional()}),oN=S({description:v(),args:gT,returns:gT,required:b()}),sN=w(`to`,[S({to:D(`instance`),instance:L}),S({to:D(`any`)})]),cN=S({args:O,result:O.optional(),note:v().optional()}),lN=E([`read`,`write`,`delete`]),uN=E([`fns`,`types`,`context`,`resources`,`kinds`,`components`,`examples`,`approvals`,`secrets`,`connections`,`records`]),dN=[`create`,`update`,`remove`],fN=E(dN),pN=S({thing:uN,action:fN,kind:Pl.optional()}).refine(e=>e.kind===void 0||e.thing===`fns`,{message:`only fns have a kind`,path:[`kind`]}),mN=E([`resources`]),hN=S({mode:lN.optional(),reads:x(I).optional(),writes:x(I).optional(),free:b().optional(),registry:x(pN).optional(),keeps:x(mN).min(1).optional()}),gN=S({language:v().min(1),code:v()}),_N=S({every:Ml.min(1e3)}),vN=E([`developer`,`admin`,`reference`]),yN=S({deps:x(I)}),bN=S({name:k,description:v(),instructions:v().optional(),kind:Pl,payload:O.optional(),readable:gN.optional(),args:gT,returns:gT,deps:x(I),handlers:T(v(),oN),progress:uE,status:FT.optional(),operations:sE,undo:gT.optional(),resume:gT.optional(),state:gT.optional(),form:gT.optional(),display:oE,limits:lE,visibility:zl,tags:x(v()),niche:vN.optional(),examples:x(cN).optional(),validate:ek.optional(),approval:$k.optional(),routing:sN.optional(),connectKey:EO.optional(),effects:hN.optional(),promptExamples:y().int().min(0).max(20).optional(),group:k.optional(),flags:b().optional(),roles:x(WD).optional(),live:_N.optional(),parallelClaims:x(qM).optional(),dynamicClaims:b().optional(),check:yN.optional()}),xN=S({name:v(),hint:v(),required:b()}),SN=S({to:I,when:v().min(1).max(200)}),CN=S({name:k,title:v().min(1).optional(),description:v(),content:v().optional(),command:S({name:v(),args:x(xN)}).optional(),imports:x(I),fns:x(I),suggestFns:x(I),suggest:zl,visible:zl,inject:Ub.optional(),tags:x(v()),niche:vN.optional(),weight:y().min(0).max(2).optional(),summary:v().optional(),parent:I.optional(),next:I.optional(),choices:x(SN).optional(),links:x(wS).optional(),question:v().min(1).max(500).optional(),when:v().min(1).max(500).optional(),lastModified:N.optional(),askedBy:zS.optional()}),wN=S({name:k,description:v(),explains:v().min(1).max(2e3).optional(),order:y(),timeout:Ml}),TN=S({name:k,title:v(),description:v(),target:gT,of:I.optional()}),EN=S({name:k,description:v(),match:aS}),DN=S({name:k,description:v(),input:gT,returns:gT,state:gT.optional(),expires:Ml.optional()}),ON=[`message`,`run`,`resources`,`system`,`fns`],kN=E(ON),AN=S({entry:v(),hash:v(),files:x(S({path:v(),size:y().int().min(0),hash:v()}))}),jN=E([`types`,`settings`,`attachments`,`kinds`,`fns`,`context`,`hooks`,`mentions`,`sectioners`,`actions`]),MN={types:x(eN),settings:x(rN),attachments:x(iN),kinds:x(aN),fns:x(bN),context:x(CN),hooks:x(wN),mentions:x(TN),sectioners:x(EN),actions:x(DN)},NN=S({name:F,version:v(),description:v(),about:v().optional(),hash:v(),...MN,events:x(kN),resources:b(),client:AN.optional(),config:gT,requires:x(F),providers:x(VO).optional(),connect:DO.optional(),registries:x(jk).optional(),contributes:x(Mk).optional(),configSecrets:uA.optional(),runtime:bc(jN,x(k)).optional(),grants:gk.optional(),configComponent:_k.optional(),pages:yA.optional(),groups:x(sM).optional(),store:uM.optional()}),PN=S({hash:v(),upsert:S(MN).partial(),remove:bc(jN,x(k)),lists:NN.pick({providers:!0,registries:!0,contributes:!0}).optional(),roots:D(!0).optional()}),FN=S({added:x(I),updated:x(I),removed:x(I),refused:x(S({name:v(),problems:x(v())}))}),IN=S({args:gT,returns:gT,description:v(),mode:lN}),LN=S({args:gT,returns:gT,deps:x(I),types:x(I).optional(),refs:x(v()).optional(),operations:sE,handlers:T(v(),oN).optional(),progress:uE.optional(),status:FT.optional(),limits:lE.optional(),display:oE.optional(),approval:$k.optional(),effects:hN.optional(),readable:gN.optional(),connectKey:TO.optional(),parallelClaims:x(qM).optional(),examples:x(cN).min(1)});function RN(e){return e===`native`||e.startsWith(`hub/`)}function zN(e){return RN(e.kind)&&(e.examples??[]).length===0}var BN=S({session:j,turn:cl,text:v(),user:tE,time:nE}),VN=y(),HN=S({label:v(),mode:lN,blocked:v().optional(),args:v().optional(),returns:v().optional(),instructions:v().optional(),examples:x(cN).optional(),moreExamples:y().int().positive().optional()}),UN={toolset:ax.optional()},WN=w(`type`,[S({type:D(`text`),tag:v(),text:v()}),S({type:D(`suggest-context`),...UN,items:x(S({context:I,title:v().optional(),why:v().optional(),score:VN.optional()}))}),S({type:D(`suggest-fns`),...UN,items:x(S({fn:I,why:v().optional(),score:VN.optional(),card:HN.optional()}))}),S({type:D(`load`),context:x(I).optional(),fns:x(I).optional()})]),GN=S({label:v(),hint:v().optional(),icon:v().optional(),target:O}),KN=S({title:v(),subtitle:v().optional(),fields:x(S({label:v(),value:v()})).optional(),body:v().optional(),open:oS.optional(),value:O.optional()});CN.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:zl.default(`both`),visible:zl.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 qN=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:qN,message:v().min(1)});var JN=S({loaded:x(I),fns:x(I),fnsRefused:x($T),refused:x(S({context:v(),reason:v().min(1),closest:x(I)})),cards:v()}),YN=S({context:x(v().min(1)).min(1),guidance:v().min(1).max(4e3),maxDepth:y().int().min(0).max(10).default(NS.maxDepth),maxDecisions:y().int().min(1).max(4096).default(NS.maxDecisions),maxTokens:y().int().min(1).max(1e6).default(NS.maxTokens),metadataOnly:b().default(!1)}),XN=E([`start`,`import`,`choice`]),ZN=S({name:I,title:v().optional(),description:v(),depth:y().int().min(0),via:XN,from:I.optional(),probability:y().min(0).max(1).optional(),tokens:y().int().min(0),content:v().optional()}),QN=E([`declined`,`max-tokens`,`max-decisions`,`max-depth`,`unavailable`,`failed`]),$N=S({context:v(),from:I.optional(),depth:y().int().min(0),reason:QN,probability:y().min(0).max(1).optional()}),eP=E([`complete`,`max-depth`,`max-decisions`,`max-tokens`,`failed`]),tP=JN.extend({crawled:x(ZN),skipped:x($N),stop:S({reason:eP,detail:v().optional()}),depth:y().int().min(0),decisions:y().int().min(0),tokens:y().int().min(0),calls:x(Ol),metadataOnly:b()}),nP=S({loaded:x(I),refused:x($T),cards:v()});C([nP.strict(),JN.strict(),tP.strict()]);var rP=S({expiresIn:Ml.nullable().optional()}),iP=S({id:Al,secret:v().min(32),expiresAt:N.optional()}),aP=iP.pick({id:!0,secret:!0}),oP=S({id:Al,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}),sP=E([`pairing`,`needs-config`,`connected`,`disconnected`,`removed`]),cP=C([S({path:v()}),S({package:v(),version:v()}),S({git:v(),ref:v()}),S({zip:v().regex(qx),file:v()})]),lP=S({policy:E([`always`,`on-failure`,`never`]),backoff:Ml,maxPerHour:y().int().min(1)}),uP=E([`installing`,`stopped`,`starting`,`running`,`crashed`,`disabled`]),dP=S({name:F,instance:L,source:cP,dir:v(),command:S({run:v(),args:x(v()),env:T(v(),v()),cwd:v().optional()}),version:v(),goodVersion:v().optional(),autoStart:b(),restart:lP,status:uP,pid:y().int().optional(),lastExit:S({code:y().int(),at:N,output:v()}).optional(),installedBy:M,installedAt:N}),fP=S({functions:b(),renderers:b(),context:b().optional()}),pP=S({value:O,version:y().int().min(1),setBy:M,setAt:N}),mP=S({keyFingerprint:v().optional(),publicKey:v().optional(),config:pP.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional()}),hP=E([`one`,`many`]),gP=S({name:F,description:v(),about:v().optional(),status:sP,enabled:fP,version:v(),manifestHash:v(),defaultInstance:L.optional(),actor:M,stage:yk.optional(),instances:hP.optional()}).extend(mP.shape),_P=S({id:pl,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:gT.optional(),configSecrets:uA.optional(),store:uM.optional(),status:E([`pending`,`approved`,`rejected`,`expired`]),createdAt:N,expiresAt:N});S({id:ml,name:F.optional(),tokenHash:v(),createdBy:M,expiresAt:N,usedAt:N.optional(),autoPair:rP.optional(),boundTo:S({instance:L,manifestHash:v().min(1),host:ql,run:A}).optional()}),S({system:F,manifest:NN,importedAt:N});var vP=cO.pick({averageCost:!0,averageQueued:!0,p95:!0,lastRunAt:!0}).extend({outcomes:tO.default(nO),averageTime:Ml,tokens:cO.shape.tokens.default(0)}),yP=E([`contract`,`runtime`]),bP=S({name:I,system:F,decl:bN,version:v(),origin:yP,addedBy:M.optional(),available:ZT,paused:b(),disabled:b(),stats:vP,updatedAt:N});S({name:I,system:F,decl:aN});var xP=eN.omit({name:!0,methods:!0}).extend({name:I,system:F,references:x(I),declaredBy:yP.optional(),version:v().optional(),updatedAt:N}),SP=S({types:x(xP),missing:x(I)}),CP=CN.extend({alwaysFor:x(I).optional()}),wP=S({name:I,system:F,origin:gS.optional(),declaredBy:yP.optional(),version:v().optional(),decl:CP,tokens:vS.optional(),status:FS.default(`active`),statusReason:v().optional(),statusHistory:x(BS).optional(),disabled:b().optional(),systemOff:b().optional(),lastModified:N.optional(),duplicate:VS.optional(),contradiction:VS.optional(),notDuplicates:x(I).optional(),checked:S({contentHash:v(),at:N}).optional(),metadata:US.optional(),split:WS.optional(),validUntil:N.optional(),askedBy:zS.optional(),mentions:S({context:x(I),fns:x(I)}),stale:b(),updatedAt:N,wantsMetadata:b().optional(),wantsCheck:b().optional(),inReview:b().optional()});function TP(e){return e.systemOff===!0||!LS(e.status)}function EP(e){return e.lastModified??e.updatedAt}var DP=[`kinds`,`commands`,`mentions`,`hooks`,`actions`,`settings`,`attachments`,`embedders`,`sectioners`,`providers`,`registries`,`components`,`examples`],OP=E(DP),kP=S({section:OP,name:v().min(1),about:v(),origin:yP,version:v(),visibility:zl.optional(),owner:I.optional(),decl:O,on:b().optional()}),AP=S({system:F}),jP=S({parts:x(kP),more:bc(OP,y().int().min(0))});function MP(e){return eT(e?.name??`otel`,{requires:e?.requires??[]})}var NP=v().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/),PP=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,FP=e=>e!==``&&e!==`.`&&e!==`..`&&!PP.test(e),IP=v().min(1).refine(e=>!e.includes(`\\`)&&!e.includes(`:`)&&e.split(`/`).every(FP),`A package path is relative, uses forward slashes and stays inside the package.`),LP=S({childProcess:b(),workers:b()});S({format:D(1),name:F,version:NP,description:v(),protocol:y().int().min(1),server:S({entry:IP,external:T(v(),v()).default({}),node:v().optional()}),client:S({entry:IP}).optional(),instances:hP.default(`one`),files:T(IP,v().regex(qx)).optional(),permissions:LP.partial().optional()});var RP=S({state:v(),data:v(),cache:v()}),zP=S({host:ql,path:v().min(1),bundleHash:v().min(1),approval:gl}),BP=S({system:F,instance:L,description:v(),status:sP,keyFingerprint:v(),publicKey:v(),version:v(),manifestHash:v(),config:pP.optional(),installed:dP.optional(),host:zP.optional(),dirs:RP.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional(),connect:wO.optional(),store:LM.optional()}),VP=S({instance:L,description:v(),online:b(),config:O,types:x(S({name:I,description:v()}))}),HP=S({pairing:pl,description:v(),instance:L,configType:gT.optional(),configSecrets:uA.optional(),store:uM.optional()});S({format:D(1),system:F,instance:L,version:v(),exportedAt:N,exportedBy:M,withSecrets:b()});var UP=S({system:F,instance:L,description:v().optional(),config:O,store:gM.optional()}),WP=S({at:N,stream:E([`stdout`,`stderr`,`hub`]),text:v()}),GP=S({meaning:b(),items:y().int().min(0),pending:y().int().min(0),embedding:b(),retrying:b(),lastError:S({at:N,message:v()}).optional()}),KP=C([TA,I]),qP=S({id:v(),provider:KP,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()}),JP=qP.extend({tier:E([`flagship`,`efficient`,`legacy`,`experimental`]),maxOutputTokens:y().int().min(1).optional(),roles:x(WD)}),YP=AA.extend({spent:P}),XP=S({setting:I,system:F,decl:rN}),ZP=fj.omit({request:!0,response:!0}),QP=w(`kind`,[S({kind:D(`budget`),id:_l}),S({kind:D(`priority`),id:vl}),S({kind:D(`policy`),id:hl}),S({kind:D(`category`),id:wl}),S({kind:D(`provider`),id:Tl})]),$P=S({uri:Wx,system:F,stat:Xx,links:x(Zx),indexedVersion:v().optional(),sectioner:I.optional(),source:RE.optional(),raw:Jx.optional(),forms:x(nS).optional(),primary:nS.optional(),seenAt:N});S({id:El,match:aS,sectioner:I,setBy:M}),S({uri:Wx,from:v(),to:v(),added:x(Gx),changed:x(Gx),removed:x(Gx)});var eF=E([`fn`,`context`,`section`,`message`,`type`,`example`,`record`,`contextSection`,`image`,`contextContent`]);S({kind:eF,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 tF=E([`words`,`meaning`,`both`]);S({kind:eF,key:v(),rank:y().min(0).max(1),similarity:y().min(-1).max(1).optional(),matched:tF.optional(),parent:v().optional(),text:v()});var nF=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`]),rF=S({system:F,segment:v().min(1),path:x(v().min(1)).optional(),query:T(v(),v()).optional()}).strict(),iF=C([S({session:j}),S({approval:gl}),S({pairing:pl}),S({run:A}),S({system:F}),S({page:rF})]),aF=E([`ok`,`failed`,`info`]),oF=S({label:v().min(1).max(24),link:iF}),sF=S({id:xl,user:M,reason:nF,title:v(),body:v(),link:iF,read:b(),pushed:b(),resolved:v().optional(),tone:aF.optional(),also:oF.optional(),key:v().min(1).max(200).optional(),createdAt:N}),cF=S({id:Sl,user:M,endpoint:Ls(),keys:S({p256dh:v(),auth:v()}),device:v(),createdAt:N}),lF=sl.fnExample;cN.extend({id:lF,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 uF=S({fn:k,upsert:x(cN.extend({key:v().min(1).max(200)})),remove:x(v().min(1).max(200))}),dF=S({fn:kb,query:v().optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(50).optional()}),fF=S({fn:I,items:x(cN.extend({id:lF,rank:y().optional()})),total:y().int().min(0),next:y().int().min(0).optional()}),pF=E([`text`,`semantic`,`hybrid`]),mF=[`session`,`user`,`everyone`],hF=E([`fn`,`context`]),gF=S({text:v().optional(),match:pF.optional(),items:x(hF).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(Ab).optional(),writes:x(Ab).optional()}).optional(),modes:x(lN).min(1).optional(),effects:x(S({thing:uN,action:fN.optional(),kind:v().min(1).optional()})).min(1).optional(),names:x(I).min(1).max(100).optional(),filters:x(Ej).max(20).optional(),off:b().optional(),statuses:YS.shape.statuses,returnNotApplicable:YS.shape.returnNotApplicable,semanticOver:YS.shape.semanticOver,scopes:x(E(mF)).min(1).optional(),available:b().optional(),niches:x(vN).min(1).optional(),order:E([`rank`,`name`]).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(100).optional()}),_F=gF.omit({items:!0,match:!0,filters:!0,off:!0,scopes:!0,statuses:!0,returnNotApplicable:!0,semanticOver:!0}).extend({kinds:gF.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(kb).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(Ab).optional(),writes:x(Ab).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.")}),vF=S({text:gF.shape.text,systems:gF.shape.systems,origins:x(E(_S)).min(1).optional(),scopes:gF.shape.scopes,tags:x(v().min(1)).min(1).max(20).optional(),names:gF.shape.names,niches:gF.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:gF.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:gF.shape.order,offset:gF.shape.offset,limit:gF.shape.limit}),yF=S({key:Gx,path:x(v()),title:v()}),bF=S({item:hF,name:I,system:F,description:v(),kind:v().optional(),mode:lN.optional(),signature:v().optional(),effects:v().optional(),instance:L.optional(),rank:y().optional(),similarity:y().optional(),matched:tF.optional(),section:yF.optional(),question:v().optional(),answer:v().optional(),status:FS.optional(),statusReason:v().optional(),niche:vN.optional(),available:b(),blocked:QT.optional(),inPrompt:E([`injected`,`loaded`]).optional(),exact:D(!0).optional()}),xF=bF.pick({rank:!0,similarity:!0,matched:!0,section:!0}),SF=wP.extend({found:xF.optional(),metadataStale:b().optional()}),CF=S({item:hF,by:E([`decision`,`llm`]),dropped:x(S({name:I,note:v().optional()})),calls:x(Ol).min(1).optional(),failed:v().optional(),action:D(`load`).optional()}),wF=S({fns:x(I),context:x(I),note:v()}),TF=S({items:x(bF),next:y().int().min(0).optional(),filtered:x(CF).optional(),loaded:wF.optional(),missing:S({names:x(I).min(1),note:v()}).optional()}),EF=S({min:P,typical:P,max:P,basis:E([`free`,`history`,`payload`,`unknown`]),runs:y().int().min(0)}),DF=S({runs:y().int().min(0),typical:Ml,slow:Ml,longest:Ml}),OF=S({fn:I,kind:v(),mode:lN,reads:x(I),writes:x(I),uses:x(I),free:b(),registry:x(pN),cost:EF,times:DF.optional(),longRunning:b(),notice:v().optional()}),kF=S({kind:v().min(1),payload:O,args:O.optional(),history:EF.optional()}),AF=S({estimate:EF.optional()}),jF=S({model:KD.optional(),messages:y().int().min(0).max(20).default(4)}),MF=S({value:jF,setBy:M.optional(),updatedAt:N.optional()}),NF=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:Ml})])).min(1).max(500),page:v().max(300).optional()}),PF=S({uri:Wx,written:y().int().min(0)});OF.pick({fn:!0,kind:!0,mode:!0,reads:!0,writes:!0,uses:!0,free:!0}).extend({registry:x(pN).optional(),system:F,instance:L.optional(),updatedAt:N}),S({fn:I,type:I,use:E([`read`,`write`])}),S({fn:I,type:I,kind:Pl,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:bN,savedBy:M.optional(),savedAt:N}),S({id:v(),type:I,number:y().int().min(1),decl:eN,instance:L.optional(),savedAt:N});var FF={fns:`fns`,types:`types`,context:`context`,resources:`resources`,kinds:`kinds`,components:`components`,examples:`examples`,approvals:`runs awaiting approval`,secrets:`secrets`,connections:`connections`,records:`records`},IF={create:`Creates`,update:`Updates`,remove:`Removes`};function LF(e){let t=[];for(let n of dN){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?FF[e]:`${FF[e]} (${[...t].sort().join(`, `)})`);t.push(`${IF[n]} ${i.join(`, `)}.`)}return t.length===0?void 0:t.join(` `)}var RF=sl.refusal,zF=[`fns`,`context`,`types`,`roots`,...DP],BF=E(zF),VF=S({section:BF,name:v().min(1)});VF.extend({system:F,by:M,at:N});var HF=S({version:v(),hash:v().min(1),grants:gk,runtime:x(VF),by:M,at:N}),UF=S({section:C([BF,E([`grants`,`config`])]),name:v().min(1),change:E([`added`,`changed`,`removed`]),origin:yP,before:O.optional(),after:O.optional()}),WF=UF.pick({section:!0,name:!0}),GF=WF.extend({change:UF.shape.change,origin:yP,version:v(),by:M,at:N}),KF=S({version:v(),hash:v().min(1),by:yP,changes:x(UF),since:N});S({system:F,live:HF.optional(),pending:KF.optional(),checks:fk.optional(),declined:x(GF).optional(),updatedAt:N});var qF=S({mode:lN,effects:v().optional(),reads:x(I),writes:x(I),deps:x(I),cost:P.optional(),free:b().optional()}),JF=S({name:v().min(1),before:qF.optional(),after:qF.optional()}),YF=KF.extend({summary:Vk,fns:x(JF),injections:x(qb).default([])}),XF=[`stage`,`effects`,`mode`,`types`,`capability`,`models`,`budget`,`secrets`,`calls`,`network`,`files`,`visibility`],ZF=E(XF),QF=S({id:RF,system:F,instance:L,rule:ZF,attempt:v().min(1),detail:v().min(1),run:A.optional(),fn:I.optional(),at:N}),$F=S({instance:ql,rule:ZF.extract([`network`,`files`]),attempt:v().min(1).max(1e3),detail:v().min(1).max(2e3)}),eI=S({system:F.optional(),rule:ZF.optional(),cursor:v().optional(),limit:y().int().min(1).max(200).optional()}),tI=S({items:x(QF),next:v().optional()}),nI=S({system:F,stage:yk,manifest:NN,facts:x(OF),checks:fk.optional(),live:HF.optional(),pending:YF.optional(),declined:x(GF).default([]),off:x(VF),refusals:S({total:y().int().min(0),last:x(QF).max(10)}),previewUrls:T(v(),v()).optional(),clientApproved:b().optional()}),rI=S({system:F,hash:v().min(1),off:x(VF).default([])}),iI=S({system:F,hash:v().min(1),approve:x(WF).default([]),decline:x(WF).default([]),off:x(VF).default([])}).refine(e=>e.approve.length+e.decline.length>0,{message:`approve or decline at least one change`,path:[`approve`]}),aI=S({hash:v(),waiting:y().int().min(0)}),oI=C([S({preview:Zk,contract:NN.optional(),ask:rA.optional()}),S({refused:v().min(1)})]),sI=S({fn:I,args:O,instance:L.optional()}),cI=sl.mentionRequest,lI=S({request:cI,query:v(),roots:x(Wx).max(20).optional(),limit:y().int().min(1).max(50)}),uI=S({hits:x(sS)}),dI=2e3,fI=S({kind:I,changedSince:N.optional(),cursor:v().optional(),limit:y().int().min(1).max(100).optional()}),pI=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()}),mI=S({fn:I,args:O,key:v().min(1).max(200),priority:Rl.extract([`background`,`interactive`]).optional(),maxSpend:P.positive().optional()}),hI=S({run:A,turn:cl,status:SE}),gI=S({title:v().min(1).max(120),body:v().max(dI),tone:aF.optional(),link:iF.optional(),also:oF.optional(),key:v().min(1).max(136).optional()}),_I=`fnloom`,vI=`hub.name`,yI=v().trim().min(1).max(40).refine(e=>!/[\r\n]/.test(e),{message:`One line only.`}),bI=S({name:yI,source:E([`setting`,`env`,`default`]),version:v()}),xI=S({name:yI.nullable()}),SI=[`off`,`text`,`model`];E(SI);var CI=w(`use`,[S({use:D(`off`)}),S({use:D(`text`)}),S({use:D(`model`),embedder:I})]),wI={use:`text`},TI=S({text:b(),images:b(),crossModal:b()}).extend({embedder:I,name:v(),dimensions:y().int().min(1)}),EI=w(`space`,[S({space:D(`none`),reason:v()}),S({space:D(`shared`),embedder:I}),S({space:D(`own`),embedder:I,crossModal:b()})]),DI=S({value:CI,setBy:M.optional(),updatedAt:N.optional(),text:I,options:x(TI),state:EI}),OI={id:M,name:v(),about:v(),createdAt:N,disabled:b()},kI=E([`admin`,`member`]),AI=S({...OI,kind:D(`user`),email:v(),role:kI,timeZone:v().optional()}),jI=w(`kind`,[AI,S({...OI,kind:D(`group`)}),S({...OI,kind:D(`agent`),fn:I}),S({...OI,kind:D(`system`),system:F}),S({...OI,kind:D(`mcp`),mcp:kl})]),MI=AI.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:Dl,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:Dl,version:y().int().min(1)});var NI=S({setting:I,actor:M,value:O,setBy:M,run:A.optional(),updatedAt:N}),PI=C([S({actor:M}),S({group:M}),S({kind:Bl}),S({everyone:D(!0)})]),FI=S({fn:v().optional(),system:F.optional(),kind:Pl.optional(),tags:x(v()).optional(),when:bT.optional(),via:I.optional()}),II=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 LI=w(`effect`,[S({effect:D(`allow`)}),S({effect:D(`deny`),reason:v()}),S({effect:D(`ask`),approver:II})]),RI=S({id:hl,description:v(),subject:PI,target:FI,decision:LI,priority:y().int(),expiresAt:N.optional(),createdBy:M,createdAt:N,yields:b().optional()}),zI=E([`once`,`session`,`always`]),BI=S({id:gl,run:A,fn:I,policy:hl.optional(),approver:II,status:E([`pending`,`approved`,`denied`,`expired`]),decisions:x(S({by:M,approve:b(),remember:zI,reason:v().optional(),at:N})),createdAt:N,preview:Zk.optional(),proposed:b().optional(),ask:rA.optional(),variant:YA.optional()}),VI=v().regex(/^[a-z0-9][a-z0-9-]{0,31}$/,`lower case letters, digits and dashes, starting with a letter or digit`),HI=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.`)}),UI=S({id:VI,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:HI.prefault({})});x(UI).refine(e=>new Set(e.map(e=>e.id)).size===e.length,`each provider needs its own id`);var WI=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`),GI=w(`mode`,[S({mode:D(`invite`)}),S({mode:D(`domains`),domains:x(WI).min(1).max(50)}),S({mode:D(`anyone`)})]),KI=`signInPolicy`,qI=S({limit:y().int().min(1).max(1e5),window:y().int().min(1e3).max(864e5)}),JI=S({account:qI,address:qI}),YI=`signInLimits`,XI=S({proxies:y().int().min(0).max(5)}),ZI=`proxyTrust`;S({issuer:v(),sub:v(),provider:VI,user:M,email:v().optional(),linkedAt:N,lastSignInAt:N});var QI=UI.pick({id:!0,label:!0}),$I=S({providers:x(UI.omit({clientSecret:!0}).extend({confidential:b()})),policy:GI,breakGlass:MI.optional(),callbackUrl:v(),limits:JI,proxy:XI}),eL=S({ok:b(),detail:v()}),tL=S({provider:VI,ok:b(),discovery:eL,keys:eL,checkedAt:N}),nL=E([`linked`,`email`,`new`,`none`]),rL=S({allowed:b(),reason:v(),link:nL,user:MI.optional(),role:kI.optional(),groups:x(v()),unknownGroups:x(v())}),iL=S({id:v(),provider:VI,at:N,problem:v().optional(),subject:v().optional(),email:v().optional(),emailVerified:b(),claims:T(v(),O),outcome:rL.optional()}),aL=S({provider:VI,label:v(),email:v().optional(),lastSignInAt:N}),oL=MI.extend({disabled:b(),createdAt:N,breakGlass:b(),password:b(),identities:x(aL),groups:x(S({id:M,name:v(),synced:b()}))}),sL=S({id:M,name:v(),about:v(),createdAt:N,members:y().int().min(0)}),cL=S({user:M,name:v().trim().min(1).max(120).optional(),role:kI.optional(),disabled:b().optional()}),lL=S({group:M,user:M,member:b()});function uL(e){return`/auth/sso/${encodeURIComponent(e)}/start`}var dL=`harness_sso_handoff`,fL=E([`score`,`decision`,`graph`]),pL=E([`below-threshold`,`top-n`,`declined`,`budget`,`rule`,`failed`]),mL={"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`},hL=[`suggest`,`load`],gL=E(hL);function _L(e){return e.by===`none`?`suggest`:e.action??`suggest`}var vL=E([`loaded`,`budget`,`blocked`]),yL={loaded:`Loaded for the turn`,budget:`No room to load it, so suggested`,blocked:`Can't be loaded now, so suggested`},bL=w(`used`,[S({used:D(!0),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),note:v().optional(),load:vL.optional()}),S({used:D(!1),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),reason:pL,note:v().optional()})]),xL=S({by:fL,threshold:y().optional(),calls:x(Ol).min(1).optional(),action:D(`load`).optional(),items:x(bL)}),SL=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)}),CL=[`decision`,`llm`,`none`];E(CL);var wL=w(`by`,[S({by:D(`none`)}),SL.extend({by:D(`decision`),model:KD.optional(),action:gL.optional()}),SL.extend({by:D(`llm`),model:KD,action:gL.optional()})]),TL={by:`none`},EL=SL.extend({enabled:b(),model:KD.optional()});function DL(e){let{enabled:t,model:n,...r}=e;return t&&n!==void 0?{by:`llm`,model:n,...r}:TL}var OL=C([wL,EL.transform(DL)]),kL=S({value:wL,setBy:M.optional(),updatedAt:N.optional()}),AL=[`none`,`decision`,`llm`];E(AL);var jL=w(`by`,[S({by:D(`none`)}),S({by:D(`decision`),model:KD.optional(),action:gL.optional()}),S({by:D(`llm`),model:KD,action:gL.optional()})]),ML={by:`none`},NL={fn:`fnsSearchDecision`,context:`contextSearchDecision`},PL=S({value:jL,setBy:M.optional(),updatedAt:N.optional()}),FL=S({fn:PL,context:PL}),IL=S({item:hF,value:jL});w(`key`,[S({key:D(`suggestDecision`),value:OL,setBy:M,updatedAt:N}),S({key:D(`autoClassifier`),value:jF,setBy:M,updatedAt:N}),S({key:D(NL.fn),value:jL,setBy:M,updatedAt:N}),S({key:D(NL.context),value:jL,setBy:M,updatedAt:N}),S({key:D(vI),value:yI,setBy:M,updatedAt:N}),S({key:D(`imageEmbedding`),value:CI,setBy:M,updatedAt:N}),S({key:D(KI),value:GI,setBy:M,updatedAt:N}),S({key:D(Fb),value:Ib,setBy:M,updatedAt:N}),S({key:D(YI),value:JI,setBy:M,updatedAt:N}),S({key:D(ZI),value:XI,setBy:M,updatedAt:N}),S({key:D(Rb),value:b(),setBy:M,updatedAt:N}),S({key:D(GS),value:KS,setBy:M,updatedAt:N})]);var LL=E([`all`,`replies`,`none`]),RL=S({actor:M,role:E([`owner`,`member`,`agent`]),notify:LL,joinedAt:N}),zL=E([`idle`,`running`,`paused`]),BL=S({hash:v(),injected:x(I),at:cl}),VL=S({id:j,title:v(),owner:M,...KA.shape,selection:kx.optional(),participants:x(RL),forkOf:j.optional(),fork:YA.optional(),tools:x(I),context:x(I),suggested:x(I).optional(),announcedSystems:PA.optional(),citationsTold:WA.optional(),fixed:BL.optional(),status:zL,transcript:x(aD),createdAt:N,updatedAt:N,archived:b()}),HL=VL.pick({id:!0,title:!0,owner:!0,agent:!0,status:!0,createdAt:!0,updatedAt:!0,archived:!0}),UL=E([`local-time`,`suggested-context`,`suggested-fns`]),WL=S({type:D(`text`),text:v()}),GL=S({type:D(`mention`),provider:I,label:v(),target:O,text:v()}),KL=S({type:D(`command`),context:I,args:T(v(),v())}),qL=S({type:D(`file`),ref:Jx,name:v(),uri:Wx.optional(),text:v().optional(),truncated:b().optional()}),JL=S({type:D(`input-answer`),run:A,title:v(),value:O,text:v()}),YL=`input-answer`,XL=S({type:D(`loaded-for-you`),by:E([`decision`,`llm`,`recall`]),toolset:ax.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()}))}),ZL=w(`type`,[WL,S({type:D(`reasoning`),text:v()}),GL,KL,S({type:D(`invocation`),run:A,fn:I}),S({type:D(`call`),run:A,fn:I}),qL,JL,S({type:D(`extra`),extra:UL,blocks:x(WN)}),S({type:D(`hook`),hook:I,blocks:x(WN)}),S({type:D(`attachment`),attachment:I,data:O,title:v()}),S({type:D(`link`),link:oS}),S({type:D(`systems-changed`),on:x(FA),off:x(FA)}),S({type:D(`kept-effects`),variants:x($A)}),XL]),QL=new Set([`extra`,`hook`,`input-answer`,`systems-changed`,`loaded-for-you`]);function $L(e){return QL.has(e.type)}var eR=w(`type`,[WL,GL.omit({text:!0}),KL,qL,JL]),tR=S({id:ll,session:j,turn:cl,author:M,role:E([`user`,`assistant`,`note`]),parts:x(ZL),runs:x(A),status:E([`streaming`,`done`,`failed`]),replyTo:ll.optional(),replyAll:b(),answerers:x(M),suggestions:xL.optional(),compared:D(!0).optional(),cacheMiss:S({call:Ol,at:N}).optional(),citations:x(UA).optional(),createdAt:N}),nR=E([`pause`,`resume`,`cancel`]),rR=S({run:A,fn:I,status:SE,pause:b(),resume:b(),cancel:b()}),iR=S({pause:b(),cancel:b(),uncancellable:x(A),undoLastTurn:b(),continueLastTurn:b().optional(),runs:x(rR).optional()}),aR=S({session:j,user:M,focused:b(),typing:b(),lastActiveAt:N}),oR=S({voiceInput:b(),voiceOutput:b(),dictation:S({engine:E(JD),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(xN),description:v(),unavailable:v().optional()})),agents:x(S({fn:I,description:v()})),display:T(v(),oE),invocations:x(S({fn:I,description:v(),args:gT})),methods:x(S({type:I,method:v(),fn:I,description:v(),args:gT})),clients:x(S({system:F,url:v(),hash:v()})),systems:x(S({name:F,status:sP,enabled:b()})),models:x(qP)}),sR=tR.pick({id:!0,session:!0,author:!0,role:!0,replyTo:!0,replyAll:!0,createdAt:!0}).extend({text:v()}),cR=sP.extract([`connected`,`disconnected`,`removed`]),lR=w(`type`,[S({type:D(`message`),message:sR}),S({type:D(`run`),run:A,fn:I,update:kE,notified:b().optional()}),S({type:D(`resources`),changes:x(iS)}),S({type:D(`system`),system:F,status:cR}),S({type:D(`fns`),added:x(I),removed:x(I),changed:x(I).default([])})]),uR=S({protocol:D(1),name:F,version:v(),instance:L.default(Kl),instances:hP.optional(),boot:v(),publicKey:v(),manifestHash:v(),contractHash:v().optional(),pairingToken:v().optional(),autoPair:aP.optional()}),dR=w(`kind`,[S({kind:D(`challenge`),nonce:v()}),S({kind:D(`pairing`),pairing:pl,code:v().optional(),url:v(),expiresAt:N})]),fR=S({signature:v()}),pR=S({maxFrame:y().int().min(1024),maxChunk:y().int().min(1024),heartbeat:Ml}),mR=S({value:O,version:y().int().min(1)}),hR=S({instance:L,config:mR.optional(),start:S({first:b(),upgradedFrom:v().optional()}),token:v(),sendManifest:b(),limits:pR,autoPair:iP.optional(),store:_M.optional()});S({system:F,instance:L,boot:v()});var gR=eT(`linkSession`,{provides:Jw()}),_R=MP({name:`linkTel`}),vR=S({state:O,calls:T(v(),jE),reason:E([`resumed`,`restart`])}),yR=S({run:iE,fn:v(),kind:Pl,payload:O.optional(),args:O,budget:PE,handlers:x(v()),resume:vR.optional(),deadline:N,configVersion:y().int().min(0),connection:MO.optional(),approved:aA.optional()}),bR=C([S({run:A}),S({delivery:ul})]),xR=S({session:j,actor:M,user:tE,time:nE}),SR=S({level:E([`debug`,`info`,`warn`,`error`]),key:v(),fields:el}),CR=S({run:A,action:E([`cancel`,`pause`])}),wR=S({accepted:b(),reason:v().optional()}),TR=E([`restart`,`upgrade`,`shutdown`,`removed`]),ER=S({title:v().min(1).max(120),body:v().max(2e3)}),DR=Z(_R,gR).group({manifest:{body:NN,response:FN,ws:`mf`},patch:{body:PN,response:FN,ws:`mp`},call:{body:S({parent:A,fn:I,args:O,key:v(),budget:S({cost:P.optional(),time:Ml.optional()}).optional(),handlers:x(v()),background:b(),on:L.optional()}),response:jE,ws:`call`},handle:{body:S({run:A,handler:v(),args:O}),response:NE,ws:`ha`},control:{body:CR,response:wR,ws:`cl`},progress:{body:S({run:A,progress:pE}),ws:`pg`},allow:{body:S({run:A,operations:cE.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:oS})])}),ws:`at`},types:{body:S({names:x(I).min(1),run:A.optional()}),response:SP,ws:`ty`},fnShape:{body:S({name:I}),response:S({fn:IN.optional()}),ws:`fsh`},resourcesChanged:{body:S({changes:x(iS)}),ws:`rc`},llm:{body:hD,streamOut:gD,ws:`llm`},model:{body:HD,response:UD,ws:`mdl`},resource:{body:S({uri:Wx,want:x(Qx),run:A.optional(),sections:x(Gx).min(1).optional()}),response:eS,ws:`rs`},resourceSections:{body:S({uri:Wx,run:A.optional()}),response:x(rS),ws:`rsc`},content:{body:S({ref:Jx,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:Jx.optional()}),ws:`up`},setting:{body:S({run:A,setting:I}),response:S({value:O.optional()}),ws:`st`},stateGet:{body:S({owner:bR}),response:S({values:el,version:y().int()}),ws:`sg`},stateSet:{body:S({owner:bR,patch:el,clear:x(v()),version:y().int().optional()}),response:C([S({version:y().int()}),S({conflict:D(!0)})]),ws:`ss`},log:{body:SR,ws:`lg`},connectionUpdate:{body:IO,ws:`cu`},instanceConnect:{body:wO,ws:`ic`},shareFn:{body:vO,ws:`sh`},usableFns:{body:yO,response:S({fns:x(k)}),ws:`uf`},propose:{body:iA,response:cA,ws:`po`},decide:{body:vD,response:yD,ws:`de`},fleet:{body:S({}),response:x(VP),ws:`fl`},searchFns:{body:gF.extend({run:A.optional()}),response:TF,ws:`sf`},fnExamples:{body:dF,response:fF,ws:`fx`},examples:{body:uF,response:S({added:y().int().min(0),removed:y().int().min(0)}),ws:`xp`},models:{body:S({}),response:x(JP),ws:`mo`},grantPairing:{body:oA,response:sA,ws:`gp`},notifyAdmins:{body:ER,ws:`na`},notify:{body:S({run:A,notice:gI}),ws:`nf`},kindFns:{body:fI,response:pI,ws:`kf`},startRun:{body:mI,response:hI,ws:`sru`},notifyOwner:{body:S({fn:I,notice:gI}),ws:`nfo`},reportRefusal:{body:$F,ws:`rx`},mentionResources:{body:lI,response:uI,ws:`mr`},records:{body:Jj,response:Yj,ws:`rq`},record:{body:Zj,response:S({record:Kj.optional()}),ws:`rg`},recordTable:{body:Xj,response:Lk,ws:`rtb`},saveRecord:{body:Qj,response:Kj,ws:`rsv`},removeRecord:{body:eM,response:S({removed:b()}),ws:`rrm`},storeOpen:{body:S({}),response:S({bytes:y().int().min(0)}),ws:`sto`},storeRun:{body:HM,response:UM,ws:`stq`},storeBegin:{body:S({}),response:WM,ws:`stb`},storeCommit:{body:S({lease:zM}),ws:`stc`},storeRollback:{body:S({lease:zM}),ws:`str`},storeSnapshot:{body:S({}),response:S({snapshot:GM}),ws:`stn`},storeRestore:{body:S({snapshot:GM}),ws:`stx`},storeStatus:{body:EM,ws:`sts`},storeExport:{body:S({move:jM}),response:S({bytes:y().int().min(0),hash:v().regex(/^[0-9a-f]{64}$/)}),ws:`ste`},storeDownload:{body:S({move:jM,offset:y().int().min(0),length:y().int().min(1).max(4e6)}),response:S({chunk:v()}),ws:`std`},storeUpload:{body:S({move:jM,offset:y().int().min(0),chunk:v().max(6e6)}),ws:`stu`},storeUploadDone:{body:S({move:jM,bytes:y().int().min(0),hash:v().regex(/^[0-9a-f]{64}$/)}),ws:`stud`},storeMoveProgress:{body:S({move:jM,progress:FM}),ws:`stmp`}});X({endpoints:{...Z(_R).group({hello:{body:uR,response:dR,ws:`hi`},prove:{body:fR,response:hR,ws:`pr`},pairingInfo:{body:HP,ws:`pi`}}),...DR}}),X({endpoints:{paired:Y({body:S({pairing:pl}),ws:`pd`}),run:Y({body:yR,response:AE,ws:`run`}),control:Y({body:CR,response:wR,ws:`ctl`}),undo:Y({body:S({run:iE,fn:v(),kind:Pl,fnPayload:O.optional(),payload:O}),response:ME,ws:`un`}),handler:Y({body:S({call:dl,run:A,key:v(),handler:v(),args:O}),response:NE,ws:`hd`}),child:Y({body:S({parent:A,key:v(),run:A,update:kE.optional()}),ws:`ch`}),check:Y({body:S({kind:v(),payload:O}),response:S({problems:x(v()),description:LN.optional()}),ws:`ck`}),context:Y({body:xR.partial({session:!0}).extend({name:v(),args:T(v(),v())}),response:S({text:v()}),ws:`cx`}),roots:Y({response:x(Yx),ws:`ro`}),list:Y({body:S({uri:Wx,cursor:v().optional()}),response:Vl(Xx),ws:`ls`}),stat:Y({body:S({uri:Wx}),response:S({stat:Xx.optional()}),ws:`sa`}),read:Y({body:S({uri:Wx,want:x(Qx)}),response:eS,ws:`rd`}),sections:Y({body:S({sectioner:v(),uri:Wx,version:v()}),response:x(rS),ws:`sc`}),watch:Y({body:S({uris:x(Wx),on:b()}),ws:`wa`}),content:Y({body:S({ref:Jx,offset:y().int().min(0),length:y().int().min(1)}),response:S({chunk:v()}),ws:`ct`}),hook:Y({body:S({hook:v(),message:BN}),response:x(WN),ws:`hk`}),mentions:Y({body:xR.extend({provider:v(),query:v(),request:cI}),response:x(GN),ws:`mn`}),mentionHover:Y({body:xR.extend({provider:v(),target:O}),response:S({hover:KN.optional()}),ws:`mh`}),mentionText:Y({body:xR.extend({provider:v(),target:O}),response:S({text:v()}),ws:`mt`}),event:Y({body:lR,ws:`ev`}),action:Y({body:xR.extend({delivery:ul,action:v(),input:O,run:A.optional()}),response:S({result:O}),ws:`ac`}),form:Y({body:S({delivery:ul,run:A,value:O}),ws:`fm`}),restart:Y({body:S({reason:v()}),ws:`rt`}),stop:Y({body:S({reason:TR,timeout:Ml}),ws:`sp`}),configure:Y({body:mR.extend({previous:O.optional()}),ws:`cf`}),export:Y({body:S({timeout:Ml}),response:S({data:v()}),ws:`ex`}),validate:Y({body:rk,response:ik,ws:`vl`}),preview:Y({body:eA,response:oI,ws:`pv`}),estimate:Y({body:kF,response:AF,ws:`es`}),providerChat:Y({body:HO,streamOut:UO,ws:`pc`}),providerEmbed:Y({body:ZO,response:QO,ws:`pe`}),providerDecide:Y({body:qO,response:JO,ws:`pdc`}),providerModels:Y({body:GO,response:KO,ws:`pml`}),connectStart:Y({body:NO,response:S({url:Nb}),ws:`cs`}),connectFinish:Y({body:PO,response:FO,ws:`cn`}),disconnect:Y({body:MO.pick({id:!0,owner:!0,credentials:!0}),ws:`dc`}),flags:Y({body:eA,response:qk,ws:`fg`}),claims:Y({body:JM,response:YM,ws:`pcl`}),checkArgs:Y({body:tA,response:nA,ws:`cka`}),storeProbe:Y({body:S({to:_M}),response:S({problems:x(v())}),ws:`spb`}),storeMove:Y({body:S({move:jM,from:_M,to:_M}),response:S({tables:y().int().min(0),rows:y().int().min(0),bytes:y().int().min(0)}),ws:`smv`}),storeMoveEnd:Y({body:S({move:jM,outcome:E([`switched`,`aborted`]),from:_M,to:_M}),response:S({backups:x(S({id:kM,bytes:y().int().min(0)}))}),ws:`sme`}),storeDiscard:Y({body:w(`what`,[S({what:D(`store`)}),S({what:D(`backup`),backup:kM})]),ws:`sdc`})}});var OR=S({session:j,parts:x(eR).min(1),variants:JA,client:aE}),kR=XA.extend({status:cj,spent:P,tokens:y().int().min(0),startedAt:N,endedAt:N.optional(),time:Ml,messages:x(tR),approvals:x(BI)}),AR=ej.omit({variants:!0}).extend({turn:cl,session:j,message:ll,status:cj,variants:x(kR)}),jR=S({turn:cl,variant:GA,adopt:b().optional()}),MR=v().regex(Nl).max(64).brand(),NR=S({uri:v(),system:F.optional(),instance:L.optional()}),PR=S({systems:x(F).optional(),fns:x(FI).optional(),types:x(Jl).optional(),context:x(Jl).optional(),resources:x(NR).optional()}),FR=S({include:PR,exclude:PR}),IR=E([`each`,`static`]),LR=S({id:kl,slug:MR,name:v().min(1),instructions:v(),rules:FR,toolMode:IR,user:M,actor:M,secretDigest:v(),grantees:x(F),origins:x(v()),enabled:b(),createdBy:M,createdAt:N,updatedAt:N}),RR=LR.pick({slug:!0,name:!0,instructions:!0,rules:!0,toolMode:!0,user:!0,grantees:!0,origins:!0,enabled:!0});S({mcp:kl,label:v().min(1),exp:y().int()});var zR=S({mcp:kl,label:v().min(1),ttl:y().int().min(1e3).optional()}),BR=S({fns:x(I),types:x(I),closure:x(I),context:x(I),resources:x(NR),reach:x(I),warnings:x(v())}),VR=S({mcp:kl,session:v(),label:v(),client:S({name:v(),version:v()}).optional(),since:N,lastCallAt:N.optional(),calls:y().int().min(0)}),HR=LR.omit({secretDigest:!0}).extend({url:v(),sessions:y().int().min(0),callsToday:y().int().min(0)}),UR=E([`added`,`changed`,`removed`]),WR=S({id:v().min(1),system:F,section:BF,name:v().min(1),number:y().int().min(1),change:UR,decl:O,hash:v().min(1),declaredBy:yP.optional(),instance:L.optional(),savedBy:M.optional(),savedAt:N}),GR=Hl.extend({system:F,section:BF,name:v().min(1)}),KR=Vl(WR);rS.extend({uri:Wx,version:v(),hash:v()});var qR=(...e)=>e.join(`\0`),JR=`bearerAuth`,YR={security:{[JR]:{type:`http`,scheme:`bearer`,bearerFormat:`JWT`}}};function XR(e){let t=e?.name??JR,n=e?.doc??YR;return eT(t,{provides:Jw(),requires:e?.requires??[],doc:n})}var ZR=v().regex(/^[a-z]+:.+$/),QR=S({fnKind:Pl.optional(),mode:lN.optional(),effects:x(pN).optional(),reads:x(I).optional(),writes:x(I).optional(),visibility:zl.optional(),on:b(),stage:yk.optional(),pending:b().optional(),examples:y().int().min(0).optional()}),$R=S({id:ZR,kind:gj,name:v().min(1),about:v(),system:F.optional(),external:b(),collapsed:y().int().min(0).optional(),facts:QR}),ez=S({from:ZR,to:ZR,kind:vj,label:v().min(1),weight:y().min(0).max(1).optional()}),tz=S({node:ZR,kind:gj,count:y().int().min(1)}),nz=Oj.pick({text:!0,filters:!0}).extend({systems:x(F).min(1).optional(),external:b().optional(),focus:S({node:ZR,hops:y().int().min(1).max(4).optional()}).optional(),collapse:x(F).min(1).optional(),limit:y().int().min(1).max(1e3).optional()}),rz=S({nodes:x($R),edges:x(ez),more:x(tz),total:S({nodes:y().int().min(0),edges:y().int().min(0)})}),iz=`hub/visuals`,az=S({columns:x(S({name:v().min(1),kind:xk,role:Sk,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()}),oz=new Set([`integer`,`number`]),sz=new Set([`date`,`datetime`]),cz=new Set([`text`,`boolean`]),lz=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function uz(e){return oz.has(e)?`measure`:sz.has(e)||cz.has(e)?`group`:`attribute`}function dz(e,t,n){return e===void 0||typeof e==typeof t&&(n===`min`?t<e:t>e)?t:e}function fz(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`&&lz.test(e)&&(o+=1),(typeof e==`number`||typeof e==`string`)&&(l=dz(l,e,`min`),u=dz(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??uz(d),numeric:oz.has(d),temporal:sz.has(d),day:d===`date`,categorical:cz.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 pz=T(k,x(v().min(1)).min(1));S({visual:k,coverage:y().int().min(0),priority:y(),bind:pz,styles:x(k).min(1),because:x(v())});var mz={floor:0,structural:10,encoded:20,"time-encoded":30},hz={"temporal-key":15,"low-cardinality":10,"enum-key":8,"high-null":-10,"many-categories":-10},gz=.5;function _z(e){return e.columns.filter(e=>!e.opaque)}function vz(e,t){return e.accepts.includes(t.kind)&&(e.role===void 0||e.role===t.role)}function yz(e,t,n){return!e.required&&e.role===`group`&&n>1&&t.distinct>=n}function bz(e,t,n){let r={},i=new Set;for(let a of e.channels){let e=t.filter(e=>!i.has(e.name)&&vz(a,e)&&!yz(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 xz(e,t,n){return(e[t]??[]).flatMap(e=>n.columns.filter(t=>t.name===e))}function Sz(e,t,n,r,i){switch(e.rule){case`distinct`:{let r=xz(t,e.channel,n);return r.some(t=>t.distinct>e.max)?`${e.channel} has more than ${String(e.max)} values.`:e.min!==void 0&&r.some(t=>t.distinct<(e.min??0))?`${e.channel} has fewer than ${String(e.min)} values.`:void 0}case`non-negative`:return xz(t,e.channel,n).every(e=>e.nonNegative)?void 0:`${e.channel} has values below 0.`;case`bounded`:return xz(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 Cz(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>gz),"many-categories":i.some(e=>e.distinct>5)},o=e.priority.terms.filter(e=>a[e]);return{priority:mz[e.priority.band]+o.reduce((e,t)=>e+hz[t],0),because:o.map(e=>`${e} (${String(hz[e])})`)}}function wz(e,t,n,r){let i=[];e.whole===!0&&!n.whole&&i.push(`style ${e.name} only draws a whole result.`);for(let n of e.needs??[])t[n]===void 0&&i.push(`style ${e.name} needs ${n} bound.`);for(let[n,r]of Object.entries(e.columns??{})){let a=t[n]?.length??0;r.min!==void 0&&a<r.min&&i.push(`style ${e.name} needs at least ${String(r.min)} ${n} columns.`),r.max!==void 0&&a>r.max&&i.push(r.max===0?`style ${e.name} draws no ${n}.`:`style ${e.name} draws at most ${String(r.max)} ${n} columns.`)}for(let a of e.rules??[]){let o=Sz(a,t,n,r?.rows,r?.columns);o!==void 0&&i.push(`style ${e.name}: ${o}`)}return i}function Tz(e,t,n,r){return e.styles.filter(e=>wz(e,t,n,r).length===0).map(e=>e.name)}function Ez(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=Sz(a,t,n,r?.rows,r?.columns);e!==void 0&&i.push(e)}return i}function Dz(e,t,n){let r=_z(t);return e.flatMap((e,i)=>{let a=bz(e.shape,r.length>0?r:t.columns,t.rows);if(typeof a==`string`||Ez(e.shape,a,t,n).length>0)return[];let[o,...s]=Tz(e.shape,a,t,n);if(o===void 0)return[];let{priority:c,because:l}=Cz(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 Oz=[`integer`,`number`];function kz(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 Az=[`table`,`value`];E(Az);var jz={table:{label:`Table`,icon:`table`,description:`Every readable column and row, sortable and paged; cards on a phone.`,shape:Ak.parse({channels:[kz(`columns`,`Columns`,bk,{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:Ak.parse({channels:[kz(`value`,`Values`,Oz,{many:!0,role:`measure`}),kz(`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:[]}})}};Az.map(e=>({name:e,shape:jz[e].shape}));var Mz=S({from:k,to:k}),Nz=S({offset:k,limit:k}),Pz=S({visual:k,style:k,label:v().min(1).optional(),bind:pz}),Fz=E([`open`,`refresh`,`status`]),Iz=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:Fz.optional()}),Lz=S({fn:I,label:v().min(1),bind:T(k,v().min(1))}),Rz=S({offset:k,limit:k,window:y().int().min(1),more:b()}),zz=S({fn:I,label:v().min(1),mode:lN,confirm:b(),bind:T(k,v().min(1)),form:gT.optional(),then:Fz}),Bz=S({title:v().min(1),table:Lk,facts:az,source:S({fn:I,run:A,args:T(v(),O)}),visuals:x(Pz).min(1),problems:x(v()),range:Mz.optional(),paging:Rz.optional(),actions:x(zz),drill:Lz.optional(),readOnly:b(),live:S({every:y().int().min(1)}).optional(),summary:v().min(1)}),Vz=S({name:k,description:v().min(1),preview:Bz,replaces:v().min(1).optional()}),Hz=S({types:x(I).max(20),narrow:x(Iz).optional()}).refine(e=>e.types.length>0||(e.narrow?.length??0)>0,{message:`name a row type or an action to offer`}),Uz=S({fn:I,args:T(v(),O)}),Wz=Uz.extend({on:L.optional()}),Gz=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 Kz(e,t){return e!==`read`||t===!0}function qz(e,t){return t?`open`:e===`read`?`status`:`refresh`}function Jz(e){return wT(e.split(/[/.]/).pop()??e)||e}var Q=MP(),$=XR(),Yz=eT(`adminOnly`,{requires:[$]}),Xz=S({access:v(),refresh:v(),expiresIn:Ml,user:MI}),Zz=bI.pick({name:!0,version:!0}).extend({needsAdmin:b(),sso:x(QI)}),Qz=S({kind:E([`fn`,`context`]),name:I,description:v(),score:VN,why:v().optional()}),$z=CA(v().min(1)),eB=S({approvals:x(BI),handlers:x(sj)}),tB=BP.omit({publicKey:!0}),nB=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)}),rB=gP.omit({keyFingerprint:!0,publicKey:!0,config:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0,instances:!0}).extend(BP.pick({keyFingerprint:!0,config:!0,installed:!0,host:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0}).shape).extend({counts:nB,instanceMode:hP,needsConfig:b(),configType:O.optional(),configSecrets:uA.optional(),store:uM.optional(),instances:x(tB)}),iB=w(`type`,[S({type:D(`message`),message:tR}),S({type:D(`token`),message:ll,text:v()}),S({type:D(`reasoning`),message:ll,text:v()}),S({type:D(`cite`),message:ll,cite:VA}),S({type:D(`controls`),controls:iR}),S({type:D(`run`),run:A,fn:I,update:kE}),S({type:D(`state`),system:F,fields:x(ij)}),S({type:D(`delivery`),delivery:oj}),S({type:D(`handler`),call:sj}),S({type:D(`approval`),approval:BI}),S({type:D(`budget`),run:A,budget:AA,reason:v()}),S({type:D(`presence`),presence:aR}),S({type:D(`session`),session:HL}),S({type:D(`compare`),turn:cl})]),aB=w(`type`,[S({type:D(`notification`),notification:sF}),S({type:D(`approval`),approval:BI}),S({type:D(`system`),system:F,status:sP}),S({type:D(`pairing`),pairing:_P}),S({type:D(`capabilities`)}),S({type:D(`session`),session:HL}),S({type:D(`session-deleted`),session:j}),S({type:D(`fn`),fn:I,system:F,stats:vP}),S({type:D(`resource`),uri:Wx,forms:x(nS)}),S({type:D(`context`),name:I}),S({type:D(`identity`),identity:bI})]),oB=nT(X({endpoints:Z(Q).group({setup:{method:`GET`,response:Zz,ws:`setup`},createAdmin:{body:S({email:Ns(),name:v().min(1),password:v().min(8),setup:v().trim().min(1)}),response:Xz,ws:`createAdmin`},signIn:{body:S({email:Ns(),password:v()}),response:Xz,errors:{401:S({reason:v()})},ws:`signIn`},refresh:{body:S({refresh:v()}),response:Xz,ws:`refresh`},redeemSso:{body:S({code:v().min(1)}),cookies:S({[dL]:v().optional()}),response:Xz,ws:`redeemSso`,httpOnly:!0}})}),X({endpoints:Z(Q,$).group({signOut:{ws:`signOut`},me:{method:`GET`,response:MI,ws:`me`},account:{method:`GET`,response:oL,ws:`account`}})})),sB=Hl.extend({query:Oj.optional()}),cB=Hl.extend({session:j}),lB=Hl.extend({unread:b().optional(),query:Oj.optional()}),uB=VL.pick({title:!0,systems:!0,agent:!0,archived:!0}).partial().extend({priority:Rl.optional(),notify:LL.optional(),model:VL.shape.model.unwrap().nullable().optional(),mode:VL.shape.mode.unwrap().nullable().optional(),contextor:VL.shape.contextor.unwrap().nullable().optional(),fnMode:VL.shape.fnMode.unwrap().nullable().optional(),instructions:VL.shape.instructions.unwrap().nullable().optional(),citations:VL.shape.citations}),dB=X({endpoints:Z(Q,$).group({capabilities:{body:S({session:j.optional()}),response:oR,ws:`capabilities`},types:{body:S({names:x(I).min(1)}),response:SP,ws:`types`},sessions:{body:sB,response:Vl(HL),ws:`sessions`},session:{body:S({session:j}),response:VL,ws:`session`},createSession:{body:VL.pick({agent:!0,systems:!0,title:!0}).partial(),response:VL,ws:`createSession`},updateSession:{body:uB.extend({session:j}),response:VL,ws:`updateSession`},deleteSession:{body:S({session:j}),response:S({deleted:b()}),ws:`deleteSession`},limits:{body:S({session:j}),response:MA,ws:`limits`},messages:{body:cB,response:Vl(tR),ws:`messages`},send:{body:S({session:j,parts:x(eR).min(1),replyTo:ll.optional(),replyAll:b().optional(),client:aE}),response:S({turn:cl,message:tR}),ws:`send`},compare:{body:OR,response:S({turn:cl,message:tR}),ws:`compare`},compareView:{body:S({turn:cl}),response:AR,ws:`compareView`},chooseVariant:{body:jR,response:AR,ws:`chooseVariant`},invoke:{body:S({session:j,fn:I,args:O,on:L.optional(),client:aE}),response:S({turn:cl,run:A}),ws:`invoke`},control:{body:S({session:j,action:nR,runs:x(A).min(1).optional()}),response:iR,ws:`control`},controls:{body:S({session:j}),response:iR,ws:`controls`},presence:{body:aR.omit({user:!0,lastActiveAt:!0}),ws:`presence`}})}),fB=X({endpoints:Z(Q,$).group({background:{body:S({run:A}),response:S({accepted:b()}),ws:`background`},undoTurn:{body:S({turn:cl}),response:mj,ws:`undoTurn`},continueTurn:{body:S({turn:cl}),response:S({turn:cl,run:A}),ws:`continueTurn`},tree:{body:S({turn:cl}),response:pj,ws:`tree`},run:{body:S({run:A}),response:nj,ws:`run`},llmCall:{body:S({id:fl}),response:fj,ws:`llmCall`},waiting:{body:S({session:j}),response:eB,ws:`waiting`},approve:{body:S({approval:gl,approve:b(),remember:zI,reason:v().optional(),answer:O.optional()}),response:BI,ws:`approve`},answer:{body:S({call:dl,value:O}),ws:`answer`},act:{body:S({session:j,system:F,action:v(),input:O,run:A.optional(),client:aE}),response:S({delivery:ul}),ws:`act`},submit:{body:S({run:A,value:O}),response:S({delivery:ul}),ws:`submit`},state:{body:S({run:A}),response:S({system:F,fields:x(ij)}),ws:`state`}})}),pB=X({endpoints:Z(Q,$).group({suggest:{body:S({session:j,text:v(),limit:y().int().min(1).max(20).optional()}),response:x(Qz),ws:`suggest`},mentions:{body:S({session:j,provider:I,query:v()}),response:x(GN),ws:`mentions`},mentionHover:{body:S({session:j,provider:I,target:O}),response:S({hover:KN.optional()}),ws:`mentionHover`},resource:{body:S({uri:Wx,want:x(Qx)}),response:eS,ws:`resource`}})}),mB=X({endpoints:Z(Q,$).group({notifications:{body:lB,response:Vl(sF),ws:`notifications`},readNotifications:{body:S({ids:x(sF.shape.id)}),ws:`readNotifications`},pushKey:{method:`GET`,response:S({publicKey:v()}),ws:`pushKey`},subscribePush:{body:cF.pick({endpoint:!0,keys:!0,device:!0}),response:cF.pick({id:!0}),ws:`subscribePush`}})}),hB=X({endpoints:Z(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:Jx,ws:`uploaded`},transcribe:{body:S({audio:Jx}),response:S({text:v()}),ws:`transcribe`}})}),gB=S({section:E([`fns`,`context`]),name:I,on:b()}),_B=S({system:F,section:BF.exclude([`fns`,`context`]),name:v().min(1),on:b()}),vB=X({endpoints:Z(Q,$,Yz).group({systems:{body:S({query:Oj.optional()}),response:x(rB),ws:`systems`},system:{body:S({system:F}),response:rB,ws:`system`},pairings:{body:S({status:_P.shape.status.optional()}),response:x(_P),ws:`pairings`},approvePairing:{body:S({pairing:pl,approve:b(),instance:L.optional(),config:O.optional(),autoPair:rP.optional(),store:gM.optional()}),response:S({system:F.optional()}),ws:`approvePairing`},createPairingToken:{body:S({name:F.optional(),expiresIn:Ml,autoPair:rP.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:fP}),ws:`enableSystem`},switchItem:{body:gB,response:S({on:b()}),ws:`switchItem`},switchPart:{body:_B,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:cP,config:O.optional(),autoStart:b().optional(),store:gM.optional()}),response:S({name:F}),ws:`installSystem`},systemStore:{body:S({system:F,instance:L.optional()}),response:RM,ws:`systemStore`},systemStoreMove:{body:S({system:F,instance:L.optional(),to:gM,runs:NM.optional()}),response:IM,ws:`systemStoreMove`},systemStoreMoveState:{body:S({system:F,instance:L.optional()}),response:S({move:IM.optional()}),ws:`systemStoreMoveState`},systemStoreMoveAnswer:{body:S({system:F,instance:L.optional(),answer:PM}),response:IM,ws:`systemStoreMoveAnswer`},systemStoreBackups:{body:S({system:F,instance:L.optional()}),response:x(AM),ws:`systemStoreBackups`},systemStoreBackupDelete:{body:S({system:F,instance:L.optional(),backup:kM}),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:FN,ws:`reimport`}})}),yB=X({endpoints:Z(Q,$,Yz).group({configureProvider:{body:$z,response:S({models:y().int()}),ws:`configureProvider`},providers:{body:S({}),response:x(S({id:Tl,provider:TA,models:y().int()})),ws:`providers`},setModelCategory:{body:EA.partial({id:!0}),response:EA.pick({id:!0}),ws:`setModelCategory`},setBudget:{body:AA.omit({setBy:!0}).partial({id:!0}),response:AA.pick({id:!0}),ws:`setBudget`},setPriority:{body:jA.omit({setBy:!0}).partial({id:!0}),response:jA.pick({id:!0}),ws:`setPriority`},setPolicy:{body:RI.omit({createdBy:!0,createdAt:!0}).partial({id:!0}),response:RI.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:kI,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:cL,response:S({id:M}),ws:`updateUser`},setMembership:{body:lL,response:S({ok:b()}),ws:`setMembership`},setSignInPolicy:{body:GI,response:GI,ws:`setSignInPolicy`},setSignInLimits:{body:JI,response:JI,ws:`setSignInLimits`},setProxyTrust:{body:XI,response:XI,ws:`setProxyTrust`}})}),bB=X({endpoints:Z(Q,$,Yz).group({systemFns:{body:S({system:F}),response:x(bP),ws:`systemFns`},systemParts:{body:AP,response:jP,ws:`systemParts`},systemLogs:{body:S({system:F,limit:y().int().min(1).max(2e3).optional()}),response:x(WP),ws:`systemLogs`},models:{body:S({provider:Tl.optional()}),response:x(qP),ws:`models`},modelCategories:{body:S({}),response:x(EA),ws:`modelCategories`},budgets:{body:S({}),response:x(YP),ws:`budgets`},priorityRules:{body:S({}),response:x(jA),ws:`priorityRules`},resolveLimits:{body:S({user:M,session:j.optional()}),response:MA,ws:`resolveLimits`},policies:{body:S({}),response:x(RI),ws:`policies`},actors:{body:S({kind:Bl.optional()}),response:x(jI),ws:`actors`},actorSettings:{body:S({}),response:S({declared:x(XP),values:x(NI)}),ws:`actorSettings`},runs:{body:Hl.extend({query:Oj.optional()}),response:Vl(nj),ws:`runs`},llmCalls:{body:Hl.extend({query:Oj.optional()}),response:Vl(ZP),ws:`llmCalls`},resources:{body:Hl.extend({query:Oj.optional()}),response:Vl($P),ws:`resources`},removeRule:{body:QP,response:S({ok:b()}),ws:`removeRule`},indexStatus:{body:S({}),response:GP,ws:`indexStatus`}}),events:{systemLog:{params:S({system:F}),data:WP,guard:[$,Yz],ws:`on.systemLog`}}}),xB=eT(`ownEvents`,{requires:[$]}),SB=eT(`sessionWatch`,{requires:[$]}),CB=S({user:M}),wB=X({endpoints:{},events:{session:{params:S({session:j}),data:iB,guard:[$,SB],ws:`on.session`},user:{params:CB,data:aB,guard:[$,xB],ws:`on.user`}}}),TB=Vl($P).extend({facets:x(qE)}),EB=S({record:$P,forms:x(IE),offers:x(LE)}),DB=X({endpoints:Z(Q,$).group({browseResources:{body:JE.extend({query:Oj.optional()}),response:TB,ws:`browseResources`},resourceForms:{body:S({uri:Wx}),response:EB,ws:`resourceForms`},readResource:{body:$E,response:eD,ws:`readResource`},convertResource:{body:S({uri:Wx,kind:nS}),response:IE,ws:`convertResource`},downloadResource:{body:S({uri:Wx,form:nS.optional()}),response:S({url:v(),mime:v(),size:y().int().min(0)}),ws:`downloadResource`},importResource:{body:tD,response:$P,ws:`importResource`},renameResource:{body:S({uri:Wx,name:v().min(1)}),response:$P,ws:`renameResource`},deleteResource:{body:S({uri:Wx}),response:S({deleted:b(),referencedBy:y().int().min(0)}),ws:`deleteResource`},contextFromResource:{body:jS,response:MS,ws:`contextFromResource`}})}),OB=Hl.extend({query:Oj.optional()}),kB=S({record:wP,links:x(ES),backlinks:x(ES),text:v().optional()}),AB=X({endpoints:Z(Q,$).group({contexts:{body:OB,response:Vl(SF),ws:`contexts`},contextItem:{body:S({name:I}),response:kB,ws:`contextItem`},remember:{body:OS,response:S({name:I}),ws:`remember`},updateMemory:{body:AS,response:S({name:I}),ws:`updateMemory`},forget:{body:S({name:I}),response:S({ok:b()}),ws:`forget`},linkContext:{body:S({from:I,to:SS,relation:xS,weight:y().min(0).max(1)}),response:ES,ws:`linkContext`},unlinkContext:{body:ES.pick({from:!0,toKey:!0,relation:!0}),response:S({ok:b()}),ws:`unlinkContext`}})}),jB=nT(X({endpoints:Z(Q,$).group({contextMetadata:{body:S({name:I}),response:uC,ws:`contextMetadata`},setContextStatus:{body:QS,response:$S,ws:`setContextStatus`}})}),X({endpoints:Z(Q,$,Yz).group({contextReview:{body:nC,response:iC,ws:`contextReview`},mergeContext:{body:aC,response:oC,ws:`mergeContext`},notDuplicate:{body:sC,response:S({ok:b()}),ws:`notDuplicate`},reextractContext:{body:cC,response:lC,ws:`reextractContext`},newContextStatus:{body:S({}),response:qS,ws:`newContextStatus`},setNewContextStatus:{body:S({value:KS}),response:qS,ws:`setNewContextStatus`}})})),MB=X({endpoints:Z(Q,$).group({contextPlans:{body:MC,response:NC,ws:`contextPlans`},contextPlan:{body:wC,response:TC,ws:`contextPlan`},answerPlan:{body:OC,response:kC,ws:`answerPlan`}})}),NB=nT(X({endpoints:Z(Q,$).group({modelLimits:{body:S({model:v().optional()}),response:x(xx),ws:`modelLimits`},previewSelection:{body:S({session:j,text:v()}),response:Ex,ws:`previewSelection`}})}),X({endpoints:Z(Q,$,Yz).group({setModelLimits:{body:S({model:v().min(1),limits:_x}),response:xx,ws:`setModelLimits`},previewPrompt:{body:Dx,response:Ox,ws:`previewPrompt`}})})),PB=X({endpoints:Z(Q,$,Yz).group({modelRoles:{body:S({}),response:x($D),ws:`modelRoles`},setModelRole:{body:ZD,response:$D,ws:`setModelRole`},clearModelRole:{body:S({role:WD}),response:$D,ws:`clearModelRole`}})}),FB=Hl.extend({run:A.optional(),query:Oj.optional()}),IB=X({endpoints:Z(Q,$,Yz).group({modelCalls:{body:FB,response:Vl(VD),ws:`modelCalls`},modelCall:{body:S({id:Ol}),response:VD,ws:`modelCall`},fnMetrics:{body:lO,response:x(cO),ws:`fnMetrics`},fnMetricsDays:{body:S({fn:I,days:y().int().min(1).max(365).optional()}),response:x(sO),ws:`fnMetricsDays`}})}),LB=X({endpoints:Z(Q,$,Yz).group({mcps:{body:S({}),response:x(HR),ws:`mcps`},mcp:{body:S({mcp:kl}),response:HR,ws:`mcp`},createMcp:{body:RR,response:S({mcp:HR,secret:v()}),ws:`createMcp`},updateMcp:{body:RR.partial().extend({mcp:kl}),response:HR,ws:`updateMcp`},rotateMcpSecret:{body:S({mcp:kl}),response:S({secret:v()}),ws:`rotateMcpSecret`},deleteMcp:{body:S({mcp:kl}),response:S({ok:b()}),ws:`deleteMcp`},previewMcp:{body:S({rules:FR}),response:BR,ws:`previewMcp`},mcpSessions:{body:S({mcp:kl}),response:x(VR),ws:`mcpSessions`}})}),RB=X({endpoints:Z(Q,$,Yz).group({pairing:{body:S({pairing:pl}),response:_P,ws:`pairing`},instances:{body:S({system:F}),response:x(tB),ws:`instances`},installPackage:{body:S({zip:Jx,instance:L.optional(),config:O.optional(),data:Jx.optional(),autoStart:b().optional(),store:gM.optional()}),response:ql,ws:`installPackage`},removeInstance:{body:ql.extend({keepStore:b().optional()}),response:S({ok:b()}),ws:`removeInstance`},addInstance:{body:UP,response:ql,ws:`addInstance`},exportSystemData:{body:ql.extend({withSecrets:b().optional()}),response:Jx.extend({url:v()}),ws:`exportSystemData`}})}),zB=nT(X({endpoints:Z(Q,$).group({query:{body:Hj,response:Uj,ws:`query`},listValues:{body:Vj,response:x(Bj),ws:`listValues`}})}),X({endpoints:Z(Q,$,Yz).group({fns:{body:Oj,response:Vl(bP),ws:`fns`}})})),BB=X({endpoints:Z(Q,$,Yz).group({suggestDecision:{body:S({}),response:kL,ws:`suggestDecision`},setSuggestDecision:{body:wL,response:kL,ws:`setSuggestDecision`},searchDecisions:{body:S({}),response:FL,ws:`searchDecisions`},setSearchDecision:{body:IL,response:FL,ws:`setSearchDecision`},previewSuggestions:{body:S({session:j,text:v().min(1)}),response:xL,ws:`previewSuggestions`}})}),VB=X({endpoints:Z(Q,$,Yz).group({imageEmbedding:{body:S({}),response:DI,ws:`imageEmbedding`},setImageEmbedding:{body:CI,response:DI,ws:`setImageEmbedding`}})}),HB=nT(X({endpoints:Z(Q,$).group({outsideImages:{body:S({}),response:Lb,ws:`outsideImages`}})}),X({endpoints:Z(Q,$,Yz).group({setOutsideImages:{body:S({value:Ib}),response:Lb,ws:`setOutsideImages`}})})),UB=nT(X({endpoints:Z(Q,$).group({https:{body:S({}),response:Vb,ws:`https`}})}),X({endpoints:Z(Q,$,Yz).group({setHttps:{body:S({on:b()}),response:Vb,ws:`setHttps`}})})),WB=X({endpoints:Z(Q,$,Yz).group({autoPairs:{body:S({system:F.optional()}),response:x(oP),ws:`autoPairs`},revokeAutoPair:{body:S({id:Al}),response:S({ok:b()}),ws:`revokeAutoPair`}})}),GB=X({endpoints:Z(Q,$).group({accessInfo:{body:S({}),response:gO,ws:`accessInfo`},access:{body:S({targets:x(pO).min(1).max(200)}),response:x(hO),ws:`access`},setAccess:{body:S({target:pO,sharing:fO.omit({owner:!0})}),response:hO,ws:`setAccess`}})}),KB=X({endpoints:Z(Q,$).group({connectPages:{body:S({}),response:x(jO),ws:`connectPages`},connect:{body:S({system:F,instance:L.optional(),key:TO.optional(),form:O.optional()}),response:C([S({url:Nb}),S({connection:AO})]),ws:`connect`,httpOnly:!0},updateConnection:{body:LO,response:AO,ws:`updateConnection`},disconnect:{body:S({connection:jl}),response:S({ok:b()}),ws:`disconnect`}})}),qB=X({endpoints:Z(Q,$).group({pick:{body:bO,response:x(xO),ws:`pick`}})}),JB=X({endpoints:Z(Q,$).group({approvals:{body:S({runs:x(A).min(1).max(200)}),response:x(BI),ws:`approvals`}})}),YB=X({endpoints:Z(Q,$).group({contributions:{body:S({registry:I}),response:x(Nk),ws:`contributions`},systemPages:{body:S({}),response:x(bA),ws:`systemPages`},systemInstances:{body:S({system:F}),response:x(xA),ws:`systemInstances`}})}),XB=nT(X({endpoints:Z(Q,$).group({searchFns:{body:gF,response:TF,ws:`searchFns`},fnExamples:{body:dF,response:fF,ws:`fnExamples`},fnFacts:{body:S({fn:I,args:O.optional()}),response:OF,ws:`fnFacts`},fnsOfModelNames:{body:S({names:x(v().min(1).max(64)).min(1).max(200)}),response:T(v(),I),ws:`fnsOfModelNames`},clientLogs:{body:NF,response:PF,ws:`clientLogs`}})}),X({endpoints:Z(Q,$,Yz).group({autoClassifier:{body:S({}),response:MF,ws:`autoClassifier`},setAutoClassifier:{body:jF,response:MF,ws:`setAutoClassifier`}})})),ZB=X({endpoints:Z(Q,$).group({exploreRoots:{body:S({system:F,instance:L.optional()}),response:x(Yx),ws:`exploreRoots`},exploreList:{body:S({uri:Wx,cursor:v().optional()}),response:Vl(Xx),ws:`exploreList`},exploreRead:{body:S({uri:Wx,want:x(Qx).min(1)}),response:eS,ws:`exploreRead`}})}),QB=X({endpoints:Z(Q,$,Yz).group({systemReview:{body:S({system:F}),response:nI,ws:`systemReview`},goLive:{body:rI,response:S({stage:yk,hash:v()}),ws:`goLive`},approveReview:{body:rI,response:S({hash:v()}),ws:`approveReview`},rejectReview:{body:S({system:F,hash:v().min(1)}),response:S({ok:b()}),ws:`rejectReview`},decideReview:{body:iI,response:aI,ws:`decideReview`},testCall:{body:sI,response:S({run:A}),ws:`testCall`},refusals:{body:eI,response:tI,ws:`refusals`}})}),$B=X({endpoints:Z(Q,$).group({graph:{body:nz,response:rz,ws:`graph`}})}),eV=S({agent:I.optional(),context:I.optional(),mode:ax.optional(),fnMode:jx.optional()}),tV=X({endpoints:Z(Q,$,Yz).group({injections:{body:eV,response:Xb,ws:`injections`},setInjection:{body:Zb,response:Yb,ws:`setInjection`}})}),nV=nT(X({endpoints:Z(Q).group({identity:{method:`GET`,response:bI,ws:`identity`}})}),X({endpoints:Z(Q,$,Yz).group({setHubName:{body:xI,response:bI,ws:`setHubName`}})})),rV=X({endpoints:Z(Q,$,Yz).group({people:{body:Oj,response:Vl(oL),ws:`people`},groups:{body:Oj,response:Vl(sL),ws:`groups`},groupMembers:{body:Hl.extend({group:M}),response:Vl(MI).extend({group:sL}),ws:`groupMembers`},signInSettings:{body:S({}),response:$I,ws:`signInSettings`},checkSsoProvider:{body:S({provider:VI}),response:tL,ws:`checkSsoProvider`},testSsoSignIn:{body:S({provider:VI}),response:S({url:Nb,test:v()}),ws:`testSsoSignIn`,httpOnly:!0},ssoTestResult:{body:S({test:v()}),response:iL,ws:`ssoTestResult`}})}),iV=X({endpoints:Z(Q,$).group({itemVersions:{body:GR,response:KR,ws:`itemVersions`}})}),aV=X({endpoints:Z(Q,$).group({dataSets:{body:iM,response:aM,ws:`dataSets`},records:{body:Jj,response:Yj,ws:`records`},record:{body:Zj,response:S({record:Kj.optional()}),ws:`record`},recordTable:{body:Xj,response:Lk,ws:`recordTable`},saveRecord:{body:Qj,response:Kj,ws:`saveRecord`},updateRecord:{body:$j,response:Kj,ws:`updateRecord`},removeRecord:{body:eM,response:S({removed:b()}),ws:`removeRecord`},recordVersions:{body:tM,response:nM,ws:`recordVersions`}})}),oV=nT(oB,dB,fB,pB,mB,hB,vB,yB,bB,wB,DB,AB,jB,MB,NB,PB,IB,LB,RB,zB,BB,WB,VB,HB,UB,GB,KB,qB,JB,YB,XB,ZB,QB,$B,tV,nV,iV,aV,X({endpoints:Z(Q,$).group({rowActions:{body:Hz,response:x(zz),ws:`rowActions`},readFn:{body:Wz,response:O,ws:`readFn`}})}),X({endpoints:Z(Q,$).group({export:{method:`GET`,query:Gz,streamOut:`text/csv`,download:`export.csv`}})}),rV),sV={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(sV).map(([e,t])=>[`hub/${e}`,`hub/${t}`])),new Map(Object.entries(sV));var cV=E([`added`,`modified`,`deleted`,`renamed`]),lV=E([`binary`,`large`,`sensitive`,`not-in-git`]),uV=S({path:v().min(1),root:v().min(1),status:cV,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:lV.optional(),sensitive:Hk.optional(),certain:b()}),dV=S({source:E([`git`,`watcher`]),cwd:v().min(1),files:x(uV),ignored:y().int().min(0),truncated:b()}),fV=S({arg:k,label:v().min(1).optional(),choices:x(O).min(1).optional(),custom:b().optional(),pinned:O.optional(),hidden:b().optional()}),pV=S({offset:k.optional(),limit:k.optional(),size:y().int().min(1).max(500)}),mV=S({visual:k,label:v().min(1).optional(),bind:T(k,x(v().min(1)).min(1))}),hV=E([`refresh`,`show`,`none`]),gV=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:hV});S({title:v().min(1),source:I,visuals:x(mV).min(1),controls:x(fV),paging:pV.optional(),actions:x(gV).optional()});var _V=sF.pick({id:!0,title:!0,body:!0,link:!0,reason:!0,also:!0,key:!0,tone:!0}),vV=`open`,yV=E([`link`,`also`]),bV=`also`;function xV(e,t=`link`){return`/inbox?${vV}=${encodeURIComponent(e.id)}${t===`also`?`&via=also`:``}`}function SV(e){return e.key??e.id}function CV(e){return e.also===void 0?{link:xV(e)}:{link:xV(e),also:xV(e,`also`)}}function wV(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{RR as $,cl as $a,fv as $i,VE as $n,DS as $r,NN as $t,fB as A,xf as Aa,vb as Ai,dA as An,ic as Ao,vT as Ar,jF as At,Hz as B,Kl as Ba,Jg as Bi,DO as Bn,T as Bo,xC as Br,DP as Bt,tV as C,Mf as Ca,zb as Ci,qA as Cn,yc as Co,kT as Cr,wI as Ct,RB as D,yf as Da,wb as Di,_A as Dn,pc as Do,DT as Dr,yI as Dt,PB as E,jf as Ea,Db as Ei,TA as En,ws as Eo,TT as Er,_I as Et,Gz as F,kl as Fa,Gg as Fi,Lk as Fn,D as Fo,JC as Fr,bF as Ft,jz as G,Ll as Ga,Rv as Gi,aO as Gn,Ls as Go,dC as Gr,EP as Gt,Jz as H,Ol as Ha,Rg as Hi,_O as Hn,vc as Ho,AC as Hr,cP as Ht,Nz as I,L as Ia,Tv as Ii,_k as In,fc as Io,zw as Ir,TF as It,fz as J,Wl as Ja,t_ as Ji,GD as Jn,PC as Jr,JN as Jt,Az as K,pl as Ka,Ev as Ki,rO as Kn,hC as Kr,YN as Kt,Vz as L,O as La,Kg as Li,gk as Ln,y as Lo,Hw as Lr,hF as Lt,BB as M,M as Ma,Wg as Mi,Nk as Mn,b as Mo,hT as Mr,fF as Mt,vB as N,Bl as Na,zg as Ni,Pk as Nn,w as No,oT as Nr,dF as Nt,zB as O,Nf as Oa,tb as Oi,vA as On,oc as Oo,OT as Or,zF as Ot,iV as P,zl as Pa,Pv as Pi,Fk as Pn,Zc as Po,cT as Pr,_F as Pt,qR as Q,N as Qa,Jv as Qi,FE as Qn,jS as Qr,sN as Qt,Uz as R,fl as Ra,qg as Ri,lk as Rn,S as Ro,OC as Rr,LF as Rt,oV as S,df as Sa,Ub as Si,aj as Sn,Vc as So,jT as Sr,FI as St,IB as T,vf as Ta,Sb as Ti,BA as Tn,Uc as To,wT as Tr,CI as Tt,Kz as U,Jl as Ua,Fv as Ui,dO as Un,C as Uo,wC as Ur,xP as Ut,Bz as V,ll as Va,Yg as Vi,TO as Vn,v as Vo,SC as Vr,wP as Vt,qz as W,xl as Wa,Av as Wi,mO as Wn,sc as Wo,TC as Wr,TP as Wt,ZR as X,j as Xa,Bv as Xi,ED as Xn,eC as Xr,cN as Xt,Dz as Y,A as Ya,e_ as Yi,ZD as Yn,HC as Yr,nP as Yt,nz as Z,F as Za,a_ as Zi,iD as Zn,XS as Zr,_N as Zt,AB as _,Lh as _a,hx as _i,Ij as _n,$s as _o,LT as _r,_L as _t,wV as a,d_ as aa,AS as ai,uM as an,ac as ao,GE as ar,eR as at,ZB as b,ff as ba,ox as bi,zj as bn,zc as bo,RT as br,JI as bt,dV as c,zv as ca,Kx as ci,yM as cn,Lc as co,xE as cr,hL as ct,GB as d,p_ as da,rS as di,oM as dn,xc as do,TE as dr,AL as dt,s_ as ea,bS as ei,ON as en,nl as eo,ZE as er,PR as et,bB as f,h_ as fa,Gx as fi,Kj as fn,Gc as fo,EE as fr,mL as ft,jB as g,Dm as ga,ix as gi,Rj as gn,kc as go,eE as gr,SL as gt,KB as h,$y as ha,Ax as hi,Ej as hn,rc as ho,$T as hr,wL as ht,_V as i,u_ as ia,OS as ii,mM as in,Il as io,XE as ir,YL as it,yB as j,Gl as ja,fb as ji,Mk as jn,x as jo,gT as jr,vF as jt,DB as k,sf as ka,eb as ki,lA as kn,E as ko,bT as kr,XF as kt,$z as l,Kv as la,nS as li,xM as ln,qc as lo,wE as lr,yL as lt,dB as m,__ as ma,fx as mi,Gj as mn,Fc as mo,QT as mr,TL as mt,yV as n,l_ as na,CS as ni,zN as nn,Ul as no,KE as nr,zR as nt,SV as o,wv as oa,fS as oi,gM as on,uc as oo,OE as or,HL as ot,WB as p,U as pa,Ux as pi,Wj as pn,Sc as po,yE as pr,CL as pt,iz as q,I as qa,Hv as qi,WD as qn,UC as qr,tP as qt,vV as r,Bg as ra,SS as ri,QM as rn,Fl as ro,YE as rr,NR as rt,CV as s,jv as sa,uS as si,fM as sn,nc as so,mE as sr,$L as st,bV as t,c_ as ta,wS as ti,RN as tn,tl as to,QE as tr,MR as tt,Xz as u,f_ as ua,Wx as ui,sM as un,jc as uo,DE as ur,ML as ut,NB as v,gf as va,Qb as vi,xj as vn,dc as vo,MT as vr,WI as vt,LB as w,cf as wa,Pb as wi,LA as wn,Es as wo,ET as wr,SI as wt,$B as x,Sf as xa,Wb as xi,hj as xn,Nc as xo,HT as xr,uL as xt,aV as y,Af as ya,_x as yi,Sj as yn,Tc as yo,UT as yr,XI as yt,zz as z,k as za,Mv as zi,BO as zn,Ec as zo,kC as zr,oF as zt};
402
+ //# sourceMappingURL=push-payload-B3EcrsVz.js.map