fnloom 0.0.1 → 0.2.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 (1520) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +174 -3
  3. package/package.json +70 -4
  4. package/packages/build/package.json +31 -0
  5. package/packages/build/src/build-system.ts +186 -0
  6. package/packages/build/src/builder.ts +225 -0
  7. package/packages/build/src/context.ts +2 -0
  8. package/packages/build/src/files.ts +73 -0
  9. package/packages/build/src/folder.ts +52 -0
  10. package/packages/build/src/index.ts +20 -0
  11. package/packages/build/src/scan.ts +82 -0
  12. package/packages/build/src/tests.ts +138 -0
  13. package/packages/build/tsconfig.json +6 -0
  14. package/packages/cli/bin/harness.mjs +17 -0
  15. package/packages/cli/package.json +27 -0
  16. package/packages/cli/src/catalog.ts +35 -0
  17. package/packages/cli/src/cli.ts +83 -0
  18. package/packages/cli/src/command.ts +112 -0
  19. package/packages/cli/src/commands/available.ts +107 -0
  20. package/packages/cli/src/commands/build.ts +57 -0
  21. package/packages/cli/src/commands/data.ts +36 -0
  22. package/packages/cli/src/commands/install.ts +167 -0
  23. package/packages/cli/src/commands/manage.ts +104 -0
  24. package/packages/cli/src/commands/mcp.ts +198 -0
  25. package/packages/cli/src/commands/new.ts +139 -0
  26. package/packages/cli/src/commands/pack.ts +37 -0
  27. package/packages/cli/src/commands/start.ts +22 -0
  28. package/packages/cli/src/commands/test.ts +57 -0
  29. package/packages/cli/src/files.ts +5 -0
  30. package/packages/cli/src/hub-client.ts +84 -0
  31. package/packages/cli/src/hub.ts +169 -0
  32. package/packages/cli/src/index.ts +13 -0
  33. package/packages/cli/src/io.ts +32 -0
  34. package/packages/cli/src/live.ts +66 -0
  35. package/packages/cli/src/local.ts +100 -0
  36. package/packages/cli/src/main.ts +6 -0
  37. package/packages/cli/src/premade.ts +80 -0
  38. package/packages/cli/src/testing.ts +216 -0
  39. package/packages/cli/tsconfig.json +6 -0
  40. package/packages/core/package.json +21 -0
  41. package/packages/core/src/access.ts +97 -0
  42. package/packages/core/src/admin.ts +90 -0
  43. package/packages/core/src/api-index.ts +26 -0
  44. package/packages/core/src/approvals.ts +229 -0
  45. package/packages/core/src/auto-pair.ts +47 -0
  46. package/packages/core/src/changes.ts +61 -0
  47. package/packages/core/src/checks.ts +93 -0
  48. package/packages/core/src/claims.ts +98 -0
  49. package/packages/core/src/compare.ts +47 -0
  50. package/packages/core/src/config-secrets.ts +28 -0
  51. package/packages/core/src/connections.ts +193 -0
  52. package/packages/core/src/context-files.ts +179 -0
  53. package/packages/core/src/context-graph.ts +270 -0
  54. package/packages/core/src/csv.ts +33 -0
  55. package/packages/core/src/data.ts +176 -0
  56. package/packages/core/src/decisions.ts +98 -0
  57. package/packages/core/src/flow.ts +225 -0
  58. package/packages/core/src/fn-block.ts +51 -0
  59. package/packages/core/src/fn-facts.ts +533 -0
  60. package/packages/core/src/fn-renames.ts +102 -0
  61. package/packages/core/src/gin-a.ts +185 -0
  62. package/packages/core/src/gin-record.ts +142 -0
  63. package/packages/core/src/gin.ts +104 -0
  64. package/packages/core/src/grants.ts +84 -0
  65. package/packages/core/src/graph-kinds.ts +44 -0
  66. package/packages/core/src/graph.ts +95 -0
  67. package/packages/core/src/https.ts +35 -0
  68. package/packages/core/src/identity.ts +38 -0
  69. package/packages/core/src/image-embeddings.ts +96 -0
  70. package/packages/core/src/index.ts +129 -0
  71. package/packages/core/src/inject.ts +104 -0
  72. package/packages/core/src/issues.ts +137 -0
  73. package/packages/core/src/labels.ts +96 -0
  74. package/packages/core/src/lifecycle.ts +237 -0
  75. package/packages/core/src/link.ts +491 -0
  76. package/packages/core/src/llm.ts +167 -0
  77. package/packages/core/src/manifest.ts +657 -0
  78. package/packages/core/src/mcp-servers.ts +134 -0
  79. package/packages/core/src/media-types.ts +145 -0
  80. package/packages/core/src/mention-search.ts +27 -0
  81. package/packages/core/src/metrics.ts +91 -0
  82. package/packages/core/src/model-calls.ts +223 -0
  83. package/packages/core/src/model-names.ts +704 -0
  84. package/packages/core/src/modes.ts +325 -0
  85. package/packages/core/src/objects.ts +15 -0
  86. package/packages/core/src/owner-runs.ts +89 -0
  87. package/packages/core/src/package.ts +195 -0
  88. package/packages/core/src/partial.ts +69 -0
  89. package/packages/core/src/people-only.ts +52 -0
  90. package/packages/core/src/pickers.ts +31 -0
  91. package/packages/core/src/ports.ts +14 -0
  92. package/packages/core/src/primitives.ts +287 -0
  93. package/packages/core/src/programs.ts +155 -0
  94. package/packages/core/src/query.ts +264 -0
  95. package/packages/core/src/records/actors.ts +188 -0
  96. package/packages/core/src/records/announced.ts +39 -0
  97. package/packages/core/src/records/chat.ts +279 -0
  98. package/packages/core/src/records/citations.ts +126 -0
  99. package/packages/core/src/records/compare.ts +97 -0
  100. package/packages/core/src/records/content.ts +196 -0
  101. package/packages/core/src/records/injections.ts +146 -0
  102. package/packages/core/src/records/mcps.ts +115 -0
  103. package/packages/core/src/records/runs.ts +280 -0
  104. package/packages/core/src/records/spend.ts +158 -0
  105. package/packages/core/src/records/systems.ts +298 -0
  106. package/packages/core/src/records/tables.ts +164 -0
  107. package/packages/core/src/registries.ts +229 -0
  108. package/packages/core/src/remote-auth.ts +111 -0
  109. package/packages/core/src/resource-forms.ts +218 -0
  110. package/packages/core/src/resources.ts +166 -0
  111. package/packages/core/src/review-summary.ts +69 -0
  112. package/packages/core/src/run.ts +312 -0
  113. package/packages/core/src/sensitivity.ts +101 -0
  114. package/packages/core/src/sso.ts +268 -0
  115. package/packages/core/src/status.ts +158 -0
  116. package/packages/core/src/suggestions.ts +228 -0
  117. package/packages/core/src/system-events.ts +47 -0
  118. package/packages/core/src/system-pages.ts +72 -0
  119. package/packages/core/src/system-parts.ts +51 -0
  120. package/packages/core/src/system-providers.ts +163 -0
  121. package/packages/core/src/urls.ts +50 -0
  122. package/packages/core/src/validation.ts +39 -0
  123. package/packages/core/src/versions.ts +52 -0
  124. package/packages/core/src/visuals.ts +478 -0
  125. package/packages/core/src/web.ts +965 -0
  126. package/packages/core/src/widgets-v1.ts +73 -0
  127. package/packages/core/src/widgets.ts +427 -0
  128. package/packages/core/tsconfig.json +5 -0
  129. package/packages/hub/context/asking.md +16 -0
  130. package/packages/hub/context/attached_files.md +27 -0
  131. package/packages/hub/context/background_runs.md +14 -0
  132. package/packages/hub/context/earlier_chats.md +16 -0
  133. package/packages/hub/context/examples.md +13 -0
  134. package/packages/hub/context/finding_fns.md +18 -0
  135. package/packages/hub/context/images.md +24 -0
  136. package/packages/hub/context/later.md +27 -0
  137. package/packages/hub/context/limits.md +13 -0
  138. package/packages/hub/context/memory.md +38 -0
  139. package/packages/hub/context/resources.md +21 -0
  140. package/packages/hub/context/saved_fns.md +28 -0
  141. package/packages/hub/context/undo.md +20 -0
  142. package/packages/hub/package.json +55 -0
  143. package/packages/hub/src/access/create.ts +29 -0
  144. package/packages/hub/src/access/hits.ts +57 -0
  145. package/packages/hub/src/access/index.ts +119 -0
  146. package/packages/hub/src/access/scope.ts +133 -0
  147. package/packages/hub/src/access/service.ts +171 -0
  148. package/packages/hub/src/api/admin-ops.ts +410 -0
  149. package/packages/hub/src/api/auth.ts +286 -0
  150. package/packages/hub/src/api/client-address.ts +55 -0
  151. package/packages/hub/src/api/connect.ts +45 -0
  152. package/packages/hub/src/api/dual.ts +103 -0
  153. package/packages/hub/src/api/events.ts +185 -0
  154. package/packages/hub/src/api/files.ts +209 -0
  155. package/packages/hub/src/api/hash.ts +23 -0
  156. package/packages/hub/src/api/http.ts +171 -0
  157. package/packages/hub/src/api/https.ts +125 -0
  158. package/packages/hub/src/api/identities.ts +246 -0
  159. package/packages/hub/src/api/index.ts +94 -0
  160. package/packages/hub/src/api/injections.ts +256 -0
  161. package/packages/hub/src/api/mime.ts +31 -0
  162. package/packages/hub/src/api/person-ops.ts +153 -0
  163. package/packages/hub/src/api/push.ts +97 -0
  164. package/packages/hub/src/api/reads.ts +145 -0
  165. package/packages/hub/src/api/secrets.ts +71 -0
  166. package/packages/hub/src/api/serve.ts +280 -0
  167. package/packages/hub/src/api/signed.ts +66 -0
  168. package/packages/hub/src/api/sso-route.ts +73 -0
  169. package/packages/hub/src/api/sso.ts +382 -0
  170. package/packages/hub/src/api/system-parts.ts +97 -0
  171. package/packages/hub/src/api/testing/issuer.ts +128 -0
  172. package/packages/hub/src/api/testing/rig.ts +272 -0
  173. package/packages/hub/src/api/tls.ts +383 -0
  174. package/packages/hub/src/api/web/access.ts +84 -0
  175. package/packages/hub/src/api/web/admin.ts +90 -0
  176. package/packages/hub/src/api/web/auth.ts +103 -0
  177. package/packages/hub/src/api/web/build3.ts +44 -0
  178. package/packages/hub/src/api/web/build4.ts +24 -0
  179. package/packages/hub/src/api/web/build5.ts +120 -0
  180. package/packages/hub/src/api/web/chat.ts +144 -0
  181. package/packages/hub/src/api/web/content.ts +42 -0
  182. package/packages/hub/src/api/web/context.ts +41 -0
  183. package/packages/hub/src/api/web/contextor.ts +37 -0
  184. package/packages/hub/src/api/web/data.ts +33 -0
  185. package/packages/hub/src/api/web/explorer.ts +22 -0
  186. package/packages/hub/src/api/web/find.ts +50 -0
  187. package/packages/hub/src/api/web/graph.ts +17 -0
  188. package/packages/hub/src/api/web/https.ts +18 -0
  189. package/packages/hub/src/api/web/identity.ts +18 -0
  190. package/packages/hub/src/api/web/images.ts +18 -0
  191. package/packages/hub/src/api/web/inbox.ts +35 -0
  192. package/packages/hub/src/api/web/index.ts +137 -0
  193. package/packages/hub/src/api/web/injections.ts +22 -0
  194. package/packages/hub/src/api/web/mcps.ts +32 -0
  195. package/packages/hub/src/api/web/metrics.ts +24 -0
  196. package/packages/hub/src/api/web/models.ts +21 -0
  197. package/packages/hub/src/api/web/outside-images.ts +32 -0
  198. package/packages/hub/src/api/web/packaging.ts +31 -0
  199. package/packages/hub/src/api/web/pages.ts +55 -0
  200. package/packages/hub/src/api/web/people.ts +92 -0
  201. package/packages/hub/src/api/web/pickers.ts +115 -0
  202. package/packages/hub/src/api/web/resources.ts +42 -0
  203. package/packages/hub/src/api/web/review.ts +119 -0
  204. package/packages/hub/src/api/web/runs.ts +94 -0
  205. package/packages/hub/src/api/web/settings.ts +35 -0
  206. package/packages/hub/src/api/web/systems.ts +83 -0
  207. package/packages/hub/src/api/web/tables.ts +31 -0
  208. package/packages/hub/src/api/web/versions.ts +17 -0
  209. package/packages/hub/src/api/web/visibility.ts +47 -0
  210. package/packages/hub/src/boot/admin-fns.ts +78 -0
  211. package/packages/hub/src/boot/admin-secrets.ts +140 -0
  212. package/packages/hub/src/boot/env.ts +170 -0
  213. package/packages/hub/src/boot/hub-context.ts +39 -0
  214. package/packages/hub/src/boot/hub-fns.ts +549 -0
  215. package/packages/hub/src/boot/hub-groups.ts +34 -0
  216. package/packages/hub/src/boot/identity.ts +66 -0
  217. package/packages/hub/src/boot/index.ts +191 -0
  218. package/packages/hub/src/boot/info.ts +22 -0
  219. package/packages/hub/src/boot/keys.ts +60 -0
  220. package/packages/hub/src/boot/log.ts +31 -0
  221. package/packages/hub/src/boot/modules.ts +277 -0
  222. package/packages/hub/src/boot/person-fns.ts +78 -0
  223. package/packages/hub/src/boot/read-fns.ts +73 -0
  224. package/packages/hub/src/boot/services.ts +156 -0
  225. package/packages/hub/src/boot/start.ts +246 -0
  226. package/packages/hub/src/bus/memory.ts +60 -0
  227. package/packages/hub/src/bus.ts +80 -0
  228. package/packages/hub/src/catalog/api-index.ts +72 -0
  229. package/packages/hub/src/catalog/availability.ts +210 -0
  230. package/packages/hub/src/catalog/catalog.ts +1062 -0
  231. package/packages/hub/src/catalog/definitions.ts +19 -0
  232. package/packages/hub/src/catalog/fixtures.ts +82 -0
  233. package/packages/hub/src/catalog/fn-names.ts +128 -0
  234. package/packages/hub/src/catalog/index.ts +126 -0
  235. package/packages/hub/src/catalog/injections.ts +90 -0
  236. package/packages/hub/src/catalog/scope.ts +86 -0
  237. package/packages/hub/src/catalog/serial.ts +10 -0
  238. package/packages/hub/src/catalog/signature.ts +69 -0
  239. package/packages/hub/src/catalog/versions.ts +110 -0
  240. package/packages/hub/src/chat/announce.ts +145 -0
  241. package/packages/hub/src/chat/cache.ts +50 -0
  242. package/packages/hub/src/chat/chat.ts +72 -0
  243. package/packages/hub/src/chat/cite-rule.ts +64 -0
  244. package/packages/hub/src/chat/cites.ts +236 -0
  245. package/packages/hub/src/chat/compare.ts +290 -0
  246. package/packages/hub/src/chat/deliveries.ts +187 -0
  247. package/packages/hub/src/chat/deps.ts +69 -0
  248. package/packages/hub/src/chat/enrich.ts +601 -0
  249. package/packages/hub/src/chat/env.ts +33 -0
  250. package/packages/hub/src/chat/errors.ts +38 -0
  251. package/packages/hub/src/chat/files.ts +72 -0
  252. package/packages/hub/src/chat/index.ts +259 -0
  253. package/packages/hub/src/chat/mention-requests.ts +49 -0
  254. package/packages/hub/src/chat/mention-search.ts +64 -0
  255. package/packages/hub/src/chat/mentions.ts +274 -0
  256. package/packages/hub/src/chat/notifications.ts +278 -0
  257. package/packages/hub/src/chat/people.ts +59 -0
  258. package/packages/hub/src/chat/presence.ts +48 -0
  259. package/packages/hub/src/chat/reply.ts +23 -0
  260. package/packages/hub/src/chat/sessions.ts +306 -0
  261. package/packages/hub/src/chat/shown.ts +158 -0
  262. package/packages/hub/src/chat/state.ts +270 -0
  263. package/packages/hub/src/chat/streams.ts +92 -0
  264. package/packages/hub/src/chat/suggestions.ts +383 -0
  265. package/packages/hub/src/chat/support.ts +144 -0
  266. package/packages/hub/src/chat/testing.ts +488 -0
  267. package/packages/hub/src/chat/turns.ts +586 -0
  268. package/packages/hub/src/chat/undo.ts +177 -0
  269. package/packages/hub/src/connections/create.ts +25 -0
  270. package/packages/hub/src/connections/env.ts +14 -0
  271. package/packages/hub/src/connections/index.ts +86 -0
  272. package/packages/hub/src/connections/service.ts +536 -0
  273. package/packages/hub/src/contextor/brought.ts +64 -0
  274. package/packages/hub/src/contextor/budget.ts +74 -0
  275. package/packages/hub/src/contextor/calibration.ts +35 -0
  276. package/packages/hub/src/contextor/choose.ts +116 -0
  277. package/packages/hub/src/contextor/contextors.ts +550 -0
  278. package/packages/hub/src/contextor/crawl.ts +252 -0
  279. package/packages/hub/src/contextor/create.ts +113 -0
  280. package/packages/hub/src/contextor/dynamic.ts +102 -0
  281. package/packages/hub/src/contextor/env.ts +83 -0
  282. package/packages/hub/src/contextor/examples.ts +204 -0
  283. package/packages/hub/src/contextor/fns.ts +147 -0
  284. package/packages/hub/src/contextor/graph.ts +137 -0
  285. package/packages/hub/src/contextor/history.ts +211 -0
  286. package/packages/hub/src/contextor/index.ts +524 -0
  287. package/packages/hub/src/contextor/injected.ts +401 -0
  288. package/packages/hub/src/contextor/limits.ts +168 -0
  289. package/packages/hub/src/contextor/links.ts +67 -0
  290. package/packages/hub/src/contextor/modes.ts +520 -0
  291. package/packages/hub/src/contextor/planner.ts +626 -0
  292. package/packages/hub/src/contextor/render.ts +531 -0
  293. package/packages/hub/src/contextor/score.ts +93 -0
  294. package/packages/hub/src/contextor/testing.ts +161 -0
  295. package/packages/hub/src/contextor/tokens.ts +102 -0
  296. package/packages/hub/src/contextor/views.ts +171 -0
  297. package/packages/hub/src/contextor/xml.ts +140 -0
  298. package/packages/hub/src/data/create.ts +45 -0
  299. package/packages/hub/src/data/env.ts +16 -0
  300. package/packages/hub/src/data/fields.ts +71 -0
  301. package/packages/hub/src/data/fns.ts +50 -0
  302. package/packages/hub/src/data/index.ts +50 -0
  303. package/packages/hub/src/data/service.ts +348 -0
  304. package/packages/hub/src/execution/agent.ts +1381 -0
  305. package/packages/hub/src/execution/ai.ts +408 -0
  306. package/packages/hub/src/execution/channel.ts +38 -0
  307. package/packages/hub/src/execution/claims.ts +103 -0
  308. package/packages/hub/src/execution/create.ts +261 -0
  309. package/packages/hub/src/execution/deadlines.ts +74 -0
  310. package/packages/hub/src/execution/deciders.ts +60 -0
  311. package/packages/hub/src/execution/env.ts +28 -0
  312. package/packages/hub/src/execution/errors.ts +103 -0
  313. package/packages/hub/src/execution/executors.ts +246 -0
  314. package/packages/hub/src/execution/gateway.ts +209 -0
  315. package/packages/hub/src/execution/handlers.ts +154 -0
  316. package/packages/hub/src/execution/hub-fns.ts +50 -0
  317. package/packages/hub/src/execution/index.ts +244 -0
  318. package/packages/hub/src/execution/interactions.ts +65 -0
  319. package/packages/hub/src/execution/ledger.ts +168 -0
  320. package/packages/hub/src/execution/limits.ts +175 -0
  321. package/packages/hub/src/execution/link-handlers.ts +142 -0
  322. package/packages/hub/src/execution/media.ts +240 -0
  323. package/packages/hub/src/execution/models.ts +42 -0
  324. package/packages/hub/src/execution/policies.ts +371 -0
  325. package/packages/hub/src/execution/ports.ts +159 -0
  326. package/packages/hub/src/execution/providers.ts +106 -0
  327. package/packages/hub/src/execution/queues.ts +161 -0
  328. package/packages/hub/src/execution/runs.ts +1237 -0
  329. package/packages/hub/src/execution/scope.ts +152 -0
  330. package/packages/hub/src/execution/spend.ts +75 -0
  331. package/packages/hub/src/execution/stream-guard.ts +138 -0
  332. package/packages/hub/src/execution/testing.ts +490 -0
  333. package/packages/hub/src/execution/time.ts +36 -0
  334. package/packages/hub/src/execution/tools.ts +84 -0
  335. package/packages/hub/src/execution/wire.ts +99 -0
  336. package/packages/hub/src/execution/wording.ts +38 -0
  337. package/packages/hub/src/fns/auto.ts +109 -0
  338. package/packages/hub/src/fns/client-logs.ts +83 -0
  339. package/packages/hub/src/fns/costs.ts +139 -0
  340. package/packages/hub/src/fns/create.ts +140 -0
  341. package/packages/hub/src/fns/decided.ts +313 -0
  342. package/packages/hub/src/fns/env.ts +23 -0
  343. package/packages/hub/src/fns/examples.ts +184 -0
  344. package/packages/hub/src/fns/facts.ts +251 -0
  345. package/packages/hub/src/fns/gate.ts +40 -0
  346. package/packages/hub/src/fns/index.ts +149 -0
  347. package/packages/hub/src/fns/search.ts +351 -0
  348. package/packages/hub/src/graph/graph.ts +667 -0
  349. package/packages/hub/src/graph/source.ts +42 -0
  350. package/packages/hub/src/index/batch.ts +96 -0
  351. package/packages/hub/src/index/context-sections.ts +51 -0
  352. package/packages/hub/src/index/embedders.ts +242 -0
  353. package/packages/hub/src/index/env.ts +25 -0
  354. package/packages/hub/src/index/image-setting.ts +55 -0
  355. package/packages/hub/src/index/images.ts +43 -0
  356. package/packages/hub/src/index/index.ts +168 -0
  357. package/packages/hub/src/index/indexer.ts +663 -0
  358. package/packages/hub/src/index/search.ts +168 -0
  359. package/packages/hub/src/index/sectioners.ts +209 -0
  360. package/packages/hub/src/index/sectioning.ts +57 -0
  361. package/packages/hub/src/index/suggester.ts +65 -0
  362. package/packages/hub/src/index/testing.ts +113 -0
  363. package/packages/hub/src/index.ts +19 -0
  364. package/packages/hub/src/link/auto-pair.ts +225 -0
  365. package/packages/hub/src/link/build.ts +216 -0
  366. package/packages/hub/src/link/config-secrets.ts +171 -0
  367. package/packages/hub/src/link/config.ts +140 -0
  368. package/packages/hub/src/link/connections.ts +139 -0
  369. package/packages/hub/src/link/describer.ts +29 -0
  370. package/packages/hub/src/link/env.ts +42 -0
  371. package/packages/hub/src/link/events.ts +123 -0
  372. package/packages/hub/src/link/gate.ts +117 -0
  373. package/packages/hub/src/link/grants.ts +346 -0
  374. package/packages/hub/src/link/handlers.ts +301 -0
  375. package/packages/hub/src/link/index.ts +232 -0
  376. package/packages/hub/src/link/install.ts +92 -0
  377. package/packages/hub/src/link/keys.ts +32 -0
  378. package/packages/hub/src/link/lifecycle.ts +520 -0
  379. package/packages/hub/src/link/migrate-api.ts +210 -0
  380. package/packages/hub/src/link/migrate.ts +44 -0
  381. package/packages/hub/src/link/output.ts +63 -0
  382. package/packages/hub/src/link/owner-runs.ts +313 -0
  383. package/packages/hub/src/link/package/data.ts +53 -0
  384. package/packages/hub/src/link/package/format.ts +126 -0
  385. package/packages/hub/src/link/package/index.ts +9 -0
  386. package/packages/hub/src/link/package/zip.ts +137 -0
  387. package/packages/hub/src/link/packages.ts +180 -0
  388. package/packages/hub/src/link/pairing.ts +503 -0
  389. package/packages/hub/src/link/process.ts +98 -0
  390. package/packages/hub/src/link/reads.ts +91 -0
  391. package/packages/hub/src/link/resources.ts +166 -0
  392. package/packages/hub/src/link/review-summary.ts +279 -0
  393. package/packages/hub/src/link/rig.ts +335 -0
  394. package/packages/hub/src/link/router.ts +118 -0
  395. package/packages/hub/src/link/services.ts +294 -0
  396. package/packages/hub/src/link/status.ts +126 -0
  397. package/packages/hub/src/link/supervisor.ts +547 -0
  398. package/packages/hub/src/link/systems.ts +101 -0
  399. package/packages/hub/src/link/tokens.ts +30 -0
  400. package/packages/hub/src/main.ts +19 -0
  401. package/packages/hub/src/mcp/calls.ts +153 -0
  402. package/packages/hub/src/mcp/create.ts +51 -0
  403. package/packages/hub/src/mcp/endpoints.ts +206 -0
  404. package/packages/hub/src/mcp/env.ts +19 -0
  405. package/packages/hub/src/mcp/fns.ts +23 -0
  406. package/packages/hub/src/mcp/index.ts +76 -0
  407. package/packages/hub/src/mcp/registry.ts +150 -0
  408. package/packages/hub/src/mcp/scopes.ts +218 -0
  409. package/packages/hub/src/mcp/sources.ts +154 -0
  410. package/packages/hub/src/mcp/tokens.ts +72 -0
  411. package/packages/hub/src/mcp/tools.ts +173 -0
  412. package/packages/hub/src/metrics/calls.ts +123 -0
  413. package/packages/hub/src/metrics/create.ts +15 -0
  414. package/packages/hub/src/metrics/fn-metrics.ts +97 -0
  415. package/packages/hub/src/metrics/index.ts +58 -0
  416. package/packages/hub/src/metrics/rollup.ts +188 -0
  417. package/packages/hub/src/models/create.ts +65 -0
  418. package/packages/hub/src/models/decide.ts +134 -0
  419. package/packages/hub/src/models/gateway.ts +102 -0
  420. package/packages/hub/src/models/index.ts +82 -0
  421. package/packages/hub/src/models/pinned.ts +10 -0
  422. package/packages/hub/src/models/remote.ts +386 -0
  423. package/packages/hub/src/models/roles.ts +160 -0
  424. package/packages/hub/src/models/structured.ts +30 -0
  425. package/packages/hub/src/query/columns.ts +55 -0
  426. package/packages/hub/src/query/contexts.ts +102 -0
  427. package/packages/hub/src/query/env.ts +17 -0
  428. package/packages/hub/src/query/evaluate.ts +181 -0
  429. package/packages/hub/src/query/index.ts +32 -0
  430. package/packages/hub/src/query/service.ts +64 -0
  431. package/packages/hub/src/query/sources.ts +344 -0
  432. package/packages/hub/src/query/sql-source.ts +93 -0
  433. package/packages/hub/src/resources/browse.ts +131 -0
  434. package/packages/hub/src/resources/content.ts +183 -0
  435. package/packages/hub/src/resources/context.ts +405 -0
  436. package/packages/hub/src/resources/converters.ts +78 -0
  437. package/packages/hub/src/resources/create.ts +88 -0
  438. package/packages/hub/src/resources/env.ts +24 -0
  439. package/packages/hub/src/resources/fetch.ts +140 -0
  440. package/packages/hub/src/resources/fns.ts +172 -0
  441. package/packages/hub/src/resources/forms.ts +285 -0
  442. package/packages/hub/src/resources/images.ts +182 -0
  443. package/packages/hub/src/resources/index.ts +186 -0
  444. package/packages/hub/src/resources/library.ts +228 -0
  445. package/packages/hub/src/resources/models.ts +116 -0
  446. package/packages/hub/src/resources/pdf-pages.ts +455 -0
  447. package/packages/hub/src/resources/raw.ts +108 -0
  448. package/packages/hub/src/resources/reader.ts +224 -0
  449. package/packages/hub/src/resources/rules.ts +110 -0
  450. package/packages/hub/src/resources/sqlite-files.ts +140 -0
  451. package/packages/hub/src/resources/storage.ts +40 -0
  452. package/packages/hub/src/resources/testing.ts +292 -0
  453. package/packages/hub/src/store/always-for.ts +46 -0
  454. package/packages/hub/src/store/auxTables.ts +97 -0
  455. package/packages/hub/src/store/codec.ts +109 -0
  456. package/packages/hub/src/store/db.ts +137 -0
  457. package/packages/hub/src/store/env.ts +13 -0
  458. package/packages/hub/src/store/errors.ts +36 -0
  459. package/packages/hub/src/store/fixtures.ts +53 -0
  460. package/packages/hub/src/store/fn-renames.ts +72 -0
  461. package/packages/hub/src/store/hybrid.ts +130 -0
  462. package/packages/hub/src/store/index.ts +231 -0
  463. package/packages/hub/src/store/lists.ts +172 -0
  464. package/packages/hub/src/store/migrate-fn-names.ts +135 -0
  465. package/packages/hub/src/store/migrate.ts +121 -0
  466. package/packages/hub/src/store/ports.ts +163 -0
  467. package/packages/hub/src/store/query.ts +166 -0
  468. package/packages/hub/src/store/records.ts +119 -0
  469. package/packages/hub/src/store/rows.ts +105 -0
  470. package/packages/hub/src/store/schema.ts +184 -0
  471. package/packages/hub/src/store/sqlite.ts +136 -0
  472. package/packages/hub/src/store/table.ts +113 -0
  473. package/packages/hub/src/store/text.ts +92 -0
  474. package/packages/hub/src/store/vectors.ts +232 -0
  475. package/packages/hub/src/tables/env.ts +15 -0
  476. package/packages/hub/src/tables/fns.ts +29 -0
  477. package/packages/hub/src/tables/index.ts +45 -0
  478. package/packages/hub/src/tables/migrate.ts +105 -0
  479. package/packages/hub/src/tables/service.ts +245 -0
  480. package/packages/hub/src/testing.ts +128 -0
  481. package/packages/hub/tsconfig.json +6 -0
  482. package/packages/sdk/AUTHORING.md +25228 -0
  483. package/packages/sdk/package.json +58 -0
  484. package/packages/sdk/src/a-gin.ts +132 -0
  485. package/packages/sdk/src/agent.ts +121 -0
  486. package/packages/sdk/src/authoring.ts +546 -0
  487. package/packages/sdk/src/build.ts +97 -0
  488. package/packages/sdk/src/chat-prompt.ts +202 -0
  489. package/packages/sdk/src/claims.ts +20 -0
  490. package/packages/sdk/src/client-runtime.ts +514 -0
  491. package/packages/sdk/src/client.ts +672 -0
  492. package/packages/sdk/src/ctx.ts +659 -0
  493. package/packages/sdk/src/declare.ts +480 -0
  494. package/packages/sdk/src/fn.ts +514 -0
  495. package/packages/sdk/src/gin.ts +245 -0
  496. package/packages/sdk/src/hub.ts +1065 -0
  497. package/packages/sdk/src/impl.ts +35 -0
  498. package/packages/sdk/src/index.ts +87 -0
  499. package/packages/sdk/src/links.ts +35 -0
  500. package/packages/sdk/src/manifest.ts +372 -0
  501. package/packages/sdk/src/page-parts.ts +153 -0
  502. package/packages/sdk/src/program/env.ts +29 -0
  503. package/packages/sdk/src/program/index.ts +13 -0
  504. package/packages/sdk/src/program/lookups.ts +82 -0
  505. package/packages/sdk/src/program/runtime.ts +576 -0
  506. package/packages/sdk/src/program/tools.ts +268 -0
  507. package/packages/sdk/src/providers.ts +77 -0
  508. package/packages/sdk/src/refs.ts +161 -0
  509. package/packages/sdk/src/relative-dates.ts +197 -0
  510. package/packages/sdk/src/remote-auth.ts +113 -0
  511. package/packages/sdk/src/resources.ts +28 -0
  512. package/packages/sdk/src/results.ts +47 -0
  513. package/packages/sdk/src/server/address.ts +167 -0
  514. package/packages/sdk/src/server/asks.ts +111 -0
  515. package/packages/sdk/src/server/assets.ts +47 -0
  516. package/packages/sdk/src/server/authored-names.ts +79 -0
  517. package/packages/sdk/src/server/calls.ts +260 -0
  518. package/packages/sdk/src/server/content.ts +124 -0
  519. package/packages/sdk/src/server/context-check.ts +214 -0
  520. package/packages/sdk/src/server/context-files.ts +244 -0
  521. package/packages/sdk/src/server/data.ts +90 -0
  522. package/packages/sdk/src/server/env.ts +144 -0
  523. package/packages/sdk/src/server/fake-hub-fns.ts +124 -0
  524. package/packages/sdk/src/server/fake-hub-widgets.ts +67 -0
  525. package/packages/sdk/src/server/fake-models.ts +89 -0
  526. package/packages/sdk/src/server/fake-records.ts +217 -0
  527. package/packages/sdk/src/server/files.ts +118 -0
  528. package/packages/sdk/src/server/host.ts +742 -0
  529. package/packages/sdk/src/server/hosted-network-guard.ts +18 -0
  530. package/packages/sdk/src/server/index.ts +220 -0
  531. package/packages/sdk/src/server/journal.ts +131 -0
  532. package/packages/sdk/src/server/js-yaml.d.ts +19 -0
  533. package/packages/sdk/src/server/keys.ts +148 -0
  534. package/packages/sdk/src/server/link.ts +93 -0
  535. package/packages/sdk/src/server/live.ts +22 -0
  536. package/packages/sdk/src/server/llm-wire.ts +647 -0
  537. package/packages/sdk/src/server/llm.ts +555 -0
  538. package/packages/sdk/src/server/log.ts +108 -0
  539. package/packages/sdk/src/server/manifest-state.ts +113 -0
  540. package/packages/sdk/src/server/mcp-caller.ts +15 -0
  541. package/packages/sdk/src/server/mcp-prompts.ts +54 -0
  542. package/packages/sdk/src/server/mcp-resources.ts +130 -0
  543. package/packages/sdk/src/server/mcp.ts +194 -0
  544. package/packages/sdk/src/server/owner-runs.ts +109 -0
  545. package/packages/sdk/src/server/package.ts +141 -0
  546. package/packages/sdk/src/server/pairing.ts +97 -0
  547. package/packages/sdk/src/server/process.ts +53 -0
  548. package/packages/sdk/src/server/providers.ts +180 -0
  549. package/packages/sdk/src/server/proxy.ts +196 -0
  550. package/packages/sdk/src/server/renderers.ts +28 -0
  551. package/packages/sdk/src/server/resources.ts +89 -0
  552. package/packages/sdk/src/server/results.ts +121 -0
  553. package/packages/sdk/src/server/run.ts +492 -0
  554. package/packages/sdk/src/server/runs.ts +103 -0
  555. package/packages/sdk/src/server/runtime.ts +597 -0
  556. package/packages/sdk/src/server/socket-guard.ts +162 -0
  557. package/packages/sdk/src/server/state.ts +112 -0
  558. package/packages/sdk/src/server/supervise.ts +257 -0
  559. package/packages/sdk/src/server/table.ts +490 -0
  560. package/packages/sdk/src/server/testing.ts +883 -0
  561. package/packages/sdk/src/server/types.ts +26 -0
  562. package/packages/sdk/src/server/wire.ts +172 -0
  563. package/packages/sdk/src/status.ts +50 -0
  564. package/packages/sdk/src/system.ts +459 -0
  565. package/packages/sdk/src/testing/context.ts +48 -0
  566. package/packages/sdk/src/testing/env.ts +28 -0
  567. package/packages/sdk/src/testing/fixtures/NoteCard.vue +17 -0
  568. package/packages/sdk/src/testing/fixtures/context/guide.md +12 -0
  569. package/packages/sdk/src/testing/hub.ts +294 -0
  570. package/packages/sdk/src/testing/index.ts +30 -0
  571. package/packages/sdk/src/testing/models.ts +192 -0
  572. package/packages/sdk/src/testing/openrouter.ts +94 -0
  573. package/packages/sdk/src/testing/preview.ts +207 -0
  574. package/packages/sdk/src/testing/scratch.ts +58 -0
  575. package/packages/sdk/src/testing/shots.ts +17 -0
  576. package/packages/sdk/src/util.ts +35 -0
  577. package/packages/sdk/src/widget-check.ts +182 -0
  578. package/packages/sdk/src/widget-schema.ts +251 -0
  579. package/packages/sdk/src/widgets.ts +386 -0
  580. package/packages/sdk/src/zod-gin.ts +213 -0
  581. package/packages/sdk/tsconfig.json +6 -0
  582. package/packages/web/dist/assets/ActorSettingsView-BuMYRDqv.js +2 -0
  583. package/packages/web/dist/assets/ActorSettingsView-GTxPZw8N.css +1 -0
  584. package/packages/web/dist/assets/AdminLayout-1hbRPV3d.css +1 -0
  585. package/packages/web/dist/assets/AdminLayout-sLjVTrmV.js +2 -0
  586. package/packages/web/dist/assets/ApiServiceForm-BrMTU-7u.js +2 -0
  587. package/packages/web/dist/assets/ApiServiceForm-BxprSaAq.css +1 -0
  588. package/packages/web/dist/assets/ApiServiceView-BMF2zD6Q.js +2 -0
  589. package/packages/web/dist/assets/ApiServiceView-BVmdRCjR.css +1 -0
  590. package/packages/web/dist/assets/ApiServicesView-BTLV6c8n.css +1 -0
  591. package/packages/web/dist/assets/ApiServicesView-bjLAWO_j.js +2 -0
  592. package/packages/web/dist/assets/AppPage-BBzZ0Pru.css +1 -0
  593. package/packages/web/dist/assets/AppPage-DSzDKCFz.js +2 -0
  594. package/packages/web/dist/assets/AutoPairPicker-ClF4nB0n.css +1 -0
  595. package/packages/web/dist/assets/AutoPairPicker-nV38ALjl.js +2 -0
  596. package/packages/web/dist/assets/BrowserFrame-Bic7U7jN.js +2 -0
  597. package/packages/web/dist/assets/BrowserFrame-BzEdhmsF.css +1 -0
  598. package/packages/web/dist/assets/ChartVisual-BnFG9aFi.css +1 -0
  599. package/packages/web/dist/assets/ChartVisual-DWw7WsfN.js +11 -0
  600. package/packages/web/dist/assets/ChatPage-7Yebk7rl.js +4 -0
  601. package/packages/web/dist/assets/ChatPage-CbsRmktV.css +1 -0
  602. package/packages/web/dist/assets/CodeViewer-D6A30AJ9.css +1 -0
  603. package/packages/web/dist/assets/CodeViewer-xHS3Xah9.js +5 -0
  604. package/packages/web/dist/assets/ConfigWithCustom-C74DTXuy.css +1 -0
  605. package/packages/web/dist/assets/ConfigWithCustom-DreTUdf0.js +3 -0
  606. package/packages/web/dist/assets/ConfirmDialog-DjQUzNqk.js +2 -0
  607. package/packages/web/dist/assets/ConfirmDialog-oABDbIMz.css +1 -0
  608. package/packages/web/dist/assets/ConnectPage-CfRDrXvJ.js +2 -0
  609. package/packages/web/dist/assets/ConnectPage-Zz1nFbcn.css +1 -0
  610. package/packages/web/dist/assets/ContextItemPage-B6rJG3OT.js +2 -0
  611. package/packages/web/dist/assets/ContextItemPage-BRsWxOmu.css +1 -0
  612. package/packages/web/dist/assets/ContextPage-CloIZ_2y.js +2 -0
  613. package/packages/web/dist/assets/ContextPage-rYKxjiVI.css +1 -0
  614. package/packages/web/dist/assets/ContextRow-Byz_7HG-.css +1 -0
  615. package/packages/web/dist/assets/ContextRow-Dvv8CTFk.js +2 -0
  616. package/packages/web/dist/assets/DataPage-CLgJtQwS.css +1 -0
  617. package/packages/web/dist/assets/DataPage-wSIoGcb5.js +2 -0
  618. package/packages/web/dist/assets/DataTypePage-Ba_zBV4b.js +4 -0
  619. package/packages/web/dist/assets/DataTypePage-Cr238Hx_.css +1 -0
  620. package/packages/web/dist/assets/DesignPage-BFC4A-wO.css +1 -0
  621. package/packages/web/dist/assets/DesignPage-DidMUX8m.js +49 -0
  622. package/packages/web/dist/assets/ExplorePage-DJmOOIhs.css +1 -0
  623. package/packages/web/dist/assets/ExplorePage-MUyVydVB.js +2 -0
  624. package/packages/web/dist/assets/FactList-CeAbKajD.js +2 -0
  625. package/packages/web/dist/assets/FactList-DuDPr7n7.css +1 -0
  626. package/packages/web/dist/assets/FnList-BCnb4kOB.css +1 -0
  627. package/packages/web/dist/assets/FnList-CjQRwYaT.js +2 -0
  628. package/packages/web/dist/assets/FnPill-BNIWrqXN.css +1 -0
  629. package/packages/web/dist/assets/FnPill-BshAvm2I.js +2 -0
  630. package/packages/web/dist/assets/FnView-B8MGAOoB.js +2 -0
  631. package/packages/web/dist/assets/FnView-BBFbPAQz.css +1 -0
  632. package/packages/web/dist/assets/FnsView-CeqIoaBT.js +2 -0
  633. package/packages/web/dist/assets/FnsView-D575syq-.css +1 -0
  634. package/packages/web/dist/assets/GinExprView-DYVUwZrd.js +4 -0
  635. package/packages/web/dist/assets/GinExprView-dqtf5BKF.css +1 -0
  636. package/packages/web/dist/assets/GinForm-CVEsGoBo.css +1 -0
  637. package/packages/web/dist/assets/GinForm-D3mwMRTQ.js +2 -0
  638. package/packages/web/dist/assets/GinTypeView-B5CGqWvh.css +1 -0
  639. package/packages/web/dist/assets/GinTypeView-C0YifSmE.js +2 -0
  640. package/packages/web/dist/assets/GinValueView-HfEPq9le.js +4 -0
  641. package/packages/web/dist/assets/GinValueView-zhWn-X48.css +1 -0
  642. package/packages/web/dist/assets/GraphPage-ySnuA4Hp.js +2 -0
  643. package/packages/web/dist/assets/GraphPanel-B9jxpJfb.css +1 -0
  644. package/packages/web/dist/assets/GraphPanel-Cy5-KGo1.js +2 -0
  645. package/packages/web/dist/assets/HubPicker-C_vA752L.js +2 -0
  646. package/packages/web/dist/assets/InboxApprovals-DcPCCmZ5.js +2 -0
  647. package/packages/web/dist/assets/InboxApprovals-DmC94LNf.css +1 -0
  648. package/packages/web/dist/assets/InboxPage-C2DT2nuF.js +2 -0
  649. package/packages/web/dist/assets/InjectedList-BgxdlaHJ.css +1 -0
  650. package/packages/web/dist/assets/InjectedList-CJsEFEbz.js +2 -0
  651. package/packages/web/dist/assets/InstallDialog-C9GDoUI2.js +2 -0
  652. package/packages/web/dist/assets/InstallDialog-yWLZK_zN.css +1 -0
  653. package/packages/web/dist/assets/InstanceTypes-D8Jcxn70.js +2 -0
  654. package/packages/web/dist/assets/InstanceTypes-DAowwLB7.css +1 -0
  655. package/packages/web/dist/assets/InstanceView-CuBD3JPU.css +1 -0
  656. package/packages/web/dist/assets/InstanceView-p7tMaylE.js +2 -0
  657. package/packages/web/dist/assets/ItemHistory-CUGa8b6s.js +2 -0
  658. package/packages/web/dist/assets/ItemHistory-Czzpyiud.css +1 -0
  659. package/packages/web/dist/assets/LimitsView-DlPW-cLw.css +1 -0
  660. package/packages/web/dist/assets/LimitsView-DsZG6u5P.js +2 -0
  661. package/packages/web/dist/assets/ListSearch-BK4p7Nxa.js +2 -0
  662. package/packages/web/dist/assets/ListSearch-CdxSo6UW.css +1 -0
  663. package/packages/web/dist/assets/LlmCallDetails-2yQftCqd.js +2 -0
  664. package/packages/web/dist/assets/LlmCallDetails-gymdroc_.css +1 -0
  665. package/packages/web/dist/assets/LlmCallsView-B1yHEIBG.css +1 -0
  666. package/packages/web/dist/assets/LlmCallsView-DOHX3r0K.js +2 -0
  667. package/packages/web/dist/assets/LoadState-C4VYnFly.css +1 -0
  668. package/packages/web/dist/assets/LoadState-DeXfLvYv.js +2 -0
  669. package/packages/web/dist/assets/McpDialog-BSCt_jWB.css +1 -0
  670. package/packages/web/dist/assets/McpDialog-CA_0WKWF.js +2 -0
  671. package/packages/web/dist/assets/McpServerForm-CAG8Wp2N.js +2 -0
  672. package/packages/web/dist/assets/McpServerForm-DsHaf5Um.css +1 -0
  673. package/packages/web/dist/assets/McpServerView-7I76EznB.css +1 -0
  674. package/packages/web/dist/assets/McpServerView-CD8qw6W_.js +2 -0
  675. package/packages/web/dist/assets/McpServersView-DNycG35u.js +2 -0
  676. package/packages/web/dist/assets/McpView-CC2oNOMa.js +2 -0
  677. package/packages/web/dist/assets/McpView-W5PhGI4_.css +1 -0
  678. package/packages/web/dist/assets/McpsView-CwJvyyxV.js +2 -0
  679. package/packages/web/dist/assets/McpsView-yH-K4ifd.css +1 -0
  680. package/packages/web/dist/assets/MemoryDialog-CpfIsygL.css +1 -0
  681. package/packages/web/dist/assets/MemoryDialog-Dbvh5uLq.js +2 -0
  682. package/packages/web/dist/assets/ModelCallsView-B__CIDge.css +1 -0
  683. package/packages/web/dist/assets/ModelCallsView-RvnW3EBP.js +2 -0
  684. package/packages/web/dist/assets/ModelPicker-5BC8W10p.css +1 -0
  685. package/packages/web/dist/assets/ModelPicker-DcjwQFHC.js +2 -0
  686. package/packages/web/dist/assets/ModelsView-C_iN19xt.js +2 -0
  687. package/packages/web/dist/assets/ModelsView-DjD8H9vc.css +1 -0
  688. package/packages/web/dist/assets/NotFoundPage-CeSwzTV-.js +2 -0
  689. package/packages/web/dist/assets/NotFoundPage-ZUNomG9O.css +1 -0
  690. package/packages/web/dist/assets/PairPage-Bs2KuRjC.css +1 -0
  691. package/packages/web/dist/assets/PairPage-TEXPpsqi.js +2 -0
  692. package/packages/web/dist/assets/PanelHost-BkrFAnPa.js +2 -0
  693. package/packages/web/dist/assets/PanelHost-_z5RyAnS.css +1 -0
  694. package/packages/web/dist/assets/PeopleView-CJ8yArTh.css +1 -0
  695. package/packages/web/dist/assets/PeopleView-D1QGPYp7.js +2 -0
  696. package/packages/web/dist/assets/PoliciesView-BU1fudNF.js +2 -0
  697. package/packages/web/dist/assets/PoliciesView-yVE8d8mj.css +1 -0
  698. package/packages/web/dist/assets/RefusalList-B3OBAsYc.css +1 -0
  699. package/packages/web/dist/assets/RefusalList-DQoyUoPG.js +2 -0
  700. package/packages/web/dist/assets/RemoteAuthFields-Dm44vz2t.css +1 -0
  701. package/packages/web/dist/assets/RemoteAuthFields-nxGWfmhf.js +2 -0
  702. package/packages/web/dist/assets/ResourceViewer-A9ZSaLUH.css +1 -0
  703. package/packages/web/dist/assets/ResourceViewer-Po24y4pj.js +2 -0
  704. package/packages/web/dist/assets/ResourcesPage-YluNBqIv.js +2 -0
  705. package/packages/web/dist/assets/ResourcesPage-mr0U0l6U.css +1 -0
  706. package/packages/web/dist/assets/ResultGrid-CuUQyTjW.css +1 -0
  707. package/packages/web/dist/assets/ResultGrid-uoq4yUYj.js +2 -0
  708. package/packages/web/dist/assets/ReviewSummaryStrip-B3ZQs5wR.css +1 -0
  709. package/packages/web/dist/assets/ReviewSummaryStrip-k3HevESg.js +2 -0
  710. package/packages/web/dist/assets/ReviewView-79Z5rU1v.js +3 -0
  711. package/packages/web/dist/assets/ReviewView-CxbVjz_R.css +1 -0
  712. package/packages/web/dist/assets/RuleRow-CG_XCvUu.css +1 -0
  713. package/packages/web/dist/assets/RuleRow-CoXDA-SH.js +2 -0
  714. package/packages/web/dist/assets/RunCard-CBSGdwdQ.js +2 -0
  715. package/packages/web/dist/assets/RunCard-CfyRaDLS.css +1 -0
  716. package/packages/web/dist/assets/RunDetails-CGhQQ6OI.js +2 -0
  717. package/packages/web/dist/assets/RunDetails-CHHCWGrP.css +1 -0
  718. package/packages/web/dist/assets/RunDot-Ch_45985.js +2 -0
  719. package/packages/web/dist/assets/RunDot-CkNUsFwg.css +1 -0
  720. package/packages/web/dist/assets/RunPage-C_t20pB7.js +2 -0
  721. package/packages/web/dist/assets/RunPage-Cq6UV6h-.css +1 -0
  722. package/packages/web/dist/assets/RunProgress-Bq2yc7Il.css +1 -0
  723. package/packages/web/dist/assets/RunProgress-VrZUHUEC.js +2 -0
  724. package/packages/web/dist/assets/RunsView-Dz9Xsvu5.js +2 -0
  725. package/packages/web/dist/assets/RunsView-fBMrETRF.css +1 -0
  726. package/packages/web/dist/assets/ServiceRows-6BU4-MeL.css +1 -0
  727. package/packages/web/dist/assets/ServiceRows-DNzDiutg.js +2 -0
  728. package/packages/web/dist/assets/SettingsPage-CykfuYj1.js +3 -0
  729. package/packages/web/dist/assets/SettingsPage-t03BqXw8.css +1 -0
  730. package/packages/web/dist/assets/SignInPage-Djx-M-0U.css +1 -0
  731. package/packages/web/dist/assets/SignInPage-DrXZ1sG2.js +2 -0
  732. package/packages/web/dist/assets/StatusBadge-Dpb9uG5e.js +2 -0
  733. package/packages/web/dist/assets/SystemConfig-72qKRkUk.js +2 -0
  734. package/packages/web/dist/assets/SystemConfig-CDtMyVWy.css +1 -0
  735. package/packages/web/dist/assets/SystemPageHost-BeZ-6N0-.css +1 -0
  736. package/packages/web/dist/assets/SystemPageHost-DLNg2FYK.js +2 -0
  737. package/packages/web/dist/assets/SystemView-C8ScHUe2.css +1 -0
  738. package/packages/web/dist/assets/SystemView-Es5wtkYU.js +2 -0
  739. package/packages/web/dist/assets/SystemsView-B6HEL9VS.css +1 -0
  740. package/packages/web/dist/assets/SystemsView-CeuSFhlF.js +2 -0
  741. package/packages/web/dist/assets/TableViewer-1Jf5BNat.css +1 -0
  742. package/packages/web/dist/assets/TableViewer-BQ7bYLOP.js +6 -0
  743. package/packages/web/dist/assets/ThemePicker-C2nJ21Vd.js +2 -0
  744. package/packages/web/dist/assets/TurnTree-CORdfTHj.js +2 -0
  745. package/packages/web/dist/assets/TurnTree-CPivE4sF.css +1 -0
  746. package/packages/web/dist/assets/UserMessage-BtECa8ka.css +1 -0
  747. package/packages/web/dist/assets/UserMessage-qyc8dG5D.js +9 -0
  748. package/packages/web/dist/assets/ValueVisual-D5Rw7PlS.css +1 -0
  749. package/packages/web/dist/assets/ValueVisual-aXEUaQ5Y.js +2 -0
  750. package/packages/web/dist/assets/WidgetView-BZyDyYRI.js +3 -0
  751. package/packages/web/dist/assets/WidgetView-DQUDeFkB.css +1 -0
  752. package/packages/web/dist/assets/_plugin-vue_export-helper-BDNMzG2s.js +1 -0
  753. package/packages/web/dist/assets/abap-CLvhMVsD.js +2 -0
  754. package/packages/web/dist/assets/abnfDiagram-S7VZAUFO-CzFPJy4G.js +2 -0
  755. package/packages/web/dist/assets/actionscript-3-Cs6JJXT5.js +2 -0
  756. package/packages/web/dist/assets/ada-X3Y2mlq2.js +2 -0
  757. package/packages/web/dist/assets/ahk-DwADkxyd.js +2 -0
  758. package/packages/web/dist/assets/ahk2-_6rzW9BS.js +2 -0
  759. package/packages/web/dist/assets/angular-html-wiqevbIE.js +2 -0
  760. package/packages/web/dist/assets/angular-ts-C32iChAu.js +2 -0
  761. package/packages/web/dist/assets/apache-U0d_L8uA.js +2 -0
  762. package/packages/web/dist/assets/apex-KFGFyKwG.js +2 -0
  763. package/packages/web/dist/assets/apl-Bl61Unn0.js +2 -0
  764. package/packages/web/dist/assets/applescript-CCn79oCD.js +2 -0
  765. package/packages/web/dist/assets/ara-4CJ0cIlV.js +2 -0
  766. package/packages/web/dist/assets/architecture-WOLXFQ4H-_l4nRfFJ.js +1 -0
  767. package/packages/web/dist/assets/architectureDiagram-YGSQEFNW-CMpVysh5.js +37 -0
  768. package/packages/web/dist/assets/asciidoc-SCjQUq34.js +2 -0
  769. package/packages/web/dist/assets/asm-Cmm7eHzH.js +2 -0
  770. package/packages/web/dist/assets/astro-CojMNcHO.js +2 -0
  771. package/packages/web/dist/assets/awk-BWXHIvNe.js +2 -0
  772. package/packages/web/dist/assets/ballerina-B7ZEbQpA.js +2 -0
  773. package/packages/web/dist/assets/bat-qdxAdBWQ.js +2 -0
  774. package/packages/web/dist/assets/beancount-C2IN4Vk8.js +2 -0
  775. package/packages/web/dist/assets/berry-DKpUyyne.js +2 -0
  776. package/packages/web/dist/assets/bibtex-Ci_nEsc7.js +2 -0
  777. package/packages/web/dist/assets/bicep-CUHmPFLl.js +2 -0
  778. package/packages/web/dist/assets/bird2-CYIUgYqB.js +2 -0
  779. package/packages/web/dist/assets/blade-CRk3fo4p.js +2 -0
  780. package/packages/web/dist/assets/blockDiagram-APKKGZFW-Jua4t10S.js +141 -0
  781. package/packages/web/dist/assets/bpmnIcons-APHXDYXF-C0jbCElo.js +2 -0
  782. package/packages/web/dist/assets/browser-BHOqNy7R.js +9 -0
  783. package/packages/web/dist/assets/browsers-BSc3bW3l.js +2 -0
  784. package/packages/web/dist/assets/bsl-_VjlB9mv.js +2 -0
  785. package/packages/web/dist/assets/c-CiNtTPN_.js +2 -0
  786. package/packages/web/dist/assets/c3-D0apG41V.js +2 -0
  787. package/packages/web/dist/assets/c4Diagram-KJ2TOQU5-08x9w6G9.js +39 -0
  788. package/packages/web/dist/assets/cadence-CQ2zXKGN.js +2 -0
  789. package/packages/web/dist/assets/cairo-DLTphjLi.js +2 -0
  790. package/packages/web/dist/assets/chapel-D5ik6Ccv.js +2 -0
  791. package/packages/web/dist/assets/chunk-2Q5K7J3B-C1jixKkw.js +2 -0
  792. package/packages/web/dist/assets/chunk-5VM5RSS4-ZNzvKenW.js +16 -0
  793. package/packages/web/dist/assets/chunk-6MUBBAK2-BHXbrulB.js +3 -0
  794. package/packages/web/dist/assets/chunk-AXFCVDMN-CI0arS1F.js +63 -0
  795. package/packages/web/dist/assets/chunk-BG4553SI-DGn4S0JL.js +130 -0
  796. package/packages/web/dist/assets/chunk-DQASFODM-ClbbgMVy.js +11 -0
  797. package/packages/web/dist/assets/chunk-DUW6YSOI-Dgx8z5s3.js +2 -0
  798. package/packages/web/dist/assets/chunk-HFQBQIA3-BNltuj9p.js +2 -0
  799. package/packages/web/dist/assets/chunk-J5ZVWO5B-oDCd-gWO.js +2 -0
  800. package/packages/web/dist/assets/chunk-JWPE2WC7-DVXcaiue.js +2 -0
  801. package/packages/web/dist/assets/chunk-KQLB2F66-DsHe5EtY.js +3 -0
  802. package/packages/web/dist/assets/chunk-KS47KZWR-BZg3mYeD.js +2 -0
  803. package/packages/web/dist/assets/chunk-LEVMRMFU-paszafIt.js +2 -0
  804. package/packages/web/dist/assets/chunk-M57EVK23-qYz6TUV4.js +2 -0
  805. package/packages/web/dist/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +137 -0
  806. package/packages/web/dist/assets/chunk-OY52VR5R-Ct_YDCfL.js +89 -0
  807. package/packages/web/dist/assets/chunk-QB3YPZ4I-i7-AWGNa.js +214 -0
  808. package/packages/web/dist/assets/chunk-R3KSYZAL-DW0WB_9q.js +2 -0
  809. package/packages/web/dist/assets/chunk-STOXU5M4-D5Gd-wq9.js +73 -0
  810. package/packages/web/dist/assets/chunk-TU62E6Q5-WtwDME_1.js +2 -0
  811. package/packages/web/dist/assets/chunk-X4PVCEUW-YYhMSieL.js +2 -0
  812. package/packages/web/dist/assets/chunk-XXDRQBXY-i7MKP1NY.js +2 -0
  813. package/packages/web/dist/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +2 -0
  814. package/packages/web/dist/assets/clarity-CtfBBspg.js +2 -0
  815. package/packages/web/dist/assets/classDiagram-v2-L25IHNXF-d25-M1pJ.js +218 -0
  816. package/packages/web/dist/assets/clojure-DqKBuwfJ.js +2 -0
  817. package/packages/web/dist/assets/cmake-Bj61d0ZC.js +2 -0
  818. package/packages/web/dist/assets/cobol-BRB8FTbz.js +2 -0
  819. package/packages/web/dist/assets/codeowners-C8r90Shi.js +2 -0
  820. package/packages/web/dist/assets/codeql-oeQT6MSM.js +2 -0
  821. package/packages/web/dist/assets/coffee-B1WQFatZ.js +2 -0
  822. package/packages/web/dist/assets/common-lisp-Cv5bFMCO.js +2 -0
  823. package/packages/web/dist/assets/coq-CGaSfhwR.js +2 -0
  824. package/packages/web/dist/assets/core-DdF778CY.js +13 -0
  825. package/packages/web/dist/assets/cose-bilkent-JH36ORCC-CYLhHv3W.js +2 -0
  826. package/packages/web/dist/assets/cpp-CxyntmKf.js +2 -0
  827. package/packages/web/dist/assets/crystal-CayBj_Aw.js +2 -0
  828. package/packages/web/dist/assets/csharp-dmMxLVLW.js +2 -0
  829. package/packages/web/dist/assets/css-CB_fh0k2.js +2 -0
  830. package/packages/web/dist/assets/csv-Dx-8-gkx.js +2 -0
  831. package/packages/web/dist/assets/cue-CE9AQfxI.js +2 -0
  832. package/packages/web/dist/assets/cynefin-EF2NZ3EQ-BOE_VX_3.js +1 -0
  833. package/packages/web/dist/assets/cynefinDiagram-L36ESFBY-cDLwrPve.js +63 -0
  834. package/packages/web/dist/assets/cypher-ClKdZ_lG.js +2 -0
  835. package/packages/web/dist/assets/cytoscape.esm-DpfQbjy7.js +322 -0
  836. package/packages/web/dist/assets/d-qD-0Kul2.js +2 -0
  837. package/packages/web/dist/assets/d3-scale-CElPUUud.js +2 -0
  838. package/packages/web/dist/assets/d3-selection-COWvaQNI.js +2 -0
  839. package/packages/web/dist/assets/dagre-SPEB5RXH-ChUYszsQ.js +5 -0
  840. package/packages/web/dist/assets/dart-CHZY9Xhz.js +2 -0
  841. package/packages/web/dist/assets/dax-BkyTk9wS.js +2 -0
  842. package/packages/web/dist/assets/desktop-Dlh5hvp9.js +2 -0
  843. package/packages/web/dist/assets/diagram-3B7GL73J-C4RMi43c.js +201 -0
  844. package/packages/web/dist/assets/diagram-DNEMPZML-COQGGiEP.js +25 -0
  845. package/packages/web/dist/assets/diagram-L3MUGCDN-mowv9Itp.js +42 -0
  846. package/packages/web/dist/assets/diagram-LA4NIPWU-hNJQSGhv.js +25 -0
  847. package/packages/web/dist/assets/diagram-MHCOC4E2-Dp-COOAx.js +4 -0
  848. package/packages/web/dist/assets/diagram-XPFHEONP-D2wzCykS.js +31 -0
  849. package/packages/web/dist/assets/diff-woXpYk--.js +2 -0
  850. package/packages/web/dist/assets/dist-DdXDFcej.js +2 -0
  851. package/packages/web/dist/assets/docker-IyjqRm3v.js +2 -0
  852. package/packages/web/dist/assets/dotenv-CuH5my32.js +2 -0
  853. package/packages/web/dist/assets/dream-maker-DW3nJb8Q.js +2 -0
  854. package/packages/web/dist/assets/ebnfDiagram-UZSYDL2S-5WCudwet.js +2 -0
  855. package/packages/web/dist/assets/edge-6p6a27tD.js +2 -0
  856. package/packages/web/dist/assets/elixir-fXwtrlGU.js +2 -0
  857. package/packages/web/dist/assets/elk-XV6XMXQE-BknTcAbm.js +28 -0
  858. package/packages/web/dist/assets/elm-rUi9A3mh.js +2 -0
  859. package/packages/web/dist/assets/emacs-lisp-DR2vtWaj.js +2 -0
  860. package/packages/web/dist/assets/engine-javascript-C30F4iNc.js +142 -0
  861. package/packages/web/dist/assets/erDiagram-EYBAPDEH-UOE6iZ1t.js +100 -0
  862. package/packages/web/dist/assets/erb-BvmuIdN-.js +2 -0
  863. package/packages/web/dist/assets/erlang-Cphh6RMH.js +2 -0
  864. package/packages/web/dist/assets/eventmodeling-K75KTNOO-CIs2h_8S.js +1 -0
  865. package/packages/web/dist/assets/export-BwFkEtcm.js +15 -0
  866. package/packages/web/dist/assets/fennel-DQxkIbk2.js +2 -0
  867. package/packages/web/dist/assets/fish-BJitypiv.js +2 -0
  868. package/packages/web/dist/assets/flowDiagram-MALGAFMO-CQLEuZ0I.js +1 -0
  869. package/packages/web/dist/assets/fluent-C03EYrpw.js +2 -0
  870. package/packages/web/dist/assets/fn-modal-DqcxUhOQ.js +2 -0
  871. package/packages/web/dist/assets/fn-notices-BYaH6IoA.js +2 -0
  872. package/packages/web/dist/assets/fn-notices-Da4tVHqJ.css +1 -0
  873. package/packages/web/dist/assets/formats-DI__ADVG.js +2 -0
  874. package/packages/web/dist/assets/fortran-fixed-form-DEKoE2YW.js +2 -0
  875. package/packages/web/dist/assets/fortran-free-form-CYNrtFtB.js +2 -0
  876. package/packages/web/dist/assets/fsharp-D13ZGOAj.js +2 -0
  877. package/packages/web/dist/assets/ganttDiagram-23REXITY-KBK93CXW.js +293 -0
  878. package/packages/web/dist/assets/gdresource-xMC7jr7x.js +2 -0
  879. package/packages/web/dist/assets/gdscript-DYvRD3hg.js +2 -0
  880. package/packages/web/dist/assets/gdshader-CBce3t8t.js +2 -0
  881. package/packages/web/dist/assets/genie-CV2tkWYe.js +2 -0
  882. package/packages/web/dist/assets/gherkin-DExj1W_8.js +2 -0
  883. package/packages/web/dist/assets/git-commit-BSykSTBG.js +2 -0
  884. package/packages/web/dist/assets/git-rebase-B09wAERM.js +2 -0
  885. package/packages/web/dist/assets/gitGraph-VSP46ZUC-Dwmw1QLM.js +1 -0
  886. package/packages/web/dist/assets/gitGraphDiagram-STJD7YCW-B2T13-ZJ.js +107 -0
  887. package/packages/web/dist/assets/gleam-CSRkHgEL.js +2 -0
  888. package/packages/web/dist/assets/glimmer-js-CpWvy9gf.js +2 -0
  889. package/packages/web/dist/assets/glimmer-ts-BAH8Czr9.js +2 -0
  890. package/packages/web/dist/assets/glsl-CVY0WJyt.js +2 -0
  891. package/packages/web/dist/assets/gn-CAXYAgV-.js +2 -0
  892. package/packages/web/dist/assets/gnuplot-7GGW24-e.js +2 -0
  893. package/packages/web/dist/assets/go-rLFTqkRN.js +2 -0
  894. package/packages/web/dist/assets/graphlib-DS17s2tU.js +2 -0
  895. package/packages/web/dist/assets/graphql-CDPCtuoQ.js +2 -0
  896. package/packages/web/dist/assets/groovy-CacY0gHj.js +2 -0
  897. package/packages/web/dist/assets/hack-CLEpeEqq.js +2 -0
  898. package/packages/web/dist/assets/haml-Bvpgs3uG.js +2 -0
  899. package/packages/web/dist/assets/handlebars-vXY9zmj1.js +2 -0
  900. package/packages/web/dist/assets/haskell-D8IpX4py.js +2 -0
  901. package/packages/web/dist/assets/haxe-C8oCnwJJ.js +2 -0
  902. package/packages/web/dist/assets/hcl-Dh228itO.js +2 -0
  903. package/packages/web/dist/assets/hjson-CxZEssPk.js +2 -0
  904. package/packages/web/dist/assets/hlsl-Cvrh5tZx.js +2 -0
  905. package/packages/web/dist/assets/html-CKMeXkCW.js +2 -0
  906. package/packages/web/dist/assets/html-derivative-C8trdkzI.js +2 -0
  907. package/packages/web/dist/assets/http-UJwVfHv3.js +2 -0
  908. package/packages/web/dist/assets/hurl-7erhC4fM.js +2 -0
  909. package/packages/web/dist/assets/hxml-Dcm88srW.js +2 -0
  910. package/packages/web/dist/assets/hy-CZbG8q4J.js +2 -0
  911. package/packages/web/dist/assets/imba-DsUTQ-LC.js +2 -0
  912. package/packages/web/dist/assets/index-Bv42jNvr.js +4 -0
  913. package/packages/web/dist/assets/index-CSisx5mi.css +1 -0
  914. package/packages/web/dist/assets/info-OHQRW6UA-Ob4q-Ec6.js +1 -0
  915. package/packages/web/dist/assets/infoDiagram-KBXO4MBG-CGQ6MwL3.js +3 -0
  916. package/packages/web/dist/assets/ini-B5eOa1yu.js +2 -0
  917. package/packages/web/dist/assets/ishikawaDiagram-M35NCXHK-CuoxiCk-.js +71 -0
  918. package/packages/web/dist/assets/java-DGv6_9mf.js +2 -0
  919. package/packages/web/dist/assets/javascript-wyDA4Fnk.js +2 -0
  920. package/packages/web/dist/assets/jinja-CRKn4_DT.js +2 -0
  921. package/packages/web/dist/assets/jison-C5fjf-e-.js +2 -0
  922. package/packages/web/dist/assets/journeyDiagram-OPLOXDXO-zEDEMkq6.js +140 -0
  923. package/packages/web/dist/assets/json-B_qwZ7m_.js +2 -0
  924. package/packages/web/dist/assets/json5-BR5RXkoi.js +2 -0
  925. package/packages/web/dist/assets/jsonc-CYpm1nAK.js +2 -0
  926. package/packages/web/dist/assets/jsonl-CmCQp5Yx.js +2 -0
  927. package/packages/web/dist/assets/jsonnet-CJTPZ8u_.js +2 -0
  928. package/packages/web/dist/assets/jssm-DXw9l8Rf.js +2 -0
  929. package/packages/web/dist/assets/jsx-Ba8EQqYd.js +2 -0
  930. package/packages/web/dist/assets/julia-mJS6zhvp.js +2 -0
  931. package/packages/web/dist/assets/just-n_L73pBN.js +2 -0
  932. package/packages/web/dist/assets/kanban-definition-BZKZHSQY-q5yqVxKo.js +90 -0
  933. package/packages/web/dist/assets/katex-MEuSR36T.js +258 -0
  934. package/packages/web/dist/assets/kdl-CsD5j6eV.js +2 -0
  935. package/packages/web/dist/assets/kotlin-DhhofPvG.js +2 -0
  936. package/packages/web/dist/assets/kusto-C7mF5XQf.js +2 -0
  937. package/packages/web/dist/assets/labels-BhJpmLWA.js +2 -0
  938. package/packages/web/dist/assets/langs-CVIiVMBh.js +3 -0
  939. package/packages/web/dist/assets/latex-0iQGLWul.js +2 -0
  940. package/packages/web/dist/assets/layout-DQKldU13.js +2 -0
  941. package/packages/web/dist/assets/lean-CewbzKMR.js +2 -0
  942. package/packages/web/dist/assets/less-DVTAwKKz.js +2 -0
  943. package/packages/web/dist/assets/liquid-B8kEVR50.js +2 -0
  944. package/packages/web/dist/assets/live-kTMxmy8I.js +2 -0
  945. package/packages/web/dist/assets/llvm-DqHOMS-s.js +2 -0
  946. package/packages/web/dist/assets/log-BNLmms1o.js +2 -0
  947. package/packages/web/dist/assets/logo-Cluzi2Zq.js +2 -0
  948. package/packages/web/dist/assets/lua-BDnDZ8k4.js +2 -0
  949. package/packages/web/dist/assets/luau-VGWVLoqX.js +2 -0
  950. package/packages/web/dist/assets/made-DYU0Ohi4.js +2 -0
  951. package/packages/web/dist/assets/make-Dixweg8N.js +2 -0
  952. package/packages/web/dist/assets/markdown-BYOwaDjH.js +2 -0
  953. package/packages/web/dist/assets/marko-Bk0_iGvT.js +2 -0
  954. package/packages/web/dist/assets/matlab-D7qyCx1q.js +2 -0
  955. package/packages/web/dist/assets/mdc-DhizV3YK.js +2 -0
  956. package/packages/web/dist/assets/mdx-DQZ5AkYe.js +2 -0
  957. package/packages/web/dist/assets/mermaid-BxpfTIzt.js +2 -0
  958. package/packages/web/dist/assets/mermaid-parser.core-BGN5zmcs.js +8 -0
  959. package/packages/web/dist/assets/mermaid.core-BNF3dRf5.js +45 -0
  960. package/packages/web/dist/assets/metrics-Cio5ykX6.js +2 -0
  961. package/packages/web/dist/assets/mindmap-definition-I2QAS2VK-CoiSJ4W4.js +99 -0
  962. package/packages/web/dist/assets/mipsasm-BMqwQI7S.js +2 -0
  963. package/packages/web/dist/assets/mojo-fg40_ntQ.js +2 -0
  964. package/packages/web/dist/assets/moonbit-D9W784E_.js +2 -0
  965. package/packages/web/dist/assets/move-BYnGhZoM.js +2 -0
  966. package/packages/web/dist/assets/narrat-_X_XdTYD.js +2 -0
  967. package/packages/web/dist/assets/nextflow-CSgcYZcx.js +2 -0
  968. package/packages/web/dist/assets/nextflow-groovy-D7IRt6Pp.js +2 -0
  969. package/packages/web/dist/assets/nginx-DoalMtUh.js +2 -0
  970. package/packages/web/dist/assets/nim-DdsQnl3h.js +2 -0
  971. package/packages/web/dist/assets/nix-IvuFDN5E.js +2 -0
  972. package/packages/web/dist/assets/now-40JhSjx0.js +2 -0
  973. package/packages/web/dist/assets/nsis-CjNLYCLg.js +2 -0
  974. package/packages/web/dist/assets/nushell--0fT3PI1.js +2 -0
  975. package/packages/web/dist/assets/objective-c-D1A_Heim.js +2 -0
  976. package/packages/web/dist/assets/objective-cpp-BsSzOQcm.js +2 -0
  977. package/packages/web/dist/assets/ocaml-O90oeIOV.js +2 -0
  978. package/packages/web/dist/assets/odin-B1RWQWA5.js +2 -0
  979. package/packages/web/dist/assets/openscad-BUDT5pXO.js +2 -0
  980. package/packages/web/dist/assets/org-B2d-Pz26.js +2 -0
  981. package/packages/web/dist/assets/packet-JDAUHWVQ-kID5-AEG.js +1 -0
  982. package/packages/web/dist/assets/pascal-4ZHwLPI5.js +2 -0
  983. package/packages/web/dist/assets/pdf-YwugTw7Y.js +55 -0
  984. package/packages/web/dist/assets/pdf.worker.min-CIqJB0yW.mjs +28 -0
  985. package/packages/web/dist/assets/pdf.worker.min-UqOn5EDC.js +2 -0
  986. package/packages/web/dist/assets/pegDiagram-FD4XPPHP-DvO7r8qd.js +2 -0
  987. package/packages/web/dist/assets/perl-CpJxFnsT.js +2 -0
  988. package/packages/web/dist/assets/php-CG5ES-ob.js +2 -0
  989. package/packages/web/dist/assets/pie-XZMESJXO-By0gro0O.js +1 -0
  990. package/packages/web/dist/assets/pieDiagram-J4AKIIQI-f_Jeo_8D.js +40 -0
  991. package/packages/web/dist/assets/pkl-ot-7Btpt.js +2 -0
  992. package/packages/web/dist/assets/plsql-DGHpHOYJ.js +2 -0
  993. package/packages/web/dist/assets/po-BiJDBrnU.js +2 -0
  994. package/packages/web/dist/assets/polar-C7UOKdEL.js +2 -0
  995. package/packages/web/dist/assets/postcss-BXeXVLqQ.js +2 -0
  996. package/packages/web/dist/assets/powerquery-DNMTfnFr.js +2 -0
  997. package/packages/web/dist/assets/powershell-QtSnmXcu.js +2 -0
  998. package/packages/web/dist/assets/preload-helper-7y9sWmk5.js +1 -0
  999. package/packages/web/dist/assets/prisma-DMgNhnYS.js +2 -0
  1000. package/packages/web/dist/assets/problems-BZY0Dwif.js +2 -0
  1001. package/packages/web/dist/assets/prolog-iXnhIJG7.js +2 -0
  1002. package/packages/web/dist/assets/proto-DB4EqR-F.js +2 -0
  1003. package/packages/web/dist/assets/pug-b31sGWmp.js +2 -0
  1004. package/packages/web/dist/assets/puppet-CDv2pdJW.js +2 -0
  1005. package/packages/web/dist/assets/purescript-9MfHhQsQ.js +2 -0
  1006. package/packages/web/dist/assets/push-payload-D5efGCzd.js +402 -0
  1007. package/packages/web/dist/assets/python-gzcpVVnB.js +2 -0
  1008. package/packages/web/dist/assets/qml-Dd7VLkrA.js +2 -0
  1009. package/packages/web/dist/assets/qmldir-DCQb3MpD.js +2 -0
  1010. package/packages/web/dist/assets/qss-Fe1Jh2GI.js +2 -0
  1011. package/packages/web/dist/assets/quadrantDiagram-XTYBLID2-Cr6SWkGn.js +8 -0
  1012. package/packages/web/dist/assets/r-yyMNTq5r.js +2 -0
  1013. package/packages/web/dist/assets/racket-DcIDlBhZ.js +2 -0
  1014. package/packages/web/dist/assets/radar-ABXABTNO-yHosJs_M.js +1 -0
  1015. package/packages/web/dist/assets/railroad-I3PHUGI6-C-LR5A-v.js +1 -0
  1016. package/packages/web/dist/assets/railroad-abnf-LNEFI6M7-DjGnF9uf.js +1 -0
  1017. package/packages/web/dist/assets/railroad-ebnf-DWYD2UWJ-BgsDVMJk.js +1 -0
  1018. package/packages/web/dist/assets/railroad-peg-JR7BVNR7-DkSNpypW.js +1 -0
  1019. package/packages/web/dist/assets/railroadDiagram-MRQ6NCDL-BdGdKtFJ.js +2 -0
  1020. package/packages/web/dist/assets/raku-B3gFvitq.js +2 -0
  1021. package/packages/web/dist/assets/razor-B0rzWF9b.js +2 -0
  1022. package/packages/web/dist/assets/rbs-C0MpOrj4.js +2 -0
  1023. package/packages/web/dist/assets/record-edits-CveFEsal.js +2 -0
  1024. package/packages/web/dist/assets/reg-CRGYupPL.js +2 -0
  1025. package/packages/web/dist/assets/regexp-DYMieNym.js +2 -0
  1026. package/packages/web/dist/assets/rel-BtDbiS_P.js +2 -0
  1027. package/packages/web/dist/assets/remote-config-BkaarDf3.js +2 -0
  1028. package/packages/web/dist/assets/requirementDiagram-Y7LWUY3S-ImkACz5a.js +85 -0
  1029. package/packages/web/dist/assets/review-CGUGvRV9.js +4 -0
  1030. package/packages/web/dist/assets/riscv-Ckw8ddFX.js +2 -0
  1031. package/packages/web/dist/assets/rolldown-runtime-COiEfhsA.js +1 -0
  1032. package/packages/web/dist/assets/ron-VUp2lXgN.js +2 -0
  1033. package/packages/web/dist/assets/rosmsg-CAekHB0j.js +2 -0
  1034. package/packages/web/dist/assets/rough.esm-Dy-Kn_BL.js +2 -0
  1035. package/packages/web/dist/assets/routes-qP_j74V5.js +4 -0
  1036. package/packages/web/dist/assets/rst-BtnuOAUZ.js +2 -0
  1037. package/packages/web/dist/assets/ruby-Dx9fBFuB.js +2 -0
  1038. package/packages/web/dist/assets/runs-k76usGfd.js +2 -0
  1039. package/packages/web/dist/assets/runtime-core.esm-bundler-wlpNGAAZ.js +4 -0
  1040. package/packages/web/dist/assets/rust-DpiIf5JO.js +2 -0
  1041. package/packages/web/dist/assets/sankeyDiagram-WGJFYUXA-Crpx7BLQ.js +41 -0
  1042. package/packages/web/dist/assets/sas-CYVU3X7O.js +2 -0
  1043. package/packages/web/dist/assets/sass-DXrisJhu.js +2 -0
  1044. package/packages/web/dist/assets/scala-BiFt_7mu.js +2 -0
  1045. package/packages/web/dist/assets/scheme-DQCgrYNe.js +2 -0
  1046. package/packages/web/dist/assets/scss-BAOTDanj.js +2 -0
  1047. package/packages/web/dist/assets/sdbl-bTVj8UrX.js +2 -0
  1048. package/packages/web/dist/assets/sequenceDiagram-5NDRBG5M-Ch5L-aWg.js +170 -0
  1049. package/packages/web/dist/assets/shaderlab-TOUzSsQk.js +2 -0
  1050. package/packages/web/dist/assets/shared-DTpYDMc_.js +2 -0
  1051. package/packages/web/dist/assets/shellscript-DUxm18QR.js +2 -0
  1052. package/packages/web/dist/assets/shellsession-DphNsVk1.js +2 -0
  1053. package/packages/web/dist/assets/size-BwnshyOe.js +2 -0
  1054. package/packages/web/dist/assets/sizeCapture-INFHLROL-3uHXrFqA.js +2 -0
  1055. package/packages/web/dist/assets/smalltalk-BHpQb5nM.js +2 -0
  1056. package/packages/web/dist/assets/smithy-Dgaz7aur.js +2 -0
  1057. package/packages/web/dist/assets/solidity-Bj7E1mRn.js +2 -0
  1058. package/packages/web/dist/assets/sources-Bm-TrxhL.js +2 -0
  1059. package/packages/web/dist/assets/soy-BprueKgI.js +2 -0
  1060. package/packages/web/dist/assets/sparql-D_iOobhT.js +2 -0
  1061. package/packages/web/dist/assets/splunk-BC2Px7Mm.js +2 -0
  1062. package/packages/web/dist/assets/sql-D4n2TlMc.js +2 -0
  1063. package/packages/web/dist/assets/src-DLK1P7oz.js +43 -0
  1064. package/packages/web/dist/assets/ssh-config-BgfXC-Er.js +2 -0
  1065. package/packages/web/dist/assets/stata-D3X-un4D.js +2 -0
  1066. package/packages/web/dist/assets/state-CjE-qA2w.js +2 -0
  1067. package/packages/web/dist/assets/state-J8VdpZXA.css +1 -0
  1068. package/packages/web/dist/assets/stateDiagram-v2-FJ4FJNEA-8fpbogV7.js +292 -0
  1069. package/packages/web/dist/assets/stores-BMEvTe-I.js +2 -0
  1070. package/packages/web/dist/assets/stylus-B6D30XZt.js +2 -0
  1071. package/packages/web/dist/assets/surrealql-5--I0FKd.js +2 -0
  1072. package/packages/web/dist/assets/svelte-DlUga76i.js +2 -0
  1073. package/packages/web/dist/assets/swift-CyEgAFGc.js +2 -0
  1074. package/packages/web/dist/assets/swimlanes-UMQ2AFYF-2-xKzyRO.js +2 -0
  1075. package/packages/web/dist/assets/swimlanesDiagram-OMPLPG4O-DHJrYwQz.js +9 -0
  1076. package/packages/web/dist/assets/system-verilog-Dh5ihWbf.js +2 -0
  1077. package/packages/web/dist/assets/systemd-BxMlprV5.js +2 -0
  1078. package/packages/web/dist/assets/systems-DIp94AET.js +2 -0
  1079. package/packages/web/dist/assets/table-LcEs15kL.js +4 -0
  1080. package/packages/web/dist/assets/talonscript-CohzipZa.js +2 -0
  1081. package/packages/web/dist/assets/tasl-DMoTqEGO.js +2 -0
  1082. package/packages/web/dist/assets/tcl-CZd0xW_V.js +2 -0
  1083. package/packages/web/dist/assets/templ-SgILQMBm.js +2 -0
  1084. package/packages/web/dist/assets/terraform-DswuEJGm.js +2 -0
  1085. package/packages/web/dist/assets/tex-B_j0g-0C.js +2 -0
  1086. package/packages/web/dist/assets/timeline-definition-SEUHKTQE-Czq0i_qO.js +121 -0
  1087. package/packages/web/dist/assets/toml-CcmNWLt0.js +2 -0
  1088. package/packages/web/dist/assets/treeView-D4JQ5SDB-B3NKij_H.js +1 -0
  1089. package/packages/web/dist/assets/treemap-SAJKECNS-Dt7uNpkP.js +1 -0
  1090. package/packages/web/dist/assets/ts-tags-Bb2M6NRT.js +2 -0
  1091. package/packages/web/dist/assets/tsv-sltzmVWM.js +2 -0
  1092. package/packages/web/dist/assets/tsx-D2H2cqPj.js +2 -0
  1093. package/packages/web/dist/assets/turtle-ByJddavk.js +2 -0
  1094. package/packages/web/dist/assets/twig-DqWgw3C7.js +2 -0
  1095. package/packages/web/dist/assets/types-D1t1HqPm.js +2 -0
  1096. package/packages/web/dist/assets/typescript-DVfyLS1i.js +2 -0
  1097. package/packages/web/dist/assets/typespec-BGhR2SqG.js +2 -0
  1098. package/packages/web/dist/assets/typst-Cs7gYQVT.js +2 -0
  1099. package/packages/web/dist/assets/ui-C7ZH_6oC.css +1 -0
  1100. package/packages/web/dist/assets/ui-W12UYhVu.js +17 -0
  1101. package/packages/web/dist/assets/url-BIg5IhGs.js +2 -0
  1102. package/packages/web/dist/assets/usecaseDiagram-AFA6YXN4-D3m4xj4y.js +329 -0
  1103. package/packages/web/dist/assets/v-DBj4K9d_.js +2 -0
  1104. package/packages/web/dist/assets/vala-zf12oZj6.js +2 -0
  1105. package/packages/web/dist/assets/vb-DOwzaHZ0.js +2 -0
  1106. package/packages/web/dist/assets/vennDiagram-NNMJR3RB-DeIkukMz.js +35 -0
  1107. package/packages/web/dist/assets/verilog-B2gwz-sJ.js +2 -0
  1108. package/packages/web/dist/assets/vhdl-BroJfC0k.js +2 -0
  1109. package/packages/web/dist/assets/viml-DvXPmvsu.js +2 -0
  1110. package/packages/web/dist/assets/vue-D0OpHdq8.js +2 -0
  1111. package/packages/web/dist/assets/vue-html-DYZahZaV.js +2 -0
  1112. package/packages/web/dist/assets/vue-vine-BsFhbSla.js +2 -0
  1113. package/packages/web/dist/assets/vyper-CgoNMtux.js +2 -0
  1114. package/packages/web/dist/assets/wardley-7MLQ67FV-DSzBQKe8.js +1 -0
  1115. package/packages/web/dist/assets/wardleyDiagram-S7YFUSEH-ef9ee0JD.js +79 -0
  1116. package/packages/web/dist/assets/wasm-ByWQv1Qj.js +2 -0
  1117. package/packages/web/dist/assets/wenyan-C8pVoKbM.js +2 -0
  1118. package/packages/web/dist/assets/wgsl-BsKzXJz4.js +2 -0
  1119. package/packages/web/dist/assets/widget-host-BCf6Tlt5.js +2 -0
  1120. package/packages/web/dist/assets/widgets-CrbkovMT.js +2 -0
  1121. package/packages/web/dist/assets/wikitext-ClFFjSW2.js +2 -0
  1122. package/packages/web/dist/assets/wit-DdvCle-K.js +2 -0
  1123. package/packages/web/dist/assets/wolfram-DLL8P-h_.js +2 -0
  1124. package/packages/web/dist/assets/xml-Cz9mX3j0.js +2 -0
  1125. package/packages/web/dist/assets/xsl-fJeiXJlj.js +2 -0
  1126. package/packages/web/dist/assets/xychartDiagram-GGNKY7IX-CuWtZyN1.js +8 -0
  1127. package/packages/web/dist/assets/yaml-BtwsWWqX.js +2 -0
  1128. package/packages/web/dist/assets/zenscript-BnlCZFoB.js +2 -0
  1129. package/packages/web/dist/assets/zig-CMLA9XwU.js +2 -0
  1130. package/packages/web/dist/favicon.svg +1 -0
  1131. package/packages/web/dist/icons/apple-touch-icon.png +0 -0
  1132. package/packages/web/dist/icons/icon-192.png +0 -0
  1133. package/packages/web/dist/icons/icon-512.png +0 -0
  1134. package/packages/web/dist/icons/maskable-512.png +0 -0
  1135. package/packages/web/dist/index.html +95 -0
  1136. package/packages/web/dist/offline.html +39 -0
  1137. package/packages/web/dist/screenshots/narrow.png +0 -0
  1138. package/packages/web/dist/screenshots/wide.png +0 -0
  1139. package/packages/web/dist/sw.js +2 -0
  1140. package/packages/web/dist/zod-config.js +7 -0
  1141. package/packages/web/package.json +25 -0
  1142. package/premade/claude.zip +0 -0
  1143. package/premade/database.zip +0 -0
  1144. package/premade/web.zip +0 -0
  1145. package/scripts/dev-env.ts +30 -0
  1146. package/scripts/hub-client.ts +2 -0
  1147. package/scripts/release/link.cjs +73 -0
  1148. package/scripts/run-stack.ts +98 -0
  1149. package/scripts/stack.ts +317 -0
  1150. package/scripts/start.ts +120 -0
  1151. package/scripts/supervise.ts +98 -0
  1152. package/systems/api/package.json +20 -0
  1153. package/systems/api/server/authoring.ts +348 -0
  1154. package/systems/api/server/env.ts +16 -0
  1155. package/systems/api/server/guard.ts +44 -0
  1156. package/systems/api/server/http.ts +274 -0
  1157. package/systems/api/server/impl.ts +233 -0
  1158. package/systems/api/server/index.ts +10 -0
  1159. package/systems/api/server/main.ts +27 -0
  1160. package/systems/api/server/openapi.ts +51 -0
  1161. package/systems/api/server/program.ts +158 -0
  1162. package/systems/api/server/services.ts +121 -0
  1163. package/systems/api/shared/http.ts +61 -0
  1164. package/systems/api/shared/index.ts +244 -0
  1165. package/systems/api/system.json +9 -0
  1166. package/systems/api/tsconfig.json +6 -0
  1167. package/systems/code/package.json +20 -0
  1168. package/systems/code/server/authoring.ts +233 -0
  1169. package/systems/code/server/env.ts +13 -0
  1170. package/systems/code/server/impl.ts +128 -0
  1171. package/systems/code/server/index.ts +5 -0
  1172. package/systems/code/server/main.ts +27 -0
  1173. package/systems/code/shared/index.ts +130 -0
  1174. package/systems/code/system.json +9 -0
  1175. package/systems/code/tsconfig.json +6 -0
  1176. package/systems/embedder/package.json +19 -0
  1177. package/systems/embedder/server/env.ts +27 -0
  1178. package/systems/embedder/server/http.ts +154 -0
  1179. package/systems/embedder/server/impl.ts +104 -0
  1180. package/systems/embedder/server/index.ts +22 -0
  1181. package/systems/embedder/server/main.ts +37 -0
  1182. package/systems/embedder/server/provider.ts +60 -0
  1183. package/systems/embedder/shared/index.ts +74 -0
  1184. package/systems/embedder/system.json +9 -0
  1185. package/systems/embedder/tsconfig.json +6 -0
  1186. package/systems/fs/client/BashView.vue +165 -0
  1187. package/systems/fs/client/ChangesView.vue +132 -0
  1188. package/systems/fs/client/DiffBody.vue +95 -0
  1189. package/systems/fs/client/DiffView.vue +73 -0
  1190. package/systems/fs/client/EntryInput.vue +102 -0
  1191. package/systems/fs/client/InstallView.vue +72 -0
  1192. package/systems/fs/client/OutputBlock.vue +65 -0
  1193. package/systems/fs/client/bash.ts +40 -0
  1194. package/systems/fs/client/changes.ts +87 -0
  1195. package/systems/fs/client/diff.ts +151 -0
  1196. package/systems/fs/client/fakes.ts +58 -0
  1197. package/systems/fs/client/index.ts +19 -0
  1198. package/systems/fs/client/preview/Preview.vue +70 -0
  1199. package/systems/fs/client/preview/index.html +12 -0
  1200. package/systems/fs/client/preview/main.ts +9 -0
  1201. package/systems/fs/client/preview/shots.ts +71 -0
  1202. package/systems/fs/client/rerun.ts +36 -0
  1203. package/systems/fs/context/authoring/index.md +42 -0
  1204. package/systems/fs/context/authoring/parts/actions.md +56 -0
  1205. package/systems/fs/context/authoring/parts/actions.reference.md +90 -0
  1206. package/systems/fs/context/authoring/parts/calling.md +71 -0
  1207. package/systems/fs/context/authoring/parts/calling.reference.md +134 -0
  1208. package/systems/fs/context/authoring/parts/client.md +273 -0
  1209. package/systems/fs/context/authoring/parts/client.reference/client.md +638 -0
  1210. package/systems/fs/context/authoring/parts/client.reference/fnpillprops.md +141 -0
  1211. package/systems/fs/context/authoring/parts/client.reference/resultview.md +619 -0
  1212. package/systems/fs/context/authoring/parts/client.reference.md +24 -0
  1213. package/systems/fs/context/authoring/parts/context.md +119 -0
  1214. package/systems/fs/context/authoring/parts/context.reference.md +458 -0
  1215. package/systems/fs/context/authoring/parts/contract.md +167 -0
  1216. package/systems/fs/context/authoring/parts/contract.reference.md +286 -0
  1217. package/systems/fs/context/authoring/parts/core-types/access-ts.md +39 -0
  1218. package/systems/fs/context/authoring/parts/core-types/admin-ts.md +41 -0
  1219. package/systems/fs/context/authoring/parts/core-types/api-index-ts.md +28 -0
  1220. package/systems/fs/context/authoring/parts/core-types/approvals-ts.md +494 -0
  1221. package/systems/fs/context/authoring/parts/core-types/auto-pair-ts.md +28 -0
  1222. package/systems/fs/context/authoring/parts/core-types/checks-ts.md +42 -0
  1223. package/systems/fs/context/authoring/parts/core-types/claims-ts.md +26 -0
  1224. package/systems/fs/context/authoring/parts/core-types/config-secrets-ts.md +24 -0
  1225. package/systems/fs/context/authoring/parts/core-types/connections-ts.md +178 -0
  1226. package/systems/fs/context/authoring/parts/core-types/context-files-ts.md +103 -0
  1227. package/systems/fs/context/authoring/parts/core-types/context-graph-ts.md +22 -0
  1228. package/systems/fs/context/authoring/parts/core-types/contextdecl.md +477 -0
  1229. package/systems/fs/context/authoring/parts/core-types/data-ts.md +236 -0
  1230. package/systems/fs/context/authoring/parts/core-types/decisions-ts.md +52 -0
  1231. package/systems/fs/context/authoring/parts/core-types/fn-block-ts.md +31 -0
  1232. package/systems/fs/context/authoring/parts/core-types/fn-facts-ts.md +228 -0
  1233. package/systems/fs/context/authoring/parts/core-types/gin-ts.md +24 -0
  1234. package/systems/fs/context/authoring/parts/core-types/grants-ts.md +55 -0
  1235. package/systems/fs/context/authoring/parts/core-types/lifecycle-ts.md +658 -0
  1236. package/systems/fs/context/authoring/parts/core-types/link-ts.md +410 -0
  1237. package/systems/fs/context/authoring/parts/core-types/llm-ts.md +268 -0
  1238. package/systems/fs/context/authoring/parts/core-types/manifest.md +460 -0
  1239. package/systems/fs/context/authoring/parts/core-types/manifestpatch.md +519 -0
  1240. package/systems/fs/context/authoring/parts/core-types/mention-search-ts.md +29 -0
  1241. package/systems/fs/context/authoring/parts/core-types/model-calls-ts.md +200 -0
  1242. package/systems/fs/context/authoring/parts/core-types/model-names-ts.md +31 -0
  1243. package/systems/fs/context/authoring/parts/core-types/modes-ts.md +89 -0
  1244. package/systems/fs/context/authoring/parts/core-types/owner-runs-ts.md +47 -0
  1245. package/systems/fs/context/authoring/parts/core-types/package-ts.md +83 -0
  1246. package/systems/fs/context/authoring/parts/core-types/primitives-ts.md +170 -0
  1247. package/systems/fs/context/authoring/parts/core-types/query-ts.md +50 -0
  1248. package/systems/fs/context/authoring/parts/core-types/records-actors-ts.md +259 -0
  1249. package/systems/fs/context/authoring/parts/core-types/records-chat-ts.md +217 -0
  1250. package/systems/fs/context/authoring/parts/core-types/records-content-ts.md +24 -0
  1251. package/systems/fs/context/authoring/parts/core-types/records-runs-ts.md +24 -0
  1252. package/systems/fs/context/authoring/parts/core-types/records-systems-ts.md +69 -0
  1253. package/systems/fs/context/authoring/parts/core-types/registries-ts.md +376 -0
  1254. package/systems/fs/context/authoring/parts/core-types/remote-auth-ts.md +60 -0
  1255. package/systems/fs/context/authoring/parts/core-types/resources-ts.md +250 -0
  1256. package/systems/fs/context/authoring/parts/core-types/run-ts.md +425 -0
  1257. package/systems/fs/context/authoring/parts/core-types/sensitivity-ts.md +52 -0
  1258. package/systems/fs/context/authoring/parts/core-types/system-events-ts.md +90 -0
  1259. package/systems/fs/context/authoring/parts/core-types/system-pages-ts.md +50 -0
  1260. package/systems/fs/context/authoring/parts/core-types/system-providers-ts.md +46 -0
  1261. package/systems/fs/context/authoring/parts/core-types/validation-ts.md +45 -0
  1262. package/systems/fs/context/authoring/parts/core-types/visuals-ts.md +107 -0
  1263. package/systems/fs/context/authoring/parts/core-types/web-ts.md +22 -0
  1264. package/systems/fs/context/authoring/parts/core-types/widgets-ts.md +299 -0
  1265. package/systems/fs/context/authoring/parts/core-types.md +164 -0
  1266. package/systems/fs/context/authoring/parts/ctx.md +94 -0
  1267. package/systems/fs/context/authoring/parts/ctx.reference/fnctx.md +516 -0
  1268. package/systems/fs/context/authoring/parts/ctx.reference/hubai.md +309 -0
  1269. package/systems/fs/context/authoring/parts/ctx.reference.md +21 -0
  1270. package/systems/fs/context/authoring/parts/data.md +162 -0
  1271. package/systems/fs/context/authoring/parts/data.reference.md +119 -0
  1272. package/systems/fs/context/authoring/parts/examples/client-findview-vue.md +77 -0
  1273. package/systems/fs/context/authoring/parts/examples/client-index-ts.md +48 -0
  1274. package/systems/fs/context/authoring/parts/examples/client-notecard-vue.md +43 -0
  1275. package/systems/fs/context/authoring/parts/examples/client-noteinput-vue.md +73 -0
  1276. package/systems/fs/context/authoring/parts/examples/client-notespage-vue.md +82 -0
  1277. package/systems/fs/context/authoring/parts/examples/client-reviewform-vue.md +57 -0
  1278. package/systems/fs/context/authoring/parts/examples/client-wordcount-vue.md +58 -0
  1279. package/systems/fs/context/authoring/parts/examples/package-json.md +40 -0
  1280. package/systems/fs/context/authoring/parts/examples/server-env-ts.md +40 -0
  1281. package/systems/fs/context/authoring/parts/examples/server-impl-ts.md +323 -0
  1282. package/systems/fs/context/authoring/parts/examples/server-index-ts.md +34 -0
  1283. package/systems/fs/context/authoring/parts/examples/server-main-ts.md +57 -0
  1284. package/systems/fs/context/authoring/parts/examples/server-notes-test-ts.md +95 -0
  1285. package/systems/fs/context/authoring/parts/examples/shared-index-ts.md +310 -0
  1286. package/systems/fs/context/authoring/parts/examples/system-json.md +36 -0
  1287. package/systems/fs/context/authoring/parts/examples/systems-fs-shared-index-ts-lines-1-189.md +214 -0
  1288. package/systems/fs/context/authoring/parts/examples/systems-fs-shared-index-ts-lines-190-370.md +202 -0
  1289. package/systems/fs/context/authoring/parts/examples/systems-fs-shared-index-ts-lines-371-533.md +183 -0
  1290. package/systems/fs/context/authoring/parts/examples/tsconfig-json.md +27 -0
  1291. package/systems/fs/context/authoring/parts/examples.md +76 -0
  1292. package/systems/fs/context/authoring/parts/fns.md +225 -0
  1293. package/systems/fs/context/authoring/parts/fns.reference/fillclaims.md +267 -0
  1294. package/systems/fs/context/authoring/parts/fns.reference/fn.md +530 -0
  1295. package/systems/fs/context/authoring/parts/fns.reference.md +21 -0
  1296. package/systems/fs/context/authoring/parts/folder.md +472 -0
  1297. package/systems/fs/context/authoring/parts/gin.md +122 -0
  1298. package/systems/fs/context/authoring/parts/gin.reference.md +483 -0
  1299. package/systems/fs/context/authoring/parts/handlers-progress.md +100 -0
  1300. package/systems/fs/context/authoring/parts/handlers-progress.reference.md +197 -0
  1301. package/systems/fs/context/authoring/parts/hooks.md +56 -0
  1302. package/systems/fs/context/authoring/parts/hooks.reference.md +110 -0
  1303. package/systems/fs/context/authoring/parts/hub/hub-auto-pair-revoke.md +189 -0
  1304. package/systems/fs/context/authoring/parts/hub/hub-fns-load.md +470 -0
  1305. package/systems/fs/context/authoring/parts/hub/hub-run-background.md +562 -0
  1306. package/systems/fs/context/authoring/parts/hub/kinds-of-hub.md +95 -0
  1307. package/systems/fs/context/authoring/parts/hub.md +45 -0
  1308. package/systems/fs/context/authoring/parts/hub.reference.md +476 -0
  1309. package/systems/fs/context/authoring/parts/internals/manifestof.md +721 -0
  1310. package/systems/fs/context/authoring/parts/internals/permissionargs.md +652 -0
  1311. package/systems/fs/context/authoring/parts/internals/usagefromwire.md +257 -0
  1312. package/systems/fs/context/authoring/parts/internals.md +39 -0
  1313. package/systems/fs/context/authoring/parts/kinds-agents.md +278 -0
  1314. package/systems/fs/context/authoring/parts/kinds-agents.reference/authoringsession.md +195 -0
  1315. package/systems/fs/context/authoring/parts/kinds-agents.reference/kind.md +496 -0
  1316. package/systems/fs/context/authoring/parts/kinds-agents.reference.md +21 -0
  1317. package/systems/fs/context/authoring/parts/lifecycle.md +89 -0
  1318. package/systems/fs/context/authoring/parts/lifecycle.reference.md +60 -0
  1319. package/systems/fs/context/authoring/parts/mentions.md +76 -0
  1320. package/systems/fs/context/authoring/parts/mentions.reference.md +105 -0
  1321. package/systems/fs/context/authoring/parts/mistakes.md +465 -0
  1322. package/systems/fs/context/authoring/parts/named-types.md +97 -0
  1323. package/systems/fs/context/authoring/parts/named-types.reference.md +168 -0
  1324. package/systems/fs/context/authoring/parts/outcomes.md +120 -0
  1325. package/systems/fs/context/authoring/parts/outcomes.reference.md +287 -0
  1326. package/systems/fs/context/authoring/parts/owner-runs.md +62 -0
  1327. package/systems/fs/context/authoring/parts/owner-runs.reference.md +224 -0
  1328. package/systems/fs/context/authoring/parts/packaging.md +201 -0
  1329. package/systems/fs/context/authoring/parts/packaging.reference.md +206 -0
  1330. package/systems/fs/context/authoring/parts/providers.md +63 -0
  1331. package/systems/fs/context/authoring/parts/providers.reference.md +88 -0
  1332. package/systems/fs/context/authoring/parts/remote.md +63 -0
  1333. package/systems/fs/context/authoring/parts/remote.reference.md +175 -0
  1334. package/systems/fs/context/authoring/parts/resources.md +58 -0
  1335. package/systems/fs/context/authoring/parts/resources.reference.md +130 -0
  1336. package/systems/fs/context/authoring/parts/server.md +120 -0
  1337. package/systems/fs/context/authoring/parts/server.reference.md +569 -0
  1338. package/systems/fs/context/authoring/parts/settings-attachments.md +55 -0
  1339. package/systems/fs/context/authoring/parts/settings-attachments.reference.md +100 -0
  1340. package/systems/fs/context/authoring/parts/start.md +67 -0
  1341. package/systems/fs/context/authoring/parts/state-forms.md +103 -0
  1342. package/systems/fs/context/authoring/parts/state-forms.reference.md +32 -0
  1343. package/systems/fs/context/authoring/parts/testing.md +160 -0
  1344. package/systems/fs/context/authoring/parts/testing.reference/fakehub.md +396 -0
  1345. package/systems/fs/context/authoring/parts/testing.reference/memoryjournal.md +539 -0
  1346. package/systems/fs/context/authoring/parts/testing.reference/toolcall.md +509 -0
  1347. package/systems/fs/context/authoring/parts/testing.reference.md +24 -0
  1348. package/systems/fs/context/authoring/parts/widgets.md +165 -0
  1349. package/systems/fs/context/authoring/parts/widgets.reference/hub-visuals.md +623 -0
  1350. package/systems/fs/context/authoring/parts/widgets.reference/sourcecompatible.md +150 -0
  1351. package/systems/fs/context/authoring/parts/widgets.reference.md +21 -0
  1352. package/systems/fs/context/authoring/topics/begin.md +37 -0
  1353. package/systems/fs/context/authoring/topics/client.md +25 -0
  1354. package/systems/fs/context/authoring/topics/declare.md +40 -0
  1355. package/systems/fs/context/authoring/topics/examples.md +25 -0
  1356. package/systems/fs/context/authoring/topics/fns.md +37 -0
  1357. package/systems/fs/context/authoring/topics/server.md +40 -0
  1358. package/systems/fs/context/authoring/topics/types.md +28 -0
  1359. package/systems/fs/package.json +28 -0
  1360. package/systems/fs/server/authoring.ts +103 -0
  1361. package/systems/fs/server/builds.ts +101 -0
  1362. package/systems/fs/server/changes.ts +430 -0
  1363. package/systems/fs/server/commands.ts +133 -0
  1364. package/systems/fs/server/documents.ts +96 -0
  1365. package/systems/fs/server/env.ts +123 -0
  1366. package/systems/fs/server/files.ts +218 -0
  1367. package/systems/fs/server/git.ts +99 -0
  1368. package/systems/fs/server/hosting.ts +742 -0
  1369. package/systems/fs/server/impl.ts +451 -0
  1370. package/systems/fs/server/index.ts +151 -0
  1371. package/systems/fs/server/loader.ts +47 -0
  1372. package/systems/fs/server/main.ts +143 -0
  1373. package/systems/fs/server/mentions.ts +176 -0
  1374. package/systems/fs/server/network-guard.ts +10 -0
  1375. package/systems/fs/server/paths.ts +148 -0
  1376. package/systems/fs/server/problem.ts +26 -0
  1377. package/systems/fs/server/resources.ts +236 -0
  1378. package/systems/fs/server/reveal.ts +33 -0
  1379. package/systems/fs/server/run-tests.ts +17 -0
  1380. package/systems/fs/server/runner.ts +221 -0
  1381. package/systems/fs/server/safe.ts +83 -0
  1382. package/systems/fs/server/search.ts +214 -0
  1383. package/systems/fs/server/sections.ts +17 -0
  1384. package/systems/fs/server/sensitive.ts +560 -0
  1385. package/systems/fs/server/shell.ts +255 -0
  1386. package/systems/fs/server/snapshots.ts +119 -0
  1387. package/systems/fs/server/stale.ts +92 -0
  1388. package/systems/fs/server/testing.ts +256 -0
  1389. package/systems/fs/server/tests.ts +203 -0
  1390. package/systems/fs/server/tree.ts +44 -0
  1391. package/systems/fs/server/walk.ts +82 -0
  1392. package/systems/fs/shared/format.ts +29 -0
  1393. package/systems/fs/shared/hosting.ts +65 -0
  1394. package/systems/fs/shared/index.ts +533 -0
  1395. package/systems/fs/system.json +10 -0
  1396. package/systems/fs/tsconfig.json +6 -0
  1397. package/systems/google-calendar/package.json +18 -0
  1398. package/systems/google-calendar/server/calendar.ts +164 -0
  1399. package/systems/google-calendar/server/connector.ts +73 -0
  1400. package/systems/google-calendar/server/env.ts +25 -0
  1401. package/systems/google-calendar/server/fake.ts +127 -0
  1402. package/systems/google-calendar/server/google.ts +234 -0
  1403. package/systems/google-calendar/server/impl.ts +140 -0
  1404. package/systems/google-calendar/server/index.ts +7 -0
  1405. package/systems/google-calendar/server/main.ts +29 -0
  1406. package/systems/google-calendar/shared/index.ts +198 -0
  1407. package/systems/google-calendar/system.json +9 -0
  1408. package/systems/google-calendar/tsconfig.json +6 -0
  1409. package/systems/input/client/FieldInput.vue +118 -0
  1410. package/systems/input/client/FormCard.vue +223 -0
  1411. package/systems/input/client/form.ts +152 -0
  1412. package/systems/input/client/host.ts +13 -0
  1413. package/systems/input/client/index.ts +28 -0
  1414. package/systems/input/package.json +22 -0
  1415. package/systems/input/server/authoring.ts +240 -0
  1416. package/systems/input/server/env.ts +17 -0
  1417. package/systems/input/server/impl.ts +177 -0
  1418. package/systems/input/server/index.ts +4 -0
  1419. package/systems/input/server/main.ts +31 -0
  1420. package/systems/input/shared/forms.ts +106 -0
  1421. package/systems/input/shared/index.ts +389 -0
  1422. package/systems/input/system.json +10 -0
  1423. package/systems/input/tsconfig.json +6 -0
  1424. package/systems/mcp/package.json +21 -0
  1425. package/systems/mcp/server/dial.ts +102 -0
  1426. package/systems/mcp/server/elicitation.ts +103 -0
  1427. package/systems/mcp/server/env.ts +27 -0
  1428. package/systems/mcp/server/fixtures/stdio-server.ts +8 -0
  1429. package/systems/mcp/server/impl.ts +190 -0
  1430. package/systems/mcp/server/index.ts +10 -0
  1431. package/systems/mcp/server/instance.ts +442 -0
  1432. package/systems/mcp/server/main.ts +42 -0
  1433. package/systems/mcp/server/mirror.ts +179 -0
  1434. package/systems/mcp/server/oauth.ts +163 -0
  1435. package/systems/mcp/server/schema.ts +56 -0
  1436. package/systems/mcp/server/server-link.ts +216 -0
  1437. package/systems/mcp/shared/index.ts +130 -0
  1438. package/systems/mcp/shared/shapes.ts +42 -0
  1439. package/systems/mcp/system.json +10 -0
  1440. package/systems/mcp/tsconfig.json +6 -0
  1441. package/systems/ollama/client/ServersPage.vue +242 -0
  1442. package/systems/ollama/client/index.ts +13 -0
  1443. package/systems/ollama/client/logic.ts +108 -0
  1444. package/systems/ollama/package.json +22 -0
  1445. package/systems/ollama/server/api.ts +106 -0
  1446. package/systems/ollama/server/detect.ts +59 -0
  1447. package/systems/ollama/server/env.ts +43 -0
  1448. package/systems/ollama/server/fakes.ts +212 -0
  1449. package/systems/ollama/server/impl.ts +362 -0
  1450. package/systems/ollama/server/index.ts +10 -0
  1451. package/systems/ollama/server/install.ts +348 -0
  1452. package/systems/ollama/server/main.ts +67 -0
  1453. package/systems/ollama/server/models.ts +93 -0
  1454. package/systems/ollama/server/provider.ts +42 -0
  1455. package/systems/ollama/server/serve.ts +315 -0
  1456. package/systems/ollama/shared/index.ts +178 -0
  1457. package/systems/ollama/shared/schemas.ts +258 -0
  1458. package/systems/ollama/system.json +11 -0
  1459. package/systems/ollama/tsconfig.json +6 -0
  1460. package/systems/schedule/client/AgendaList.vue +74 -0
  1461. package/systems/schedule/client/AllSchedulesPage.vue +129 -0
  1462. package/systems/schedule/client/CalendarGrid.vue +155 -0
  1463. package/systems/schedule/client/CalendarPage.vue +203 -0
  1464. package/systems/schedule/client/ChangeResult.vue +23 -0
  1465. package/systems/schedule/client/FiringResult.vue +45 -0
  1466. package/systems/schedule/client/ScheduleCard.vue +63 -0
  1467. package/systems/schedule/client/ScheduleForm.vue +227 -0
  1468. package/systems/schedule/client/ScheduleListResult.vue +36 -0
  1469. package/systems/schedule/client/SchedulePage.vue +342 -0
  1470. package/systems/schedule/client/ScheduleResult.vue +23 -0
  1471. package/systems/schedule/client/host.ts +31 -0
  1472. package/systems/schedule/client/index.ts +29 -0
  1473. package/systems/schedule/client/logic.ts +655 -0
  1474. package/systems/schedule/client/results.ts +114 -0
  1475. package/systems/schedule/client/state.ts +372 -0
  1476. package/systems/schedule/package.json +27 -0
  1477. package/systems/schedule/server/args.ts +137 -0
  1478. package/systems/schedule/server/authoring.ts +202 -0
  1479. package/systems/schedule/server/env.ts +32 -0
  1480. package/systems/schedule/server/fns.ts +791 -0
  1481. package/systems/schedule/server/impl.ts +52 -0
  1482. package/systems/schedule/server/index.ts +10 -0
  1483. package/systems/schedule/server/kind.ts +48 -0
  1484. package/systems/schedule/server/main.ts +33 -0
  1485. package/systems/schedule/server/store.ts +195 -0
  1486. package/systems/schedule/server/summary.ts +184 -0
  1487. package/systems/schedule/server/timer.ts +893 -0
  1488. package/systems/schedule/shared/index.ts +376 -0
  1489. package/systems/schedule/shared/types.ts +264 -0
  1490. package/systems/schedule/shared/when.ts +395 -0
  1491. package/systems/schedule/shared/zoned.ts +44 -0
  1492. package/systems/schedule/system.json +15 -0
  1493. package/systems/schedule/tsconfig.json +6 -0
  1494. package/systems/template/README.md +46 -0
  1495. package/systems/template/client/index.ts +16 -0
  1496. package/systems/template/client/vue-shim.d.ts +13 -0
  1497. package/systems/template/package.json +20 -0
  1498. package/systems/template/server/env.ts +19 -0
  1499. package/systems/template/server/impl.ts +58 -0
  1500. package/systems/template/server/index.ts +13 -0
  1501. package/systems/template/server/main.ts +30 -0
  1502. package/systems/template/shared/index.ts +81 -0
  1503. package/systems/template/system.json +15 -0
  1504. package/systems/template/tsconfig.json +6 -0
  1505. package/systems/widgets/client/ProposalCard.vue +83 -0
  1506. package/systems/widgets/client/SavedWidget.vue +35 -0
  1507. package/systems/widgets/client/WidgetsPage.vue +112 -0
  1508. package/systems/widgets/client/index.ts +19 -0
  1509. package/systems/widgets/client/proposal.ts +52 -0
  1510. package/systems/widgets/package.json +23 -0
  1511. package/systems/widgets/server/authoring.ts +261 -0
  1512. package/systems/widgets/server/env.ts +21 -0
  1513. package/systems/widgets/server/impl.ts +252 -0
  1514. package/systems/widgets/server/index.ts +6 -0
  1515. package/systems/widgets/server/main.ts +32 -0
  1516. package/systems/widgets/server/run.ts +104 -0
  1517. package/systems/widgets/shared/index.ts +194 -0
  1518. package/systems/widgets/system.json +10 -0
  1519. package/systems/widgets/tsconfig.json +6 -0
  1520. package/tsconfig.base.json +30 -0
@@ -0,0 +1,402 @@
1
+ function e(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function t(e,t=`|`){return e.map(e=>pe(e)).join(t)}function n(e,t){return typeof t==`bigint`?t.toString():t}var r=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function i(e){return new r(e)}function a(e){return e==null}function o(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function s(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}var c=Symbol(`evaluating`);function l(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==c)return r===void 0&&(r=c,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function u(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function d(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function f(e){return d(e._zod.def)??e._zod.def.shape}function p(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return u(this,t,e),e},enumerable:!0,configurable:!0})}function m(e,t,n){t in e?u(e,t,n):e[t]=n}function h(e,t,n,r){let i=f(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?p(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):m(e,a,r?r(n.value,a):n.value))}}function ee(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?p(e,n,()=>t[n]):m(e,n,r.value))}}function te(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function ne(e){return JSON.stringify(e)}function re(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var ie=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function ae(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var oe=i(()=>{if(rt.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function se(e){if(ae(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return ae(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function ce(e){return se(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var le=new Set([`string`,`number`,`symbol`]),ue=new Set([`string`,`number`,`bigint`,`boolean`,`symbol`,`undefined`]);function de(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function fe(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function g(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function pe(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function me(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}var he={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},ge={int64:[BigInt(`-9223372036854775808`),BigInt(`9223372036854775807`)],uint64:[BigInt(0),BigInt(`18446744073709551615`)]};function _e(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return h(i,e,ve(e,t)),fe(e,te(n,{shape:i,checks:[]}))}function ve(e,t){let n=f(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function ye(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(ve(e,t)),a={};return h(a,e,Reflect.ownKeys(f(e)).filter(e=>!i.has(e))),fe(e,te(n,{shape:a,checks:[]}))}function be(e,t){if(!se(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=f(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return fe(e,te(e._zod.def,{shape:xe(e,t)}))}function xe(e,t){let n={};return h(n,e,Reflect.ownKeys(f(e))),ee(n,t),n}function Se(e,t){if(!se(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return fe(e,te(e._zod.def,{shape:xe(e,t)}))}function Ce(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return h(n,e,Reflect.ownKeys(f(e))),h(n,t,Reflect.ownKeys(f(t))),fe(e,te(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function we(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(ve(t,n)):void 0,o={};return h(o,t,Reflect.ownKeys(f(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),fe(t,te(t._zod.def,{shape:o,checks:[]}))}function Te(e,t,n){let r=n?new Set(ve(t,n)):void 0,i={};return h(i,t,Reflect.ownKeys(f(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),fe(t,te(t._zod.def,{shape:i}))}function Ee(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function De(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Oe(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function ke(e){return typeof e==`string`?e:e?.message}function Ae(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function je(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function Me(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:ke(e.inst?._zod.def?.error?.(e))??ke(a?.(e))??ke(t?.error?.(e))??ke(n.customError?.(e))??ke(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}var Ne=/[\uD800-\uDBFF]/;function Pe(e){let t=e.length;if(!Ne.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function Fe(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Ie(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function Le(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function Re(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):He(e,n,r.value)}}function ze(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Be(e,t,n){return ze(e,t,n,!1)}function Ve(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return ze(this,n,r(this))},set(e){ze(this,n,e)}})}return t}function He(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:ze(this,t,n.bind(this))},set(e){ze(this,t,e)}})}function Ue(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var We,Ge=!1,Ke={configurable:!0,get(){Ge=!0}};function qe(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&We!==e._zod?We=void 0:(We=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Ke);let e=Ge;Ge=!1;try{let r=n(this);return Ge?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Ge||=e,r}catch(n){throw delete this[t],Ge||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function Je(e,t,n,r){let i=Ue(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}var Ye=`~constantCatch`;function Xe(e){let t=()=>e;return t[Ye]=!0,t}var Ze,Qe={value:void 0,enumerable:!1},$e=`captureStackTrace`in Error?Error:null;function et(e){let t=$e;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return $e=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function _(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){Qe.value=new a(r);try{Object.defineProperty(n,"_zod",Qe)}finally{Qe.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),Re(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?et(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var tt=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},nt=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Ze=globalThis).__zod_globalConfig??(Ze.__zod_globalConfig={});var rt=globalThis.__zod_globalConfig;function it(e){return e&&Object.assign(rt,e),rt}function at(){let e=this._zod;return e.message??=JSON.stringify(e.def,n,2),e.message}function ot(e){this._zod.message=e}var st={get:at,set:ot,enumerable:!0,configurable:!0},ct={value:void 0,enumerable:!1},lt=new WeakSet([Object.prototype,Error.prototype]),ut=_(`$ZodError`,(e,t)=>{e.name=`$ZodError`,ct.value=t,Object.defineProperty(e,"issues",ct),ct.value=void 0,Object.defineProperty(e,"message",st);let n=Object.getPrototypeOf(e);lt.has(n)||(lt.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))});function dt(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function ft(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?dt(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function pt(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function mt(e,t){return{callee:t?.callee??e,Err:t?.Err}}var ht=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new tt;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>Me(e,o,it())));throw ie(n,a?.callee??t),n}return s.value};return t},gt=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>Me(e,o,it())));throw ie(n,a?.callee??t),n}return s.value};return t},_t=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new tt;return a.issues.length?vt(e,a.issues,i):{success:!0,data:a.value}};function vt(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>Me(e,n,it()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}var yt=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?vt(e,a.issues,i):{success:!0,data:a.value}},bt=Symbol.for(`zod.compile.invalid`),xt=Symbol.for(`zod.compile.fallback`),St=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==bt)return!0;if(r.definite===!0&&n===void 0)return!1}return Ct(e,t,n)});function Ct(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[xt]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new tt;return a.issues.length===0}var wt=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},Tt=e=>{let t=ht(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,mt(n,a))};return n},Et=e=>{let t=ht(e),n=(e,r,i,a)=>t(e,r,i,mt(n,a));return n},Dt=e=>{let t=gt(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,mt(n,a))};return n},Ot=e=>{let t=gt(e),n=async(e,r,i,a)=>await t(e,r,i,mt(n,a));return n},kt=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _t(e)(t,n,i)},At=e=>(t,n,r)=>_t(e)(t,n,r),jt=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return yt(e)(t,n,i)},Mt=e=>async(t,n,r)=>yt(e)(t,n,r),Nt=/^[cC][0-9a-z]{6,}$/,Pt=/^[0-9a-z]+$/,Ft=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,It=/^[0-9a-vA-V]{20}$/,Lt=/^[A-Za-z0-9]{27}$/,Rt=/^[a-zA-Z0-9_-]{21}$/;function zt(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Bt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Vt=/^([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})$/,Ht=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ut=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Wt=`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;function Gt(){return new RegExp(Wt,`u`)}var Kt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,qt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Jt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Yt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Xt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Zt=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Qt=/^https?$/,$t=/^\+[1-9]\d{6,14}$/,en=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function tn(e){return RegExp(`^${e}$`)}var nn=tn(en);function rn(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function an(e){return RegExp(`^${rn(e)}$`)}function on(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${rn({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${rn({precision:e.precision})}`:n;return RegExp(`^${en}T(?:${r})$`)}var sn=/^[\s\S]{0,}$/,cn=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},ln=/^-?\d+$/,un=/^-?\d+(?:\.\d+)?$/,dn=/^(?:true|false)$/i,fn=/^null$/i,pn=/^[^A-Z]*$/,mn=/^[^a-z]*$/,hn=_(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),gn=e=>{let t=e.value;return!a(t)&&t.length!==void 0},_n={number:`number`,bigint:`bigint`,object:`date`},vn=_(`$ZodCheckLessThan`,(e,t)=>{hn.init(e,t);let n=_n[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:_n[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),yn=_(`$ZodCheckGreaterThan`,(e,t)=>{hn.init(e,t);let n=_n[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:_n[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),bn=_(`$ZodCheckMultipleOf`,(e,t)=>{hn.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):s(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),xn=_(`$ZodCheckNumberFormat`,(e,t)=>{hn.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=he[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Sn=_(`$ZodCheckMaxLength`,(e,t)=>{var n;hn.init(e,t),(n=e._zod.def).when??(n.when=gn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?Pe(r):i)<=t.maximum)return;let a=Fe(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Cn=_(`$ZodCheckMinLength`,(e,t)=>{var n;hn.init(e,t),(n=e._zod.def).when??(n.when=gn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?Pe(r):i)>=t.minimum)return;let a=Fe(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),wn=_(`$ZodCheckLengthEquals`,(e,t)=>{var n;hn.init(e,t),(n=e._zod.def).when??(n.when=gn),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?Pe(r):i;if(a===t.length)return;let o=Fe(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Tn=_(`$ZodCheckStringFormat`,(e,t)=>{var n,r;hn.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),En=_(`$ZodCheckRegex`,(e,t)=>{Tn.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,t.pattern.test(n.value)||n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Dn=_(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=pn,Tn.init(e,t)}),On=_(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=mn,Tn.init(e,t)}),kn=_(`$ZodCheckIncludes`,(e,t)=>{hn.init(e,t);let n=de(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),An=_(`$ZodCheckStartsWith`,(e,t)=>{hn.init(e,t);let n=RegExp(`^${de(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),jn=_(`$ZodCheckEndsWith`,(e,t)=>{hn.init(e,t);let n=RegExp(`.*${de(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Mn=_(`$ZodCheckOverwrite`,(e,t)=>{hn.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Nn=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
2
+ `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
3
+ `)}\n};`)(...Object.values(this.closed))}},Pn={major:4,minor:6,patch:7},Fn=_(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Pn;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=Ee(t),a;for(let o of n){if(o._zod.def.when){if(De(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new tt;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(je(t.issues,n,e),i||=Ee(t,n))});else{if(t.issues.length===n)continue;je(t.issues,n,e),i||=Ee(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(Ee(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new tt;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new tt;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return Be(this,`~standard`,Rn(this))},set"~standard"(e){ze(this,`~standard`,e)}}),In=(e,t)=>e.issues.length?{issues:e.issues.map(e=>Me(e,t,it()))}:{value:e.value};async function Ln(e,t){let n={async:!0};return In(await e._zod.run({value:t,issues:[]},n),n)}function Rn(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return In(r,n)}catch{}return Ln(e,t)},vendor:`zod`,version:1}}var zn=_(`$ZodString`,(e,t)=>{Fn.init(e,t),e._zod.pattern=t.pattern??sn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),Bn=_(`$ZodStringFormat`,(e,t)=>{Tn.init(e,t),zn.init(e,t)}),Vn=_(`$ZodGUID`,(e,t)=>{t.pattern??=Vt,Bn.init(e,t)}),Hn=_(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Ht(e)}else t.pattern??=Ht();Bn.init(e,t)}),Un=_(`$ZodEmail`,(e,t)=>{t.pattern??=Ut,Bn.init(e,t)});function Wn(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function Gn(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?Wn(e)||2:Kn(e,t)}function Kn(e,t){if(!t.normalize&&t.protocol?.source===Qt.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}var qn=/[\t\n\r]/g;function Jn(e){return e.replace(qn,``)}function Yn(e,t){return t.lastIndex=0,t.test(e.hostname)}function Xn(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}var Zn=_(`$ZodURL`,(e,t)=>{Bn.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=Gn(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=Jn(r);return}t.hostname&&!Yn(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!Xn(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:Jn(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Qn=_(`$ZodEmoji`,(e,t)=>{t.pattern??=Gt(),Bn.init(e,t)}),$n=_(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?Rt:zt(t.length),Bn.init(e,t)}),er=_(`$ZodCUID`,(e,t)=>{t.pattern??=Nt,Bn.init(e,t)}),tr=_(`$ZodCUID2`,(e,t)=>{t.pattern??=Pt,Bn.init(e,t)}),nr=_(`$ZodULID`,(e,t)=>{t.pattern??=Ft,Bn.init(e,t)}),rr=_(`$ZodXID`,(e,t)=>{t.pattern??=It,Bn.init(e,t)}),ir=_(`$ZodKSUID`,(e,t)=>{t.pattern??=Lt,Bn.init(e,t)}),ar=_(`$ZodISODateTime`,(e,t)=>{t.pattern??=on(t),Bn.init(e,t)}),or=_(`$ZodISODate`,(e,t)=>{t.pattern??=nn,Bn.init(e,t)}),sr=_(`$ZodISOTime`,(e,t)=>{t.pattern??=an(t),Bn.init(e,t)}),cr=_(`$ZodISODuration`,(e,t)=>{t.pattern??=Bt,Bn.init(e,t)}),lr=_(`$ZodIPv4`,(e,t)=>{t.pattern??=Kt,Bn.init(e,t)}),ur=/^[0-9a-fA-F:.]+$/;function dr(e){return ur.test(e)?Wn(`http://[${e}]`):!1}var fr=_(`$ZodIPv6`,(e,t)=>{t.pattern??=qt,Bn.init(e,t),e._zod.check=n=>{dr(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),pr=_(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Jt,Bn.init(e,t)});function mr(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:dr(n)}var hr=_(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Yt,Bn.init(e,t),e._zod.check=n=>{mr(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function gr(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var _r=/^[0-9a-zA-Z+/]*={0,2}$/,vr=_(`$ZodBase64`,(e,t)=>{t.pattern??=_r,Bn.init(e,t),e._zod.check=n=>{gr(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),yr=/^[A-Za-z0-9_-]*$/;function br(e){if(!yr.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return gr(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var xr=_(`$ZodBase64URL`,(e,t)=>{t.pattern??=yr,Bn.init(e,t),e._zod.check=n=>{br(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Sr=_(`$ZodE164`,(e,t)=>{t.pattern??=$t,Bn.init(e,t)});function Cr(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var wr=_(`$ZodJWT`,(e,t)=>{Bn.init(e,t),e._zod.check=n=>{Cr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Tr=_(`$ZodNumber`,(e,t)=>{Fn.init(e,t),e._zod.pattern=un,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Er=_(`$ZodNumberFormat`,(e,t)=>{xn.init(e,t),Tr.init(e,t)}),Dr=_(`$ZodBoolean`,(e,t)=>{Fn.init(e,t),e._zod.pattern=dn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Or=_(`$ZodNull`,(e,t)=>{Fn.init(e,t),e._zod.pattern=fn,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),kr=_(`$ZodAny`,(e,t)=>{Fn.init(e,t),e._zod.parse=e=>e}),Ar=_(`$ZodUnknown`,(e,t)=>{Fn.init(e,t),e._zod.parse=e=>e}),jr=_(`$ZodNever`,(e,t)=>{Fn.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Mr(e,t){let n=Ae(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of Ae(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,je(n.issues,t,e),n}}return i(n,a)}}var Nr=e=>Array.isArray(e)?e.length:-1;function Pr(e,t,n){e.issues.length&&t.issues.push(...Oe(n,e.issues)),t.value[n]=e.value}var Fr=_(`$ZodArray`,(e,t)=>{Fn.init(e,t);let n=rt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>Pr(t,r,e)));else if(Pr(c,r,e),s&&c.issues.length!==0&&Ee(c))break}return o.length?Promise.all(o).then(()=>r):r},Mr(e,Nr)});function Ir(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...Oe(n,e.issues))}!o&&i===void 0?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}var Lr=[];function Rr(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Lr,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=me(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function zr(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(Ee(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Ir(e,n,i,t,d,f))):Ir(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var Br=_(`$ZodObject`,(e,t)=>{Fn.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let a=i(()=>Rr(t));qe(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||u(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let o=ae,s=t.catchall,c,l=rt.memoizer;l?.attach(e),e._zod.parse=(t,n)=>{c??=a.value;let r=t.value;if(!o(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=l?l.alloc(e,t,{},n):{};let i=[],u=c.shape,d=n?.abortEarly,f=t.issues.length;for(let e of c.allKeys){if(d&&t.issues.length!==f){if(Ee(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let a=u[e],o=a._zod.optin,s=a._zod.optout,c=a._zod.run({value:r[e],issues:[]},n);c instanceof Promise?i.push(c.then(n=>Ir(n,t,e,r,o,s))):Ir(c,t,e,r,o,s)}return s?zr(i,r,t,n,a.value,e,d===!0):i.length?Promise.all(i).then(()=>t):t}}),Vr=_(`$ZodObjectJIT`,(e,t)=>{Br.init(e,t);let n=e._zod.parse,r=i(()=>Rr(t)),a=rt.memoizer,o=t=>{let n=r.value,i=n.symbolKeys,o=new Nn([`payload`,`ctx`],{shape:t,inst:e,memo:a,syms:i}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
4
+ let ${e}_ab = false;
5
+ for (let i = 0; i < ${e}.issues.length; i++) {
6
+ const iss = ${e}.issues[i];
7
+ iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
8
+ payload.issues.push(iss);
9
+ if (iss.continue !== true) ${e}_ab = true;
10
+ }
11
+ if (${e}_ab && ctx && ctx.abortEarly) {
12
+ payload.value = newResult;
13
+ return payload;
14
+ }`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(a?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${i.indexOf(e)}]`:ne(e),a=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
15
+ const ${n}_present = ${a};
16
+ if (!${n}.issues.length || ${n}_present) {
17
+ if (${n}.issues.length) {${c(n,r)}
18
+ }
19
+
20
+ if (${e}) {
21
+ newResult[${r}] = ${n}.value;
22
+ }
23
+ }
24
+
25
+ `)}else f?(o.write(`
26
+ if (${n}.issues.length) {${c(n,r)}
27
+ }
28
+ `),d===`defaulted`?o.write(`newResult[${r}] = ${n}.value;`):o.write(`
29
+ if (${n}.value !== undefined || ${a}) {
30
+ newResult[${r}] = ${n}.value;
31
+ }
32
+ `)):o.write(`
33
+ const ${n}_present = ${a};
34
+ if (${n}.issues.length) {${c(n,r)}
35
+ }
36
+ if (!${n}_present && !${n}.issues.length) {
37
+ payload.issues.push({
38
+ code: "invalid_type",
39
+ expected: "nonoptional",
40
+ input: undefined,
41
+ path: [${r}]
42
+ });
43
+ if (ctx && ctx.abortEarly) {
44
+ payload.value = newResult;
45
+ return payload;
46
+ }
47
+ }
48
+
49
+ if (${n}_present) {
50
+ newResult[${r}] = ${n}.value;
51
+ }
52
+
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
+
55
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function io(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;io(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ao=new Set([`type`,`properties`,`required`,`additionalProperties`]),oo=[`oneOf`,`anyOf`];function so(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function co(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ao.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??so(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}u(n,r,e.length===1?e[0]:co(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=so(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function lo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ao)if(t in e)return;let n=t.filter(e=>oo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=co(t);else{let e=n[0],i=oo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>co([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Qa(e,r))}function uo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Qa(i,s),Qa(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())io(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])lo(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Qa(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,u(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:mo(t,`input`,e.processors),output:mo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function fo(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return fo(r.element,n);if(r.type===`set`)return fo(r.valueType,n);if(r.type===`lazy`)return fo(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return fo(r.innerType,n);if(r.type===`intersection`)return fo(r.left,n)||fo(r.right,n);if(r.type===`record`||r.type===`map`)return fo(r.keyType,n)||fo(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:fo(r.in,n)||fo(r.out,n);if(r.type===`object`){for(let e in r.shape)if(fo(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(fo(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(fo(e,n))return!0;return!!(r.rest&&fo(r.rest,n))}return!1}var po=(e,t={})=>n=>{let r=$a({...n,processors:t});return to(e,r),ro(r,e),uo(r,e)},mo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=$a({...i??{},target:a,io:t,processors:n});return to(e,o),ro(o,e),uo(o,e)},ho=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},go=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},_o=(e,t)=>{ho(e,`minimum`,t),go(e,`maximum`,t)},vo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},yo=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},bo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},xo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},So=(e,t)=>ho(e,`minimum`,t.minimum),Co=(e,t)=>go(e,`maximum`,t.maximum),wo=e=>(t,n)=>{xo(t,n.format);let[r,i]=e[n.format];ho(t,`minimum`,r),go(t,`maximum`,i)},To={greater_than:(e,t)=>ho(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>go(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>vo(e,t.value),number_format:wo(he),bigint_format:wo(ge),min_length:So,max_length:Co,length_equals:(e,t)=>_o(e,t.length),min_size:So,max_size:Co,size_equals:(e,t)=>_o(e,t.size),string_format:(e,t)=>{xo(e,t.format),t.pattern&&yo(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>bo(e,t.mime)};function Eo(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)To[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&ho(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&ho(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&go(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&go(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&vo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&bo(t,i.mime);for(let e of i.patterns??[])yo(t,e);return t}var Do={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Oo=new Map([[_r,Xt],[yr,Zt]]),ko=e=>Oo.get(e)??e,Ao=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=Eo(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Do[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(ko);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},jo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Eo(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):eo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Mo=(e,t,n,r)=>{n.type=`boolean`},No=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Po=(e,t,n,r)=>{n.not={}},Fo=(t,n,r,i)=>{let a=t._zod.def,o=e(a.entries);o.length===0?r.not={}:(o.every(e=>typeof e==`number`)&&(r.type=`number`),o.every(e=>typeof e==`string`)&&(r.type=`string`),r.enum=o)},Io=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(eo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(eo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Lo=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Ro=(e,t,n,r)=>{eo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},zo=(e,t,n,r)=>{eo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Bo=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=Eo(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=to(a.element,t,{...r,path:[...r.path,`items`]})};function Vo(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Vo(t.out):t.type===`catch`?Vo(t.innerType):e._zod.optin}var Ho=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&eo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)u(i.properties,e,to(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Vo(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=to(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Uo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>to(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Wo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=to(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},Go=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>to(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?to(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?Vo(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=Eo(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function Ko(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Ko(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Ko(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?un:ln).source)),p}var qo=new WeakMap;function Jo(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of qo.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Ko(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var Yo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=Eo(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=to(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)u(i.patternProperties,ko(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=to(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=qo.get(t);n||(n=[],qo.set(t,n),t.deferred.push(()=>Jo(t))),n.push(e)}i.additionalProperties=to(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Vo(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Xo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Zo=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Qo=Symbol();function $o(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(eo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Qo):JSON.parse(o)}var es=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n.default=o)},ts=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n._prefault=o)},ns=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{eo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},rs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;to(o,t,r);let s=t.seen.get(e);s.ref=o},is=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},as=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},os=(e,t,n,r)=>{let i=e._zod.innerType;to(i,t,r);let a=t.seen.get(e);a.ref=i},ss=new WeakSet([Object.prototype,Error.prototype]);function cs(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var ls=_(`ZodError`,(e,t)=>{ut.init(e,t),e.name=`ZodError`;let r=Object.getPrototypeOf(e);ss.has(r)||(ss.add(r),cs(r,`format`,e=>t=>pt(e,t)),cs(r,`flatten`,e=>t=>ft(e,t)),cs(r,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,n,2)}),cs(r,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,n,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),us=ht(ls),ds=gt(ls),fs=_t(ls),ps=yt(ls),ms=Tt(ls),hs=Et(ls),gs=Dt(ls),_s=Ot(ls),vs=kt(ls),ys=At(ls),bs=jt(ls),xs=Mt(ls);function Ss(){rt.localeError||it(Hi())}function Cs(){rt.memoizer||it({memoizer:zi()})}var ws=_(`ZodType`,(e,t)=>(Ss(),Fn.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(te(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return fe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Yc(e,t))},superRefine(e,t){return this.check(Xc(e,t))},overwrite(e){return this.check(Va(e))},optional(){return Ec(this)},exactOptional(){return Oc(this)},nullable(){return Ac(this)},nullish(){return Ec(Ac(this))},nonoptional(e){return Ic(this,e)},array(){return x(this)},or(e){return C([this,e])},and(e){return gc(this,e)},transform(e){return Bc(this,wc(e))},default(e){return Mc(this,e)},prefault(e){return Pc(this,e)},catch(e){return Rc(this,e)},pipe(e){return Bc(this,e)},readonly(){return Hc(this)},describe(e){let t=this.clone();return Ki.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ki.get(this);let t=this.clone();return Ki.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Be(this,`~standard`,{...Rn(this),jsonSchema:{input:mo(this,`input`),output:mo(this,`output`)}})},set"~standard"(e){ze(this,`~standard`,e)},parse:function e(t,n){return us(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await ds(this,t,n,{callee:e})},safeParse(e,t){return fs(this,e,t)},async safeParseAsync(e,t){return ps(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){ze(this,`spa`,e)},validate(e,t){return St(this,e,t)},validateAsync(e,t){return wt(this,e,t)},encode:function e(t,n){return ms(this,t,n,{callee:e})},decode:function e(t,n){return hs(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await gs(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await _s(this,t,n,{callee:e})},safeEncode(e,t){return vs(this,e,t)},safeDecode(e,t){return ys(this,e,t)},async safeEncodeAsync(e,t){return bs(this,e,t)},async safeDecodeAsync(e,t){return xs(this,e,t)},toJSONSchema(e){return po(this,{})(e)},get description(){return Ki.get(this)?.description},get _def(){return this._zod.def}}),Ts=_(`_ZodString`,(e,t)=>{zn.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r)},Ve({format:e=>Eo(e).format??null,minLength:e=>Eo(e).minimum??null,maxLength:e=>Eo(e).maximum??null},{regex(...e){return this.check(Fa(...e))},includes(...e){return this.check(Ra(...e))},startsWith(...e){return this.check(za(...e))},endsWith(...e){return this.check(Ba(...e))},min(...e){return this.check(Na(...e))},max(...e){return this.check(Ma(...e))},length(...e){return this.check(Pa(...e))},nonempty(...e){return this.check(Na(1,...e))},lowercase(e){return this.check(Ia(e))},uppercase(e){return this.check(La(e))},trim(){return this.check(Ua())},normalize(...e){return this.check(Ha(...e))},toLowerCase(){return this.check(Wa())},toUpperCase(){return this.check(Ga())},slugify(){return this.check(Ka())}})),Es=_(`ZodString`,(e,t)=>{zn.init(e,t),Ts.init(e,t)},{email(e){return this.check(Yi(Ms,e))},url(e){return this.check(ta(Is,e))},jwt(e){return this.check(ga(Qs,e))},emoji(e){return this.check(na(Rs,e))},guid(e){return this.check(Xi(Ps,e))},uuid(e){return this.check(Zi(Fs,e))},uuidv4(e){return this.check(Qi(Fs,e))},uuidv6(e){return this.check($i(Fs,e))},uuidv7(e){return this.check(ea(Fs,e))},nanoid(e){return this.check(ra(zs,e))},cuid(e){return this.check(ia(Bs,e))},cuid2(e){return this.check(aa(Vs,e))},ulid(e){return this.check(oa(Hs,e))},base64(e){return this.check(pa(Ys,e))},base64url(e){return this.check(ma(Xs,e))},xid(e){return this.check(sa(Us,e))},ksuid(e){return this.check(ca(Ws,e))},ipv4(e){return this.check(la(Gs,e))},ipv6(e){return this.check(ua(Ks,e))},cidrv4(e){return this.check(da(qs,e))},cidrv6(e){return this.check(fa(Js,e))},e164(e){return this.check(ha(Zs,e))},datetime(e){return this.check(_a(Os,e))},date(e){return this.check(va(ks,e))},time(e){return this.check(ya(As,e))},duration(e){return this.check(ba(js,e))}});function v(e){return Ji(Es,e)}var Ds=_(`ZodStringFormat`,(e,t)=>{Bn.init(e,t),Ts.init(e,t)}),Os=_(`ZodISODateTime`,(e,t)=>{ar.init(e,t),Ds.init(e,t)}),ks=_(`ZodISODate`,(e,t)=>{or.init(e,t),Ds.init(e,t)}),As=_(`ZodISOTime`,(e,t)=>{sr.init(e,t),Ds.init(e,t)}),js=_(`ZodISODuration`,(e,t)=>{cr.init(e,t),Ds.init(e,t)}),Ms=_(`ZodEmail`,(e,t)=>{Un.init(e,t),Ds.init(e,t)});function Ns(e){return Yi(Ms,e)}var Ps=_(`ZodGUID`,(e,t)=>{Vn.init(e,t),Ds.init(e,t)}),Fs=_(`ZodUUID`,(e,t)=>{Hn.init(e,t),Ds.init(e,t)}),Is=_(`ZodURL`,(e,t)=>{Zn.init(e,t),Ds.init(e,t)});function Ls(e){return ta(Is,e)}var Rs=_(`ZodEmoji`,(e,t)=>{Qn.init(e,t),Ds.init(e,t)}),zs=_(`ZodNanoID`,(e,t)=>{$n.init(e,t),Ds.init(e,t)}),Bs=_(`ZodCUID`,(e,t)=>{er.init(e,t),Ds.init(e,t)}),Vs=_(`ZodCUID2`,(e,t)=>{tr.init(e,t),Ds.init(e,t)}),Hs=_(`ZodULID`,(e,t)=>{nr.init(e,t),Ds.init(e,t)}),Us=_(`ZodXID`,(e,t)=>{rr.init(e,t),Ds.init(e,t)}),Ws=_(`ZodKSUID`,(e,t)=>{ir.init(e,t),Ds.init(e,t)}),Gs=_(`ZodIPv4`,(e,t)=>{lr.init(e,t),Ds.init(e,t)}),Ks=_(`ZodIPv6`,(e,t)=>{fr.init(e,t),Ds.init(e,t)}),qs=_(`ZodCIDRv4`,(e,t)=>{pr.init(e,t),Ds.init(e,t)}),Js=_(`ZodCIDRv6`,(e,t)=>{hr.init(e,t),Ds.init(e,t)}),Ys=_(`ZodBase64`,(e,t)=>{vr.init(e,t),Ds.init(e,t)}),Xs=_(`ZodBase64URL`,(e,t)=>{xr.init(e,t),Ds.init(e,t)}),Zs=_(`ZodE164`,(e,t)=>{Sr.init(e,t),Ds.init(e,t)}),Qs=_(`ZodJWT`,(e,t)=>{wr.init(e,t),Ds.init(e,t)}),$s=_(`ZodNumber`,(e,t)=>{Tr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jo(e,t,n,r),e.isFinite=!0},Ve({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Eo(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Eo(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=Eo(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Eo(e).format??null},{gt(e,t){return this.check(ka(e,t))},gte(e,t){return this.check(Aa(e,t))},min(e,t){return this.check(Aa(e,t))},lt(e,t){return this.check(Da(e,t))},lte(e,t){return this.check(Oa(e,t))},max(e,t){return this.check(Oa(e,t))},int(e){return this.check(tc(e))},safe(e){return this.check(tc(e))},positive(e){return this.check(ka(0,e))},nonnegative(e){return this.check(Aa(0,e))},negative(e){return this.check(Da(0,e))},nonpositive(e){return this.check(Oa(0,e))},multipleOf(e,t){return this.check(ja(e,t))},step(e,t){return this.check(ja(e,t))},finite(){return this}}));function y(e){return xa($s,e)}var ec=_(`ZodNumberFormat`,(e,t)=>{Er.init(e,t),$s.init(e,t)});function tc(e){return Sa(ec,e)}var nc=_(`ZodBoolean`,(e,t)=>{Dr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mo(e,t,n,r)});function b(e){return Ca(nc,e)}var rc=_(`ZodNull`,(e,t)=>{Or.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>No(e,t,n,r)});function ic(e){return wa(rc,e)}var ac=_(`ZodAny`,(e,t)=>{kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0}),oc=_(`ZodUnknown`,(e,t)=>{Ar.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function sc(){return Ta(oc)}var cc=_(`ZodNever`,(e,t)=>{jr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Po(e,t,n,r)});function lc(e){return Ea(cc,e)}var uc=_(`ZodArray`,(e,t)=>{Cs(),Fr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Na(e,t))},nonempty(e){return this.check(Na(1,e))},max(e,t){return this.check(Ma(e,t))},length(e,t){return this.check(Pa(e,t))},unwrap(){return this.element}});function x(e,t){return qa(uc,e,t)}var dc=_(`ZodObject`,(e,t)=>{Cs(),Vr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ho(e,t,n,r),Je(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return E(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(te(this._zod.def,{catchall:e}))},passthrough(){return this.clone(te(this._zod.def,{catchall:sc()}))},loose(){return this.clone(te(this._zod.def,{catchall:sc()}))},strict(){return this.clone(te(this._zod.def,{catchall:lc()}))},strip(){return this.clone(te(this._zod.def,{catchall:void 0}))},extend(e){return be(this,e)},safeExtend(e){return Se(this,e)},merge(e){return Ce(this,e)},pick(e){return _e(this,e)},omit(e){return ye(this,e)},partial(...e){return we(Tc,this,e[0])},exactPartial(...e){return we(Dc,this,e[0],`exactPartial`)},required(...e){return Te(Fc,this,e[0])}});function S(e,t){return new dc({type:`object`,shape:e??{},...g(t)})}function fc(e,t){return new dc({type:`object`,shape:e,catchall:sc(),...g(t)})}var pc=_(`ZodUnion`,(e,t)=>{Ur.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uo(e,t,n,r),e.options=t.options});function C(e,t){return new pc({type:`union`,options:e,...g(t)})}var mc=_(`ZodDiscriminatedUnion`,(e,t)=>{pc.init(e,t),Gr.init(e,t)});function w(e,t,n){return new mc({type:`union`,options:t,discriminator:e,...g(n)})}var hc=_(`ZodIntersection`,(e,t)=>{Kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wo(e,t,n,r)});function gc(e,t){return new hc({type:`intersection`,left:e,right:t})}var _c=_(`ZodTuple`,(e,t)=>{Cs(),Yr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Go(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Tc({type:`optional`,innerType:e}))})}});function vc(e,t,n){let r=t instanceof Fn;return new _c({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}var yc=_(`ZodRecord`,(e,t)=>{Cs(),$r.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function T(e,t,n){return!t||!t._zod?new yc({type:`record`,keyType:v(),valueType:e,...g(t)}):new yc({type:`record`,keyType:e,valueType:t,...g(n)})}function bc(e,t,n){return new yc({type:`record`,keyType:e,valueType:t,...g(n),partial:!0})}var xc=_(`ZodEnum`,(e,t)=>{ei.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})}});function E(e,t){return new xc({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...g(t)})}var Sc=_(`ZodLiteral`,(e,t)=>{ti.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Io(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function D(e,t){return new Sc({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}var Cc=_(`ZodTransform`,(e,t)=>{Cs(),ni.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zo(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Le(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Le(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function wc(e){return new Cc({type:`transform`,transform:e})}var Tc=_(`ZodOptional`,(e,t)=>{ii.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ec(e){return new Tc({type:`optional`,innerType:e})}var Dc=_(`ZodExactOptional`,(e,t)=>{ai.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Oc(e){return new Dc({type:`optional`,innerType:e})}var kc=_(`ZodNullable`,(e,t)=>{oi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ac(e){return new kc({type:`nullable`,innerType:e})}var jc=_(`ZodDefault`,(e,t)=>{si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mc(e,t){return new jc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Nc=_(`ZodPrefault`,(e,t)=>{li.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pc(e,t){return new Nc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Fc=_(`ZodNonOptional`,(e,t)=>{ui.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e,t){return new Fc({type:`nonoptional`,innerType:e,...g(t)})}var Lc=_(`ZodCatch`,(e,t)=>{pi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Rc(e,t){return new Lc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Xe(t)})}var zc=_(`ZodPipe`,(e,t)=>{mi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),e.in=t.in,e.out=t.out});function Bc(e,t){return new zc({type:`pipe`,in:e,out:t})}var Vc=_(`ZodReadonly`,(e,t)=>{gi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e){return new Vc({type:`readonly`,innerType:e})}var Uc=_(`ZodTemplateLiteral`,(e,t)=>{bi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lo(e,t,n,r)});function Wc(e,t){return new Uc({type:`template_literal`,parts:e,...g(t)})}var Gc=_(`ZodLazy`,(e,t)=>{xi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Kc(e){return new Gc({type:`lazy`,getter:e})}var qc=_(`ZodCustom`,(e,t)=>{Si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ro(e,t,n,r)});function Jc(e,t){return Ja(qc,e??(()=>!0),t)}function Yc(e,t={}){return Ya(qc,e,t)}function Xc(e,t){return Xa(e,t)}function Zc(e){let t=Kc(()=>C([v(e),y(),b(),ic(),x(t),T(v(),t)]));return t}var O=Zc(),Qc=T(v(),O);function $c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var el={run:`run`,turn:`trn`,session:`ses`,actor:`act`,message:`msg`,delivery:`dlv`,handlerCall:`hcl`,llmInteraction:`llm`,pairing:`par`,pairingToken:`ptk`,policy:`pol`,approval:`apr`,budget:`bgt`,priorityRule:`pri`,reservation:`rsv`,ledger:`led`,notification:`ntf`,push:`psh`,secret:`sec`,modelCategory:`mct`,provider:`prv`,sectionRule:`srl`,authSession:`aus`,modelCall:`mdl`,mcp:`mcp`,autoPair:`apk`,connection:`cnx`,fnExample:`fex`,refusal:`rfs`,record:`rec`,mentionRequest:`mrq`},tl=e=>v().regex(RegExp(`^${el[e]}_.+$`),`expected a ${e} id starting with "${el[e]}_"`).brand().describe(`${e} id`),nl=e=>Object.hasOwn(el,e);function rl(){return Object.fromEntries(Object.keys(el).filter(nl).map(e=>[e,tl(e)]))}var k=v().regex(/^[A-Za-z_][A-Za-z0-9_.-]*$/),il=rl(),A=il.run,al=il.turn,j=il.session,M=il.actor,ol=il.message,sl=il.delivery,cl=il.handlerCall,ll=il.llmInteraction,ul=il.pairing,dl=il.pairingToken,fl=il.policy,pl=il.approval,ml=il.budget,hl=il.priorityRule,gl=il.reservation,_l=il.ledger,vl=il.notification,yl=il.push,bl=il.secret,xl=il.modelCategory,Sl=il.provider,Cl=il.sectionRule,wl=il.authSession,Tl=il.modelCall,El=il.mcp,Dl=il.autoPair,Ol=il.connection,kl=y().int().min(0),N=y().int(),P=y(),Al=/^[a-z][a-z0-9-]*$/,F=v().regex(Al).brand(),I=Wc([v().regex(Al),`/`,v().min(1)]),jl=C([D(`native`),I]);function Ml(e,t){return`${e}/${t}`}function Nl(e){let t=e.indexOf(`/`);return{system:e.slice(0,t),local:e.slice(t+1)}}var Pl=[`urgent`,`interactive`,`normal`,`background`],Fl=E(Pl),Il=E([`user`,`llm`,`both`,`none`]),Ll=E([`user`,`group`,`agent`,`system`,`mcp`]),Rl=e=>S({items:x(e),cursor:v().optional()}),zl=S({cursor:v().optional(),limit:y().int().min(1).max(200).optional()});function Bl(e){return e instanceof Error?e.message:String(e)}var Vl=`read`,Hl=`admin`,L=v().regex(Al).brand(),Ul=L.parse(`main`),Wl=S({system:F,instance:L}),Gl=v().regex(/^[a-z*][a-z0-9*-]*\/[A-Za-z0-9_.*-]+$/).brand(),Kl=Object.defineProperty,ql=(e,t)=>{for(var n in t)Kl(e,n,{get:t[n],enumerable:!0})},R={};ql(R,{array:()=>dp,boolean:()=>rp,codec:()=>Tp,conditional:()=>vp,declare:()=>Op,default:()=>xp,define:()=>Dp,dependent:()=>yp,discriminatedUnion:()=>hp,dispatch:()=>Ep,enum:()=>op,fromJSONSchema:()=>Qf,int:()=>np,intersection:()=>gp,json:()=>lp,literal:()=>ap,module:()=>kp,never:()=>sp,not:()=>_p,null:()=>ip,nullable:()=>Sp,number:()=>tp,object:()=>up,optional:()=>bp,record:()=>pp,ref:()=>Cp,refOf:()=>wp,string:()=>ep,tuple:()=>fp,union:()=>mp,unknown:()=>cp});var Jl=Object.freeze({length:!0,range:!0,items:`all`,pattern:`full`}),Yl=Object.freeze({length:!1,range:!1,items:`none`,pattern:`none`}),Xl=Object.freeze({id:`lenient`,family:`lenient`,strict:!1,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!0,conditionals:!0,patternProperties:!0,defs:!0,recursion:!0,any:`empty`,constraints:Jl,formats:`all`,examples:`keyword`,propertyOrdering:!1,rootObject:!1}),Zl=Object.freeze({...Xl,id:`people`,family:`people`,audience:`people`}),Ql=Object.freeze({...Xl,id:`openai`,family:`openai`,rootObject:!0,request:Object.freeze({maxTools:128})}),$l=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`ipv4`,`ipv6`,`uuid`]),eu=Object.freeze({id:`openai-strict`,family:`openai`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`anyOf`,nulls:`anyOf`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,refSiblings:!1,recursion:!0,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:$l,examples:`description`,propertyOrdering:!1,maxDepth:10,rootObject:!0,limits:Object.freeze({maxProperties:5e3,maxDepth:10,maxStringChars:12e4,maxEnumValues:1e3,largeEnumValues:250,maxLargeEnumChars:15e3}),request:Object.freeze({maxTools:128}),loose:Ql}),tu=Object.freeze({...eu,id:`openai-finetuned-strict`,constraints:Yl,formats:new Set}),nu=Object.freeze({...Xl,id:`anthropic`,family:`anthropic`,rootObject:!0}),ru=Object.freeze({id:`anthropic-strict`,family:`anthropic`,strict:!0,optional:`omit`,closedObjects:!0,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!1,range:!1,items:`min-0-1`,pattern:`basic`}),formats:new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]),examples:`description`,propertyOrdering:!1,rootObject:!0,request:Object.freeze({maxStrictTools:20,totals:Object.freeze({maxOptional:24,maxUnions:16})}),loose:nu,alwaysStrictOutput:!0}),iu=`Return ONLY a single raw JSON object that conforms to the schema above. Do NOT wrap it in markdown code fences, do NOT add any prose before or after it, and do NOT echo the schema itself: emit only the JSON instance.`,au=Object.freeze({...Xl,id:`google`,family:`google`,recursion:`guarded`,maxEnumValues:40,rootObject:!0,jsonInstruction:iu}),ou=Object.freeze({id:`google-strict`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:`guarded`,any:`empty`,constraints:Object.freeze({length:!1,range:!0,items:`all`,pattern:`none`}),formats:new Set([`date-time`,`date`,`time`]),examples:`description`,propertyOrdering:!1,maxEnumValues:40,rootObject:!0,loose:au,jsonInstruction:iu}),su=Object.freeze({id:`google-openapi`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`nullable`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:new Set([`date-time`,`date`,`time`,`duration`]),examples:`description`,propertyOrdering:!0,maxEnumValues:40,maxDepth:10,rootObject:!0,loose:au,jsonInstruction:iu}),cu=new Set([`date`,`time`,`date-time`,`email`,`uuid`,`ipv4`,`ipv6`,`uri`]),lu=Object.freeze({id:`xai-strict`,family:`xai`,strict:!0,optional:`omit`,closedObjects:!0,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`flat`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:cu,examples:`description`,propertyOrdering:!1,rootObject:!0}),uu=Object.freeze({...lu,id:`xai`,strict:!1}),du=Object.freeze({...Xl,id:`ollama`,family:`ollama`,rootObject:!0}),fu=Object.freeze({id:`minimal`,family:`minimal`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`tagged`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Yl,formats:new Set,examples:`description`,propertyOrdering:!1,maxDepth:6,maxEnumValues:8,rootObject:!0}),pu=new Map,mu=new Map;function hu(e){pu.set(e.id,e);let t=mu.get(e.family)??{};e.strict?t.strict??=e:t.loose??=e,mu.set(e.family,t)}for(let e of[Xl,Zl,Ql,eu,tu,nu,ru,au,ou,su,lu,uu,du,fu])hu(e);var gu=new WeakMap;function _u(e){let t=gu.get(e);return t||(t=Object.freeze({profile:e,records:e.records,optional:e.optional,recordWord:e.records===`pairs`?`a list of {key, value} entries`:`an object`}),gu.set(e,t)),t}Object.freeze({properties:0,depth:0,stringChars:0,enumValues:0,enums:Object.freeze([]),optional:0,unions:0});function vu(e){let t=0,n=0,r=0,i=0,a=0,o=[],s=e.$defs??{};for(let e of Object.keys(s))n+=e.length;let c=e=>{if(!e||typeof e!=`object`)return;if(Array.isArray(e)){for(let t of e)c(t);return}let s=e;if(s.properties&&typeof s.properties==`object`){let e=s.properties,r=new Set(Array.isArray(s.required)?s.required:[]);for(let[a,o]of Object.entries(e))t++,n+=a.length,r.has(a)||i++,c(o)}if(Array.isArray(s.enum)){let e=0;for(let t of s.enum)typeof t==`string`&&(e+=t.length);r+=s.enum.length,n+=e,o.push({values:s.enum.length,chars:e})}typeof s.const==`string`&&(n+=s.const.length);let l=s.anyOf??s.oneOf;(Array.isArray(l)&&l.length>1||Array.isArray(s.type)&&s.type.length>1)&&a++;for(let e of[`items`,`prefixItems`,`anyOf`,`oneOf`,`allOf`,`additionalProperties`,`not`,`if`,`then`,`else`])e in s&&c(s[e]);if(s.patternProperties&&typeof s.patternProperties==`object`)for(let e of Object.values(s.patternProperties))c(e)},{$defs:l,...u}=e;c(u);for(let e of Object.values(s))c(e);let d=e=>{if(typeof e.$ref==`string`)return/^#\/\$defs\/(.+)$/.exec(e.$ref)?.[1]?.replace(/~1/g,`/`).replace(/~0/g,`~`)},f=yu(s,d),p=new Set,m=new Map,h=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e;if(typeof t.$ref==`string`){let e=d(t);if(!e||p.has(e)||!s[e])return 0;let n=f.get(e),r=e;if(n){r+=`|`;for(let e of n)r+=p.has(e)?`1`:`0`}let i=m.get(r);if(i!==void 0)return i;p.add(e);let a=h(s[e]);return p.delete(e),m.set(r,a),a}let n=t.type===`object`||t.type===`array`||Array.isArray(t.type)&&(t.type.includes(`object`)||t.type.includes(`array`)),r=0,i=e=>{let t=h(e);t>r&&(r=t)};if(t.properties&&typeof t.properties==`object`)for(let e of Object.values(t.properties))i(e);for(let e of[`items`,`additionalProperties`,`not`])e in t&&i(t[e]);for(let e of[`prefixItems`,`anyOf`,`oneOf`,`allOf`])if(Array.isArray(t[e]))for(let n of t[e])i(n);return+!!n+r},ee=h(u);return{properties:t,depth:ee,stringChars:n,enumValues:r,enums:o,optional:i,unions:a}}function yu(e,t){let n=new Map,r=(n,i)=>{if(!n||typeof n!=`object`)return;if(Array.isArray(n)){for(let e of n)r(e,i);return}let a=t(n);a!==void 0&&e[a]&&i.add(a);for(let e of Object.values(n))r(e,i)};for(let t of Object.keys(e)){let i=new Set;r(e[t],i),n.set(t,[...i])}let i=new Map,a=new Map,o=new Set,s=[],c=new Map,l=0;for(let e of n.keys()){if(i.has(e))continue;let t=[[e,0]];for(;t.length;){let e=t[t.length-1],[r,u]=e;u===0&&(i.set(r,l),a.set(r,l),l++,s.push(r),o.add(r));let d=n.get(r);if(u<d.length){e[1]++;let n=d[u];i.has(n)?o.has(n)&&a.set(r,Math.min(a.get(r),i.get(n))):t.push([n,0]);continue}t.pop();let f=t[t.length-1];if(f&&a.set(f[0],Math.min(a.get(f[0]),a.get(r))),a.get(r)===i.get(r)){let e=[],t;do t=s.pop(),o.delete(t),e.push(t);while(t!==r);if(e.length>1||d.includes(r))for(let t of e)c.set(t,e)}}}return c}var bu=class extends Error{constructor(e){super(`@aeye/schema: ${e}`),this.name=`SchemaDefinitionError`}},xu=class extends Error{constructor(e,t=Vd(e)){super(t),this.issues=e,this.name=`SchemaParseError`}issues};function Su(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function Cu(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function wu(e,t,n=Cu(e.length)){let r=e.toLowerCase(),i=[];for(let a=0;a<t.length;a++){let o=t[a];if(Math.abs(o.length-e.length)>n)continue;let s=Su(r,o.toLowerCase());s<=n&&i.push({candidate:o,index:a,ci:s,exact:Su(e,o)})}return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function Tu(e,t,n){return wu(e,t,n)[0]}var Eu=Object.freeze({detail:`full`,maxErrors:5,maxChars:2e3,suggestions:!0,context:3,depth:6,header:!0});function Du(...e){let t;for(let n of e)n!==void 0&&(t={...t,...ku(typeof n==`string`?{detail:n}:n)});return t}function Ou(...e){let t=Du(...e)??{},n=t.detail??Eu.detail;return{...Eu,...t,detail:n,expected:t.expected??n===`full`}}function ku(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Au(e){let t=typeof e==`string`?e:e?.detail??Eu.detail;return t===`markers`||t===`full`}var ju=new WeakMap;function Mu(e,t){ju.set(e,t)}function Nu(e,t,n){for(let r=t;r<e.length;r++){let t=ju.get(e[r]);t&&!t.node&&(t.node=n)}}var Pu=/^[A-Za-z_$][\w$]*$/;function Fu(e){let t=``,n=``;for(let r of e)r===`(json)`?(t+=`${n||`(root)`} \u2192 JSON text \u2192 `,n=``):n+=typeof r==`number`?`[${r}]`:Pu.test(r)?n?`.${r}`:r:`[${JSON.stringify(r)}]`;return t&&!n?t.slice(0,-3):t+(n||(t?``:`(root)`))}var Iu=Symbol(`absent`);function Lu(e,t){let n=e;for(let e of t)if(e===`(json)`){if(typeof n!=`string`)continue;if(n=zu(n),n===Iu)return Iu}else{if(typeof n==`string`&&(n=zu(n)),typeof n!=`object`||!n||!Object.prototype.hasOwnProperty.call(n,e))return Iu;n=n[e]}return n}var Ru;function zu(e){let t=Ru?.get(e);if(t!==void 0)return t;let n;try{n=JSON.parse(e)}catch{n=Iu}return Ru?.set(e,n),n}function Bu(e,t=160){for(let n of[2,1,0]){let r=Hu(e,n,6);if(r.length<=t)return r}let n=Hu(e,0,3);return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Vu(e){return e.replace(/^#\/\$defs\//,``).replace(/~1/g,`/`).replace(/~0/g,`~`)}function Hu(e,t,n){if(typeof e.$ref==`string`)return Vu(e.$ref);if(`const`in e)return JSON.stringify(e.const);if(Array.isArray(e.enum))return Wu(e.enum.map(e=>JSON.stringify(e)),n,` | `);let r=e.anyOf??e.oneOf;if(Array.isArray(r))return Wu([...new Set(r.map(e=>Hu(e,t,n)))],n,` | `,`options`);if(Array.isArray(e.allOf))return e.allOf.map(e=>Uu(Hu(e,t,n))).join(` & `);if(Array.isArray(e.type))return e.type.map(r=>Hu({...e,type:r},t,n)).join(` | `);if(e.nullable===!0)return`${Uu(Hu({...e,nullable:!1},t,n))} | null`;switch(e.type){case`string`:if(typeof e.description==`string`&&/JSON text/.test(e.description)){let t=/TypeScript type: ([^\n(]+?)(?: \(its named types|\.\s*$)/.exec(e.description);return t?`string (JSON text of ${t[1].trim()})`:`string (JSON text)`}return typeof e.format==`string`?`string (${e.format})`:`string`;case`integer`:return`integer`;case`number`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:return Array.isArray(e.prefixItems)?`[${e.prefixItems.map(e=>Hu(e,t-1,n)).join(`, `)}]`:`${Uu(e.items&&typeof e.items==`object`?Hu(e.items,t-1,n):`any`)}[]`;case`object`:{let r=e.properties??{},i=Object.keys(r),a=e.additionalProperties&&typeof e.additionalProperties==`object`?e.additionalProperties:void 0;if(!i.length&&!a)return e.additionalProperties===!1?`{}`:`object`;if(t<=0)return`{…}`;let o=new Set(e.required??[]),s=i.slice(0,n).map(e=>`${Pu.test(e)?e:JSON.stringify(e)}${o.has(e)?``:`?`}: ${Hu(r[e],t-1,n)}`);return i.length>n&&s.push(`\u2026 ${i.length-n} more`),a&&s.push(`[key: string]: ${Hu(a,t-1,n)}`),`{ ${s.join(`; `)} }`}default:return`any JSON value`}}function Uu(e){return/ \| | & /.test(e)&&!/^[{[(]/.test(e)?`(${e})`:e}function Wu(e,t,n,r=`more`){return e.length<=t?e.join(n):`${e.slice(0,t).join(n)}${n}\u2026 (${e.length} ${r===`more`?`values`:r})`}function Gu(e,t){let n=t?.node;if(n&&t&&t.kind!==`enum`&&t.kind!==`literal`&&t.kind!==`tag`&&t.kind!==`tool`&&t.kind!==`rule`&&t.kind!==`unknown-key`&&t.kind!==`not-allowed`)try{if(n.jsonText&&n.schema){let e=n.typeText();return`string (JSON text of ${e.length>120?`${e.slice(0,119)}\u2026`:e})`}let e=Bu(n.json());return t.kind===`type`&&/^(string|number|integer|boolean|null)$/.test(e)?void 0:e}catch{return}}function Ku(e){let t=e.message;for(let n of e.path)t+=`\0${typeof n==`number`?`#`:n}`;return t}function qu(e){let t=[],n=new Map;for(let r of e){let e=Ku(r),i=n.get(e);if(i){i.paths.push(r.path);continue}let a={issue:r,info:ju.get(r),paths:[r.path]};n.set(e,a),t.push(a)}return t}function Ju(e,t){let n=e.issue.message,r=e.info?.kind;if(t.terse&&e.info?.candidates&&(r===`enum`||r===`tag`||r===`tool`)){let t=e.info.candidates().length;n=n.replace(/ one of: .*$/s,` one of ${t} value${t===1?``:`s`}.`)}if(t.suggestions&&e.info?.candidates){let t=Yu(e.issue,e.info);t&&(n=n.replace(/\.$/,``)+t)}if(e.paths.length>1){if(t.terse)n+=` (the same at ${e.paths.length-1} more place${e.paths.length===2?``:`s`})`;else{let t=e.paths.slice(1,3).map(Fu),r=e.paths.length-1-t.length;n+=` (the same at ${t.join(`, `)}${r>0?` and ${r} more place${r===1?``:`s`}`:``})`}}return n.length>400?`${n.slice(0,399)}\u2026`:n}function Yu(e,t){let n=t.candidates();if(!n.length)return``;if(t.kind===`required`){let t=e.path[e.path.length-1];if(typeof t!=`string`)return``;let r=Tu(t,n);return r?` \u2014 you wrote \`${r}\`; did you mean \`${t}\`?`:``}let r=t.kind===`unknown-key`?e.path[e.path.length-1]:t.received;if(typeof r!=`string`)return``;let i=wu(r,n)[0];return i!==void 0&&i!==r?` \u2014 did you mean \`${i}\`?`:``}function Xu(e,t,n,r=`your answer`){if(!e.length)return``;let i=Qu(n)?n:Ou(n),a=qu(i.suggestions?Zu(e):e),o=Ru;Ru=new Map;try{for(let e of $u(i)){let n=td(a,t,e,r);if(n.length<=i.maxChars)return n}let e=td(a,t,{...i,detail:`summary`,maxErrors:1,terse:!0},r);return e.length<=i.maxChars?e:`${e.slice(0,Math.max(0,i.maxChars-1))}\u2026`}finally{Ru=o}}function Zu(e){let t,n=0;for(let r of e){let e=ju.get(r);if(e?.kind!==`required`||!e.candidates||++n>50)continue;let i=r.path[r.path.length-1],a=typeof i==`string`?Tu(i,e.candidates()):void 0;a!==void 0&&(t??=new Set).add(nd([...r.path.slice(0,-1),a]))}return t?e.filter(e=>!(ju.get(e)?.kind===`unknown-key`&&t.has(nd(e.path)))):e}function Qu(e){return typeof e==`object`&&!!e&&`detail`in e&&`maxChars`in e&&`expected`in e&&`context`in e&&`depth`in e&&`header`in e&&`suggestions`in e&&`maxErrors`in e}function*$u(e){for(let t of ed(e))yield t,yield{...t,terse:!0}}function*ed(e){let t=e;if(yield t,t.detail===`markers`||t.detail===`full`){for(t.expected&&(yield t={...t,expected:!1}),t.context>0&&(yield t={...t,context:0}),t.depth>2&&(yield t={...t,depth:2});t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};yield t={...t,detail:`list`,maxErrors:e.maxErrors}}for(;t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};t.detail!==`summary`&&(yield{...t,detail:`summary`})}function td(e,t,n,r){let i=e.slice(0,Math.max(1,n.maxErrors)),a=e.reduce((e,t)=>e+t.paths.length,0),o=e.length-i.length,s=e.slice(i.length).reduce((e,t)=>e+t.paths.length,0),c=`${a} problem${a===1?``:`s`}`;if(n.detail===`summary`){let e=i[0],t=a-e.paths.length;return`${n.header?`${a===1?`A problem`:c} in ${r}: `:``}at ${Fu(e.issue.path)}: ${Ju(e,n)}${t>0?` (and ${t} more problem${t===1?``:`s`})`:``}`}let l=[];if(n.header&&l.push(`${c} in ${r}:`),n.detail===`list`)for(let e of i){let t=n.expected?Gu(e.issue,e.info):void 0;l.push(`- at ${Fu(e.issue.path)}: ${Ju(e,n)}${t?` (expected: ${t})`:``}`)}else n.header&&l.push(``),l.push(...od(i,t,n));return s>0&&l.push(`\u2026 and ${s} more problem${s===1?``:`s`}${o>1?` (${o} kinds)`:``} not shown.`),l.join(`
56
+ `)}var nd=e=>{let t=``;for(let n of e)t+=`${typeof n==`number`?`#`:`$`}${n}\0`;return t};function rd(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n];if(r!==i)return typeof r==`number`&&typeof i==`number`?r-i:String(r)<String(i)?-1:1}return e.length-t.length}function id(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}var ad=e=>e.filter(e=>e!==`(json)`).length;function od(e,t,n){let r=[],i=[];for(let n of e){let e=n.issue.path,a=n.info?.kind;t===void 0?i.push(n):Lu(t,e)===Iu?e.length&&sd(Lu(t,e.slice(0,-1)))?r.push({p:n,at:e.slice(0,-1),where:`missing`}):i.push(n):r.push({p:n,at:e,where:a===`unknown-key`||a===`not-allowed`?`key`:`value`})}r.sort((e,t)=>rd(e.p.issue.path,t.p.issue.path));let a=[],o=e=>{let t=[];for(let r of e){if(ad(e)-ad(t)<=n.depth)break;t.push(r)}return t};for(let e of r){let t=a[a.length-1];if(t){let r=id(t.anchor,e.at);if([...t.members,e].every(e=>ad(e.at)-ad(r)<=n.depth+1)){t.anchor=r,t.members.push(e);continue}}a.push({anchor:o(e.at),members:[e]})}let s=[];for(let e of a){let r=e.anchor;for(;r.length&&Lu(t,r)===Iu;)r=r.slice(0,-1);let i=new Map,a=new Map;for(let t of e.members){let e=nd(t.at),n=i.get(e);n?n.push({p:t.p,where:t.where}):i.set(e,[{p:t.p,where:t.where}]);for(let e=r.length;e<t.at.length;e++){let n=nd(t.at.slice(0,e)),r=a.get(n);r?r.add(t.at[e]):a.set(n,new Set([t.at[e]]))}}s.length&&s.push(``),r.length&&s.push(`at ${Fu(r)}:`),new ld(i,a,n,s,r.length).node(Lu(t,r),r,``,``,``)}for(let e of i)s.push(`- at ${Fu(e.issue.path)}: ${Ju(e,n)}`);return s}var sd=e=>typeof e==`object`&&!!e;function cd(e){if(!e.length)return`…`;let t=e[0],n=Fu(e);return t===`(json)`?`\u2026 \u2192 ${n.replace(/^\(root\) → /,``)}`:typeof t==`number`||!Pu.test(t)?`\u2026${n}`:`\u2026.${n}`}var ld=class{constructor(e,t,n,r,i=0){this.marks=e,this.below=t,this.f=n,this.out=r,this.from=i}marks;below;f;out;from;node(e,t,n,r,i){let a=nd(t),o=this.below.has(a);if(typeof e==`string`&&o){let a=zu(e);if(a!==Iu){let e=[...t,`(json)`],o=nd(e);return this.marks.has(o)||this.below.has(o)?this.node(a,e,n,`${r}/* JSON text */ `,i):this.node(a,t,n,r,i)}}let s=this.marks.get(a)??[];if(!(sd(e)&&(o||s.some(e=>e.where===`missing`)))){let t=ud(e,60);this.out.push(n+r+t+i);for(let e of s)e.where===`key`?this.mark(e.p,n.length,r.length+t.length):this.mark(e.p,n.length+r.length,t.length);return}let c=Array.isArray(e);this.out.push(`${n}${r}${c?`[`:`{`}`);for(let e of s)this.mark(e.p,n.length+r.length,1);let l=`${n} `;c?this.items(e,t,l):this.keys(e,t,l),this.out.push(`${n}${c?`]`:`}`}${i}`)}keys(e,t,n){let r=Object.keys(e),i=this.below.get(nd(t)),a=r.filter(e=>i?.has(e)),o=r.filter(e=>!a.includes(e)),s=new Set(o.filter(t=>ud(e[t],40).length<=40&&!sd(e[t])).slice(0,this.f.context));for(let e of o)s.size<this.f.context&&!s.has(e)&&s.add(e);let c=r.filter(e=>a.includes(e)||s.has(e)),l=r.length-c.length;c.forEach((r,i)=>{let a=i===c.length-1&&!l;this.node(e[r],[...t,r],n,`${JSON.stringify(r)}: `,a?``:`,`)}),l&&this.out.push(`${n}\u2026 ${l} more key${l===1?``:`s`}`)}items(e,t,n){let r=new Set;for(let n of this.below.get(nd(t))??[])typeof n==`number`&&n<e.length&&r.add(n);let i=e.length-r.size<=this.f.context&&e.every((e,t)=>r.has(t)||ud(e,40).length<=40),a=0,o=!1,s=()=>{a&&(this.out.push(`${n}\u2026 ${a} item${a===1?``:`s`}`),a=0,o=!0)};for(let c=0;c<e.length;c++){if(!i&&!r.has(c)){a++;continue}s();let l=c===e.length-1,u=o||!i&&c>0?`/* ${c} */ `:``;this.node(e[c],[...t,c],n,u,l?``:`,`)}s()}mark(e,t,n){let r=Math.max(1,Math.min(n,40)),i=`${this.from?cd(e.issue.path.slice(this.from)):Fu(e.issue.path)}: ${Ju(e,this.f)}`;this.out.push(`${` `.repeat(t)}${`^`.repeat(r)} ${i}`);let a=this.f.expected?Gu(e.issue,e.info):void 0;a&&this.out.push(`${` `.repeat(t+r+1)}expected: ${a}`)}};function ud(e,t){if(typeof e==`string`){let n=JSON.stringify(e);return n.length<=t?n:`${n.slice(0,t-2)}\u2026"`}if(!sd(e))return e===void 0?`undefined`:JSON.stringify(e);let n=dd(e,t);if(n!==void 0)return n;if(Array.isArray(e))return`[\u2026 ${e.length} item${e.length===1?``:`s`}]`;let r=Object.keys(e).length;return`{\u2026 ${r} key${r===1?``:`s`}}`}function dd(e,t){let n=``,r=e=>{if(n.length>t)return!1;if(Array.isArray(e)){n+=`[`;for(let t=0;t<e.length;t++)if(t&&(n+=`,`),!r(e[t]))return!1;return n+=`]`,n.length<=t}if(sd(e)){n+=`{`;let i=!0;for(let t of Object.keys(e)){let a=e[t];if(a!==void 0&&(i||(n+=`,`),i=!1,n+=`${JSON.stringify(t)}:`,!r(a)))return!1}return n+=`}`,n.length<=t}return n+=e===void 0?`null`:JSON.stringify(e),n.length<=t};return r(e)?n:void 0}var fd=class{constructor(e){this.issues=e}issues};function pd(){return{objects:0,arrays:0,edits:0,parsed:0,repaired:0}}function md(e){let t=``;for(let n of e)t+=typeof n==`number`?`[${n}]`:/^[A-Za-z_$][\w$]*$/.test(n)?t?`.${n}`:n:`[${JSON.stringify(n)}]`;return t||`(root)`}var hd=Object.freeze({path:[],codePath:[],message:``}),gd=pd(),_d=Symbol(`absent`),vd=Symbol(`order`),yd,bd=class e{constructor(e,t,n,r=!0,i=!1){this.inPlace=e,this.dry=t,this.stats=n,this.repair=r,this.countOnly=i}inPlace;dry;stats;repair;countOnly;errors=[];undo;undoN=0;wire=[];code=[];wd=0;cd=0;fail(e,t=`other`,n,r,i){if(this.countOnly){this.errors.push(hd);return}let a={path:this.wire.slice(0,this.wd),codePath:this.code.slice(0,this.cd),message:e};this.errors.push(a),Mu(a,{kind:t,node:i,received:n,candidates:r})}failAt(e,t,n=`rule`){if(!e.length)return this.fail(t,n);if(this.countOnly){this.errors.push(hd);return}let r={path:[...this.wire.slice(0,this.wd),...e],codePath:[...this.code.slice(0,this.cd),...e],message:t};this.errors.push(r),Mu(r,{kind:n})}enter(e,t=e){this.wire[this.wd++]=e,t!==null&&(this.code[this.cd++]=t)}leave(e=!0){this.wd--,e&&this.cd--}dryRun(t=!1){if(!t)return new e(!1,!0,gd,this.repair,!0);let n=new e(!1,!0,gd,this.repair);for(let e=0;e<this.wd;e++)n.wire[n.wd++]=this.wire[e];for(let e=0;e<this.cd;e++)n.code[n.cd++]=this.code[e];return n}saving(e,t,n=!1){let r=this.undo;if(!r)return;n&&this.ordered!==e&&(this.ordered=e,r[this.undoN++]=e,r[this.undoN++]=vd,r[this.undoN++]=Object.keys(e));let i=Object.prototype.hasOwnProperty.call(e,t);r[this.undoN++]=e,r[this.undoN++]=t,r[this.undoN++]=i?e[t]:_d}ordered;restore(){let e=this.undo;if(e)for(let t=this.undoN-3;t>=0;t-=3){let n=e[t],r=e[t+1],i=e[t+2];if(r===vd)for(let e of i){let t=n[e];delete n[e],n[e]=t}else i===_d?delete n[r]:n[r]=i}}keepUndo(){this.undo=yd??[],yd=void 0,this.undoN=0}releaseUndo(){let e=this.undo;if(e){for(let t=0;t<this.undoN;t++)e[t]=void 0;this.undo=void 0,this.undoN=0,e.length<=65536&&(yd=e)}}},xd=class{constructor(e,t){this.impl=e,this.compiler=t}impl;compiler;needs=!1;schema;outer;jsonText=!1;_json;get own(){return!!this.impl?.own}get deps(){return this.impl?.deps??[]}json(){return this._json||=this.compiler.decorate(this,this.impl.emit()),this._json}run(e,t){let n=t.errors,r=n.length,i=this.impl.run(e,t);return n.length===r&&(this.schema?.checks.length&&this.check(i,t,this.schema),this.outer?.checks.length&&n.length===r&&this.check(i,t,this.outer),n.length===r)||t.countOnly||Nu(n,r,this),i}check(e,t,n){if(n)for(let r of n.checks){let n=r.fn(e);if(n!==!0){if(Array.isArray(n))for(let e of n)typeof e==`string`?t.fail(e,`rule`):t.failAt(e.path,e.message,`rule`);else t.fail(typeof n==`string`?n:r.message??`Failed a check.`,`rule`)}}}typeText(){return this.schema?this.schema.print(new Sd(this.compiler.env)):`any JSON value`}encode(e,t=pd()){return this.needs?this.impl.encode(e,t):e}child(e){return this.impl?.child?.(e)}},Sd=class{constructor(e){this.env=e}env;names=new Set;print(e){return e.print(this)}ref(e){return this.names.add(e),e}used(){return[...this.names]}definitions(e){for(let t of e)this.names.add(t);let t=[],n=new Set;for(let e=!0;e;){e=!1;for(let r of[...this.names]){if(n.has(r))continue;n.add(r),e=!0;let i=this.env.get(r);i&&t.push(`type ${r} = ${i.print(this)}`)}}return t.join(`
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
+ where
59
+ ${n.join(`
60
+ `)}`:t}},Cd=new Set([`object`,`array`,`record`,`tuple`]),wd=new WeakMap;function Td(e){let t=wd.get(e);return t===void 0&&(t=e.kind===`dependent`||e.children().some(Td),wd.set(e,t)),t}var Ed=new WeakMap;function Dd(e){let t=Ed.get(e);return t===void 0&&(t=+!!Cd.has(e.kind)+Math.max(0,...e.children().map(Dd)),Ed.set(e,t)),t}var Od=new WeakMap,kd=new WeakMap;function Ad(e){let t=kd.get(e);return t||kd.set(e,t=new Fd(e,jd,Nd,!1,!0)),t}var jd=new Map,Md;function Nd(){if(!Md){let e=Ad(Xl);Md=new zd(e,e.node({emit:()=>({}),run:e=>e,encode:e=>e}))}return Md}var Pd=class extends Error{},Fd=class{constructor(e,t,n,r=!1,i=!1){this.profile=e,this.env=t,this.lenient=n,this.inlineOnce=r,this.shared=i,this.view=_u(e)}profile;env;lenient;inlineOnce;shared;nodes=[];defs=new Map;glossary=new Set;inlined=new Set;recursive=new Map;view;stack=[];depth=0;guard=0;isRecursive(e){let t=this.recursive.get(e);if(t===void 0){let n=new Set,r=[...this.env.get(e)?.refNames()??[]];for(t=!1;r.length;){let i=r.pop();if(i===e){t=!0;break}n.has(i)||(n.add(i),r.push(...this.env.get(i)?.refNames()??[]))}this.recursive.set(e,t)}return t}node(e){return new xd(e,this)}compile(e,t){if(this.profile.audience!==`people`&&e.meta.forModels){let{forModels:t,...n}=e.meta,r=t;e=r.meta.description===void 0&&n.description!==void 0?r.describe(n.description):r}let n=Cd.has(e.kind);if(n&&this.profile.maxDepth!==void 0&&this.depth>=this.profile.maxDepth)return this.escape(e,`Nested too deep for this model to describe directly.`);let r=!t&&e.refNames().size===0&&!Td(e)&&(this.profile.maxDepth===void 0||this.depth+Dd(e)<this.profile.maxDepth);if(r){let t=Od.get(e)?.get(this.profile.id);if(t)return t;if(!this.shared){let t=Ad(this.profile),n=t.compile(e);return t.finish(),n}}n&&this.depth++;let i=e.compile(this);if(n&&this.depth--,i.schema=e,i.outer=t,this.nodes.push(i),r){let t=Od.get(e);t||Od.set(e,t=new Map),t.set(this.profile.id,i)}return i}guarded(e,t){this.guard++;try{return this.compile(e,t)}finally{this.guard--}}ref(e){let t=this.env.get(e);if(!t)throw new bu(`ref "${e}" is not defined (the chain's types should have prevented this).`);let n=this.profile,r=this.stack.find(t=>t.name===e);if(r)return n.defs&&(n.recursion===!0||n.recursion===`guarded`&&this.guard>r.guard)?this.defRef(e,this.defs.get(e)):this.escape(t,`"${e}" contains itself, which this model cannot describe directly.`,e);if(n.defs){let n=this.defs.get(e);if(n)return this.defRef(e,n);let r=new Id(this);return this.defs.set(e,r),this.stack.push({name:e,guard:this.guard}),r.target=this.compile(t),this.stack.pop(),this.nodes.push(r),this.defRef(e,r)}if(this.inlineOnce&&this.isRecursive(e)){if(this.inlined.has(e))return this.escape(t,`"${e}" is written out once elsewhere in this schema.`,e);this.inlined.add(e)}else if(!this.inlineOnce&&this.nodes.length>4e3)throw new Pd;this.stack.push({name:e,guard:this.guard});let i=this.compile(t);return this.stack.pop(),i}defRef(e,t){let n=this.node({deps:[t],emit:()=>({$ref:`#/$defs/${e.replace(/~/g,`~0`).replace(/\//g,`~1`)}`}),run:(e,n)=>t.run(e,n),encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)});return this.nodes.push(n),n.refName=e,n}escape(e,t,n){let r=new Sd(this.env),i=n??r.print(e);for(let e of n?[n]:r.used())this.glossary.add(e);let a=n||r.used().length?` (its named types are defined in the description of the whole schema)`:``,o,s=()=>o??=this.lenient().nodeFor(e),c=this.node({own:!0,emit:()=>({type:`string`,description:`${t} Write it as JSON text of this TypeScript type: ${i}${a}.`}),run:(e,t)=>{let n=Rd(e,t);if(n===Ld)return e;t.enter(`(json)`,null);let r=s().run(n,t);return t.leave(!1),r},encode:e=>JSON.stringify(e)});return c.jsonText=!0,this.nodes.push(c),c}late(e){let t=this.compile(e);return this.finish(),t}finish(){for(let e=!0;e;){e=!1;for(let t of this.nodes)t.needs||(t.own||t.deps.some(e=>e.needs))&&(t.needs=!0,e=!0)}this.shared&&(this.nodes.length=0)}text(e){return e===void 0?void 0:typeof e==`function`?e(this.view):e}nullable(e){let t=this.profile.nulls;if(e.nullable===!0||Array.isArray(e.type)&&e.type.includes(`null`)||e.type===`null`)return e;if(t===`nullable`)return{...e,nullable:!0};if(t===`type-array`&&typeof e.type==`string`&&!(`$ref`in e)&&!(`anyOf`in e)){let t={...e,type:[e.type,`null`]};return Array.isArray(e.enum)&&(t.enum=[...e.enum,null]),t}if(Array.isArray(e.anyOf)&&!(`$ref`in e))return e.anyOf.some(e=>e.type===`null`)?e:{...e,anyOf:[...e.anyOf,{type:`null`}]};let{description:n,...r}=e;return n===void 0?{anyOf:[r,{type:`null`}]}:{anyOf:[r,{type:`null`}],description:n}}object(e,t,n=this.profile.closedObjects){let r={type:`object`,properties:e,required:[...t]};return n&&(r.additionalProperties=!1),this.profile.propertyOrdering&&(r.propertyOrdering=Object.keys(e)),r}decorate(e,t){let n=[],r=[e.schema?.meta,e.outer?.meta],i,a=[];for(let t of r){if(!t)continue;let r=this.text(t.description);if(r&&n.push(r),t.title&&(i=t.title),t.examples)for(let n of t.examples)this.checkExample(e,n),a.push(e.encode(n))}let o=e.impl?.hint?.(this.view);o&&n.push(o);let s=typeof t.description==`string`?t.description:void 0;s&&n.push(s);let c={...t};if(i&&(c.title=i),a.length&&(this.profile.examples===`keyword`?c.examples=a:this.profile.examples===`description`&&n.push(`Example${a.length>1?`s`:``}: ${a.map(e=>JSON.stringify(e)).join(` ; `)}`)),n.length&&(c.description=n.join(`
61
+ `)),this.profile.refSiblings===!1&&typeof c.$ref==`string`&&(c.description!==void 0||c.title!==void 0||c.examples!==void 0)){let{$ref:e,...t}=c;return{anyOf:[{$ref:e}],...t}}return c}checkExample(e,t){let n=e.schema;if(!n)return;let r=new bd(!1,!0,pd(),!1);if(this.lenient().nodeFor(n).run(t,r),r.errors.length)throw new bu(`example ${JSON.stringify(t)} does not fit its schema:
62
+ ${Vd(r.errors)}`)}},Id=class extends xd{target;constructor(e){super(void 0,e)}get own(){return!1}get deps(){return this.target?[this.target]:[]}json(){return this.target.json()}run(e,t){return this.target.run(e,t)}encode(e,t=pd()){return this.target.encode(e,t)}child(e){return this.target.child(e)}},Ld=Symbol(`failed`);function Rd(e,t){if(typeof e!=`string`)return t.repair&&e!==void 0?(t.dry||t.stats.repaired++,e):(t.fail(`Expected a string of JSON text.`,`type`),Ld);try{let n=JSON.parse(e);return t.dry||t.stats.parsed++,n}catch(e){return t.fail(`Not valid JSON text: ${e.message}`,`json`),Ld}}var zd=class{constructor(e,t){this.compiler=e,this.root=t}compiler;root;_json;_body;_wrapped;_measure;_encoder;get profile(){return this.compiler.profile}body(){if(!this._body){let e=this.root.refName;this._body=e?this.compiler.defs.get(e).json():this.root.json()}return this._body}get wrapped(){if(this._wrapped===void 0){let e=this.body();this._wrapped=this.profile.rootObject&&!(e.type===`object`&&!(`anyOf`in e))}return this._wrapped}get jsonSchema(){if(this._json)return this._json;let e=this.body();if(this.wrapped&&(e=this.compiler.object({input:e},[`input`],this.profile.closedObjects||this.profile.strict)),this.compiler.glossary.size){let t=`Named types used by the fields written as JSON text:
63
+ ${new Sd(this.compiler.env).definitions(this.compiler.glossary)}`;e={...e,description:typeof e.description==`string`?`${e.description}
64
+ ${t}`:t}}let t={};for(let[e,n]of this.compiler.defs)t[e]=n.json();return this._json=this.compiler.defs.size?{...e,$defs:t}:e,this._json}get measure(){return this._measure??=vu(this.jsonSchema)}parse(e,t){return this.decode(e,t,void 0)}decode(e,t,n){let r=pd(),i=t?.inPlace??!0,a=new bd(i,!1,r,t?.repair??!0),o=i&&!n&&Au(t?.errorFormat);o&&a.keepUndo();let s;if(this.wrapped?typeof e!=`object`||!e||Array.isArray(e)||!(`input`in e)?a.fail(`Expected an object with an "input" field.`,`type`):(a.enter(`input`,null),s=this.root.run(e.input,a),a.leave(!1)):s=this.root.run(e,a),a.errors.length){a.restore(),a.releaseUndo();let i=n?n():e;return{ok:!1,issues:a.errors,message:Xu(a.errors,i,Ou(t?.errorFormat),t?.label),stats:r}}return o&&a.releaseUndo(),{ok:!0,value:s,stats:r}}parseText(e,t){let n;try{n=JSON.parse(e)}catch(e){let n=[{path:[],codePath:[],message:`Not valid JSON: ${e.message}`}];return Mu(n[0],{kind:`json`}),{ok:!1,issues:n,message:Xu(n,void 0,Ou(t?.errorFormat),t?.label),stats:pd()}}return this.decode(n,t,()=>JSON.parse(e))}parseOrThrow(e,t){let n=this.parse(e,t);if(!n.ok)throw new xu(n.issues,n.message);return n.value}encode(e,t=pd()){let n=this.root.encode(e,t);return this.wrapped?(t.objects++,{input:n}):n}encodeAt(e,t,n=pd()){let r=Bd(t);if(!r.length)return this.encode(e,n);let i=this.root;for(let e of r)if(i=i?.child(e),!i)throw new bu(`no schema at path ${md(r)}.`);return i.encode(e,n)}encodeText(e,t={}){let n=t.path===void 0?this.encode(e):this.encodeAt(e,t.path),r=t.pretty===!0?2:typeof t.pretty==`number`?t.pretty:void 0;return JSON.stringify(n,null,r)}get encoder(){if(!this._encoder){let e=((e,t)=>this.encodeText(e,t));e.wire=(e,t)=>t===void 0?this.encode(e):this.encodeAt(e,t),this._encoder=Object.freeze(e)}return this._encoder}nodeFor(e){let t=this.lateNodes.get(e);return t||this.lateNodes.set(e,t=this.compiler.late(e)),t}lateNodes=new WeakMap;typescript(){let e=this.root.schema;return new Sd(this.compiler.env).full(e)}};function Bd(e){return e===void 0||e===``?[]:typeof e==`string`?e.split(`.`).map(e=>/^\d+$/.test(e)?Number(e):e):[...e]}function Vd(e){return e.map(e=>`- at ${md(e.path)}: ${e.message}`).join(`
65
+ `)}var Hd=class e{constructor(e={}){this.defs=e}defs;define(t){for(let e of Object.keys(t))if(e in this.defs)throw new bu(`"${e}" is already defined.`);return new e({...this.defs,...t})}declare(){return this}dynamic(e,t={}){return new Ud(this.defs,e,t)}result(e){return new Gd(this.defs,Wd(e))}},Ud=class{constructor(e,t,n){this.defs=e,this.fn=t,this.opts=n}defs;fn;opts;result(e){return new Gd(this.defs,Wd(e),{fn:this.fn,opts:this.opts})}};function Wd(e){return typeof e==`string`?new Of(e):e}var Gd=class e{constructor(e,t,n){this.defs=e,this.root=t,this.dyn=n}defs;root;dyn;cache=new Map;staticBound;bind=(...e)=>{let t=this.dyn;if(!t)return this.staticBound??=new Kd(new Map(Object.entries(this.defs)),this.root);let n=t.opts.key?.(...e);if(n!==void 0){let e=this.cache.get(n);if(e)return this.cache.delete(n),this.cache.set(n,e),e}let r=t.fn(...e),i=new Map(Object.entries(this.defs));for(let[e,t]of Object.entries(r)){if(i.has(e))throw new bu(`the dynamic step redefined "${e}".`);i.set(e,t)}let a=new Kd(i,this.root);if(n!==void 0){this.cache.set(n,a);let e=t.opts.cacheSize??4;for(;this.cache.size>e;)this.cache.delete(this.cache.keys().next().value)}return a};adapt(t){let n=this.dyn;if(!n)return this;let r=n.opts.key;return new e(this.defs,this.root,{fn:(...e)=>n.fn(...t(...e)),opts:{...n.opts,...r?{key:(...e)=>r(...t(...e))}:{}}})}render(e,...t){return this.bind(...t).render(e)}},Kd=class{constructor(e,t){this.env=e,this.root=t;let n=[],r=t=>{for(let r of t.refNames())!e.has(r)&&!n.includes(r)&&n.push(r)};r(t);for(let t of e.values())r(t);if(n.length)throw new bu(`unresolved ref(s) ${n.join(`, `)}.`)}env;root;rendered=new Map;render(e){let t=this.rendered.get(e.id);if(!t){let n=()=>this.render(Xl),r=new Fd(e,this.env,n),i;try{i=r.compile(this.root)}catch(t){if(!(t instanceof Pd))throw t;r=new Fd(e,this.env,n,!0),i=r.compile(this.root)}r.finish(),t=new zd(r,i),this.rendered.set(e.id,t)}return t}},qd=new WeakMap;function Jd(e){let t=qd.get(e);return t||qd.set(e,t=new Gd({},e)),t}var Yd=Object.freeze({}),Xd=Object.freeze([]),Zd=class{meta=Yd;checks=Xd;_refNames;refNames(){if(!this._refNames){let e=new Set;this instanceof Of&&e.add(this.name);for(let t of this.children())for(let n of t.refNames())e.add(n);if(this.meta.forModels)for(let t of this.meta.forModels.refNames())e.add(t);this._refNames=e}return this._refNames}with(e){let t=Object.create(Object.getPrototypeOf(this));return Object.assign(t,this,e,{_refNames:void 0}),t}describe(e){return this.with({meta:{...this.meta,description:e}})}title(e){return this.with({meta:{...this.meta,title:e}})}example(...e){return this.with({meta:{...this.meta,examples:[...this.meta.examples??[],...e]}})}refine(e,t,n){let r={fn:e,...t===void 0?{}:{message:t},visible:n?.visible??t!==void 0};return this.with({checks:[...this.checks,r]})}brand(){return this}forPeople(){return this.with({meta:{...this.meta,audience:`people`}})}forModels(e){return this.with({meta:{...this.meta,forModels:e}})}optional(){return new Ef(this)}nullable(){return new Df(this)}default(e){return new Tf(this,e)}bind(){return Jd(this).bind()}render(e){return Jd(this).bind().render(e)}ruleHint(){let e=this.checks.filter(e=>e.visible&&e.message).map(e=>e.message);return e.length?`Rules: ${e.join(` `)}`:void 0}hintOf(e){let t=[...e],n=this.ruleHint();return n&&t.push(n),t.length?t.join(` `):void 0}},Qd={"date-time":/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,date:/^\d{4}-\d{2}-\d{2}$/,time:/^\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,duration:/^-?P(?=\d|T\d)(\d+(\.\d+)?Y)?(\d+(\.\d+)?M)?(\d+(\.\d+)?W)?(\d+(\.\d+)?D)?(T(?=\d)(\d+(\.\d+)?H)?(\d+(\.\d+)?M)?(\d+(\.\d+)?S)?)?$/,email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,uuid:/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,uri:/^[a-zA-Z][a-zA-Z\d+.-]*:\S*$/,hostname:/^(?=.{1,253}$)[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,ipv4:/^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:{test:e=>e.includes(`:`)&&/^[0-9a-fA-F:.]+$/.test(e)&&$d(`[${e}]`)}};function $d(e){try{return new URL(`http://${e}/`),!0}catch{return!1}}function ef(e){if(/\(\?<?[=!]|\\[bB]|\\[pP]\{|\\[1-9]|\\k</.test(e))return!1;for(let t of e.matchAll(/\{(\d+)(?:,(\d*))?\}/g))if(Number(t[1])>100||Number(t[2]||0)>100)return!1;return!0}var tf=class extends Zd{constructor(e={}){super(),this.options=e}options;kind=`string`;children(){return[]}min(e){return this.opts({minLength:e})}max(e){return this.opts({maxLength:e})}pattern(e,t){let n=typeof e==`string`?t:t??(e.flags||void 0);return this.opts({pattern:typeof e==`string`?e:e.source,...n?{flags:n}:{}})}format(e){return this.opts({format:e})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`string`}compile(e){let t=this.options,n=e.profile,r=t.pattern===void 0?void 0:new RegExp(t.pattern,t.flags?.replace(/[gy]/g,``)),i=`/${t.pattern}/${t.flags??``}`,a=t.format===void 0?void 0:Qd[t.format],o=[];return e.node({hint:()=>this.hintOf(o),emit:()=>{let e={type:`string`};Kf(e,o,`minLength`,t.minLength,n.constraints.length,`At least ${t.minLength} characters.`),Kf(e,o,`maxLength`,t.maxLength,n.constraints.length,`At most ${t.maxLength} characters.`);let r=!t.flags&&(n.constraints.pattern===`full`||n.constraints.pattern===`basic`&&t.pattern!==void 0&&ef(t.pattern));return Kf(e,o,`pattern`,t.pattern,r,`Must match ${i}.`),Kf(e,o,`format`,t.format,n.formats===`all`||t.format!==void 0&&n.formats.has(t.format),`Format: ${t.format}.`),e},run:(e,n)=>typeof e==`string`?(t.minLength!==void 0&&e.length<t.minLength&&n.fail(`Must be at least ${t.minLength} characters.`,`rule`),t.maxLength!==void 0&&e.length>t.maxLength&&n.fail(`Must be at most ${t.maxLength} characters.`,`rule`),r&&!r.test(e)&&n.fail(`Must match ${i}.`,`rule`),a&&!a.test(e)&&n.fail(`Must be a valid ${t.format}.`,`rule`),e):Pf(n,e,`Expected a string, got ${jf(e)}.`),encode:e=>e})}},nf=class extends Zd{constructor(e={}){super(),this.options=e}options;kind=`number`;children(){return[]}min(e){return this.opts({minimum:e})}max(e){return this.opts({maximum:e})}gt(e){return this.opts({exclusiveMinimum:e})}lt(e){return this.opts({exclusiveMaximum:e})}positive(){return this.gt(0)}negative(){return this.lt(0)}nonnegative(){return this.min(0)}int(){return this.opts({int:!0})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`number`}compile(e){let t=this.options,n=e.profile.constraints.range,r=[];return e.node({hint:()=>this.hintOf(r),emit:()=>{let e={type:t.int?`integer`:`number`};return Kf(e,r,`minimum`,t.minimum,n,`At least ${t.minimum}.`),Kf(e,r,`maximum`,t.maximum,n,`At most ${t.maximum}.`),Kf(e,r,`exclusiveMinimum`,t.exclusiveMinimum,n,`Greater than ${t.exclusiveMinimum}.`),Kf(e,r,`exclusiveMaximum`,t.exclusiveMaximum,n,`Less than ${t.exclusiveMaximum}.`),e},run:(e,n)=>typeof e!=`number`||!Number.isFinite(e)?Pf(n,e,`Expected a number, got ${jf(e)}.`):(t.int&&!Number.isInteger(e)&&n.fail(`Expected a whole number.`,`type`),t.minimum!==void 0&&e<t.minimum&&n.fail(`Must be at least ${t.minimum}.`,`rule`),t.exclusiveMinimum!==void 0&&e<=t.exclusiveMinimum&&n.fail(`Must be greater than ${t.exclusiveMinimum}.`,`rule`),t.exclusiveMaximum!==void 0&&e>=t.exclusiveMaximum&&n.fail(`Must be less than ${t.exclusiveMaximum}.`,`rule`),t.maximum!==void 0&&e>t.maximum&&n.fail(`Must be at most ${t.maximum}.`,`rule`),e),encode:e=>e})}},rf=class extends Zd{kind=`boolean`;children(){return[]}print(){return`boolean`}compile(e){return e.node({hint:()=>this.ruleHint(),emit:()=>({type:`boolean`}),run:(e,t)=>typeof e==`boolean`?e:Pf(t,e,`Expected true or false, got ${jf(e)}.`),encode:e=>e})}},af=class extends Zd{kind=`null`;children(){return[]}print(){return`null`}compile(e){return e.node({emit:()=>({type:`null`}),run:(e,t)=>e===null?e:Pf(t,e,`Expected null, got ${jf(e)}.`),encode:e=>e})}},of=class extends Zd{constructor(e){super(),this.value=e}value;kind=`literal`;children(){return[]}print(){return JSON.stringify(this.value)}compile(e){let t=this.value;return e.node({hint:()=>this.ruleHint(),emit:()=>t===null?{type:`null`}:{type:Nf(t),enum:[t]},run:(e,n)=>e===t?e:Pf(n,e,`Expected ${JSON.stringify(t)}.`,`literal`,typeof t==`string`?()=>[t]:void 0),encode:e=>e})}},sf=class extends Zd{constructor(e){super(),this.values=e}values;kind=`enum`;children(){return[]}print(){return this.values.length?this.values.map(e=>JSON.stringify(e)).join(` | `):`never`}compile(e){let t=this.values;if(!t.length)return wf(e,()=>this.ruleHint());let n=new Set(t),r=e.profile.maxEnumValues,i=r!==void 0&&t.length>r;return e.node({hint:()=>this.hintOf(i?[`One of: ${t.join(`, `)}.`]:[]),emit:()=>i?{type:`string`}:{type:`string`,enum:[...t]},run:(e,r)=>typeof e!=`string`||!n.has(e)?Pf(r,e,`Expected one of: ${Ff(t)}.`,`enum`,()=>t):e,encode:e=>e})}},cf=class extends Zd{kind=`any`;children(){return[]}print(){return`any JSON value`}compile(e){let t=e.profile.any;return t===`empty`||t===`flat`?e.node({hint:()=>this.ruleHint(),emit:()=>t===`empty`?{}:{anyOf:uf.map(e=>({...e}))},run:(e,t)=>e===void 0?Pf(t,e,`Required.`,`required`):e,encode:e=>e}):lf(e.node({own:!0,hint:()=>this.hintOf([`Write the value as JSON text.`]),emit:()=>({type:`string`}),run:(e,t)=>{let n=Rd(e,t);return n===Ld?e:n},encode:e=>JSON.stringify(e)}))}};function lf(e){return e.jsonText=!0,e}var uf=Object.freeze([{type:`string`},{type:`number`},{type:`boolean`},{type:`null`},{type:`array`},{type:`object`,additionalProperties:!0}]),df=class extends Zd{constructor(e,t={}){super(),this.element=e,this.options=t}element;options;kind=`array`;children(){return[this.element]}min(e){return this.with({options:{...this.options,minItems:e}})}max(e){return this.with({options:{...this.options,maxItems:e}})}print(e){let t=e.print(this.element);return/[|&]/.test(t)?`(${t})[]`:`${t}[]`}compile(e){let t=Cf(this.element,e.env)?{...this.options,maxItems:0}:this.options,n=(t.minItems??0)>0?e.compile(this.element):e.guarded(this.element),r=e.profile.constraints.items,i=[];return e.node({deps:[n],hint:()=>this.hintOf(i),emit:()=>{let e={type:`array`,items:n.json()};return Kf(e,i,`minItems`,t.minItems,r===`all`||r===`min-0-1`&&(t.minItems??0)<=1,`At least ${t.minItems} items.`),Kf(e,i,`maxItems`,t.maxItems,r===`all`,`At most ${t.maxItems} items.`),e},run:(e,r)=>{let i=qf(e,r,`array`);if(!Array.isArray(i))return Pf(r,i,`Expected a list, got ${jf(i)}.`);t.minItems!==void 0&&i.length<t.minItems&&r.fail(`Must have at least ${t.minItems} items.`,`rule`),t.maxItems!==void 0&&i.length>t.maxItems&&r.fail(`Must have at most ${t.maxItems} items.`,`rule`);let a=i;for(let e=0;e<i.length;e++){r.enter(e);let t=n.run(i[e],r);r.leave(),t!==i[e]&&!r.dry&&(a=Zf(a,i,e,t,r))}return a},encode:(e,t)=>Jf(e,e=>n.encode(e,t),t),child:()=>n})}},ff=class extends Zd{constructor(e){super(),this.items=e}items;kind=`tuple`;children(){return this.items}print(e){return`[${this.items.map(t=>e.print(t)).join(`, `)}]`}compile(e){let t=this.items.map(t=>e.compile(t)),n=e.profile.tuples,r=t.length,i=(e,n,i)=>{let a=e;for(let o=0;o<r;o++){n.enter(i(o),o);let r=t[o].run(e[o],n);n.leave(),r!==e[o]&&!n.dry&&(a=Zf(a,e,o,r,n))}return a};return e.node({own:n===`object`,deps:t,hint:()=>this.hintOf(n===`object`?[`Positions are written as keys "0".."${r-1}".`]:n===`array`?[`Exactly ${r} items, in order: ${this.items.map(t=>t.print(new Sd(e.env))).join(`, `)}.`]:[]),emit:()=>{if(n===`object`){let n={};return t.forEach((e,t)=>n[String(t)]=e.json()),e.object(n,Object.keys(n))}return n===`prefixItems`?{type:`array`,prefixItems:t.map(e=>e.json()),minItems:r,maxItems:r}:{type:`array`,items:{anyOf:t.map(e=>e.json())}}},run:(e,t)=>{if(n===`object`){let n=qf(e,t,`object`);if(!Af(n))return Pf(t,n,`Expected an object with keys "0".."`+(r-1)+`".`);let a=Array(r);for(let e=0;e<r;e++)a[e]=n[String(e)];t.dry||t.stats.arrays++;let o=i(a,t,e=>String(e));return t.dry?n:o}let a=qf(e,t,`array`);return Array.isArray(a)?(a.length!==r&&t.fail(`Expected exactly ${r} items.`,`rule`),i(a,t,e=>e)):Pf(t,a,`Expected a list of ${r} items.`)},encode:(e,r)=>{let i=e;if(n!==`object`)return Jf(i,(e,n)=>t[n].encode(e,r),r);let a={};return r.objects++,i.forEach((e,n)=>a[String(n)]=t[n].encode(e,r)),a},child:e=>t[Number(e)]})}},pf=class e extends Zd{constructor(e,t=!1,n={}){super(),this.shape=e,this.closed=t,this.extras=n}shape;closed;extras;kind=`object`;children(){let e=Object.values(this.shape);this.extras.rest&&e.push(this.extras.rest);for(let t of this.extras.patterns??[])e.push(t.schema);return e}strict(){return this.with({closed:!0})}extend(t){return new e({...this.shape,...t},this.closed,this.extras)}rest(t){return new e(this.shape,this.closed,{...this.extras,rest:t})}patterns(t){let n=Object.entries(t).map(([e,t])=>({pattern:e,schema:t}));return new e(this.shape,this.closed,{...this.extras,patterns:[...this.extras.patterns??[],...n]})}dependent(t,n,r,i){let a=new bf(n,r,i??new cf);return new e({...this.shape,[t]:a},this.closed,this.extras)}print(e){let t=Object.entries(this.shape).map(([t,n])=>{let r=n instanceof Ef||n instanceof Tf;return`${/^[A-Za-z_$][\w$]*$/.test(t)?t:JSON.stringify(t)}${r?`?`:``}: ${e.print(r?n.inner:n)}`}),n=this.extraValue();return n&&t.push(`[key: string]: ${e.print(n)}`),`{ ${t.join(`; `)} }`}_extraValue;extraValue(){if(this._extraValue===void 0){let e=[...(this.extras.patterns??[]).map(e=>e.schema),...this.extras.rest?[this.extras.rest]:[]];this._extraValue=e.length===0?null:e.length===1?e[0]:new gf(e)}return this._extraValue??void 0}compile(e){let t=e.profile,n=t.optional===`null`,r=t.audience!==`people`,i=[],a=new Set;for(let[t,n]of Object.entries(this.shape)){let o=r?n.meta.forModels:void 0,s=o?o.meta.description===void 0&&n.meta.description!==void 0?o.describe(n.meta.description):o:n;if(r&&n.meta.audience===`people`){a.add(t);continue}let c=s instanceof Tf?s:void 0,l=s instanceof Ef||!!c,u=s instanceof Ef?s.inner:c?c.inner:s;if(l&&Cf(u,e.env)){a.add(t);continue}let d=l?e.guarded(u,s):e.compile(u);i.push({key:t,optional:l,node:d,nullable:u instanceof Df,...u instanceof bf?{dep:u}:{},...c?{dflt:c}:{}})}let o=i.filter(e=>!e.dep),s=i.filter(e=>e.dep),c=new Set(Object.keys(this.shape)),l=this.extraValue(),u=(this.extras.patterns??[]).map(t=>({re:new RegExp(t.pattern),pattern:t.pattern,node:e.guarded(t.schema)})),d=this.extras.rest?e.guarded(this.extras.rest):void 0,f=l?t.records===`pairs`?`pairs`:t.patternProperties?`keywords`:`open`:`none`,p=f===`pairs`?c.has(`extra`)?`_extra`:`extra`:``,m=l&&f!==`keywords`?e.guarded(l):void 0,h=e=>u.find(t=>t.re.test(e))?.node??d;return e.node({own:n&&i.some(e=>e.optional&&!e.nullable)||a.size>0||f===`pairs`||i.some(e=>e.dflt),deps:[...i.map(e=>e.node),...u.map(e=>e.node),...d?[d]:[],...m?[m]:[]],hint:()=>this.hintOf(f===`pairs`?[`Other keys go in "${p}" as a list of {key, value} entries.`]:f===`open`&&u.length?[`Other keys: ${u.map(t=>`keys matching /${t.pattern}/ hold ${t.node.schema?.print(new Sd(e.env))??`a value`}`).join(`; `)}${d?`; any other key holds the rest`:``}.`]:[]),emit:()=>{let r={},a=[];for(let t of i){let i=t.node.json();t.dep&&(i={...i,description:[i.description,`Its type is given by "${t.dep.on}".`].filter(Boolean).join(`
66
+ `)}),t.dflt&&(i={...i,description:[i.description,`Default when left out: ${JSON.stringify(t.node.encode(t.dflt.value))}.`].filter(Boolean).join(`
67
+ `)}),t.optional&&n&&(i=e.nullable(i),i.description=[i.description,`Write null to leave it out.`].filter(Boolean).join(`
68
+ `)),r[t.key]=i,(!t.optional||n)&&a.push(t.key)}f===`pairs`&&(r[p]={type:`array`,items:e.object({key:{type:`string`},value:m.json()},[`key`,`value`],!0)},n&&a.push(p));let o=e.object(r,a,this.closed||t.closedObjects);return f===`keywords`?(u.length&&(o.patternProperties=Object.fromEntries(u.map(e=>[e.pattern,e.node.json()]))),d&&(o.additionalProperties=d.json())):f===`open`&&(o.additionalProperties=m.json()),o},run:(t,r)=>{let i=qf(t,r,`object`);if(!Af(i))return Pf(r,i,`Expected an object, got ${jf(i)}.`);let u=i,d=u;for(let e=0;e<o.length;e++){let t=o[e],i=Object.prototype.hasOwnProperty.call(u,t.key)?u[t.key]:void 0;if(i===void 0){t.dflt?r.dry||(d=Yf(d,u,t.key,t.dflt.fresh(r.stats),r)):t.optional||(r.enter(t.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),t.node),r.leave());continue}if(i===null&&t.optional&&n&&!t.nullable){r.dry||(d=t.dflt?Yf(d,u,t.key,t.dflt.fresh(r.stats),r):Xf(d,u,t.key,r));continue}r.enter(t.key);let a=t.node.run(i,r);r.leave(),a!==i&&!r.dry&&(d=Yf(d,u,t.key,a,r))}for(let t=0;t<s.length;t++){let i=s[t],a=u[i.key];if(a===void 0||a===null&&i.optional&&n){a===null&&!r.dry?d=Xf(d,u,i.key,r):i.optional||(r.enter(i.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),i.node),r.leave());continue}r.enter(i.key);let o=r.errors.length,l=i.node.run(a,r);if(r.errors.length===o){let t=i.dep.schemaFor(d[i.dep.on]);t&&(l=e.lenient().nodeFor(t).run(l,r))}r.leave(),l!==a&&!r.dry&&(d=Yf(d,u,i.key,l,r))}if(a.size)for(let e of a)Object.prototype.hasOwnProperty.call(u,e)&&(r.enter(e),r.fail(`Not allowed.`,`not-allowed`),r.leave());if(f===`pairs`){let e=u[p];if(e!=null){r.enter(p,null);let t=qf(e,r,`array`);if(!Array.isArray(t))Pf(r,t,`Expected a list of {key, value} entries.`);else{r.dry||(d=Xf(d,u,p,r));for(let e=0;e<t.length;e++){let n=t[e];if(r.enter(e,null),!Af(n)||typeof n.key!=`string`){r.fail(`Expected a {key, value} entry with a string key.`,`type`),r.leave(!1);continue}let i=n.key;if(c.has(i)||Object.prototype.hasOwnProperty.call(d,i)){r.enter(`key`,null),r.fail(`Duplicate key "${i}".`,`rule`),r.leave(!1),r.leave(!1);continue}let a=h(i);r.enter(`value`,i);let o=a?a.run(n.value,r):this.closed?Pf(r,n.value,`Key "${i}" is not allowed.`,`not-allowed`):n.value;r.leave(),r.dry||(d=Yf(d,u,i,o,r)),r.leave(!1)}}r.leave(!1)}else p&&e===null&&!r.dry&&(d=Xf(d,u,p,r))}else if(l||this.closed){let e=Object.keys(u);for(let t=0;t<e.length;t++){let n=e[t];if(c.has(n))continue;let i=l?h(n):void 0;if(i){r.enter(n);let e=i.run(u[n],r);r.leave(),e!==u[n]&&!r.dry&&(d=Yf(d,u,n,e,r))}else this.closed&&(r.enter(n),r.fail(`Unknown field "${n}".`,`unknown-key`,n,()=>[...c].filter(e=>!Object.prototype.hasOwnProperty.call(u,e))),r.leave())}}return d},encode:(e,t)=>{let r=e,o={};t.objects++;let s=[];for(let e of Object.keys(r)){if(a.has(e)||c.has(e))continue;let n=h(e),i=n?n.encode(r[e],t):r[e];f===`pairs`?s.push({key:e,value:i}):o[e]=i}for(let e of i){let i=r[e.key];i===void 0?e.optional&&n&&(o[e.key]=null):o[e.key]=e.node.encode(i,t)}return f===`pairs`&&(s.length||n)&&(t.arrays++,t.objects+=s.length,o[p]=s),o},child:e=>i.find(t=>t.key===e)?.node??(typeof e==`string`?h(e):void 0)})}},mf=class extends Zd{constructor(e,t){super(),this.value=e,this.key=t}value;key;kind=`record`;children(){return this.key?[this.key,this.value]:[this.value]}print(e){return`{ [key: ${this.key?e.print(this.key):`string`}]: ${e.print(this.value)} }`}compile(e){let t=e.guarded(this.value),n=e.compile(this.key??hf),r=e.profile.records===`pairs`;return e.node({own:r,deps:[t,n],hint:e=>this.hintOf(r?[`A map written as ${e.recordWord}; each key at most once.`]:[]),emit:()=>{if(r)return{type:`array`,items:e.object({key:n.json(),value:t.json()},[`key`,`value`],!0)};let i={type:`object`,additionalProperties:t.json()};return this.key&&!e.profile.closedObjects&&!(this.key instanceof tf&&!Object.keys(this.key.options).length)&&(i.propertyNames=n.json()),i},run:(i,a)=>{if(r){let r=qf(i,a,`array`);if(!Array.isArray(r)){let t=a.repair?qf(i,a,`object`):i;if(a.repair&&!a.dry&&Af(t)){t===i&&a.stats.repaired++;let r=t,o=e.lenient().nodeFor(this.value),s=r;for(let e of Object.keys(r)){a.enter(e),n.run(e,a);let t=o.run(r[e],a);a.leave(),t!==r[e]&&!a.dry&&(s=Yf(s,r,e,t,a))}return s}return Pf(a,r,`Expected a list of {key, value} entries, got ${jf(r)}.`)}let o={};a.dry||a.stats.objects++;for(let e=0;e<r.length;e++){let i=r[e];if(a.enter(e,null),!Af(i)){Pf(a,i,`Expected a {key, value} entry.`),a.leave(!1);continue}let s=i.key;a.enter(`key`,null),s===void 0?a.fail(`Required.`,`required`,void 0,()=>Object.keys(i).filter(e=>e!==`key`&&e!==`value`),n):n.run(s,a),a.leave(!1),typeof s==`string`&&(Object.prototype.hasOwnProperty.call(o,s)&&(a.enter(`key`,null),a.fail(`Duplicate key "${s}".`,`rule`),a.leave(!1)),a.enter(`value`,s),o[s]=t.run(i.value,a),a.leave()),a.leave(!1)}return a.dry?r:o}let o=qf(i,a,`object`);if(!Af(o))return Pf(a,o,`Expected an object, got ${jf(o)}.`);let s=o,c=s;for(let e of Object.keys(s)){this.key&&(a.enter(e),n.run(e,a),a.leave()),a.enter(e);let r=t.run(s[e],a);a.leave(),r!==s[e]&&!a.dry&&(c=Yf(c,s,e,r,a))}return c},encode:(e,n)=>{let i=e;if(r){let e=Object.keys(i);return n.arrays++,n.objects+=e.length,e.map(e=>({key:e,value:t.encode(i[e],n)}))}let a=i;for(let e of Object.keys(i)){let r=t.encode(i[e],n);r!==i[e]&&(a===i&&(a={...i},n.objects++),a[e]=r)}return a},child:()=>t})}},hf=new tf,gf=class extends Zd{constructor(e,t){super(),this.options=e,this.tag=t}options;tag;kind=`union`;children(){return this.options}print(e){return this.options.map(t=>e.print(t)).join(` | `)}tagIndex(e,t){let n=this.tag??Vf(this.options,e);if(!n)return;let r=new Map,i=[];return this.options.forEach((a,o)=>{let s=t.has(o)?void 0:Lf(a,n,e);if(s)for(let e of s)r.has(e)||r.set(e,o);else i.push(o)}),{tag:n,byTag:r,fallback:i}}label(e,t){let n=this.tag?Wf(this.options[e],t).shape?.[this.tag]:void 0;return n instanceof of&&typeof n.value==`string`?n.value:`option${e+1}`}compile(e){if(this.options.some(t=>Cf(t,e.env))){let t=this.options.filter(t=>!Cf(t,e.env));return t.length?this.with({options:t}).compile(e):wf(e,()=>this.ruleHint())}let t=e.profile.unions===`tagged`,n=new Set,r=this.options.map(t=>e.compile(t));if(r.length>1&&r.every(e=>e.jsonText))return e.escape(this,`Nested too deep for this model to describe directly.`);let i=t=>Wf(t,e.env)?.kind,a=this.options.some(t=>i(t)===`array`||i(t)===`tuple`&&e.profile.tuples!==`object`),o=r.map((r,o,s)=>t||s.length<2?r:r.jsonText?(n.add(o),Uf(e,r)):a&&e.profile.records===`pairs`&&i(this.options[o])===`record`?(n.add(o),Uf(e,r,`entries`)):r),s=this.tagIndex(e.env,n),c=s?.byTag,l=s?.tag,u=this.options.map((t,n)=>this.label(n,e.env)),d=t=>Wf(this.options[t],e.env)instanceof af,f=(t,n)=>{if(c&&Af(t)){let r=c.get(t[l]);if(r!==void 0){let i=new Set(zf(this.options[r],e.env));if(e.profile.closedObjects&&i.size&&s.fallback.length&&Object.keys(t).some(e=>!i.has(e)))for(let e of s.fallback){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return r}}let r=!Af(t)||t[l]===void 0;for(let e of s&&!r?s.fallback:o.keys()){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return-1},p=()=>new Sd(e.env);return e.node({own:t,deps:o,hint:()=>this.hintOf(t?[`Fill exactly one of these fields and set the others to null.`]:[]),emit:()=>{if(t){let t={};return o.forEach((n,r)=>t[u[r]]=e.nullable(d(r)?{type:`boolean`,enum:[!0],description:`true for null`}:n.json())),e.object(t,u)}return{anyOf:o.map(e=>e.json())}},run:(n,r)=>{if(t){if(!Af(n))return Pf(r,n,`Expected an object with one of: ${u.join(`, `)}.`);let e=u.filter(e=>n[e]!=null);if(e.length!==1)return Pf(r,n,`Fill exactly one of: ${u.join(`, `)} (got ${e.length}).`,`union`);let t=u.indexOf(e[0]);if(d(t))return n[e[0]]===!0?null:Pf(r,n,`Set ${e[0]} to true for null.`,`literal`);r.enter(e[0],null);let i=o[t].run(n[e[0]],r);return r.leave(!1),i}let i=f(n,r);if(i<0){if(c&&!s.fallback.length&&Af(n)&&n[l]!==void 0){r.enter(l);let e=n[l];return r.fail(`Expected ${l} to be one of: ${Ff([...c.keys()].map(e=>JSON.stringify(e)))}.`,`tag`,e,()=>[...c.keys()].filter(e=>typeof e==`string`)),r.leave(),n}let t=Hf(this.options,n,e.env);return t>=0?o[t].run(n,r):Pf(r,n,`Did not match any of: ${If(this.options.map(e=>e.print(p())).join(` | `),300)}.`,`union`,typeof n==`string`?()=>Rf(this.options,e.env):void 0)}return o[i].run(n,r)},encode:(n,r)=>{let i=this.optionOf(n,e,c,l);if(i<0)return n;let a=d(i)&&t?!0:o[i].encode(n,r);return t?(r.objects++,Object.fromEntries(u.map((e,t)=>[e,t===i?a:null]))):a},child:t=>{let n=o.map(e=>e.child(t)).filter(e=>!!e);if(n.length<=1)return n[0];let r=t=>n.find(n=>!n.schema||Gf(e,n.schema,t))??n[0],i=e.node({deps:n,emit:()=>({anyOf:n.map(e=>e.json())}),run:(e,t)=>r(e).run(e,t),encode:(e,t)=>r(e).encode(e,t),child:e=>n[0].child(e)});return i.needs=n.some(e=>e.needs),i}})}optionOf(e,t,n,r){if(n&&Af(e)){let t=n.get(e[r]);if(t!==void 0)return t}let i=t.lenient();return this.options.findIndex(t=>{let n=new bd(!1,!0,pd(),!1,!0);return i.nodeFor(t).run(e,n),n.errors.length===0})}},_f=class extends Zd{constructor(e){super(),this.members=e}members;kind=`intersection`;children(){return this.members}print(e){return this.members.map(t=>e.print(t)).join(` & `)}mergedByEnv=new WeakMap;merged(e){let t=this.mergedByEnv.get(e);if(t===void 0){let n=this.members.map(t=>Wf(t,e));if(n.every(e=>e instanceof pf)){let e=n,r={};for(let t of e)Object.assign(r,t.shape);let i=e.map(e=>e.extras.rest).filter(Boolean).at(-1),a=e.flatMap(e=>e.extras.patterns??[]);t=new pf(r,e.some(e=>e.closed),{...i?{rest:i}:{},...a.length?{patterns:a}:{}}).with({checks:[...e.flatMap(e=>e.checks),...this.checks],meta:this.meta})}else t=null;this.mergedByEnv.set(e,t)}return t??void 0}compile(e){let t=this.merged(e.env);if(t){let n=e.compile(t);return e.node({deps:[n],emit:()=>n.json(),run:(e,t)=>n.run(e,t),encode:(e,t)=>n.encode(e,t),child:e=>n.child(e)})}let n=this.members.map(t=>e.compile(t)),r=this.members.slice(1),i=()=>e.profile.allOf&&n.every(e=>!e.needs);return e.node({deps:n,hint:()=>this.hintOf(i()?[]:[`Must also be: ${r.map(t=>t.print(new Sd(e.env))).join(` & `)}.`]),emit:()=>i()?{allOf:n.map(e=>e.json())}:n[0].json(),run:(t,i)=>{let a=i.errors.length,o=n[0].run(t,i);if(i.errors.length!==a)return o;let s=e.lenient();for(let e of r){let t=i.dryRun(!0);s.nodeFor(e).run(o,t);for(let e of t.errors)i.errors.push(e)}return o},encode:(e,t)=>n[0].encode(e,t),child:e=>n[0].child(e)})}},vf=class extends Zd{constructor(e,t){super(),this.excluded=e,this.base=t}excluded;base;kind=`not`;children(){return[this.base,this.excluded]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=()=>e.profile.conditionals?[]:[`Must not be: ${this.excluded.print(new Sd(e.env))}.`];return e.node({deps:[t],hint:()=>this.hintOf(n()),emit:()=>e.profile.conditionals?{...t.json(),not:e.lenient().nodeFor(this.excluded).json()}:t.json(),run:(n,r)=>{let i=r.errors.length,a=t.run(n,r);return r.errors.length===i&&Gf(e,this.excluded,a)&&r.fail(`Must not be: ${this.excluded.print(new Sd(e.env))}.`,`rule`),a},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},yf=class extends Zd{constructor(e,t,n,r){super(),this.base=e,this.when=t,this.then=n,this.otherwise=r}base;when;then;otherwise;kind=`conditional`;children(){return[this.base,this.when,...this.then?[this.then]:[],...this.otherwise?[this.otherwise]:[]]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=t=>t.print(new Sd(e.env)),r=[this.then?`If it is ${n(this.when)}, it must also be ${n(this.then)}.`:``,this.otherwise?`${this.then?`Otherwise`:`If it is not ${n(this.when)}`}, it must be ${n(this.otherwise)}.`:``].filter(Boolean).join(` `);return e.node({deps:[t],hint:()=>this.hintOf(e.profile.conditionals?[]:[r]),emit:()=>{if(!e.profile.conditionals)return t.json();let n=e.lenient();return{...t.json(),if:n.nodeFor(this.when).json(),...this.then?{then:n.nodeFor(this.then).json()}:{},...this.otherwise?{else:n.nodeFor(this.otherwise).json()}:{}}},run:(n,i)=>{let a=i.errors.length,o=t.run(n,i);if(i.errors.length!==a)return o;let s=Gf(e,this.when,o)?this.then:this.otherwise;return s&&!Gf(e,s,o)&&i.fail(r,`rule`),o},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},bf=class extends Zd{constructor(e,t,n=new cf){super(),this.on=e,this.schemaFor=t,this.base=n}on;schemaFor;base;kind=`dependent`;children(){return[this.base]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>t.run(e,n),encode:(e,n)=>t.encode(e,n)})}},xf=class extends Zd{constructor(e,t=`tool`,n=`args`){super(),this.cases=e,this.tagKey=t,this.argsKey=n}cases;tagKey;argsKey;kind=`dispatch`;children(){return this.cases.map(e=>e.schema)}print(e){return this.cases.map(t=>`{ ${this.tagKey}: ${JSON.stringify(t.name)}; ${this.argsKey}: ${e.print(t.schema)} }`).join(` | `)}compile(e){let t=this.cases.map(e=>e.name),n=new Map(t.map((e,t)=>[e,t])),r=this.cases.map(t=>e.compile(t.schema)),i=e.compile(new sf(t)),a=e.profile.unions===`tagged`,{tagKey:o,argsKey:s}=this,c=this.cases.map(e=>`- ${e.name}${e.description?`: ${e.description}`:``}`).join(`
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
+ ${c}`].filter(Boolean).join(`
71
+ `)},l;if(a){let n={};t.forEach((t,i)=>n[t]=e.nullable(r[i].json())),l={...e.object(n,t),description:`Fill only the field named by "${o}"; set the others to null.`}}else l=r.length===1?r[0].json():{anyOf:r.map(e=>e.json())};return e.object({[o]:n,[s]:l},[o,s])},run:(e,i)=>{let c=qf(e,i,`object`);if(!Af(c))return Pf(i,c,`Expected an object with "${o}" and "${s}".`);let l=c,u=l[o],d=typeof u==`string`?n.get(u):void 0;if(d===void 0)return i.enter(o),i.fail(`Expected one of: ${Ff(t)}.`,`tool`,u,()=>t),i.leave(),c;let f=l[s];if(a){let e=qf(f,i,`object`);f=Af(e)?e[u]:void 0,i.enter(s),i.enter(u,null)}else i.enter(s);let p=f===void 0?Pf(i,f,`Required.`,`required`,r[d]):r[d].run(f,i);return a&&i.leave(!1),i.leave(),p!==l[s]&&!i.dry?Yf(l,l,s,p,i):l},encode:(e,i)=>{let c=e,l=c[o],u=n.get(l);if(u===void 0)return e;let d=r[u].encode(c[s],i);return i.objects++,a?(i.objects++,{[o]:l,[s]:Object.fromEntries(t.map(e=>[e,e===l?d:null]))}):{[o]:l,[s]:d}}})}},Sf=class extends Zd{kind=`never`;children(){return[]}print(){return`never`}compile(e){return wf(e,()=>this.ruleHint())}};function Cf(e,t){let n=Wf(e,t);return n?n.kind===`never`?!0:n instanceof sf?n.values.length===0:n instanceof gf&&n.options.every(e=>Cf(e,t)):!1}function wf(e,t){return e.node({hint:()=>[`No value is allowed here.`,t()].filter(Boolean).join(` `),emit:()=>e.profile.conditionals?{not:{}}:{type:`null`},run:(e,t)=>Pf(t,e,`No value is allowed here.`,`not-allowed`),encode:e=>e})}var Tf=class extends Zd{constructor(e,t){super(),this.inner=e,this.value=t}inner;value;kind=`default`;children(){return[this.inner]}print(e){return e.print(this.inner)}fresh(e){let t=this.value;return typeof t!=`object`||!t?t:(e&&(Array.isArray(t)?e.arrays++:e.objects++),structuredClone(t))}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`,r=this.inner instanceof Df;return e.node({own:!0,deps:[t],hint:()=>this.hintOf([`Default when left out: ${JSON.stringify(t.encode(this.value))}.`]),emit:()=>n&&!r?e.nullable(t.json()):t.json(),run:(e,i)=>e===void 0||e===null&&n&&!r?this.fresh(i.dry?void 0:i.stats):t.run(e,i),encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},Ef=class extends Zd{constructor(e){super(),this.inner=e}inner;kind=`optional`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | undefined`}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`;return e.node({own:n,deps:[t],emit:()=>n?e.nullable(t.json()):t.json(),run:(e,r)=>e===void 0?e:e===null&&n&&!(this.inner instanceof Df)?void 0:t.run(e,r),encode:(e,r)=>e===void 0?n?null:void 0:t.encode(e,r),child:e=>t.child(e)})}},Df=class extends Zd{constructor(e){super(),this.inner=e}inner;kind=`nullable`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | null`}compile(e){let t=e.guarded(this.inner);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>e.nullable(t.json()),run:(e,n)=>e===null?e:t.run(e,n),encode:(e,n)=>e===null?null:t.encode(e,n),child:e=>t.child(e)})}},Of=class extends Zd{constructor(e){super(),this.name=e}name;kind=`ref`;children(){return[]}print(e){return e.ref(this.name)}compile(e){return e.ref(this.name)}},kf=class extends Zd{constructor(e,t){super(),this.wire=e,this.codec=t}wire;codec;kind=`codec`;children(){return[this.wire]}print(e){return e.print(this.wire)}compile(e){let t=e.compile(this.wire);return e.node({own:!0,deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>{let r=n.errors.length,i=t.run(e,n);if(n.errors.length!==r)return e;let a=this.codec.decode(i);if(a instanceof Error)return Pf(n,e,a.message,`other`);if(a instanceof fd){if(!a.issues.length)return Pf(n,e,`Rejected.`,`rule`);for(let e of a.issues)n.failAt(e.path,e.message,`rule`);return e}return a},encode:(e,n)=>t.encode(this.codec.encode(e),n)})}};function Af(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jf(e){return typeof e==`string`?Mf(e)??`string`:e===null?`null`:Array.isArray(e)?`a list`:typeof e==`object`?`an object`:typeof e}function Mf(e){let t=e.trimStart()[0];if(t===`{`||t===`[`)try{JSON.parse(e);return}catch(e){return`a string of JSON text that doesn't parse (${e.message}); send the value itself, not as a string`}}function Nf(e){return typeof e==`string`?`string`:typeof e==`number`?`number`:typeof e==`boolean`?`boolean`:`null`}function Pf(e,t,n,r=`type`,i){return typeof i==`function`?e.fail(n,r,t,i):e.fail(n,r,t,void 0,i),t}function Ff(e,t=30){return e.length<=t?e.join(`, `):`${e.slice(0,t).join(`, `)}, \u2026 (${e.length-t} more)`}function If(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Lf(e,t,n,r=0){let i=Wf(e,n);if(i instanceof pf){let e=Wf(i.shape[t],n);return e instanceof of?[e.value]:e instanceof sf?[...e.values]:void 0}if(i instanceof gf&&r<8){let e=[];for(let a of i.options){let i=Lf(a,t,n,r+1);if(!i)return;e.push(...i)}return e}}function Rf(e,t,n=0){let r=[];for(let i of e){let e=Wf(i,t);e instanceof sf?r.push(...e.values):e instanceof of&&typeof e.value==`string`?r.push(e.value):e instanceof gf&&n<8&&r.push(...Rf(e.options,t,n+1))}return r}function zf(e,t,n=0){let r=Wf(e,t);return r instanceof pf?Object.keys(r.shape):r instanceof gf&&n<8?zf(r.options[0],t,n+1):[]}var Bf=new WeakMap;function Vf(e,t){let n=Bf.get(e);n||Bf.set(e,n=new WeakMap);let r=n.get(t);if(r===void 0){if(r=null,e.length>1)for(let n of zf(e[0],t)){let i=new Set,a=!0;for(let r of e){let e=Lf(r,n,t);if(!e||e.some(e=>i.has(e))){a=!1;break}for(let t of e)i.add(t)}if(a){r=n;break}}n.set(t,r)}return r??void 0}function Hf(e,t,n){if(!Af(t))return-1;let r=t,i=-1,a=0,o=!1;if(e.forEach((e,t)=>{let s=0;for(let t of zf(e,n)){let i=Lf(e,t,n);i&&t in r&&(s+=i.includes(r[t])?1:-1)}s>a?(i=t,a=s,o=!1):s===a&&s>0&&(o=!0)}),!o&&i>=0)return i;let s=Object.keys(r);return s.length?(i=-1,a=0,o=!1,e.forEach((e,t)=>{let r=new Set(zf(e,n));if(!r.size||s.some(e=>!r.has(e)))return;let c=s.length;c>a?(i=t,a=c,o=!1):c===a&&(o=!0)}),o?-1:i):-1}function Uf(e,t,n=`json`){let r=e.node({own:!0,deps:[t],emit:()=>e.object({[n]:t.json()},[n]),run:(e,r)=>{if(!Af(e)||!(n in e))return Pf(r,e,n===`json`?`Expected {"json": "<JSON text>"}.`:`Expected {"${n}": [...]}.`);r.enter(n,null);let i=t.run(e[n],r);return r.leave(!1),i},encode:(e,r)=>(r.objects++,{[n]:t.encode(e,r)})});return e.nodes.push(r),r}function Wf(e,t){for(let n=0;e instanceof Of&&n<16;n++)e=t.get(e.name);return e}function Gf(e,t,n){let r=new bd(!1,!0,pd(),!1,!0);return e.lenient().nodeFor(t).run(n,r),r.errors.length===0}function Kf(e,t,n,r,i,a){r!==void 0&&(i?e[n]=r:t.includes(a)||t.push(a))}function qf(e,t,n){if(!t.repair||typeof e!=`string`)return e;let r=e;for(let t=0;t<2&&typeof r==`string`;t++){let t=r.trim();if(!/^[[{"]/.test(t))return e;try{r=JSON.parse(t)}catch{return e}}return(n===`array`?Array.isArray(r):Af(r))?(t.dry||t.stats.repaired++,r):e}function Jf(e,t,n){let r=e;for(let i=0;i<e.length;i++){let a=t(e[i],i);a!==e[i]&&(r===e&&(r=e.slice(),n.arrays++),r[i]=a)}return r}function Yf(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e={...t},i.stats.objects++),e[n]=r,e)}function Xf(e,t,n,r){return r.inPlace?(r.saving(t,n,!0),delete t[n],r.stats.edits++,t):(e===t&&(e={...t},r.stats.objects++),delete e[n],e)}function Zf(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e=t.slice(),i.stats.arrays++),e[n]=r,e)}function Qf(e,t={unsupported:[]}){let n=typeof e==`object`?e:{},r={...n.definitions??{},...n.$defs??{}},i={},a=!1,o=e=>{if(e===`#`)return a=!0,`__root`;let n=/^#\/(?:\$defs|definitions)\/(.+)$/.exec(e);return n?n[1].replace(/~1/g,`/`).replace(/~0/g,`~`):(t.unsupported.push(`$ref ${e}`),`__any`)},s=e=>{if(e===!0||e===void 0)return new cf;if(e===!1)return new gf([new af]).refine(()=>!1,`No value is allowed here.`);let{allOf:n,not:r,if:i,then:a,else:o,...l}=e,u=Object.keys(l).every(e=>[`description`,`title`,`examples`,`$comment`,`default`].includes(e)),d=c(l);if(Array.isArray(n)&&n.length){let e=n.map(s),t=u?e:[d,...e];d=t.length===1?t[0]:new _f(t)}r!==void 0&&(d=new vf(s(r),d)),i!==void 0&&(d=new yf(d,s(i),a===void 0?void 0:s(a),o===void 0?void 0:s(o)));for(let n of[`dependentSchemas`,`dependentRequired`])n in e&&t.unsupported.push(n);return typeof e.description==`string`&&(d=d.describe(e.description)),typeof e.title==`string`&&(d=d.title(e.title)),Array.isArray(e.examples)&&(d=d.example(...e.examples)),d},c=e=>{if(typeof e.$ref==`string`)return new Of(o(e.$ref));if(`const`in e)return new of(e.const);if(Array.isArray(e.enum)){let t=e.enum,n=t.filter(e=>typeof e==`string`),r=t.includes(null),i=n.length===t.length-+!!r&&n.length?new sf(n):new gf(t.filter(e=>e!==null).map(e=>new of(e)));return r?new Df(i):i}let t=e.anyOf??e.oneOf;if(Array.isArray(t)){let e=t.map(s),n=e.filter(e=>!(e instanceof af)),r=n.length===1?n[0]:new gf(n);return n.length<e.length?new Df(r):r}if(Array.isArray(e.type)){let t=e.type,n=t.filter(e=>e!==`null`).map(t=>c({...e,type:t})),r=n.length===1?n[0]:n.length?new gf(n):new af;return t.includes(`null`)&&n.length?new Df(r):r}let n=e.type??$f(e);switch(n){case`string`:{let t=new tf;return typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),typeof e.pattern==`string`&&(t=t.pattern(e.pattern)),typeof e.format==`string`&&(t=t.format(e.format)),t}case`number`:case`integer`:{let t=new nf({int:e.type===`integer`});return typeof e.minimum==`number`&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&(t=t.max(e.maximum)),t}case`boolean`:return new rf;case`null`:return new af;case`array`:{if(Array.isArray(e.prefixItems)&&e.prefixItems.length)return new ff(e.prefixItems.map(s));let t=new df(s(e.items??!0));return typeof e.minItems==`number`&&(t=t.min(e.minItems)),typeof e.maxItems==`number`&&(t=t.max(e.maxItems)),t}default:{if(n===void 0&&!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new cf;if(!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new mf(new cf);let t=e.properties??{},r=new Set(e.required??[]),i=e.additionalProperties,a=e.patternProperties;if(!Object.keys(t).length&&!a&&i!==void 0&&i!==!1)return new mf(i===!0?new cf:s(i));let o={};for(let[e,n]of Object.entries(t))o[e]=r.has(e)?s(n):new Ef(s(n));for(let e of r)e in o||(o[e]=new cf);let c=new pf(o);return a&&(c=c.patterns(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,s(t)])))),i===!0?c=c.rest(new cf):i!==void 0&&typeof i==`object`&&(c=c.rest(s(i))),i===!1?c.strict():c}}};for(let[e,t]of Object.entries(r))i[e]=s(t);let{$defs:l,definitions:u,...d}=n,f=s(d);a&&(i.__root=f),(t.unsupported.includes(`$ref`)||Object.values(i).some(()=>!1))&&(i.__any=new cf);for(let e of[f,...Object.values(i)].flatMap(e=>[...e.refNames()]))e in i||(e.startsWith(`__`)||t.unsupported.push(`$ref to a missing definition "${e}" (any JSON instead)`),i[e]=new cf().describe(`Unknown reference ${e}.`));return new Gd(i,a?new Of(`__root`):f)}function $f(e){if([`minLength`,`maxLength`,`pattern`,`format`].some(t=>t in e))return`string`;if([`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`].some(t=>t in e))return`number`;if([`items`,`prefixItems`,`minItems`,`maxItems`].some(t=>t in e))return`array`;if([`properties`,`required`,`patternProperties`,`additionalProperties`].some(t=>t in e))return`object`}var ep=()=>new tf,tp=()=>new nf,np=()=>new nf({int:!0}),rp=()=>new rf,ip=()=>new af,ap=e=>new of(e);function op(e){return new sf([...e])}var sp=()=>new Sf,cp=()=>new cf,lp=()=>new cf,up=e=>new pf(e),dp=e=>new df(e),fp=e=>new ff(e);function pp(e,t){return t?new mf(t,e):new mf(e)}function mp(e){return new gf([...e])}function hp(e,t){return new gf([...t],e)}var gp=e=>new _f(e);function _p(e,t){return new vf(e,t??new cf)}function vp(e,t){return new yf(e,t.if,t.then,t.else)}function yp(e,t,n){return new bf(e,t,n)}var bp=e=>new Ef(e),xp=(e,t)=>new Tf(e,t),Sp=e=>new Df(e),Cp=e=>new Of(e),wp=e=>new Of(e),Tp=(e,t)=>new kf(e,t),Ep=(e,t={})=>new xf(e,t.tag??`tool`,t.args??`args`),Dp=e=>new Hd(e),Op=()=>new Hd,kp=()=>new Hd;function Ap(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function jp(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function Mp(e,t,n){let r=e.toLowerCase(),i=t.map((t,n)=>({candidate:t,index:n,ci:Ap(r,t.toLowerCase()),exact:Ap(e,t)})).filter(e=>e.ci<=n);return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function Np(e,t,n=jp(e.length)){return Mp(e,t,n)[0]}function Pp(e,t,n={}){let r=Math.max(1,n.max??1),i=Mp(e,t,jp(e.length)).slice(0,r);return i.length===0?``:` \u2014 did you mean ${Fp(i.map(e=>`\`${e}\``))}?`}function Fp(e){return e.length===2?`${e[0]} or ${e[1]}`:e.length>2?`${e.slice(0,-1).join(`, `)}, or ${e[e.length-1]}`:e.join(`, `)}function Ip(e,t,n=2){let r=e.length,i=t.length,a=[];for(let e=0;e<=i;e++)a[e]=e*n;for(let o=1;o<=r;o++){let r=a[0];a[0]=o*n;let s=e[o-1].toLowerCase();for(let e=1;e<=i;e++){let i=a[e],o=r+Ap(s,t[e-1].toLowerCase());a[e]=Math.min(a[e]+n,a[e-1]+n,o),r=i}}return a[i]}function Lp(e,t,n,r,i={}){if(r.length===0)return;let a=i.maxDepth??Math.min(6,r.length+1),o=r[r.length-1].toLowerCase(),s=jp(o.length),c=r.reduce((e,t)=>e+jp(t.length),0)+2,l=i.nodeBudget??2e3,u,d=new Set,f=(e,i)=>{if(!(l<=0)){for(let n of t(e)){if(l<=0)return;if(l--,Ap(n.toLowerCase(),o)>s)continue;let e=[...i,n],t=Ip(e,r);t>c||(!u||t<u.score||t===u.score&&e.length<u.path.length)&&(u={score:t,path:e})}if(!(i.length>=a||d.has(e))){d.add(e);for(let[t,r]of n(e)){if(l<=0)break;f(r,[...i,t])}d.delete(e)}}};return f(e,[]),u?.path}var Rp=[`name`,`docs`,`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`],zp=[`docs`,`type`,`get`,`default`,`set`],Bp=[`docs`,`key`,`value`,`get`,`set`,`loop`,`loopDynamic`],Vp=[`docs`,`types`,`args`,`returns`,`throws`,`get`,`set`],Hp=[`docs`,`args`,`run`];function Up(e,t,n,r){let i=e;for(let n of Jp(i))if(!Rp.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown key '${n}'`+Qp(n,i[n],Rp,t,`top`,r));let a=Yp(e.options)?e.options:void 0;if(t?.optionKeys&&a){for(let n of Jp(a))if(!t.optionKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown options key '${n}'`+Qp(n,a[n],t.optionKeys,t,`options`,r))}let o=Yp(e.generic)?e.generic:void 0;if(n&&t?.genericKeys&&o){for(let n of Jp(o))if(!t.genericKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown generic parameter '${n}'`+Qp(n,o[n],t.genericKeys,t,`generic`,r))}}function Wp(e,t,n,r,i){if(Yp(t))for(let a of Jp(t)){if(n.includes(a))continue;let o=r?.[a],s=typeof o==`function`?o(t[a],i):o,c=Np(a,n);throw Error(`gin.parse: ${e} has unknown key '${a}'`+(s?` \u2014 ${s}`:c?` \u2014 did you mean \`${c}\`?`:` \u2014 valid keys: ${n.join(`, `)}`))}}var Gp={generic:`a fn declares its type parameters on the TYPE, not the call: {"name":"fn","generic":{"T":{"name":"any"}},"call":{"args":…,"returns":…}}`},Kp=[{by:`prop`,keys:[`prop`],example:`{"prop":"name"}`},{by:`args`,keys:[`args`,`generic`,`catch`],example:`{"args":{…}}`},{by:`key`,keys:[`key`],example:`{"key":<expr>}`}];function qp(e){if(!Yp(e))return;let t=Kp.filter(t=>e[t.by]!==void 0);if(t.length===0){let t=Jp(e),n=Kp.map(e=>e.by),r=t.map(e=>Np(e,n)).find(e=>e!==void 0);throw Error(`gin.parse: path step selects no form (keys: ${t.join(`, `)||`none`})`+(r?` \u2014 did you mean \`${r}\`?`:``)+` \u2014 a step is one of ${Kp.map(e=>e.example).join(`, `)}`)}if(t.length>1){let n=t.map(e=>`'${e.by}'`).join(` and `),r=t.map(t=>t.by===`prop`?JSON.stringify({prop:e.prop}):t.example).join(`, `);throw Error(`gin.parse: path step names ${t.length} forms (${n}) \u2014 each is its own step: [${r}]`)}Wp(`path step`,e,t[0].keys)}function Jp(e){return Object.keys(e).filter(t=>e[t]!==void 0)}function Yp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xp(e){return Array.isArray(e)?e.length>0&&Xp(e[0]):Yp(e)&&typeof e.name==`string`}function Zp(e){return Yp(e)&&`type`in e}function Qp(e,t,n,r,i,a){let o=[],s=Np(e,n);if(s)return` \u2014 did you mean \`${s}\`?`;let c=r?.genericKeys??[],l=i===`options`?em(t,r,a):void 0;return l?o.push(l):r&&i!==`generic`&&c.length>0&&Xp(t)?o.push(`that value is a TypeDef, and '${r.NAME}' takes its type argument${c.length>1?`s`:``} in \`generic\` (${c.join(`, `)})`):i===`top`&&Zp(t)&&(r?.consumes??[]).includes(`props`)&&o.push("that value is a PropDef — declare it under `props`"),o.push(rm(n,r,i)),` \u2014 ${o.join(`; `)}`}var $p=12;function em(e,t,n){if(!(!t||t.NAME===`enum`||(t.genericKeys?.length??0)>0))return nm(e,n,"an `enum` in gin, not an option")}var tm={values:(e,t)=>t?nm(e,t,`the prop's TYPE in gin, not a key beside it`,e=>`{"type":${e}}`):"a closed set of constants is the prop's TYPE in gin, not a key beside it: declare `type` as an `enum`"};function nm(e,t,n,r=e=>e){let i=!Array.isArray(e)&&Yp(e),a=Array.isArray(e)?e:i?Object.values(e):void 0;if(!a||a.length===0)return;let o=typeof a[0];if(!a.every(e=>typeof e===o)||o!==`number`&&o!==`boolean`&&o!==`string`)return;let s=`a closed set of constants is ${n}`;if(a.length>$p)return s;let c=i?e:Object.fromEntries(a.map(e=>[String(e),e])),l=o===`number`?t.enum(c,t.num()):o===`boolean`?t.enum(c,t.bool()):o===`string`?t.enum(c,t.text()):void 0;if(l)return`${s}: ${r(JSON.stringify(l.toJSON()))}`}function rm(e,t,n){let r=t?`'${t.NAME}'`:`this type`;return n===`top`?`valid keys: ${e.join(`, `)}`:n===`options`?e.length===0?`${r} takes no options`:`valid options for ${r}: ${e.join(`, `)}`:e.length===0?`${r} is not generic`:`valid generic parameters for ${r}: ${e.join(`, `)}`}var im=/^(?:\w[\w-]*\/)*\w+$/;function am(e){return typeof e==`string`&&im.test(e)}var om={any:`Type_any`,void:`Type_void`,null:`Type_null`,bool:`Type_bool`,num:`Type_num`,text:`Type_text`,list:`Type_list`,map:`Type_map`,tuple:`Type_tuple`,obj:`Type_object`,optional:`Type_optional`,nullable:`Type_nullable`,not:`Type_not`,or:`Type_or`,and:`Type_and`,enum:`Type_enum`,literal:`Type_literal`,fn:`Type_function`,interface:`Type_interface`,typ:`Type_typ`,date:`Type_date`,timestamp:`Type_timestamp`,duration:`Type_duration`,color:`Type_color`},sm=()=>R.string().pattern(im.source).describe(`A type name: an identifier, optionally namespaced as ns/Name.`);function cm(e,t){let n=om[t],r=e.typeClass(t);return r!==void 0&&n!==void 0&&e.namedTypeList().every(e=>e.name!==t)?R.ref(n):r===void 0?R.object({name:R.literal(t)}):r.toA?.()??R.object({name:R.literal(t)})}function lm(){return R.object({name:sm()}).strict().describe(`A named type, by its name.`)}function um(e){return R.object({name:sm(),extends:e.length>0?R.enum([...new Set(e)]):R.never(),docs:R.string().optional(),satisfies:R.array(sm()).optional(),generic:R.ref(`Generic`).optional(),options:R.record(R.unknown()).optional(),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional(),init:R.ref(`InitDef`).optional(),constraint:R.ref(`Expr`).optional()}).describe(`A NEW named type declared inline: a name, the type it extends, and what it adds.`)}var dm=R.ref(`TypeDef`),z=R.ref(`Expr`),fm=R.string().optional().describe("Optional one-line note explaining why this expression exists. Travels with the node, surfaces in `toCode` as a `/* … */` annotation, and shows up in error paths. Use for non-obvious steps; skip for trivial reads."),pm={Generic:R.record(dm).describe(`Generic-parameter bindings: parameter name → TypeDef.`),PathStep:R.union([R.object({prop:R.string().describe("Named-property access. First step looks up a scope variable by name; subsequent steps read the previous value's prop / method. Reject if the name isn't on the type's `props()`.")}).describe("PROP step — `.<name>` access (scope var on first step, prop/method on later steps)."),R.object({args:R.record(z).describe("Map of arg-name → ExprDef. Calls the previous step (a method or any callable). Each arg expression is evaluated in the caller scope before the call; the result obj is bound as `args` inside the call body."),generic:R.ref(`Generic`).optional().describe("Optional generic-parameter map for parameterized callables (e.g. `list.map<R>` binds `R` to the element type of the result list). Usually unnecessary — most callables infer generics."),catch:z.optional().describe("Optional handler expression evaluated if this call throws. The thrown value is bound under `error` in the handler scope.")}).describe("CALL step — invoke the previous step, as its OWN step. Comes after a method (e.g. `list.push`) or any callable value; never fused into the prop step as `{prop, args}`."),R.object({key:z.describe("Indexed-access key expression. Evaluated at run time and passed to the previous value's `[key]` get/set surface.")}).describe("INDEX step — `[<key>]` access for types with index signatures (lists by `num`, maps by their key type).")]),PropDef:R.object({docs:R.string().optional(),type:dm,get:z.optional(),default:z.optional(),set:z.optional()}),GetSetDef:R.object({docs:R.string().optional(),key:dm,value:dm,get:z.optional(),set:z.optional(),loop:z.optional(),loopDynamic:R.boolean().optional().describe("When true, `loop over: <this-typed value>` re-evaluates the expression each iteration and exits when the result's raw is falsy. Bool uses this for while-loop semantics. The type may have either `loop` (for static iterables) OR `loopDynamic` set; with loopDynamic, no `loop` ExprDef is required.")}),CallDef:R.object({docs:R.string().optional(),types:R.record(dm).optional().describe('Call-local type aliases. Declare reusable named types here ONCE and reference them inside `args` / `returns` / `throws` / `get` / `set` as a bare `{name: "<alias>"}`. Aliases process AFTER any enclosing generics (so they may reference generic placeholders) and BEFORE the call slots — the call slots resolve them at parse time. Sequential: later aliases may reference earlier ones. Use this whenever the same composite type appears more than once in a signature — instead of writing `num{whole:true, min:1}` four times, declare `{ counter: { name:"num", options:{whole:true,min:1} } }` once and reference `{name:"counter"}`.'),args:dm,returns:dm.optional(),throws:dm.optional(),get:z.optional(),set:z.optional()}),InitDef:R.object({docs:R.string().optional(),args:dm,run:z})},mm=[`any`,`void`,`null`,`bool`,`num`,`text`,`list`,`map`,`tuple`,`obj`,`optional`,`nullable`,`not`,`or`,`and`,`enum`,`literal`,`fn`,`interface`,`typ`,`date`,`timestamp`,`duration`,`color`],hm={Type_any:R.object({name:R.literal(`any`)}),Type_void:R.object({name:R.literal(`void`)}),Type_null:R.object({name:R.literal(`null`)}),Type_bool:R.object({name:R.literal(`bool`),options:R.object({trueText:R.string().optional(),falseText:R.string().optional()}).optional()}),Type_num:R.object({name:R.literal(`num`),options:R.object({min:R.number().optional().describe('Only set when a real lower bound is part of the spec — e.g. "positive count" → min: 1, "age" → min: 0. Do NOT add `min: 0` to every num just because most numbers happen to be non-negative.'),max:R.number().optional().describe(`Only set when there is an actual upper bound — a percentage capped at 100, a year capped at 9999. Do NOT pick a generic ceiling like 1000/9999 to fill the field.`),whole:R.boolean().optional().describe(`Only set to true when the value is genuinely integral (counts, indices, ids). Leave unset (allow fractions) for measurements, ratios, etc.`),minPrecision:R.number().optional().describe(`Decimal-place floor. Almost never needed; omit unless the spec explicitly requires N decimal places.`),maxPrecision:R.number().optional().describe(`Decimal-place ceiling. Same rule as minPrecision — omit unless explicitly required.`),prefix:R.string().optional().describe(`Display-only prefix (e.g. "$"). Has no effect on validation. Omit unless rendering needs it.`),suffix:R.string().optional().describe(`Display-only suffix (e.g. "%"). Same as prefix — omit unless rendering needs it.`)}).optional().describe(`Omit entirely for ordinary numbers. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_text:R.object({name:R.literal(`text`),options:R.object({minLength:R.number().optional().describe(`Only set when a real lower bound is part of the spec — e.g. "non-empty input" → minLength: 1. Do NOT default to 0.`),maxLength:R.number().optional().describe(`Only set when there is an actual upper bound — a database column width, an API limit, an explicit "no longer than X chars" rule. Do NOT pick a generic ceiling like 100/200/1000 just to fill the field.`),pattern:R.string().optional().describe(`Only set for actual format constraints (UUID, ISO date, slug, etc.). Do NOT use ".*" or other accept-anything patterns — they add zero validation and clutter the schema.`),flags:R.string().optional().describe('Regex flags (e.g. "i"). Omit unless `pattern` is set AND requires flags.')}).optional().describe(`Omit entirely for ordinary strings. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_list:R.object({name:R.literal(`list`),generic:R.object({V:dm}).optional(),options:R.object({minLength:R.number().optional(),maxLength:R.number().optional()}).optional()}),Type_map:R.object({name:R.literal(`map`),generic:R.object({K:dm,V:dm}).optional()}),Type_tuple:R.object({name:R.literal(`tuple`),options:R.object({elements:R.array(dm)})}),Type_object:R.object({name:R.literal(`obj`),props:R.record(R.ref(`PropDef`)).optional()}),Type_optional:R.object({name:R.literal(`optional`),generic:R.object({T:dm}).optional()}),Type_nullable:R.object({name:R.literal(`nullable`),generic:R.object({T:dm}).optional()}),Type_not:R.object({name:R.literal(`not`),options:R.object({excluded:dm})}),Type_or:R.object({name:R.literal(`or`),options:R.object({types:R.array(dm)})}),Type_and:R.object({name:R.literal(`and`),options:R.object({types:R.array(dm)})}),Type_enum:R.object({name:R.literal(`enum`),generic:R.object({V:dm}).optional(),options:R.object({values:R.record(R.unknown())})}),Type_literal:R.object({name:R.literal(`literal`),generic:R.object({T:dm}).optional(),options:R.object({value:R.unknown()})}),Type_function:R.object({name:R.literal(`fn`),call:R.ref(`CallDef`).optional()}),Type_interface:R.object({name:R.literal(`interface`),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional()}),Type_typ:R.object({name:R.literal(`typ`),generic:R.object({T:dm}).optional()}),Type_date:R.object({name:R.literal(`date`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional()}).optional()}),Type_timestamp:R.object({name:R.literal(`timestamp`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional(),precision:R.enum([`ms`,`s`,`us`]).optional()}).optional()}),Type_duration:R.object({name:R.literal(`duration`)}),Type_color:R.object({name:R.literal(`color`),options:R.object({hasAlpha:R.boolean().optional()}).optional()})},gm={Expr_block:R.object({kind:R.literal(`block`),comment:fm,lines:R.array(z).describe(`Sequence of expressions evaluated in order. The block's value is the LAST line's value (an empty block returns void). Earlier lines run for their side effects (set, fns.fetch, etc.).`)}),Expr_define:R.object({kind:R.literal(`define`),comment:fm,vars:R.array(R.object({name:R.string().describe(`Variable name. Must NOT be a reserved name (args, recurse, this, super, key, value, yield, error) and must NOT shadow anything already in scope.`),type:dm.optional().describe("Optional declared type. OMIT this field when the value already determines the type — every value Expr (`new`, `get`, `if`, ...) is typed, and the var inherits that type. Set this only when you need to widen / narrow / annotate beyond what the value alone produces; a mismatch with the value's inferred type is reported as `define.var.type-mismatch`."),value:z.describe("The expression whose result is bound under `name`. May reference any earlier var in this define — each var is added to scope before the next var's value is evaluated.")})).describe("Bindings introduced before `body`. Evaluated sequentially, so `vars[i].value` may reference any of `vars[0..i-1]`."),body:z}),Expr_flow:R.object({kind:R.literal(`flow`),action:R.enum([`break`,`continue`,`return`,`exit`,`throw`]).describe("Which control-flow signal to raise. `break`/`continue` only valid inside a loop. `return` only valid inside a fn body / lambda; unwinds to the enclosing call with `value`. `exit` unwinds all the way to `engine.run`, returning `value` as the program result. `throw` raises `error` (caught by a path step's `catch:` handler)."),value:z.optional().describe("Required for `return` and `exit` (the value being returned). Ignored by `break` / `continue` / `throw`."),error:z.optional().describe("Required for `throw` — the value to raise. Ignored otherwise.")}),Expr_get:R.object({kind:R.literal(`get`),path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right starting from a scope variable. Step shapes: `{prop:"name"}` for prop/method access, `{args:{…}}` to call the previous step, `{key:Expr}` for index access. The first step MUST be a prop step (the scope-var name). A step names exactly ONE shape — a call is its own step, so a method with arguments is `[{"prop":"m"},{"args":{…}}]` and never `{"prop":"m","args":{…}}`. Result is the final step\'s value.')}),Expr_if:R.object({kind:R.literal(`if`),comment:fm,ifs:R.array(R.object({condition:z.describe("Bool-typed expression. First branch whose condition is `true` wins; the rest are skipped."),body:z.describe(`Evaluated when this branch's condition is true. The if-expression's value is this body's value.`)})).describe("Ordered list of `{condition, body}` branches — first true condition wins. Each `condition` must be bool-typed (warned otherwise). With multiple branches this is the gin equivalent of `if / else if / else if`."),else:z.optional().describe("Optional fallback evaluated when every `ifs[i].condition` is false. Without an else, a no-match if-expression evaluates to void.")}),Expr_lambda:R.object({kind:R.literal(`lambda`),comment:fm,type:dm.describe('The lambda\'s function type — `{ name: "fn", call: { args, returns } }` (or a registered named fn type). The `args` obj defines what the body sees under the `args` scope variable; `returns` is what the body must produce.'),body:z.describe('The lambda body. At runtime, scope contains the lexical scope at definition site PLUS `args` (the call arguments) and `recurse` (this same lambda, for self-calls). Read params via `[{prop:"args"},{prop:"<name>"}]`.'),constraint:z.optional().describe("Optional bool-typed precondition evaluated before the body on every call (with `args` in scope). If it returns false, the call throws. Use for input invariants you want enforced regardless of caller.")}),Expr_loop:R.object({kind:R.literal(`loop`),comment:fm,over:z.describe("The iterable expression. Two evaluation modes: (1) iterable types (list, map, etc. — anything whose `get().loop` is defined) iterate once; the expression is evaluated ONCE at the start. (2) bool — while-loop semantics: the expression is RE-EVALUATED each iteration; the loop continues while the value is `true` and exits the moment it becomes `false`. Use `flow:break` / `flow:continue` inside the body to control iteration regardless of mode."),body:z.describe("Evaluated once per iteration with the current `key` and `value` bound in scope. Use `{kind:'flow', action:'break'}` or `'continue'` for early-exit. The loop expression itself returns void."),key:R.string().optional().describe("Override the scope-variable name the iteration index/key is bound under (default: `key`). Must NOT be reserved or shadow an outer scope var. Use to disambiguate when looping inside another loop."),value:R.string().optional().describe("Override the scope-variable name the iteration value is bound under (default: `value`). Same rules as `key`."),parallel:R.object({concurrent:z.optional().describe(`Max in-flight iterations as a num (omit / 1 → strictly sequential). Use when iterations are independent I/O — e.g. fetching N URLs concurrently.`),rate:z.optional().describe(`Minimum interval between iteration starts. Accepts a num (milliseconds) or a duration. Use to rate-limit fan-out (e.g. avoid hammering an API).`)}).optional().describe("Opt-in parallelism. Both fields are optional and independent: `concurrent` caps fan-out width, `rate` paces start times. Iterations may finish out of order; the body should not assume sequential ordering. Composes with dynamic (bool while-loop) iteration: the body fans out up to `concurrent`, and `over` is re-evaluated against the outer scope each time a task completes — so accumulating side effects of earlier tasks decide whether more tasks spawn.")}),Expr_native:R.object({kind:R.literal(`native`),comment:fm,id:R.string().describe("Identifier of a native impl registered via `registry.setNative(id, fn)` (e.g. `list.push`, `num.add`). The model should NOT generate `native` expressions directly — methods on built-in types are reached via `get` paths, which gin resolves to natives internally."),type:dm.optional().describe("Optional type to wrap the native's raw return value with when the impl returns a non-Value. Defaults to `any` if omitted.")}),Expr_set:R.object({kind:R.literal(`set`),comment:fm,path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right to a writable target. Single-step `[{prop:"x"}]` re-assigns scope variable `x`. Multi-step targets need the type to support set on the final step (a prop with a `set` ExprDef, an indexed slot, or a method whose call has `set:`).'),value:z.describe("The expression evaluated and assigned to the path target. Its type must be compatible with the target's declared type — checked statically as `set.type-mismatch`.")}),Expr_switch:R.object({kind:R.literal(`switch`),comment:fm,value:z.describe("Expression whose result is compared against each case's `equals` candidates. Evaluated once."),cases:R.array(R.object({equals:R.array(z).describe("Candidate values for this case. The case wins if `value` equals ANY one of them (logical OR). Each candidate's type must be compatible with `value`'s type — checked as `switch.case.type`."),body:z.describe(`Evaluated when this case wins. The switch expression's value is this body's value.`)})).describe(`Ordered list of cases — first match wins. Cases are NOT fall-through; only the matching case's body runs.`),else:z.optional().describe(`Optional fallback evaluated when no case matches. Without an else, a no-match switch evaluates to void.`)}),Expr_template:R.object({kind:R.literal(`template`),template:R.union([z,R.string()]).describe("The template string — either a literal string (auto-wrapped as `new text`) or an Expr that evaluates to text. Placeholders use `{name}` syntax; each `name` is looked up first in `params` (when supplied) and then in the surrounding scope."),params:z.optional().describe("Optional obj-typed expression supplying placeholder values. When omitted or when a key is missing, `{name}` falls back to a scope lookup of the same name — so a `${baseUrl}` placeholder resolves to a surrounding `define baseUrl = ...`. Provide `params` only when placeholders need values not already in scope (or to override scope values).")})},_m=[`new`,`get`,`set`,`define`,`block`,`if`,`switch`,`loop`,`lambda`,`template`,`flow`,`native`],vm={any:R.unknown(),void:R.null(),null:R.null(),bool:R.boolean(),num:R.number(),text:R.string(),list:R.array(z),map:R.array(R.object({key:z,value:z})),tuple:R.array(z),obj:R.record(z),optional:z,nullable:R.nullable(z),not:R.unknown(),or:z,and:z,enum:R.union([R.string(),R.number()]),literal:R.unknown(),fn:R.union([R.string(),R.object({kind:R.string()})]),interface:R.record(z),typ:dm,date:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`),timestamp:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`),duration:R.object({days:R.number().optional(),hours:R.number().optional(),minutes:R.number().optional(),seconds:R.number().optional(),ms:R.number().optional()}),color:R.object({r:R.int().min(0).max(255),g:R.int().min(0).max(255),b:R.int().min(0).max(255),a:R.number().min(0).max(1).optional()})},ym=(e,t,n)=>R.object({kind:R.literal(`new`),type:t.describe(`Full TypeDef for a \`${e}\` instance (name + options + per-class fields).`),value:R.optional(n).describe(`Initial value matching this \`${e}\` instance. Composites accept Expr slots; primitives accept their raw form.`)}),bm=Object.fromEntries(mm.map(e=>[`New_${e}`,ym(e,R.ref(om[e]),vm[e])])),xm=R.object({kind:R.literal(`new`),type:dm.describe("TypeDef of the value being constructed. The `value` field is interpreted relative to this type — primitives take their raw form (`new num` → number), composites take Expr slots (`new list` → Expr[])."),value:R.unknown().optional().describe("Initial value matching `type`. Optional when the type has a defined `init` constructor or a sensible default (empty list, zero num with no constraints, etc.).")}),Sm=new Set([...Object.keys(pm),...Object.keys(hm),...Object.keys(gm),...Object.keys(bm),`TypeDef`,`Type_Extension`,`Expr_new`,`Expr`]),Cm=(e,t)=>t.length===0?R.never():t.length===1?t[0]:R.discriminatedUnion(e,t);function wm(e,t){let n=new Map;for(let e of t?.types??[])n.set(e.name,e);for(let t of e.namedTypeList())n.has(t.name)||n.set(t.name,t);return n}function Tm(e,t){let n=wm(e,t),r=[...n.keys()],i=e.typeClasses(),a=[...r.map(e=>R.object({name:R.literal(e)}).describe(`The registered named type \`${e}\`, by name.`)),...i.map(t=>cm(e,t.NAME)),R.ref(`Type_Extension`)];t?.namedRefs&&a.push(lm());let o=um([...i.map(e=>e.NAME),...r]),s=e.exprClassList().map(e=>_m.includes(e.KIND)&&e.KIND!==`new`?R.ref(`Expr_${e.KIND}`):e.KIND===`new`?R.ref(`Expr_new`):e.toA?.()??R.object({kind:R.literal(e.KIND)}).describe(`A \`${e.KIND}\` expression.`)),c=xm,l={};if(t?.newStrict){let t=[...n].map(([e,t])=>{let r=R.object({kind:R.literal(`new`),type:R.object({name:R.literal(e)}).describe(`Reference to the registered named type \`${e}\` \u2014 name-only, the registry resolves it to its full definition.`),value:R.optional(t.toNewA()).describe(`Initial value for the new \`${e}\` instance. Each composite slot accepts an Expr (Get, NewExpr, etc.); per-slot type correctness is enforced at runtime.`)});return Sm.has(`New_${e}`)||n.has(`New_${e}`)?r:(l[`New_${e}`]=r,R.ref(`New_${e}`))}),r=i.map(t=>om[t.NAME]!==void 0&&mm.includes(t.NAME)?R.ref(`New_${t.NAME}`):ym(t.NAME,cm(e,t.NAME),t.toNewA?.()??R.unknown()));c=R.union([...t,...r])}let u={};for(let[e,t]of n)Sm.has(e)||(u[e]=t.defineA({includeDocs:`all`}));return{...u,...l,TypeDef:Cm(`name`,a),Type_Extension:o,Expr_new:c,Expr:Cm(`kind`,s)}}var Em=new WeakMap,Dm=0,Om=e=>{let t=Em.get(e);return t===void 0&&Em.set(e,t=++Dm),t},km=(e,t)=>`${Om(e)}:${e.version}|${t?.newStrict?`s`:``}${t?.namedRefs?`r`:``}|${(t?.types??[]).map(e=>e.name).join(`,`)}`,Am=R.define(pm).define(hm).define(gm).define(bm).declare(),jm=Am.dynamic((e,t)=>Tm(e,t),{key:km,cacheSize:8});jm.result(`TypeDef`),jm.result(`Expr`);var Mm=class{list=[];stack=[];enter(e){return Array.isArray(e)?this.stack.push(...e):this.stack.push(e),this}leave(e=1){return this.stack.length=Math.max(0,this.stack.length-e),this}at(e,t){let n=Array.isArray(e)?e.length:1;this.enter(e);try{return t()}finally{this.leave(n)}}push(e,t,n=`error`,r){this.list.push({path:this.stack.slice(),code:e,message:t,severity:n,source:r})}error(e,t,n){this.push(e,t,`error`,n)}warn(e,t,n){this.push(e,t,`warning`,n)}info(e,t,n){this.push(e,t,`info`,n)}get hasErrors(){return this.list.some(e=>e.severity===`error`)}},Nm=class extends Error{constructor(e){super(`${e.code}: ${e.message} at ${e.path.join(`.`)}`),this.problem=e,this.name=`TypeError`}problem},B={NONE:0,STATE:1,SYSTEM:2,EXTERNAL:4};function Pm(...e){let t=B.NONE;for(let n of e)t|=n;return t}var V=class e{constructor(e,t=[]){this.text=e,this.spans=t}text;spans;toString(){return this.text}concat(t){if(typeof t==`string`)return new e(this.text+t,this.spans);let n=this.text.length,r=t.spans.map(e=>({...e,start:e.start+n,end:e.end+n}));return new e(this.text+t.text,[...this.spans,...r])}indent(t){if(!t||!this.text.includes(`
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
+ `&&(i+=t.length);r[n]=i;let a=this.text.replace(/\n/g,`
74
+ ${t}`),o=this.spans.map(e=>({...e,start:e.start+r[e.start],end:e.end+r[e.end]}));return new e(a,o)}static jsonObject(t,n,r=0,i=2){let a=t.filter(e=>e.value!==void 0);if(a.length===0)return Fm(`{}`,n);let o=` `.repeat((r+1)*i),s=` `.repeat(r*i);return Fm(H`{\n${Im(a.map(({key:t,value:n})=>{let r=typeof n==`string`?new e(n):n;return H`${o}${JSON.stringify(t)}: ${r}`}),`,
75
+ `)}\n${s}}`,n)}static jsonArray(t,n,r=0,i=2){if(t.length===0)return Fm(`[]`,n);let a=` `.repeat((r+1)*i),o=` `.repeat(r*i);return Fm(H`[\n${Im(t.map(t=>{let n=typeof t==`string`?new e(t):t;return H`${a}${n}`}),`,
76
+ `)}\n${o}]`,n)}static jsonString(e){return JSON.stringify(e)}formatProblems(e,t={}){return Vm(this,e.list,t)}formatProblem(e,t={}){return Vm(this,[e],{...t,sectionHeaders:!1,lineNumbers:!1,contextLines:0})}spanFor(e){let t,n=-1,r=1/0;for(let i of this.spans){if(!Gm(i.path,e))continue;let a=i.end-i.start;(i.path.length>n||i.path.length===n&&a<r)&&(t=i,n=i.path.length,r=a)}return t}toLines(){let e=[],t=this.text.split(`
77
+ `),n=0;for(let r=0;r<t.length;r++){let i=t[r],a=n,o=n+i.length,s=[];for(let e of this.spans){if(e.end<=a||e.start>=o)continue;let t=Math.max(e.start,a)-a,n=Math.min(e.end,o)-a;s.push({...e,start:t,end:n})}e.push({text:i,spans:s,lineNum:r+1}),n=o+1}return e}};function Fm(e,t){let n=typeof e==`string`?new V(e):e,r={start:0,end:n.text.length,path:t.path,expr:t.expr,type:t.type};return new V(n.text,[r,...n.spans])}function H(e,...t){let n=``,r=[];for(let i=0;i<e.length;i++)if(n+=e[i],i<t.length){let e=t[i];if(typeof e==`string`)n+=e;else{let t=n.length;n+=e.text;for(let n of e.spans)r.push({...n,start:n.start+t,end:n.end+t})}}return new V(n,r)}function Im(e,t=``){if(e.length===0)return new V(``);let n=typeof t==`string`?new V(t):t,r=typeof e[0]==`string`?new V(e[0]):e[0];for(let t=1;t<e.length;t++)r=r.concat(n).concat(e[t]);return r}function Lm(e){return Im(e,`
78
+ `)}var Rm={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,cyan:`\x1B[36m`},zm={error:`error`,warning:`warning`,info:`info`},Bm={error:Rm.red,warning:Rm.yellow,info:Rm.blue};function Vm(e,t,n){if(t.length===0)return``;let r=n.color??!1,i=n.contextLines??2,a=n.sectionHeaders??!0,o=n.lineNumbers??!0,s=n.maxProblems??1/0,c=(e,t)=>r?`${e}${t}${Rm.reset}`:t,l=e.toLines(),u=[],d=[],f=0;for(let n=0;n<t.length;n++){if(n>=s){f=t.length-n;break}let r=t[n],i=Hm(e,l,r);if(i)u.push(i);else{let e=Bm[r.severity],t=`${zm[r.severity]}:`,n=r.path.length>0?` @ ${r.path.join(`.`)}`:``;d.push(`${c(e,t)} ${r.message}${n}`)}}let p=Um(u,l.length,i),m=l.length,h=o?String(m).length:0,ee=p.map(e=>Wm(e,l,{color:r,sectionHeaders:a,lineNumbers:o,gutterWidth:h,c}));return d.length>0&&ee.push(d.join(`
79
+ `)),f>0&&ee.push(`\u2026 (${f} more problem${f===1?``:`s`} suppressed)`),ee.join(`
80
+
81
+ `)}function Hm(e,t,n){let r=e.spanFor(n.path);if(!r)return null;let i=new Map,a=0,o=-1,s=-1;for(let e=0;e<t.length;e++){let n=t[e].text,c=a,l=a+n.length;if(r.end>c&&r.start<=l){let t=Math.max(r.start,c)-c,n=Math.min(r.end,l)-c;i.set(e,{startCol:t,endCol:n}),o<0&&(o=e),s=e}a=l+1}return o<0?null:{problem:n,firstLine:o,lastLine:s,hits:i}}function Um(e,t,n){if(e.length===0)return[];let r=[...e].sort((e,t)=>e.firstLine-t.firstLine),i=[];for(let e of r){let r=Math.max(0,e.firstLine-n),a=Math.min(t-1,e.lastLine+n),o=i[i.length-1];o&&r<=o.lastLine+1?(o.lastLine=Math.max(o.lastLine,a),o.problems.push(e)):i.push({firstLine:r,lastLine:a,problems:[e]})}return i}function Wm(e,t,n){let{color:r,sectionHeaders:i,lineNumbers:a,gutterWidth:o,c:s}=n,c=[],l=e=>a?s(Rm.dim,`${String(e).padStart(o)} \u2502 `):``,u=()=>a?s(Rm.dim,`${` `.repeat(o)} \u2502 `):``;if(i){let t=e.firstLine===e.lastLine?`line ${e.firstLine+1}`:`lines ${e.firstLine+1}-${e.lastLine+1}`,n=`─`.repeat(Math.max(3,60-t.length-4));c.push(s(Rm.dim,`\u2500\u2500 ${t} ${n}`))}let d={error:0,warning:1,info:2};for(let n=e.firstLine;n<=e.lastLine;n++){c.push(l(n+1)+t[n].text);let r=new Map;for(let t of e.problems){let e=t.hits.get(n);if(!e)continue;let i=`${e.startCol}:${e.endCol}`,a=r.get(i);(!a||d[t.problem.severity]<d[a])&&r.set(i,t.problem.severity)}for(let[e,t]of r){let[n,r]=e.split(`:`),i=Number(n),a=Number(r),o=` `.repeat(i)+`^`.repeat(Math.max(1,a-i));c.push(u()+s(Bm[t],o))}for(let t of e.problems){if(t.lastLine!==n)continue;let e=t.problem.severity,r=s(Bm[e],`${zm[e]}:`);c.push(u()+`${r} ${t.problem.message}`)}}return c.join(`
82
+ `)}function Gm(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Km(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}var qm=new WeakMap,Jm=0,Ym=e=>{let t=qm.get(e);return t===void 0&&qm.set(e,t=++Jm),t},Xm=new WeakMap;function Zm(e){let t=Xm.get(e);return t===void 0&&(t=e instanceof Qm?`${Zm(e.parent)}/${Ym(e.bindingsRecord)}`:String(Ym(e)),Xm.set(e,t)),t}var Qm=class{parent;registry;local;constructor(e,t={}){this.parent=e,this.registry=e.registry,this.local=t}lookup(e){return this.local[e]??this.parent.lookup(e)}localLookup(e){return this.local[e]}get bindingsRecord(){return this.local}parse(e){return this.registry.parse(e,this)}parseExpr(e){return this.registry.parseExpr(e,this)}bind(e,t){this.local[e]=t}ownNames(){return Object.keys(this.local)}},$m=class e{comment;withComment(e){return e&&(this.comment=e),this}useLineComment(e={}){return e.expectsValue===!1}commentPrefix(e={}){return!this.comment||e.includeComments===!1?``:this.useLineComment(e)?`// ${this.comment}
83
+ `:`/* ${this.comment} */ `}withCommentOn(e){return this.comment?{...e,comment:this.comment}:e}validate(e,t){let n=new Mm,r=t??e.globalTypeScope();return this.validateWalk(e,r,n,{inLoop:!1,inLambda:!1}),n}toCode(e,t){return this.toGinCode(e,t).toString()}toGinCode(e,t,n=[]){return Fm(this._toCodeFallback(e,t),{path:n,expr:this})}renderStatementBody(e,t={},n=!1){let r=this.kind;if(r===`flow`)return`${this.toCode(e,{...t,expectsValue:!1})};`;if(n&&r===`if`)return this.toCode(e,{...t,expectsValue:!1});if(r===`block`){let n=this.toCode(e,{...t,expectsValue:!1});return n.startsWith(`{`)?n:`{
84
+ ${eh(n)}
85
+ }`}return r===`if`||r===`switch`||r===`loop`?`{
86
+ ${eh(this.toCode(e,{...t,expectsValue:!1}))}
87
+ }`:`{
88
+ ${eh(this.toCode(e,{...t,expectsValue:!0}))};
89
+ }`}renderStatementBodyRich(e,t={},n=[],r=!1){let i=this.kind;if(i===`flow`)return H`${this.toGinCode(e,{...t,expectsValue:!1},n)};`;if(r&&i===`if`)return this.toGinCode(e,{...t,expectsValue:!1},n);if(i===`block`){let r=this.toGinCode(e,{...t,expectsValue:!1},n);return r.text.startsWith(`{`)?r:H`{\n ${r.indent(` `)}\n}`}return i===`if`||i===`switch`||i===`loop`?H`{\n ${this.toGinCode(e,{...t,expectsValue:!1},n).indent(` `)}\n}`:H`{\n ${this.toGinCode(e,{...t,expectsValue:!0},n).indent(` `)};\n}`}toJSONCode(e=[],t=2,n=0){let r=JSON.stringify(this.toJSON(),null,t);if(n>0){let e=` `.repeat(n*t);r=r.replace(/\n/g,`
90
+ `+e)}return Fm(r,{path:e,expr:this})}_toCodeFallback(t,n){let r=Object.getPrototypeOf(this).toCode;return r&&r!==e.prototype.toCode?r.call(this,t,n):`<unrendered:${this.kind??`?`}>`}forEachChild(e){}};function eh(e){return e.replace(/\n/g,`
91
+ `)}var th=new Set([`args`,`recurse`,`this`,`super`,`key`,`value`,`yield`,`error`]),nh=class e{parent;vars;control;constructor(e=null,t,n){this.parent=e,this.vars=new Map(t?Object.entries(t):[]),this.control=n??e?.control}async checkpoint(){this.control&&await this.control.checkpoint()}get(e){let t=this.vars.get(e);return t===void 0?this.parent?.get(e):t}set(e,t){this.vars.has(e)?this.vars.set(e,t):this.parent&&this.parent.has(e)?this.parent.set(e,t):this.vars.set(e,t)}has(e){return this.vars.has(e)?!0:this.parent?.has(e)??!1}child(t){return new e(this,t)}names(){let e=new Set;for(let t=this;t;t=t.parent)for(let n of t.vars.keys())e.add(n);return[...e]}};function rh(e,t,n){let r=t instanceof $m?t:ih(e,t);return r?r.typeOf(e,n):e.registry.any()}function ih(e,t){try{return e.registry.parseExpr(t)}catch{return}}function ah(e,t,n,r={inLoop:!1,inLambda:!1}){let i=new Mm;return oh(e,t,n,i,r),i}function oh(e,t,n,r,i){let a;if(t instanceof $m)a=t;else try{a=e.registry.parseExpr(t)}catch{return r.warn(`expr.unknown-kind`,`unknown expr kind '${t.kind}'`),e.registry.any()}return a.validateWalk(e,n,r,i)}function sh(e,t,n){th.has(e)?n.error(`binding.reserved`,`'${e}' is a reserved name (gin binds it automatically in fn/loop/path contexts) \u2014 pick a different name`):t.has(e)&&n.error(`binding.shadow`,`'${e}' is already in scope \u2014 pick a different name to avoid shadowing`)}var ch=class{constructor(e){this.action=e}action},lh=class extends ch{constructor(){super(`break`)}},uh=class extends ch{constructor(){super(`continue`)}},dh=class extends ch{constructor(e){super(`return`),this.value=e}value},fh=class extends ch{constructor(e){super(`exit`),this.value=e}value},ph=class extends ch{constructor(e){super(`throw`),this.error=e}error};function mh(e,t){let n=new vh(t);n.type(e,_h);let r=new Set(n.defines);return{refs:n.refs.filter(e=>!r.has(e)),defines:n.defines}}function hh(e,t,n){let r=new Map,i=[],a=[],o=new Map,s=new Set;for(let n of e)for(let e of mh(n,t).defines)s.add(e);let c=e=>{if(o.has(e)||s.has(e))return;let l=n(e);if(!l)o.set(e,`done`),i.push(e);else{o.set(e,`visiting`),r.set(e,l);for(let e of mh(l,t).refs)c(e);o.set(e,`done`),a.push(e)}};for(let n of e)for(let e of mh(n,t).refs)c(e);return{order:a,defs:r,missing:i}}var gh=new Set([`enum`,`literal`]),_h=new Set,vh=class{constructor(e){this.registry=e}registry;refs=[];defines=[];seenRefs=new Set;seenDefines=new Set;type(e,t){let n=this.registry.typeClass(e.name),r=e.extends!==void 0||n?.declaresGenerics===!0;e.extends===void 0?n||this.name(e.name,t):(this.define(e.name),this.name(e.extends,t));for(let n of e.satisfies??[])this.name(n,t);let i=r&&e.generic?xh(t,Object.keys(e.generic)):t;for(let t of Object.values(e.generic??{}))this.type(t,i);n&&gh.has(n.NAME)||this.options(e.options,i);for(let t of Object.values(e.props??{}))this.prop(t,i);e.get&&this.getSet(e.get,i),e.call&&this.call(e.call,i),e.init&&(this.type(e.init.args,i),this.expr(e.init.run,i)),e.constraint&&this.expr(e.constraint,i)}name(e,t){t.has(e)||this.registry.typeClass(e)||this.seenRefs.has(e)||(this.seenRefs.add(e),this.refs.push(e))}define(e){this.seenDefines.has(e)||(this.seenDefines.add(e),this.defines.push(e))}options(e,t){if(yh(e))for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)bh(e)&&this.type(e,t);else bh(n)&&this.type(n,t)}prop(e,t){this.type(e.type,t),this.expr(e.get,t),this.expr(e.set,t),this.expr(e.default,t)}getSet(e,t){this.type(e.key,t),this.type(e.value,t),this.expr(e.get,t),this.expr(e.set,t),this.expr(e.loop,t)}call(e,t){let n=t;for(let[t,r]of Object.entries(e.types??{}))this.type(r,n),n=xh(n,[t]);this.type(e.args,n),e.returns&&this.type(e.returns,n),e.throws&&this.type(e.throws,n),this.expr(e.get,n),this.expr(e.set,n)}expr(e,t){if(Array.isArray(e)){for(let n of e)this.expr(n,t);return}if(!yh(e))return;let n=bh(e.type)&&this.registry.typeClass(e.type.name)?.valuesAreTypes===!0;for(let[r,i]of Object.entries(e))if(r===`type`&&bh(i))this.type(i,t);else if(r===`generic`&&yh(i))for(let e of Object.values(i))bh(e)&&this.type(e,t);else r===`value`?n&&bh(i)?this.type(i,t):this.data(i,t):this.expr(i,t)}data(e,t){if(Array.isArray(e))for(let n of e)this.data(n,t);else if(yh(e)){if(this.isExpr(e))this.expr(e,t);else for(let n of Object.values(e))this.data(n,t)}}isExpr(e){return typeof e.kind==`string`&&this.registry.exprClass(e.kind)!==void 0}};function yh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function bh(e){return yh(e)&&typeof e.name==`string`}function xh(e,t){return t.length===0?e:new Set([...e,...t])}function Sh(e,t,n){if(e===t||e.compatible(t,void 0,n))return!0;for(let r=Ch(t);r;r=Ch(r))if(e.compatible(r,void 0,n))return!0;return!1}function Ch(e){let t=e.base;return t instanceof U&&t!==e?t:void 0}function wh(e){if(e.name!==`or`)return;let t=e.variants;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function Th(e){if(e.name!==`and`)return;let t=e.parts;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function Eh(e,t,n){let r=e.type.encodeAs(e.raw,t,n);return t.form===`logical`?r:{type:e.type.toJSONRef(t),value:r}}function Dh(e,t,n,r,i){n instanceof W&&n.raw!==void 0&&(e[t]=Eh(n,r,i))}var Oh={form:`envelope`,typeRefs:`definition`};function kh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&!(e instanceof W)}function Ah(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return;let n=e.kind;if(typeof n==`string`&&t.registry.exprClass(n))try{return t.registry.parseExpr(e,t)}catch{return}}var jh=class e{type;get;set;default;docs;constructor(e){this.type=e.type,this.get=e.get,this.set=e.set,this.default=e.default,this.docs=e.docs}static from(t,n,r){if(t instanceof U)return new e({type:t});t instanceof e||Wp(r?`prop '${r}'`:`prop`,t,zp,tm,n?.registry);let i=t.type,a=i instanceof U?i:(()=>{if(!n)throw Error(`Prop.from: type is TypeDef but no scope provided to parse it`);return n.parse(i)})(),o=e=>e instanceof $m?e:n?.parseExpr(e),s=o(t.get),c=o(t.set),l=o(t.default);return t instanceof e&&t.type===a&&t.get===s&&t.set===c&&t.default===l?t:new e({type:a,get:s,set:c,default:l,docs:t.docs})}static fromMap(t,n){let r={};for(let[i,a]of Object.entries(t))r[i]=e.from(a,n,i);return r}static toJSONMap(t){let n={};for(let[r,i]of Object.entries(t))n[r]=e.from(i).toJSON();return n}toJSON(){return Km({docs:this.docs,type:this.type.toJSON(),get:this.get?.toJSON(),default:this.default?.toJSON(),set:this.set?.toJSON()})}async read(e,t,n,r,i=this.type){if(this.get){let i={this:e},a=e.type.propSuperFor(e,t,`get`,n,r);return a&&(i.super=a),this.get.evaluate(r,n.child(i))}return e.type.propGet(e,t,i)}async write(e,t,n,r,i){if(this.set){let a={this:e,value:n},o=e.type.propSuperFor(e,t,`set`,r,i);o&&(a.super=o),await this.set.evaluate(i,r.child(a))}else{if(this.get&&!this.type.call())throw Error(`path: prop '${t}' is computed (has 'get', no 'set') \u2014 cannot assign to it`);e.type.propSet(e,t,n)}}async invokeMethod(e,t,n,r,i,a){let o=a??this.type;if(!this.get){let a=e.raw?.[t],o=a instanceof W?a.raw:a;if(typeof o==`function`)return await o(n);if(o&&typeof o==`object`&&`kind`in o){let e=await i.evaluate(o,r);if(typeof e.raw==`function`)return await e.raw(n)}throw Error(`path: callable prop '${t}' has no get expression and raw is not a callable`)}let s=this.get,c=async n=>{let a={this:e,args:n,recurse:new W(o,c)},l=e.type.propSuperFor(e,t,`get`,r,i);l&&(a.super=l);try{return await s.evaluate(i,r.child(a))}catch(e){if(e instanceof dh)return e.value??new W(i.registry.void(),void 0);throw e}};return c(n)}async invokeMethodSet(e,t,n,r,i,a,o){let s=o??this.type,c=s.call?.();if(!c?.set)throw Error(`path: method '${t}' has no call.set`);let l=async n=>{let o={this:e,args:n,value:r,recurse:new W(s,l)},u=e.type.propSuperFor(e,t,`callSet`,i,a);return u&&(o.super=u),await c.set.evaluate(a,i.child(o)),G(a.registry.void(),void 0)};await l(n)}},Mh=class e{key;value;get;set;loop;loopDynamic;docs;constructor(e){this.key=e.key,this.value=e.value,this.get=e.get,this.set=e.set,this.loop=e.loop,this.loopDynamic=e.loopDynamic,this.docs=e.docs}static from(t,n){t instanceof e||Wp(`get/set surface`,t,Bp);let r=t.key,i=t.value,a=r instanceof U?r:(()=>{if(!n)throw Error(`GetSet.from: key is TypeDef but no scope provided`);return n.parse(r)})(),o=i instanceof U?i:(()=>{if(!n)throw Error(`GetSet.from: value is TypeDef but no scope provided`);return n.parse(i)})(),s=e=>e instanceof $m?e:n?.parseExpr(e),c=s(t.get),l=s(t.set),u=s(t.loop);return t instanceof e&&t.key===a&&t.value===o&&t.get===c&&t.set===l&&t.loop===u?t:new e({key:a,value:o,get:c,set:l,loop:u,loopDynamic:t.loopDynamic,docs:t.docs})}toJSON(){return Km({docs:this.docs,key:this.key.toJSON(),value:this.value.toJSON(),get:this.get?.toJSON(),set:this.set?.toJSON(),loop:this.loop?.toJSON(),loopDynamic:this.loopDynamic})}async indexRead(e,t,n,r){if(!this.get)throw Error(`path: type '${e.type.name}' has no index get`);let i={this:e,key:t},a=e.type.indexSuperFor(e,`get`,n,r);return a&&(i.super=a),this.get.evaluate(r,n.child(i))}async indexWrite(e,t,n,r,i){if(!this.set)throw Error(`path: type '${e.type.name}' has no index set`);let a={this:e,key:t,value:n},o=e.type.indexSuperFor(e,`set`,r,i);o&&(a.super=o),await this.set.evaluate(i,r.child(a))}},Nh=class e{args;returns;throws;get;set;docs;types;constructor(e){this.args=e.args,this.returns=e.returns,this.throws=e.throws,this.get=e.get,this.set=e.set,this.docs=e.docs,this.types=e.types}static from(t,n){t instanceof e||Wp(`call signature`,t,Vp,Gp);let r=t.types,i=n,a;if(r&&Object.keys(r).length>0){if(Object.values(r).every(e=>e instanceof U))a=r;else{if(!n)throw Error(`Call.from: types contain TypeDef but no scope provided`);let e=new Qm(n);i=e,a={};for(let[t,n]of Object.entries(r)){let r=n instanceof U?n:e.parse(n);e.bind(t,r),a[t]=r}}}let o=t.args,s=t.returns,c=t.throws,l=o instanceof U?o:(()=>{if(!i)throw Error(`Call.from: args is TypeDef but no scope provided`);return i.parse(o)})(),u=s===void 0?void 0:s instanceof U?s:(()=>{if(!i)throw Error(`Call.from: returns is TypeDef but no scope provided`);return i.parse(s)})(),d=c===void 0?void 0:c instanceof U?c:(()=>{if(!i)throw Error(`Call.from: throws is TypeDef but no scope provided`);return i.parse(c)})(),f=e=>e instanceof $m?e:i?.parseExpr(e),p=f(t.get),m=f(t.set),h=t.docs;return t instanceof e&&t.args===l&&t.returns===u&&t.throws===d&&t.get===p&&t.set===m&&t.types===a?t:new e({args:l,returns:u,throws:d,get:p,set:m,docs:h,types:a})}toJSON(){let e=this.types&&Object.keys(this.types).length>0?Object.fromEntries(Object.entries(this.types).map(([e,t])=>[e,t.toJSON()])):void 0;return Km({docs:this.docs,types:e,args:this.args.toJSON(),returns:this.returns?.toJSON(),throws:this.throws?.toJSON(),get:this.get?.toJSON(),set:this.set?.toJSON()})}renderTypes(e){if(!this.types)return``;let t=Object.keys(this.types);return t.length===0?``:`{${Bh(t.map(t=>`${t}: ${this.types[t].toCode(void 0,e)}`),{sep:`; `})}}`}effects(){let e=0;return this.get&&(e|=this.get.effects()),this.set&&(e|=this.set.effects()),e}},Ph=class e{args;run;docs;constructor(e){this.args=e.args,this.run=e.run,this.docs=e.docs}static from(t,n){t instanceof e||Wp(`init constructor`,t,Hp);let r=t.args,i=r instanceof U?r:(()=>{if(!n)throw Error(`Init.from: args is TypeDef but no scope provided`);return n.parse(r)})(),a=t.run,o=a instanceof $m?a:(()=>{if(!n)throw Error(`Init.from: run is ExprDef but no scope provided`);return n.parseExpr(a)})();return t instanceof e&&t.args===i&&t.run===o?t:new e({args:i,run:o,docs:t.docs})}toJSON(){return Km({docs:this.docs,args:this.args.toJSON(),run:this.run.toJSON()})}},U=class e{constructor(e,t,n={}){this.scope=e,this.options=t,this.generic=n}scope;options;generic;get registry(){return this.scope.registry}priority=0;docs;parsesExprValue(e){return!1}encodeAs(e,t,n){return this.encode(e,n)}toJSONRef(e){if(e?.typeRefs!==`name`)return this.toJSON();if(this.registry.lookup(this.name)===this)return{name:this.name};let t=this.toJSON(),n=Object.keys(this.generic);if(n.length===0)return t;let r={...t.generic??{}};for(let t of n)r[t]=this.generic[t].toJSONRef(e);return{...t,generic:r}}toDefinitionJSON(){let e=Lh.depth;Lh.active++,Lh.depth=this.registry.lookup(this.name)===this?0:1;try{return this.toJSON()}finally{Lh.active--,Lh.depth=e}}references(){return mh(this.toDefinitionJSON(),this.registry)}closure(e=this.scope){return hh([this.toDefinitionJSON()],this.registry,t=>e.lookup(t)?.toDefinitionJSON())}compatibleWithParts(e,t,n){let r=Th(e);if(!r)return!1;if(r.some(e=>this.compatible(e,t,n)))return!0;let i=e.simplify(n);return i!==e&&this.compatible(i,t,n)}compatible(e,t,n){for(let t=0;e.name===`alias`&&t<8;t++){let t=e.simplify(n);if(t===e)break;e=t}if(e===this)return!0;let r=Fh,i=Ih(t,n),a=r.active.get(this)?.get(e);if(a!==void 0&&a.key===i)return r.lowWater=Math.min(r.lowWater,a.depth),!0;let o=r.memo.get(this)?.get(e)?.get(i);if(o!==void 0)return o;let s=r.depth++,c=r.active.get(this);c||r.active.set(this,c=new Map),c.set(e,{depth:s,key:i});let l=r.lowWater;r.lowWater=1/0;let u=!1;try{let a=wh(e);if(u=a?a.every(e=>this.compatible(e,t,n)):this.compatibleType(e,t,n)||this.compatibleWithParts(e,t,n)||this.compatibleWithBase(e,t,n),!u||r.lowWater>=s){let t=r.memo.get(this);t||r.memo.set(this,t=new Map);let n=t.get(e);n||t.set(e,n=new Map),n.set(i,u)}return u}finally{c.delete(e),r.lowWater=Math.min(l,r.lowWater),--r.depth===0&&(r.memo=new Map,r.active=new Map,r.lowWater=1/0)}}compatibleWithBase(t,n,r){if(n?.strict||n?.exact)return!1;let i=t.base;return i instanceof e&&i!==t&&this.compatible(i,n,r)}accepts(e,t){return this.compatible(e,{strict:!0},t)}exact(e,t){return this.compatible(e,{strict:!0,exact:!0},t)}flexible(){return!1}like(e,t){return this}isUniversal(){return!1}simplify(e){return this}required(){return this}isOptional(){return!1}props(e){let t={toAny:this.registry.method({},this.registry.any(),`type.toAny`)},n=this.registry.augmentation(this.name);return n?.props?{...t,...n.props}:t}static UNIVERSAL_PROP_NAMES=new Set([`toAny`]);constraints(){return[]}get(e){return this.registry.augmentation(this.name)?.get}call(e){return this.registry.augmentation(this.name)?.call}init(e){return this.registry.augmentation(this.name)?.init}prop(e,t){let n=this.props(t)[e];return n?jh.from(n):void 0}follow(e,t){if(`prop`in e)return this.prop(e.prop,t)?.type;if(`args`in e)return this.call(t)?.returns;if(`key`in e)return this.get(t)?.value}at(e,t){let n=this;for(let r of e){if(!n)return;n=n.follow(r,t)}return n}toA(e){return e?.override?.(this)||(this.isRegisteredNamed()?R.ref(this.name):this.defineA(e))}defineA(e){return this.describeA(this.valueA(e),e)}valueA(e){return R.unknown()}toNewA(e){let t=this.init(e?.scope);return t?this.describeA(t.args.toA(e),e):this.toA(e)}isRegisteredNamed(){let e=this.registry;return e.typeClass(this.name)===void 0&&e.namedTypeList().includes(this)}objectA(e,t){let n=R.object(e);return t?.unknownKeys===`refuse`?n.strict():n}describeA(e,t){let n=t?.includeDocs??`none`,r=[];n!==`none`&&this.docs&&r.push(this.docs);let i=this.constraints();return i.length>0&&r.push(i.map(e=>`must satisfy ${e.toCode(this.registry,{expectsValue:!0})}`).join(`; `)),r.length>0?e.describe(r.join(` — `)):e}newEffects(e){let t=this.initEffects();return this.forEachNewSlot(e,{slot:(e,n)=>{t|=e.newEffects(n)},missing:e=>{t|=e.effects()}})?t:t|this.exprValueEffects(e)}exprValueEffects(e){if(!e||typeof e!=`object`||Array.isArray(e))return B.NONE;let t=e.kind;if(typeof t!=`string`||!this.registry.exprClass(t))return B.NONE;try{return this.registry.parseExpr(e,this.scope).effects()}catch{return B.NONE}}initEffects(){let e=this.init();if(!e)return B.NONE;try{return this.registry.parseExpr(e.run,this.scope).effects()}catch{return B.NONE}}newComplexity(e){let t=1+this.initComplexity();return this.forEachNewSlot(e,{slot:(e,n)=>{t+=e.elementComplexity(n)},missing:e=>{t+=e.complexity()}})?t:t+this.exprValueComplexity(e)}exprValueComplexity(e){if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e.kind;if(typeof t!=`string`||!this.registry.exprClass(t))return 0;try{return this.registry.parseExpr(e,this.scope).complexity()}catch{return 0}}initComplexity(){let e=this.init();if(!e)return 0;try{return this.registry.parseExpr(e.run,this.scope).complexity()}catch{return 0}}elementComplexity(e){let t=this.exprValueComplexity(e);return t>0?t:1}forEachNewSlot(e,t){return!1}validateNewValue(e,t,n,r,i){if(this.forEachNewSlot(e,{slot:(e,a,o)=>{r.at([o],()=>e.validateNewValue(a,t,n,r,i))}}))return;let a=Ah(e,this.scope);if(!a)return;let o=a.validateWalk(t,n,r,i);o.name!==`any`&&(Sh(this,o)||r.error(`new.slot.type`,`this slot is declared \`${this.toCode()}\` but the expression here produces \`${o.toCode()}\``))}async newFill(e,t,n){let r=Ah(e,this.scope);return r?r.evaluate(t,n):e}toGinCode(e,t,n=[]){return Fm(this.toCode(e,t),{path:n,type:this})}toJSONCode(e=[],t=2,n=0){return Jh(this.toJSON(),this.registry,e,t,n,this)}docsPrefix(e){return``}extendsClause(e){return``}toCodeRef(e,t){return this.toCode(e,t)}refProps(){return{}}refGet(){}refCall(){}static renderGenerics(e,t){let n=Object.keys(e);return n.length===0?``:`<${Bh(n.map(n=>{let r=e[n],i=r.name===`alias`&&r.options?.name===n;return r.name===`any`||i?n:`${n}: ${r.toCode(void 0,t)}`}),{indent:Vh(t)})}>`}static renderGenericArgs(t,n){let r=Object.keys(t);return r.length===0||!r.some(n=>!e.isGenericPlaceholder(n,t[n]))?``:`<${Bh(r.map(e=>t[e].toCode(void 0,n)),{indent:Vh(n)})}>`}static isGenericPlaceholder(e,t){return t.name===`any`||t.name===`alias`&&t.options?.name===e}static formatParams(e,t,n=`auto`){let r=e.fields;if(!r)return e.name===`void`||e.name===`any`?``:`args: ${e.toCode(void 0,t)}`;let i=Object.entries(r).map(([e,n])=>{let r=n.type.isOptional(),i=r?n.type.required():n.type;return`${n.docs&&t?.includeComments!==!1?`/* ${n.docs} */ `:``}${e}${r?`?`:``}: ${i.toCode(void 0,t)}`}),a=Vh(t);return n===`auto`?Bh(i,{indent:a}):i.length<=1?i.join(``):`
92
+ ${i.map(e=>Hh(e,a)).join(`
93
+ `)}
94
+ `}definitionInit(){return this.init()}definitionCall(){return this.call()}definitionGet(){return this.get()}definitionProps(){return this.props()}toCodeDefinition(t){let n=[],r=t?.includeComments!==!1,i=Vh(t),a=e=>`/// ${e}`,o=this.definitionCall();if(o?.types)for(let[e,r]of Object.entries(o.types))n.push(`type ${e} = ${r.toCode(void 0,t)};`);let s=this.definitionInit();if(s&&(s.docs&&r&&n.push(a(s.docs)),n.push(`new(${e.formatParams(s.args,t,`lines`)})`)),o){let r=o.returns?.toCode(void 0,t)??`void`;n.push(`(${e.formatParams(o.args,t,`lines`)}): ${r}`)}let c=this.definitionGet();c&&n.push(`[key: ${c.key.toCode(void 0,t)}]: ${c.value.toCode(void 0,t)}`);let l=new Set(Object.keys(this.generic));for(let[i,o]of Object.entries(this.definitionProps())){let s=o instanceof jh?o:jh.from(o);s.docs&&r&&n.push(a(s.docs));let c=s.type.isOptional(),u=c?s.type.required():s.type,d=c?`?`:``,f=u.call(),p=Object.keys(u.props()).filter(t=>!e.UNIVERSAL_PROP_NAMES.has(t));if(f&&!u.get()&&p.length===0){let r=f.returns?.toCode(void 0,t)??`void`,a=Object.fromEntries(Object.entries(u.generic).filter(([e])=>!l.has(e))),o=e.renderGenerics(a,t);n.push(`${i}${d}${o}(${e.formatParams(f.args,t,`lines`)}): ${r}`)}else n.push(`${i}${d}: ${u.toCode(void 0,t)}`)}let u=`${this.docs&&r?`${a(this.docs)}
95
+ `:``}type ${this.name}${e.renderGenerics(this.generic,t)}${this.extendsClause(t)}`;return n.length===0?`${u} {}`:`${u} {
96
+ ${n.map(e=>Hh(e,i)).join(`
97
+ `)}
98
+ }`}propSuperFor(e,t,n,r,i){}indexSuperFor(e,t,n,r){}propGet(e,t,n){let r=e.raw&&typeof e.raw==`object`?e.raw[t]:void 0;return r instanceof W?r:G(n,r)}propSet(e,t,n){if(e.raw&&typeof e.raw==`object`)e.raw[t]=n;else throw Error(`type '${this.name}': cannot set prop '${t}' \u2014 value's raw is not an object`)}validate(e){let t=new Mm;try{this.registry.parse(this.toDefinitionJSON())}catch(e){t.error(`type.invalid`,e.message)}return Uh(this,e,t),t}},Fh={depth:0,lowWater:1/0,active:new Map,memo:new Map};function Ih(e,t){return`${+!!e?.strict}${+!!e?.value}${+!!e?.exact}:${t?Zm(t):``}`}var Lh={active:0,depth:0};function Rh(e,t){if(!e)return``;let n=Object.entries(e).filter(([e,n])=>!(n===void 0||n===``||t&&e in t&&zh(t[e],n)));return n.length===0?``:`{${Bh(n.map(([e,t])=>`${e}=${typeof t==`string`?JSON.stringify(t):typeof t==`number`||typeof t==`boolean`?String(t):t===null?`null`:JSON.stringify(t)}`))}}`}function zh(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function Bh(e,t={}){if(e.length===0)return``;let n=t.sep??`, `,r=t.threshold??32,i=t.totalThreshold??80,a=e.join(n);if(!(a.length>i||e.some(e=>e.length>r||e.includes(`
99
+ `))))return a;let o=n.replace(/\s+$/,``),s=t.indent??` `;return`
100
+ ${e.map(e=>Hh(e,s)).join(`${o}
101
+ `)}
102
+ `}function Vh(e){return e?.indent??` `}function Hh(e,t){return t+e.replace(/\n/g,`
103
+ ${t}`)}function Uh(e,t,n){let r=e.registry,i={inLoop:!1,inLambda:!1},a=e.props();for(let[o,s]of Object.entries(a)){let a=s instanceof jh?s:jh.from(s);n.at([`props`,o],()=>{qh(a.get,Wh(a,e,r),Kh(a),`get`,t,n,i),qh(a.set,Gh(a,e,r),r.void(),`set`,t,n,i),qh(a.default,new Map,a.type,`default`,t,n,i)})}let o=e.get();o&&n.at(`get`,()=>{let a=new Map([[`this`,e],[`key`,o.key]]),s=new Map([[`this`,e],[`key`,o.key],[`value`,o.value]]);qh(o.get,a,o.value,`get`,t,n,i),qh(o.set,s,r.void(),`set`,t,n,i),qh(o.loop,a,void 0,`loop`,t,n,i)});let s=e.call();s&&n.at(`call`,()=>{let a=new Map([[`this`,e],[`args`,s.args],[`recurse`,r.fn({args:s.args,returns:s.returns??r.any()})]]);qh(s.get,a,s.returns,`get`,t,n,{...i,inLambda:!0});let o=new Map([[`this`,e],[`args`,s.args],[`value`,s.returns??r.any()],[`recurse`,r.fn({args:s.args,returns:s.returns??r.any()})]]);qh(s.set,o,r.void(),`set`,t,n,{...i,inLambda:!0})});let c=e.init();c&&n.at(`init`,()=>{let r=new Map([[`this`,e],[`args`,c.args]]);qh(c.run,r,void 0,`run`,t,n,i)});for(let a of e.constraints())n.at(`constraint`,()=>{let o=oh(t,a,new Map([[`this`,e]]),n,i),s=r.bool();o.name!==`any`&&!s.compatible(o)&&n.warn(`type.surface.return-type`,`constraint must return bool, got '${o.name}'`)})}function Wh(e,t,n){let r=new Map([[`this`,t]]),i=e.type.call?.();return i&&(r.set(`args`,i.args),r.set(`recurse`,n.fn({args:i.args,returns:i.returns??n.any()}))),r}function Gh(e,t,n){return new Map([[`this`,t],[`value`,e.type]])}function Kh(e){let t=e.type.call?.();return t?t.returns:e.type}function qh(e,t,n,r,i,a,o){e&&a.at(r,()=>{let s=oh(i,e,t,a,o);n&&s.name!==`any`&&!n.compatible(s)&&a.warn(`type.surface.return-type`,`${r} body returns '${s.name}', not compatible with declared '${n.name}'`)})}function Jh(e,t,n,r,i,a){let o=i+1,s=[];return e.name!==void 0&&s.push({key:`name`,value:V.jsonString(e.name)}),e.extends!==void 0&&s.push({key:`extends`,value:V.jsonString(e.extends)}),e.satisfies!==void 0&&e.satisfies.length>0&&s.push({key:`satisfies`,value:ng(e.satisfies,[...n,`satisfies`],r,o)}),e.docs!==void 0&&s.push({key:`docs`,value:V.jsonString(e.docs)}),e.options!==void 0&&Object.keys(e.options).length>0&&s.push({key:`options`,value:ng(e.options,[...n,`options`],r,o)}),e.generic!==void 0&&Object.keys(e.generic).length>0&&s.push({key:`generic`,value:Yh(e.generic,t,[...n,`generic`],r,o)}),e.props!==void 0&&Object.keys(e.props).length>0&&s.push({key:`props`,value:Xh(e.props,t,[...n,`props`],r,o)}),e.get!==void 0&&s.push({key:`get`,value:Qh(e.get,t,[...n,`get`],r,o)}),e.call!==void 0&&s.push({key:`call`,value:$h(e.call,t,[...n,`call`],r,o)}),e.init!==void 0&&s.push({key:`init`,value:eg(e.init,t,[...n,`init`],r,o)}),e.constraint!==void 0&&s.push({key:`constraint`,value:tg(e.constraint,t,[...n,`constraint`],r,o)}),V.jsonObject(s,{path:n,type:a},i,r)}function Yh(e,t,n,r,i){let a=Object.entries(e).map(([e,a])=>({key:e,value:Jh(a,t,[...n,e],r,i+1,void 0)}));return V.jsonObject(a,{path:n},i,r)}function Xh(e,t,n,r,i){let a=Object.entries(e).map(([e,a])=>({key:e,value:Zh(a,t,[...n,e],r,i+1)}));return V.jsonObject(a,{path:n},i,r)}function Zh(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`type`,value:Jh(e.type,t,[...n,`type`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:tg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:tg(e.set,t,[...n,`set`],r,a)}),e.default!==void 0&&o.push({key:`default`,value:tg(e.default,t,[...n,`default`],r,a)}),V.jsonObject(o,{path:n},i,r)}function Qh(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`key`,value:Jh(e.key,t,[...n,`key`],r,a,void 0)}),o.push({key:`value`,value:Jh(e.value,t,[...n,`value`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:tg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:tg(e.set,t,[...n,`set`],r,a)}),e.loop!==void 0&&o.push({key:`loop`,value:tg(e.loop,t,[...n,`loop`],r,a)}),e.loopDynamic!==void 0&&o.push({key:`loopDynamic`,value:String(e.loopDynamic)}),V.jsonObject(o,{path:n},i,r)}function $h(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),e.types!==void 0&&Object.keys(e.types).length>0&&o.push({key:`types`,value:Yh(e.types,t,[...n,`types`],r,a)}),o.push({key:`args`,value:Jh(e.args,t,[...n,`args`],r,a,void 0)}),e.returns!==void 0&&o.push({key:`returns`,value:Jh(e.returns,t,[...n,`returns`],r,a,void 0)}),e.throws!==void 0&&o.push({key:`throws`,value:Jh(e.throws,t,[...n,`throws`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:tg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:tg(e.set,t,[...n,`set`],r,a)}),V.jsonObject(o,{path:n},i,r)}function eg(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`args`,value:Jh(e.args,t,[...n,`args`],r,a,void 0)}),o.push({key:`run`,value:tg(e.run,t,[...n,`run`],r,a)}),V.jsonObject(o,{path:n},i,r)}function tg(e,t,n,r,i){try{return t.parseExpr(e).toJSONCode(n,r,i)}catch{return ng(e,n,r,i)}}function ng(e,t,n,r){let i=JSON.stringify(e,null,n);if(r>0){let e=` `.repeat(r*n);i=i.replace(/\n/g,`
104
+ `+e)}return Fm(i,{path:t})}var W=class{type;raw;constructor(e,t){this.type=e,this.raw=t}toLogical(){return rg(this.raw)}encode(){return this.type.encode(this.raw)}toJSON(e=Oh){return{type:this.type.toJSONRef(e),value:this.type.encodeAs(this.raw,e)}}encodeLogical(){return this.type.encodeAs(this.raw,og)}toJSONRefs(){return this.toJSON({form:`envelope`,typeRefs:`name`})}toJSONLogical(){return this.toJSON(og)}};function rg(e){if(e instanceof W)return e.toLogical();if(Array.isArray(e))return e.map(rg);if(e instanceof Map){let t=new Map;for(let n of e.values())ig(n)&&t.set(n[0].toLogical(),n[1].toLogical());return t}if(ag(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=rg(r);return t}return e}function ig(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function ag(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var og={form:`logical`,typeRefs:`name`};function G(e,t){return new W(e,t)}var sg=class extends Error{constructor(){super(`The run was stopped.`),this.name=`RunStoppedError`}},cg=class{signal;slice;#e=Date.now();constructor(e={}){this.signal=e.signal,this.slice=e.slice??10}check(){let e=this.signal;if(e?.aborted!==!0)return;let t=e.reason;throw t instanceof Error?t:new sg}async checkpoint(){this.check(),Date.now()-this.#e<this.slice||(await new Promise(e=>{setTimeout(e,0)}),this.#e=Date.now(),this.check())}},lg=new Set([`text`,`num`,`bool`,`enum`,`literal`,`date`,`timestamp`,`duration`,`color`,`null`]);function ug(e){let t=e;for(let e=0;e<16;e+=1){let e=t.inner??t.base;if(e===void 0||e===t)return t;t=e}return t}function dg(e){return lg.has(ug(e).name)}function fg(e,t){let n=e.isOptional()?e.inner??e:e;return dg(n)?R.union([n.toA(t),R.ref(`Expr`)]):R.ref(`Expr`)}function pg(e,t){if(e===t)return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;let n=e,r=t,i=Object.keys(n);return i.length===Object.keys(r).length&&i.every(e=>n[e]===r[e])}function mg(e,t,n){let r=Object.keys(e);return r.length===0?t?jh.toJSONMap(t):void 0:{...n&&Object.keys(n).length===r.length&&r.every(e=>e in n)?n:jh.toJSONMap(e),...t?jh.toJSONMap(t):{}}}function hg(e,t){return{...e,props:e.props?jh.fromMap(e.props,t):void 0,get:e.get?Mh.from(e.get,t):void 0,call:e.call?Nh.from(e.call,t):void 0,init:e.init?Ph.from(e.init,t):void 0}}var gg=class e extends U{name;docs;base;original;local;bindings;constructor(e,t,n,r,i){let a=n.options?t.narrow(n.options):t.options,o=n.options&&!pg(a,t.options)?e.parse({...t.toJSON(),options:a},i):t;super(r??e,a,n.generic??{}),this.original=t,this.base=o,this.local=hg(n,e),this.name=n.name,this.docs=n.docs;let s=Object.entries(n.generic??{}).filter(([e,t])=>!U.isGenericPlaceholder(e,t));this.bindings=s.length>0?Object.fromEntries(s):void 0}storedLocalProps(){let e=[];for(let[t,n]of Object.entries(this.local.props??{})){let r=n instanceof jh?n:jh.from(n);r.get||r.type.call()||e.push([t,r])}return e}valid(e,t){let n=this.bindScope(t);if(!this.base.valid(e,n))return!1;let r=this.storedLocalProps();if(r.length===0||!kh(e))return!0;let i=e;for(let[e,t]of r){let r=i[e];if(!(r instanceof W))return t.type.isOptional();if(!r.type.valid(r.raw,n)||!Sh(t.type,r.type,n))return!1}return!0}parse(e,t){let n=this.bindScope(t),r=this.base.parse(e,n),i=this.storedLocalProps();if(i.length===0||!kh(r.raw))return new W(this,r.raw);let a=kh(e)?e:{},o={...r.raw};for(let[e,t]of i)o[e]=this.registry.parseValue(a[e],t.type,n);return new W(this,o)}parsesExprValue(e){return this.base.parsesExprValue(this.bindScope(e))}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){let r=this.bindScope(n),i=this.base.encodeAs(e,t,r),a=this.storedLocalProps();if(a.length===0||!kh(i)||!kh(e))return i;let o=e,s={...i};for(let[e]of a)Dh(s,e,o[e],t,r);return s}create(){return this.withLocalSlots(this.base.create(),e=>e.create())}random(e){return this.withLocalSlots(this.base.random(e),t=>t.random(e))}withLocalSlots(e,t){let n=this.storedLocalProps();if(n.length===0||!kh(e))return e;let r={...e};for(let[e,i]of n)r[e]=new W(i.type,t(i.type));return r}forEachNewSlot(e,t){let n=this.base.forEachNewSlot(e,t),r=this.storedLocalProps();if(r.length===0||!kh(e))return n;let i=e;for(let[e,n]of r)e in i?t.slot(n.type,i[e],e):n.default!==void 0&&t.missing?.(n.default,e);return!0}async newFill(e,t,n){let r=await this.base.newFill(e,t,n),i=this.storedLocalProps();if(i.length===0||!kh(r))return r;let a=r,o;for(let[e,r]of i)if(e in a){let i=await r.type.newFill(a[e],t,n);i!==a[e]&&(o??={...a},o[e]=i)}else r.default!==void 0&&(o??={...a},o[e]=await r.default.evaluate(t,n));return o??a}compatibleType(t,n,r){return n?.exact?t instanceof e&&t.name===this.name&&this.base.compatible(t.base,n,r):t instanceof e?this.base.compatible(t.base,n,r):this.base.compatible(t,n,r)}or(t){if(t instanceof e&&t.name===this.name){let n={name:this.name,docs:this.docs??t.docs,options:{...this.local.options??{},...t.local.options??{}},props:{...this.local.props??{},...t.local.props??{}},get:this.local.get??t.local.get,call:this.local.call??t.local.call,init:this.local.init??t.local.init};return new e(this.registry,this.original,n)}return this.base.or(t)}simplify(){return this}required(){return this.base.required()}isOptional(){return this.base.isOptional()}narrow(e){return this.base.narrow(e)}props(e){let t=this.registry.augmentation(this.name);return{...this.base.props(this.bindScope(e)),...t?.props??{},...this.local.props??{}}}get(e){return this.local.get??this.registry.augmentation(this.name)?.get??this.base.get(this.bindScope(e))}call(e){return this.local.call??this.registry.augmentation(this.name)?.call??this.base.call(this.bindScope(e))}init(e){return this.local.init??this.registry.augmentation(this.name)?.init??this.base.init(this.bindScope(e))}toJSON(){if(Lh.active>0&&Lh.depth>0&&!this.local.useSite&&this.registry.lookup(this.name)!==void 0&&(this.registry.lookup(this.name)===this||this.bindings)){let e=Object.entries(this.bindings??{});return e.length>0?{name:this.name,generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{name:this.name}}Lh.depth++;try{return this.toJSONInner()}finally{Lh.depth--}}toJSONInner(){if(this.local.useSite){let e=Object.entries(this.bindings??{});return{name:this.name,...e.length>0?{generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{},options:{...this.local.options}}}let e=this.original.toJSON(),t=this.original.name!==this.name,n={...e.options,...this.local.options},r={...e.generic??{}};if(this.local.generic)for(let[e,t]of Object.entries(this.local.generic))r[e]=t.toJSON();return Km({name:this.name,extends:t?this.original.name:void 0,docs:this.docs,generic:Object.keys(r).length>0?r:void 0,options:n&&Object.keys(n).length>0?n:void 0,props:mg(t?this.original.refProps():{},this.local.props,e.props),get:(this.local.get??(t?this.original.refGet():void 0))?.toJSON(),call:(this.local.call??(t?this.original.refCall():void 0))?.toJSON(),init:this.local.init?.toJSON(),constraint:this.local.constraint?this.local.constraint.toJSON():void 0})}clone(){let t=this.local.generic?Object.fromEntries(Object.entries(this.local.generic).map(([e,t])=>[e,t.clone()])):void 0;return new e(this.registry,this.original.clone(),{name:this.local.name,docs:this.local.docs,options:this.local.options?{...this.local.options}:void 0,generic:t,props:this.local.props?{...this.local.props}:void 0,get:this.local.get,call:this.local.call,init:this.local.init,constraint:this.local.constraint?.clone(),useSite:this.local.useSite},this.bindings?this.scope:void 0)}toCode(e,t){return this.docsPrefix(t)+this.name+U.renderGenericArgs(this.generic,t)+(this.local.useSite?Rh(this.local.options):``)}extendsClause(e){return` extends ${this.base.toCodeRef(void 0,e)}`}baseMembersElided(e){return this.base.toCodeRef(void 0,e)!==this.base.toCode(void 0,e)}ownAugmentation(){return this.registry.augmentation(this.name)}definitionInit(){return this.local.init??this.ownAugmentation()?.init}definitionCall(){return this.local.call??this.ownAugmentation()?.call??(this.baseMembersElided()?this.base.refCall():void 0)}definitionGet(){return this.local.get??this.ownAugmentation()?.get??(this.baseMembersElided()?this.base.refGet():void 0)}definitionProps(){return{...this.baseMembersElided()?this.base.refProps():{},...this.ownAugmentation()?.props??{},...this.local.props??{}}}specialize(t){let n={...this.local.generic??{}},r={};for(let e of Object.keys(this.local.generic??{})){let i=t[e];i&&(n[e]=i,r[e]=i)}return Object.keys(r).length===0?this:new e(this.registry,this.original,{...this.local,generic:n},new Qm(this.scope,r))}bindScope(e){return this.bindings?e?new Qm(e,this.bindings):this.scope:e}constraints(){let e=this.base.constraints();return this.local.constraint?[this.local.constraint,...e]:e}valueA(e){return this.mergeLocalPropsA(this.base.defineA(e),e,t=>t.type.toA(e))}toNewA(e){return this.describeA(this.mergeLocalPropsA(this.base.toNewA(e),e,t=>fg(t.type,e)),e)}mergeLocalPropsA(e,t,n){if(!(e instanceof pf))return e;let r=t?.includeDocs??`none`,i={};for(let[e,t]of this.storedLocalProps()){let a=n(t);r===`all`&&t.docs&&(a=a.describe(t.docs)),i[e]=t.type.isOptional()&&a.kind!==`optional`?R.optional(a):a}return Object.keys(i).length===0?e:e.extend(i)}propSuperFor(e,t,n,r,i){let a=this.local.props;if(!(a&&Object.hasOwn(a,t)))return;let o=this.base.prop(t);if(!o)return;let s=new W(this.base,e.raw);if(n===`get`){if(o.type.call()&&o.get){let e=o.type;return new W(e,async e=>{let n={this:s,args:e},a=s.type.propSuperFor(s,t,`get`,r,i);return a&&(n.super=a),i.evaluate(o.get,r.child(n))})}return new W(i.registry.fn({args:i.registry.obj({}),returns:o.type}),async e=>{if(!o.get)return G(o.type,s.raw?.[t]);let n={this:s},a=s.type.propSuperFor(s,t,`get`,r,i);return a&&(n.super=a),i.evaluate(o.get,r.child(n))})}if(n===`set`)return o.set?new W(i.registry.fn({args:i.registry.obj({value:{type:o.type}}),returns:i.registry.void()}),async e=>{let n=e.raw.value,a={this:s,value:n},c=s.type.propSuperFor(s,t,`set`,r,i);return c&&(a.super=c),await i.evaluate(o.set,r.child(a)),G(i.registry.void(),void 0)}):void 0;let c=o.type.call();return c?.set?new W(i.registry.fn({args:i.registry.obj({args:{type:c.args},value:{type:c.returns??i.registry.any()}}),returns:i.registry.void()}),async e=>{let n=e.raw,a={this:s,args:n.args,value:n.value},o=s.type.propSuperFor(s,t,`callSet`,r,i);return o&&(a.super=o),await i.evaluate(c.set,r.child(a)),G(i.registry.void(),void 0)}):void 0}indexSuperFor(e,t,n,r){let i=this.local.get;if(!i)return;let a=this.base.get();if(!a)return;let o=new W(this.base,e.raw);return t===`get`?!i.get||!a.get?void 0:new W(r.registry.fn({args:r.registry.obj({key:{type:a.key}}),returns:a.value}),async e=>{let t=e.raw.key,n=r.createRootScope();return n.vars.set(`this`,o),n.vars.set(`key`,t),r.evaluate(a.get,n)}):!i.set||!a.set?void 0:new W(r.registry.fn({args:r.registry.obj({key:{type:a.key},value:{type:a.value}}),returns:r.registry.void()}),async e=>{let t=e.raw,n=r.createRootScope();return n.vars.set(`this`,o),n.vars.set(`key`,t.key),n.vars.set(`value`,t.value),await r.evaluate(a.set,n),G(r.registry.void(),void 0)})}},_g=class e extends U{static NAME=`any`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return!0}parse(e){return new W(this,e)}encode(e){return e}create(){return null}random(e){return null}compatibleType(e,t){return!0}flexible(){return!0}isUniversal(){return!0}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new Nm({path:[],code:`any.no-options`,message:`any has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),typeOf:e.method({},e.text(),`any.typeOf`),is:e.method({},e.bool(),`any.is`,{generic:{T:e.any()}}),as:e.method({},e.optional(e.alias(`T`)),`any.as`,{generic:{T:e.any()}}),toText:e.method({},e.text(),`any.toText`),toBool:e.method({},e.bool(),`any.toBool`),eq:e.method({other:e.any()},e.bool(),`any.eq`),neq:e.method({other:e.any()},e.bool(),`any.neq`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`any`}valueA(){return R.unknown()}},vg=class e extends U{static NAME=`obj`;static consumes=[`props`];name=e.NAME;static optionKeys=[];static genericKeys=[];fields;static from(t,n){let r=jh.fromMap(t.props??{},n);return new e(n,r)}constructor(e,t){super(e,{});let n={};for(let[e,r]of Object.entries(t))n[e]=jh.from(r);this.fields=n}valid(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let[n,r]of Object.entries(this.fields)){let i=e[n];if(!(i instanceof W)||!i.type.valid(i.raw,t)||!Sh(r.type,i.type,t))return!1}return!0}parse(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new Nm({path:[],code:`object.invalid`,message:`object.parse: expected object, got ${typeof e}`,severity:`error`});let n={};for(let[r,i]of Object.entries(this.fields)){let a=e[r];n[r]=this.registry.parseValue(a,i.type,t)}return new W(this,n)}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){let r=e,i={};for(let[e]of Object.entries(this.fields))Dh(i,e,r[e],t,n);return i}create(){let e={};for(let[t,n]of Object.entries(this.fields))e[t]=new W(n.type,n.type.create());return e}random(e){let t={};for(let[n,r]of Object.entries(this.fields))t[n]=new W(r.type,r.type.random(e));return t}forEachNewSlot(e,t){if(!yg(e)||Ah(e,this.scope))return!1;let n=e;for(let[e,r]of Object.entries(this.fields))e in n?t.slot(r.type,n[e],e):r.default!==void 0&&t.missing?.(r.default,e);return!0}async newFill(e,t,n){if(!yg(e)||Ah(e,this.scope))return super.newFill(e,t,n);let r=e,i;for(let[e,a]of Object.entries(this.fields))if(e in r){let o=await a.type.newFill(r[e],t,n);o!==r[e]&&(i??={...r},i[e]=o)}else a.default!==void 0&&(i??={...r},i[e]=await a.default.evaluate(t,n));return i??r}like(t){if(!(t instanceof e))return this;let n={};for(let[e,r]of Object.entries(t.fields)){let t=this.registry.like(r.type);if(t.name===`null`)return this.registry.null();n[e]={type:t}}return this.registry.obj(n)}compatibleType(t,n,r){if(!(t instanceof e))return!1;for(let[e,i]of Object.entries(this.fields)){let a=t.fields[e];if(!a){if(n?.exact)return!1;if(i.type.isOptional())continue;return!1}if(!i.type.compatible(a.type,n,r))return!1}if(n?.exact){let e=new Set(Object.keys(this.fields));for(let n of Object.keys(t.fields))if(!e.has(n))return!1}return!0}or(t){if(!(t instanceof e))return this;let n={};for(let[e,r]of Object.entries(this.fields)){let i=t.fields[e];i&&(n[e]={type:r.type.or(i.type)})}return new e(this.registry,n)}narrow(e){return{}}props(){let e=this.registry,t=Object.values(this.fields).map(e=>e.type),n=t.length===0?e.any():t.length===1?t[0]:e.or(t),r={keys:e.method({},e.list(e.text()),`object.keys`),values:e.method({},e.list(n),`object.values`),entries:e.method({},e.list(e.tuple([e.text(),n])),`object.entries`),has:e.method({key:e.text()},e.bool(),`object.has`),eq:e.method({other:e.any()},e.bool(),`object.eq`),neq:e.method({other:e.any()},e.bool(),`object.neq`),toText:e.method({},e.text(),`object.toText`)};return{...super.props(),...r,...this.fields}}get(){let e=Object.keys(this.fields);if(e.length===0)return;let t=this.registry.text(),n=e.map(e=>this.registry.literal(t,e)),r=n.length===1?n[0]:this.registry.or(n),i=Object.values(this.fields).map(e=>e.type),a=i.length===1?i[0]:this.registry.or(i),o=this.registry;return new Mh({key:r,value:a,get:o.nativeExpr(`object.indexGet`),set:o.nativeExpr(`object.indexSet`),loop:o.nativeExpr(`object.iterate`)})}toJSON(){return{name:e.NAME,props:jh.toJSONMap(this.fields)}}clone(){let t={};for(let[e,n]of Object.entries(this.fields))t[e]={...n,type:n.type.clone()};return new e(this.registry,t)}toCode(e,t){let n=Object.entries(this.fields);if(n.length===0)return this.docsPrefix(t)+`obj`;let r=t?.includeComments!==!1,i=n.map(([e,n])=>{let i=n.type.isOptional(),a=i?n.type.required():n.type,o=i?`${e}?`:e;return`${n.docs&&r?`/* ${n.docs} */ `:``}${o}: ${a.toCode(void 0,t)}`});return this.docsPrefix(t)+`obj{${Bh(i,{indent:Vh(t)})}}`}toCodeRef(e,t){return this.docsPrefix(t)+`obj`}refProps(){return this.fields}valueA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this.fields)){let a=i.type.toA(e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=a}return this.objectA(n,e)}toNewA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this.fields)){let a=fg(i.type,e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=i.type.isOptional()?R.optional(a):a}return this.describeA(R.object(n),e)}describe(t){if(typeof t!=`object`||!t||Array.isArray(t))return;let n={};for(let[e,r]of Object.entries(t))n[e]={type:this.registry.any().describe?.(r)??this.registry.any()};return new e(this.registry,n)}};function yg(e){return kh(e)}var bg=class e extends U{static NAME=`and`;name=e.NAME;static optionKeys=[`types`];static genericKeys=[];static from(t,n){n.registry;let r=(t.options?.types??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,{parts:t})}get parts(){return this.options.parts}valid(e,t){return this.parts.every(n=>n.valid(e,t))}effective(){let e=this.parts;if(e.length===0)return;if(e.length===1)return e[0];let t=this.mergedObjFields();return t?this.registry.obj(t):e[0]}mergedObjFields(){let e=[];for(let t of this.parts){if(!(t instanceof vg))return;e.push(t)}let t={};for(let n of e)for(let[e,r]of Object.entries(n.fields)){let n=t[e];t[e]=n?{type:this.registry.and([n.type,r.type])}:r}return t}parse(e,t){let n=this.effective();if(!n)return new W(this,e);let r=n.parse(e,t).raw;for(let e of this.parts)if(!e.valid(r,t))throw new Nm({path:[],code:`and.constraint`,message:`and: value fails part ${e.name}`,severity:`error`});return new W(this,r)}encode(e,t){return this.effective()?.encode(e,t)??e}parsesExprValue(e){return this.effective()?.parsesExprValue(e)??!1}encodeAs(e,t,n){return this.effective()?.encodeAs(e,t,n)??e}forEachNewSlot(e,t){return this.effective()?.forEachNewSlot(e,t)??!1}async newFill(e,t,n){let r=this.effective();return r?r.newFill(e,t,n):super.newFill(e,t,n)}create(){let e=this.effective();if(!e)return null;for(let t of[e,...this.parts]){let e=t.create();if(this.valid(e))return e}return e.create()}random(e){let t=this.effective();if(!t)return null;for(let n of[t,...this.parts]){let t=n.random(e);if(this.valid(t))return t}return t.random(e)}like(t){if(!(t instanceof e))return this;let n=t.parts.map(e=>this.registry.like(e)).filter(e=>e.name!==`null`);return n.length===0?this.registry.null():n.length===1?n[0]:this.registry.and(n)}compatibleType(e,t,n){return this.parts.every(r=>r.compatible(e,t,n))}isUniversal(){return this.parts.length===0||this.parts.every(e=>e.isUniversal())}or(t){return t instanceof e?new e(this.registry,[...this.parts,...t.parts]):this}simplify(){if(this.parts.length===1)return this.parts[0];if(this.parts.length===0)return this;let e=this.mergedObjFields();return e?this.registry.obj(e):this}narrow(e){return this.options}props(){let e={};for(let t of this.parts)for(let[n,r]of Object.entries(t.props()))e[n]=n in e?{type:this.registry.and([e[n].type,r.type])}:r;return e}get(){let e=this.parts.map(e=>e.get()).filter(e=>!!e);if(e.length!==0)return new Mh({key:this.registry.or(e.map(e=>e.key)),value:this.registry.and(e.map(e=>e.value))})}call(){let e=this.parts.map(e=>e.call()).filter(e=>!!e);if(e.length===0)return;let t=e.map(e=>e.returns).filter(e=>!!e);return new Nh({args:this.registry.or(e.map(e=>e.args)),returns:t.length>0?this.registry.and(t):void 0})}toJSON(){return{name:e.NAME,options:{types:this.parts.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.parts.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`and<${this.parts.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){return this.parts.length===0?R.unknown():this.parts.length===1?this.parts[0].toA(e):R.intersection(this.parts.map(t=>t.toA(e)))}toNewA(e){return this.parts.length===0?this.describeA(R.unknown(),e):this.parts.length===1?this.describeA(this.parts[0].toNewA(e),e):this.describeA(R.intersection(this.parts.map(t=>t.toNewA(e))),e)}},xg=new Set,Sg=class e extends U{static NAME=`alias`;name=e.NAME;constructor(e,t,n={}){super(e,t,n)}get hasUse(){return Object.keys(this.generic).length>0||this.options.options!==void 0}applied;static from(t,n){return new e(n,{name:t.name})}resolve(e){let t=(e?e.lookup(this.options.name):void 0)??this.scope.lookup(this.options.name);if(!t||!this.hasUse)return t;this.applied??=new WeakMap;let n=this.applied.get(t);return n||(n=this.registry.applyUse(t,this.generic,this.options.options),this.applied.set(t,n)),n}valid(e,t){let n=this.resolve(t);return!n||n.valid(e,t)}parse(e,t){let n=this.resolve(t);if(!n)return new W(this,e);let r=n.parse(e,t);return new W(this,r.raw)}encode(e,t){let n=this.resolve(t);return n?n.encode(e,t):e}parsesExprValue(e){return this.resolve(e)?.parsesExprValue(e)??!1}encodeAs(e,t,n){let r=this.resolve(n);return r?r.encodeAs(e,t,n):e}create(){let e=this.resolve();return e?e.create():null}random(e){let t=this.resolve();return t?t.random(e):null}compatibleType(e,t,n){let r=this.resolve(n);return!r||r.compatible(e,t,n)}flexible(){return!0}isUniversal(){let e=this.resolve();return!e||e.isUniversal()}or(e){let t=this.resolve();return t?t.or(e):this}simplify(e){return this.resolve(e)??this}narrow(e){return{...this.options,name:e.name??this.options.name}}props(e){let t=this.resolve(e);return t?t.props(e):super.props(e)}get(e){return this.resolve(e)?.get(e)}call(e){return this.resolve(e)?.call(e)}init(e){return this.resolve(e)?.init(e)}follow(e,t){return this.resolve(t)?.follow(e,t)}forEachNewSlot(e,t){return this.resolve()?.forEachNewSlot(e,t)??!1}async newFill(e,t,n){let r=this.resolve();return r?r.newFill(e,t,n):super.newFill(e,t,n)}toJSON(){if(!this.hasUse)return{name:this.options.name};let e=Object.entries(this.generic);return{name:this.options.name,...e.length>0?{generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{},...this.options.options===void 0?{}:{options:{...this.options.options}}}}clone(){return new e(this.scope,{...this.options},{...this.generic})}toCode(e,t){return this.docsPrefix(t)+this.options.name+U.renderGenericArgs(this.generic,t)+Rh(this.options.options)}valueA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(xg.has(this.options.name))return R.json().describe(`A value of the named type ${this.options.name}.`);xg.add(this.options.name);try{return t.toA(e)}finally{xg.delete(this.options.name)}}toNewA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(xg.has(this.options.name))return R.ref(`Expr`);xg.add(this.options.name);try{return t.toNewA(e)}finally{xg.delete(this.options.name)}}},Cg=class e extends U{static NAME=`bool`;name=e.NAME;static optionKeys=[`trueText`,`falseText`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return typeof e==`boolean`}parse(e){if(typeof e==`boolean`)return new W(this,e);if(e===this.options.trueText)return new W(this,!0);if(e===this.options.falseText)return new W(this,!1);throw Error(`bool.parse: expected boolean, got ${typeof e}`)}encode(e){return e}create(){return!1}random(e){return e(0,1,!0)===1}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e?new e(this.registry,{trueText:this.options.trueText??t.options.trueText,falseText:this.options.falseText??t.options.falseText}):this}narrow(e){return{...this.options,...e}}props(){let e=this.registry;return{...super.props(),eq:e.method({other:e.bool()},e.bool(),`bool.eq`),neq:e.method({other:e.bool()},e.bool(),`bool.neq`),and:e.method({other:e.bool()},e.bool(),`bool.and`),or:e.method({other:e.bool()},e.bool(),`bool.or`),xor:e.method({other:e.bool()},e.bool(),`bool.xor`),not:e.method({},e.bool(),`bool.not`),toText:e.method({},e.text(),`bool.toText`),toNum:e.method({},e.num(),`bool.toNum`)}}get(){let e=this.registry;return new Mh({key:e.num({whole:!0,min:0}),value:e.bool(),loopDynamic:!0})}toJSON(){return Km({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`bool`+Rh(this.options)}valueA(){return R.boolean()}describe(e){return typeof e==`boolean`?this:void 0}},wg=class e extends U{static NAME=`color`;name=e.NAME;static optionKeys=[`hasAlpha`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=4294967295}parse(e){let t=typeof e==`number`?e:Number(e);if(!this.valid(t))throw new Nm({path:[],code:`color.invalid`,message:`color.parse: not a valid 32-bit color int: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e}create(){return 255}random(e){return e(0,4294967295,!0)}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e?new e(this.registry,{hasAlpha:this.options.hasAlpha===t.options.hasAlpha?this.options.hasAlpha:void 0}):this}narrow(e){return{...this.options,...e}}init(){let e=this.registry,t=e.num({whole:!0,min:0,max:255}),n=e.optional(e.num({min:0,max:1}));return new Ph({args:e.obj({r:{type:t},g:{type:t},b:{type:t},a:{type:n}}),run:e.nativeExpr(`color.init`)})}props(){let e=this.registry,t=e.num(),n=e.bool(),r=e.text(),i=e.color();return{...super.props(),r:e.prop(t,`color.r`),g:e.prop(t,`color.g`),b:e.prop(t,`color.b`),a:e.prop(t,`color.a`),hue:e.prop(t,`color.hue`),saturation:e.prop(t,`color.saturation`),lightness:e.prop(t,`color.lightness`),eq:e.method({other:i},n,`color.eq`),neq:e.method({other:i},n,`color.neq`),lighten:e.method({amount:t},i,`color.lighten`),darken:e.method({amount:t},i,`color.darken`),saturate:e.method({amount:t},i,`color.saturate`),desaturate:e.method({amount:t},i,`color.desaturate`),opacity:e.method({alpha:t},i,`color.opacity`),invert:e.method({},i,`color.invert`),mix:e.method({other:i,weight:e.optional(t)},i,`color.mix`),complement:e.method({},i,`color.complement`),toHex:e.method({},r,`color.toHex`),toRgb:e.method({},r,`color.toRgb`),toHsl:e.method({},r,`color.toHsl`),toText:e.method({},r,`color.toText`)}}toJSON(){return Km({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`color`+Rh(this.options)}valueA(){return R.int().min(0).max(4294967295).describe(this.options.hasAlpha?`A color as a 32-bit integer 0xRRGGBBAA.`:`A color as an integer 0xRRGGBB.`)}},Tg=class e extends U{static NAME=`date`;name=e.NAME;static optionKeys=[`min`,`max`,`utc`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}boundDate(e){return e?new Date(e):void 0}valid(e){if(!(e instanceof Date)||Number.isNaN(e.getTime()))return!1;let t=this.boundDate(this.options.min),n=this.boundDate(this.options.max);return!(t&&e<t||n&&e>n)}parse(e){let t=e instanceof Date?e:typeof e==`string`?new Date(e):new Date(NaN);if(!this.valid(t))throw new Nm({path:[],code:`date.invalid`,message:`date.parse: invalid or out-of-range: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e.toISOString().slice(0,10)}create(){return new Date}random(e){let t=this.boundDate(this.options.min)?.getTime()??Date.UTC(2e3,0,1),n=this.boundDate(this.options.max)?.getTime()??Date.UTC(2050,11,31);return new Date(e(t,n,!0))}compatibleType(t,n){return t instanceof e}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{min:n.min&&r.min?n.min<r.min?n.min:r.min:void 0,max:n.max&&r.max?n.max>r.max?n.max:r.max:void 0,utc:n.utc===r.utc?n.utc:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Nm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.min!==void 0&&(t.min&&e.min<t.min&&n(`date.widen.min`,`cannot move min earlier`),r.min=e.min),e.max!==void 0&&(t.max&&e.max>t.max&&n(`date.widen.max`,`cannot move max later`),r.max=e.max),e.utc!==void 0&&(r.utc=e.utc),r}props(){let e=this.registry,t=e.num({whole:!0}),n=e.bool(),r=e.text(),i=e.date();return{...super.props(),year:e.prop(t,`date.year`),month:e.prop(t,`date.month`),day:e.prop(t,`date.day`),dayOfWeek:e.prop(t,`date.dayOfWeek`),dayOfYear:e.prop(t,`date.dayOfYear`),eq:e.method({other:i},n,`date.eq`),neq:e.method({other:i},n,`date.neq`),before:e.method({other:i},n,`date.before`),after:e.method({other:i},n,`date.after`),addDays:e.method({days:t},i,`date.addDays`),addMonths:e.method({months:t},i,`date.addMonths`),addYears:e.method({years:t},i,`date.addYears`),diffDays:e.method({other:i},t,`date.diffDays`),diffMonths:e.method({other:i},t,`date.diffMonths`),diffYears:e.method({other:i},t,`date.diffYears`),toText:e.method({format:e.optional(r)},r,`date.toText`)}}toJSON(){return Km({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`date`+Rh(this.options)}valueA(){return R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`).describe(`An ISO 8601 date (YYYY-MM-DD).`)}describe(e){return e instanceof Date?this:void 0}},Eg=class e extends U{static NAME=`duration`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return typeof e==`number`&&!Number.isNaN(e)}parse(e){let t=typeof e==`number`?e:Number(e);return new W(this,t)}encode(e){return e}create(){return 0}random(e){return e(0,864e5,!0)}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){return{}}init(){let e=this.registry,t=e.num();return new Ph({args:e.obj({days:{type:e.optional(t)},hours:{type:e.optional(t)},minutes:{type:e.optional(t)},seconds:{type:e.optional(t)},ms:{type:e.optional(t)}}),run:e.nativeExpr(`duration.init`)})}props(){let e=this.registry,t=e.num({whole:!0}),n=e.text();return{...super.props(),totalSeconds:e.prop(e.num(),`duration.totalSeconds`),totalMinutes:e.prop(e.num(),`duration.totalMinutes`),totalHours:e.prop(e.num(),`duration.totalHours`),totalDays:e.prop(e.num(),`duration.totalDays`),days:e.prop(t,`duration.days`),hours:e.prop(t,`duration.hours`),minutes:e.prop(t,`duration.minutes`),seconds:e.prop(t,`duration.seconds`),ms:e.prop(t,`duration.ms`),toText:e.method({format:e.optional(n)},n,`duration.toText`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`duration`}valueA(){return R.number().describe(`A duration in milliseconds.`)}},Dg=class e extends U{static NAME=`enum`;name=e.NAME;static optionKeys=[`values`];static genericKeys=[`V`];static from(t,n){let r=n.registry,i=t.generic?.V?n.parse(t.generic.V):r.text(),a=t.options?.values??{};return new e(n,i,{values:a})}constructor(e,t,n){super(e,n,{V:t})}get value(){return this.generic.V}valid(e,t){return this.value.valid(e,t)?Object.values(this.options.values).some(t=>t===e):!1}parse(e,t){let n=this.value.parse(e,t);if(!this.valid(n.raw,t))throw new Nm({path:[],code:`enum.not-a-member`,message:`enum.parse: ${String(n.raw)} is not one of ${Object.values(this.options.values).join(`, `)}`,severity:`error`});return new W(this,n.raw)}encode(e,t){return this.value.encode(e,t)}encodeAs(e,t,n){return this.value.encodeAs(e,t,n)}create(){let e=Object.values(this.options.values)[0];return e===void 0?this.value.create():e}random(e){let t=Object.values(this.options.values);return t.length===0?this.value.random(e):t[e(0,t.length-1,!0)]}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.value);return n.name===`null`?this.registry.null():this.registry.enum(t.options.values,n)}compatibleType(t,n,r){return!(t instanceof e)||!this.value.compatible(t.value,n,r)?!1:!n?.value||Object.values(t.options.values).every(e=>Object.values(this.options.values).some(t=>t===e))}or(t){return t instanceof e?new e(this.registry,this.value.or(t.value),{values:{...t.options.values,...this.options.values}}):this}narrow(e){let t=this.options.values;if(e.values===void 0)return this.options;for(let[n,r]of Object.entries(e.values))if(!Object.values(t).some(e=>e===r))throw new Nm({path:[],code:`enum.widen`,message:`enum.narrow: ${n}=${String(r)} not in base values`,severity:`error`});return{values:e.values}}props(){let e=this.registry,t=this.value;return{...super.props(),name:e.prop(e.text(),`enum.name`),value:e.prop(t,`enum.value`),eq:e.method({other:t},e.bool(),`enum.eq`),neq:e.method({other:t},e.bool(),`enum.neq`),toText:e.method({},e.text(),`enum.toText`)}}toJSON(){return{name:e.NAME,generic:{V:this.value.toJSON()},options:{values:this.options.values}}}clone(){return new e(this.registry,this.value.clone(),{values:{...this.options.values}})}toCode(e,t){let n=`enum<${this.value.toCode(void 0,t)}>`+kg(this.options.values,t);return this.docsPrefix(t)+n}valueA(){let e=Object.values(this.options.values);return e.length>0&&e.every(e=>typeof e==`string`)?R.enum(e):R.union(e.map(e=>R.literal(e)))}},Og=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function kg(e,t){let n=Object.entries(e);return n.length===0?``:`{${Bh(n.map(([e,t])=>{let n=Og.test(e)?e:JSON.stringify(e);return t===e?n:`${n}=${typeof t==`number`||typeof t==`boolean`?String(t):JSON.stringify(t??null)}`}),{indent:Vh(t)})}}`}var Ag=class e extends U{static NAME=`fn`;static consumes=[`call`];name=e.NAME;static optionKeys=[];static declaresGenerics=!0;_call;static from(t,n){let r=n.registry,i={},a=new Qm(n);if(t.generic)for(let[e,n]of Object.entries(t.generic))i[e]=a.parse(n);return t.call?new e(a,Nh.from(t.call,a),i):new e(a,new Nh({args:r.any(),returns:r.any()}),i)}constructor(e,t,n={}){super(e,{},n),this._call=t instanceof Nh?t:new Nh(t)}parsesExprValue(e){return!0}valid(e,t){return!!(typeof e==`function`||typeof e==`string`||e&&typeof e==`object`&&`kind`in e)}parse(e,t){return typeof e==`string`||e&&typeof e==`object`&&`kind`in e||typeof e==`function`?new W(this,e):new W(this,null)}encode(e,t){return typeof e==`function`?null:e}create(){return{kind:`new`,type:(this._call.returns??this.registry.void()).toJSON()}}random(e){return this.create()}like(t){if(!(t instanceof e))return this;let n=this.registry,r=n.like(t._call.args);if(r.name===`null`)return n.null();let i=t._call.returns?n.like(t._call.returns):void 0;if(i&&i.name===`null`)return n.null();let a=t._call.throws?n.like(t._call.throws):void 0;return a&&a.name===`null`?n.null():n.fn({args:r,returns:i,throws:a,generic:this.generic})}compatibleType(t,n,r){return!(!(t instanceof e)||!this._call.args.compatible(t._call.args,n,r)||this._call.returns&&t._call.returns&&!this._call.returns.compatible(t._call.returns,n,r))}or(t){return t instanceof e?new e(this.registry,{args:this._call.args.or(t._call.args),returns:this._call.returns&&t._call.returns?this._call.returns.or(t._call.returns):this._call.returns??t._call.returns,throws:this._call.throws&&t._call.throws?this._call.throws.or(t._call.throws):this._call.throws??t._call.throws}):this}narrow(e){return{}}call(e){return this._call}props(e){return super.props(e)}toJSON(){let t=Object.keys(this.generic),n=t.length===0?void 0:Object.fromEntries(t.map(e=>[e,this.generic[e].toJSON()]));return Km({name:e.NAME,call:this._call.toJSON(),generic:n})}clone(){let t={};for(let[e,n]of Object.entries(this.generic))t[e]=n.clone();return new e(this.registry,{args:this._call.args.clone(),returns:this._call.returns?.clone(),throws:this._call.throws?.clone(),get:this._call.get,set:this._call.set},t)}toCode(e,t){let n=this._call.returns?.toCode(void 0,t)??`void`;return this.docsPrefix(t)+`${U.renderGenerics(this.generic,t)}${this._call.renderTypes(t)}(${U.formatParams(this._call.args,t)}): ${n}`}valueA(){return R.union([R.string(),R.ref(`Expr`)])}},jg=class e extends U{static NAME=`interface`;static consumes=[`props`,`get`,`call`];name=e.NAME;static optionKeys=[];static genericKeys=[];_props;_get;_call;static from(t,n){return n.registry,new e(n,{props:t.props?jh.fromMap(t.props,n):{},get:t.get?Mh.from(t.get,n):void 0,call:t.call?Nh.from(t.call,n):void 0})}constructor(e,t){super(e,{});let n={};if(t.props)for(let[e,r]of Object.entries(t.props))n[e]=jh.from(r);this._props=n,this._get=t.get,this._call=t.call}valid(e,t){return!0}parse(e,t){return new W(this,e)}encode(e,t){return e}create(){return null}random(e){return null}like(t){if(!(t instanceof e))return this;let n=this.registry,r={};for(let[e,i]of Object.entries(t._props)){let t=n.like(i.type);if(t.name===`null`)return n.null();r[e]={type:t}}let i;if(t._get){let e=n.like(t._get.key),r=n.like(t._get.value);if(e.name===`null`||r.name===`null`)return n.null();i=new Mh({key:e,value:r})}let a;if(t._call){let e=n.like(t._call.args);if(e.name===`null`)return n.null();let r=t._call.returns?n.like(t._call.returns):void 0;if(r&&r.name===`null`)return n.null();a=new Nh({args:e,returns:r})}return new e(n,{props:r,get:i,call:a})}compatibleType(e,t,n){let r=e.props(n);for(let[e,i]of Object.entries(this._props)){let a=r[e];if(!a||!i.type.compatible(a.type,t,n))return!1}if(this._get){let r=e.get(n);if(!r||!this._get.key.compatible(r.key,t,n)||!this._get.value.compatible(r.value,t,n))return!1}if(this._call){let r=e.call(n);if(!r||!this._call.args.compatible(r.args,t,n)||this._call.returns&&r.returns&&!this._call.returns.compatible(r.returns,t,n))return!1}return!0}flexible(){return!0}isUniversal(){return Object.keys(this._props).length===0&&!this._get&&!this._call}or(t){if(!(t instanceof e))return this;let n={};for(let e of Object.keys(this._props))e in t._props&&(n[e]={type:this._props[e].type.or(t._props[e].type)});return new e(this.registry,{props:n})}narrow(e){return{}}props(e){return{...super.props(e),...this._props}}get(e){return this._get}call(e){return this._call}toJSON(){return Km({name:e.NAME,props:Object.keys(this._props).length>0?jh.toJSONMap(this._props):void 0,get:this._get?.toJSON(),call:this._call?.toJSON()})}clone(){let t={};for(let[e,n]of Object.entries(this._props))t[e]={...n,type:n.type.clone()};return new e(this.registry,{props:t,get:this._get,call:this._call})}toCode(e,t){let n=t?.includeComments!==!1,r=[];for(let[e,i]of Object.entries(this._props)){let a=i.type.isOptional(),o=a?i.type.required():i.type,s=a?`${e}?`:e,c=i.docs&&n?`/* ${i.docs} */ `:``;r.push(`${c}${s}: ${o.toCode(void 0,t)}`)}if(this._get&&r.push(`[key: ${this._get.key.toCode(void 0,t)}]: ${this._get.value.toCode(void 0,t)}`),this._call){let e=this._call.returns?.toCode(void 0,t)??`void`;r.push(`(${this._call.args.toCode(void 0,t)}): ${e}`)}let i=r.length===0?`iface`:`iface{${Bh(r,{indent:Vh(t)})}}`;return this.docsPrefix(t)+i}toCodeRef(e,t){return this.docsPrefix(t)+`iface`}refProps(){return this._props}refGet(){return this._get}refCall(){return this._call}valueA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this._props)){let a=i.type.toA(e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=a}return this.objectA(n,e)}toNewA(e){let t=e?.includeDocs??`none`,n={};for(let[e,r]of Object.entries(this._props)){let i=R.ref(`Expr`);t===`all`&&r.docs&&(i=i.describe(r.docs)),n[e]=i}return this.describeA(R.object(n),e)}},Mg=class e extends U{static NAME=`literal`;name=e.NAME;static optionKeys=[`value`];static genericKeys=[`T`];inner;static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any(),a=t.options?.value;return new e(n,i,a)}constructor(e,t,n){super(e,{value:n},{T:t}),this.inner=t}get literal(){return this.options.value}valid(e,t){return this.inner.valid(e,t)&&e===this.literal}parse(e,t){let n=this.inner.parse(e,t);if(n.raw!==this.literal)throw new Nm({path:[],code:`literal.not-match`,message:`literal: expected ${String(this.literal)}, got ${String(n.raw)}`,severity:`error`});return new W(this,n.raw)}encode(e,t){return this.inner.encode(e,t)}encodeAs(e,t,n){return this.inner.encodeAs(e,t,n)}create(){return this.literal}random(e){return this.literal}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r)&&this.literal===t.literal:!n?.exact&&this.inner.compatible(t,n,r)}isUniversal(){return this.inner.isUniversal()}or(t){return t instanceof e&&(t.literal,this.literal),this}narrow(e){if(e.value!==void 0&&e.value!==this.literal)throw new Nm({path:[],code:`literal.narrow`,message:`literal value cannot change via narrow`,severity:`error`});return this.options}props(){return this.inner.props()}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()},options:{value:this.literal}}}clone(){return new e(this.registry,this.inner.clone(),this.literal)}toCode(e,t){return this.docsPrefix(t)+`literal<${this.inner.toCode(void 0,t)}>`+Rh({value:this.literal})}valueA(){return R.literal(this.literal)}},Ng=class e extends U{static NAME=`list`;name=e.NAME;static optionKeys=[`minLength`,`maxLength`];static genericKeys=[`V`];static from(t,n){let r=n.registry,i=t.generic?.V?n.parse(t.generic.V):r.any();return new e(n,i,t.options??{})}constructor(e,t,n={}){super(e,n,{V:t})}get item(){return this.generic.V}valid(e,t){if(!Array.isArray(e))return!1;let{minLength:n,maxLength:r}=this.options;return n!==void 0&&e.length<n||r!==void 0&&e.length>r?!1:e.every(e=>e instanceof W&&e.type.valid(e.raw,t)&&Sh(this.item,e.type,t))}parse(e,t){if(!Array.isArray(e))throw new Nm({path:[],code:`list.invalid`,message:`list.parse: expected array, got ${typeof e}`,severity:`error`});let n=e.map(e=>this.registry.parseValue(e,this.item,t));if(!this.valid(n,t))throw new Nm({path:[],code:`list.constraint`,message:`list.parse: length constraints violated`,severity:`error`});return new W(this,n)}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){return e.map(e=>Eh(e,t,n))}create(){let e=this.options.minLength??0;return Array.from({length:e},()=>new W(this.item,this.item.create()))}random(e){let t=this.options.minLength??0,n=e(t,this.options.maxLength??Math.max(t,5),!0);return Array.from({length:n},()=>new W(this.item,this.item.random(e)))}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<e.length;n++)t.slot(this.item,e[n],n);return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i of e)r.push(await this.item.newFill(i,t,n));return r}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.item);return n.name===`null`?n:this.registry.list(n)}compatibleType(t,n,r){if(!(t instanceof e)||!this.item.compatible(t.item,n,r))return!1;if(!n?.value)return!0;let i=this.options,a=t.options;return!(i.minLength!==void 0&&(a.minLength===void 0||a.minLength<i.minLength)||i.maxLength!==void 0&&(a.maxLength===void 0||a.maxLength>i.maxLength))}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,this.item.or(t.item),{minLength:n.minLength!==void 0&&r.minLength!==void 0?Math.min(n.minLength,r.minLength):void 0,maxLength:n.maxLength!==void 0&&r.maxLength!==void 0?Math.max(n.maxLength,r.maxLength):void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Nm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.minLength!==void 0&&(t.minLength!==void 0&&e.minLength<t.minLength&&n(`list.widen.minLength`,`local ${e.minLength} < base ${t.minLength}`),r.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength!==void 0&&e.maxLength>t.maxLength&&n(`list.widen.maxLength`,`local ${e.maxLength} > base ${t.maxLength}`),r.maxLength=e.maxLength),r}get(){let e=this.registry;return new Mh({key:e.num({whole:!0,min:0}),value:this.item,get:e.nativeExpr(`list.indexGet`),set:e.nativeExpr(`list.indexSet`),loop:e.nativeExpr(`list.iterate`)})}props(){let e=this.registry,t=this.item,n=e.num(),r=e.bool(),i=e.text(),a=e.void(),o=e.optional(t),s=e.list(t),c=r=>e.fn({args:e.obj({value:{type:t},index:{type:n}}),returns:r});return{...super.props(),length:e.prop(n,`list.length`),at:e.method({index:n},o,`list.at`),push:e.method({value:t},a,`list.push`),pop:e.method({},o,`list.pop`),shift:e.method({},o,`list.shift`),unshift:e.method({value:t},a,`list.unshift`),insert:e.method({index:n,value:t},a,`list.insert`),remove:e.method({index:n},t,`list.remove`),clear:e.method({},a,`list.clear`),slice:e.method({start:e.optional(n),end:e.optional(n)},s,`list.slice`),concat:e.method({other:s},s,`list.concat`),reverse:e.method({},s,`list.reverse`),join:e.method({separator:e.optional(i)},i,`list.join`),indexOf:e.method({value:t},n,`list.indexOf`),contains:e.method({value:t},r,`list.contains`),unique:e.method({},s,`list.unique`),duplicates:e.method({},s,`list.duplicates`),map:e.method({fn:c(e.alias(`R`))},e.list(e.alias(`R`)),`list.map`,{generic:{R:e.any()}}),filter:e.method({fn:c(r)},s,`list.filter`),find:e.method({fn:c(r)},o,`list.find`),reduce:e.method({fn:e.fn({args:e.obj({acc:{type:e.alias(`R`)},value:{type:t},index:{type:n}}),returns:e.alias(`R`)}),initial:e.alias(`R`)},e.alias(`R`),`list.reduce`,{generic:{R:e.any()}}),some:e.method({fn:c(r)},r,`list.some`),every:e.method({fn:c(r)},r,`list.every`),sort:e.method({fn:e.optional(e.fn({args:e.obj({a:{type:t},b:{type:t}}),returns:n}))},s,`list.sort`),isEmpty:e.method({},r,`list.isEmpty`),isNotEmpty:e.method({},r,`list.isNotEmpty`),first:e.prop(o,`list.first`),last:e.prop(o,`list.last`)}}toJSON(){return Km({name:e.NAME,generic:{V:this.item.toJSON()},options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,this.item.clone(),{...this.options})}toCode(e,t){return this.docsPrefix(t)+`list<${this.item.toCode(void 0,t)}>`+Rh(this.options,{minLength:0})}valueA(e){let t=R.array(this.item.toA(e));return this.options.minLength!==void 0&&(t=t.min(this.options.minLength)),this.options.maxLength!==void 0&&(t=t.max(this.options.maxLength)),t}toNewA(e){let t=R.array(R.ref(`Expr`));return this.options.minLength!==void 0&&(t=t.min(this.options.minLength)),this.options.maxLength!==void 0&&(t=t.max(this.options.maxLength)),this.describeA(t,e)}describe(t){if(Array.isArray(t))return new e(this.registry,this.registry.any(),{})}};function Pg(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function Fg(e){if(Array.isArray(e))return[e[0],e[1]];let t=e;return[t?.key,t?.value]}function Ig(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var Lg=class e extends U{static NAME=`map`;name=e.NAME;static optionKeys=[];static genericKeys=[`K`,`V`];static from(t,n){let r=n.registry,i=t.generic?.K?n.parse(t.generic.K):r.text(),a=t.generic?.V?n.parse(t.generic.V):r.any();return new e(n,i,a)}constructor(e,t,n){super(e,{},{K:t,V:n})}get key(){return this.generic.K}get value(){return this.generic.V}valid(e,t){if(!(e instanceof Map))return!1;for(let[,n]of e){if(!Array.isArray(n)||n.length!==2)return!1;let[e,r]=n;if(!(e instanceof W)||!(r instanceof W)||!e.type.valid(e.raw,t)||!r.type.valid(r.raw,t)||!Sh(this.key,e.type,t)||!Sh(this.value,r.type,t))return!1}return!0}parse(e,t){let n=e instanceof Map?Array.from(e,([e,t])=>Pg(t)?t:[e,t]):this.textKeyed()&&Ig(e)?Object.entries(e):e;if(!Array.isArray(n))throw new Nm({path:[],code:`map.invalid`,message:`map.parse: expected array of [key, value] pairs`,severity:`error`});let r=new Map;for(let e of n){let[n,i]=Array.isArray(e)?e:[e.key,e.value],a=this.registry.parseValue(n,this.key,t),o=this.registry.parseValue(i,this.value,t);r.set(a.raw,[a,o])}return new W(this,r)}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){return t.form===`logical`&&this.textKeyed()?Object.fromEntries(Array.from(e,([,[e,r]])=>[String(Eh(e,t,n)),Eh(r,t,n)])):Array.from(e,([,[e,r]])=>({key:Eh(e,t,n),value:Eh(r,t,n)}))}textKeyed(){return this.key.name===`text`}create(){return new Map}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<e.length;n++){let[r,i]=Fg(e[n]);t.slot(this.key,r,`${n}.key`),t.slot(this.value,i,`${n}.value`)}return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i of e){let[e,a]=Fg(i);r.push({key:await this.key.newFill(e,t,n),value:await this.value.newFill(a,t,n)})}return r}random(e){let t=e(0,5,!0),n=new Map;for(let r=0;r<t;r++){let t=this.key.random(e),r=this.value.random(e);n.set(t,[new W(this.key,t),new W(this.value,r)])}return n}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.key),r=this.registry.like(t.value);return n.name===`null`||r.name===`null`?this.registry.null():this.registry.map(n,r)}compatibleType(t,n,r){return t instanceof e&&this.key.compatible(t.key,n,r)&&this.value.compatible(t.value,n,r)}or(t){return t instanceof e?new e(this.registry,this.key.or(t.key),this.value.or(t.value)):this}narrow(e){return{}}get(){let e=this.registry;return new Mh({key:this.key,value:this.value,get:e.nativeExpr(`map.indexGet`),set:e.nativeExpr(`map.indexSet`),loop:e.nativeExpr(`map.iterate`)})}props(){let e=this.registry,t=this.key,n=this.value,r=e.num(),i=e.bool(),a=e.void(),o=e.optional(n);return{...super.props(),size:e.prop(r,`map.size`),at:e.method({key:t},o,`map.at`),has:e.method({key:t},i,`map.has`),delete:e.method({key:t},i,`map.delete`),clear:e.method({},a,`map.clear`),keys:e.method({},e.list(t),`map.keys`),values:e.method({},e.list(n),`map.values`),isEmpty:e.method({},i,`map.isEmpty`),isNotEmpty:e.method({},i,`map.isNotEmpty`)}}toJSON(){return{name:e.NAME,generic:{K:this.key.toJSON(),V:this.value.toJSON()}}}clone(){return new e(this.registry,this.key.clone(),this.value.clone())}toCode(e,t){return this.docsPrefix(t)+`map<${this.key.toCode(void 0,t)}, ${this.value.toCode(void 0,t)}>`}valueA(e){return this.key.name===`text`?R.record(this.value.toA(e)):R.array(this.objectA({key:this.key.toA(e),value:this.value.toA(e)},e))}toNewA(e){return this.describeA(R.array(R.object({key:R.ref(`Expr`),value:R.ref(`Expr`)})),e)}describe(t){return t instanceof Map?new e(this.registry,this.registry.any(),this.registry.any()):void 0}},Rg=class e extends U{constructor(e,t){super(e,{excluded:t.toJSON()}),this.excluded=t}excluded;static NAME=`not`;name=e.NAME;static optionKeys=[`excluded`];static genericKeys=[];static from(t,n){let r=n.registry,i=t.options?.excluded?n.parse(t.options.excluded):r.any();return new e(n,i)}valid(e,t){return!this.excluded.valid(e,t)}parse(e,t){if(this.excluded.valid(e,t))throw new Nm({path:[],code:`not.excluded`,message:`not: value matches excluded type ${this.excluded.name}`,severity:`error`});return new W(this,e)}encode(e,t){return e}create(){return null}random(e){return null}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.excluded);return n.name===`null`?n:this.registry.not(n)}compatibleType(t,n,r){return n?.exact?t instanceof e&&this.excluded.exact(t.excluded,r):!this.excluded.compatible(t,n,r)}flexible(){return!0}or(t){return t instanceof e?new e(this.registry,this.registry.or([this.excluded,t.excluded])):this}narrow(e){return{excluded:e.excluded??this.options.excluded}}props(){let e=this.registry;return{...super.props(),typeOf:e.method({},e.text(),`not.typeOf`),toText:e.method({},e.text(),`not.toText`)}}toJSON(){return{name:e.NAME,options:{excluded:this.excluded.toJSON()}}}clone(){return new e(this.registry,this.excluded.clone())}toCode(e,t){return this.docsPrefix(t)+`not<${this.excluded.toCode(void 0,t)}>`}valueA(e){return R.not(this.excluded.toA(e))}},zg=class e extends U{static NAME=`null`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return e===null}parse(e){if(e!==null)throw new Nm({path:[],code:`null.invalid`,message:`null expects null, got ${typeof e}`,severity:`error`});return new W(this,null)}encode(e){return null}create(){return null}random(e){return null}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new Nm({path:[],code:`null.no-options`,message:`null has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),toText:e.method({},e.text(),`null.toText`),toBool:e.method({},e.bool(),`null.toBool`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`null`}valueA(){return R.null()}},Bg=class e extends U{constructor(e,t){super(e,{},{T:t}),this.inner=t}inner;static NAME=`nullable`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e===null||this.inner.valid(e,t)}parse(e,t){if(e===null)return new W(this,null);let n=this.inner.parse(e,t);return new W(this,n.raw)}parsesExprValue(e){return this.inner.parsesExprValue(e)}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){return e===null?null:this.inner.encodeAs(e,t,n)}forEachNewSlot(e,t){return e!=null&&this.inner.forEachNewSlot(e,t)}async newFill(e,t,n){return e==null?e:this.inner.newFill(e,t,n)}create(){return null}random(e){return e(0,9,!0)<3?null:this.inner.random(e)}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.inner);return n.name===`null`?n:this.registry.nullable(n)}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r):!n?.exact&&this.inner.compatible(t,n,r)}or(t){return t instanceof e?new e(this.registry,this.inner.or(t.inner)):this}required(){return this.inner}isUniversal(){return this.inner.isUniversal()}narrow(e){if(e&&Object.keys(e).length>0)throw new Nm({path:[],code:`nullable.no-options`,message:`nullable has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry,t=this.inner;return{...super.props(),value:e.prop(t,`nullable.value`),isNull:e.method({},e.bool(),`nullable.isNull`),or:e.method({fallback:t},t,`nullable.or`),map:e.method({fn:e.fn({args:e.obj({value:{type:t}}),returns:e.alias(`R`)})},e.nullable(e.alias(`R`)),`nullable.map`,{generic:{R:e.any()}})}}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()}}}clone(){return new e(this.registry,this.inner.clone())}toCode(e,t){return this.docsPrefix(t)+`nullable<${this.inner.toCode(void 0,t)}>`}valueA(e){return R.nullable(this.inner.toA(e))}toNewA(e){return this.describeA(R.nullable(this.inner.toNewA(e)),e)}},Vg=class e extends U{static NAME=`num`;name=e.NAME;static optionKeys=[`min`,`max`,`whole`,`minPrecision`,`maxPrecision`,`prefix`,`suffix`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){if(typeof e!=`number`||Number.isNaN(e))return!1;let{min:t,max:n,whole:r}=this.options;return!(t!==void 0&&e<t||n!==void 0&&e>n||r&&!Number.isInteger(e))}parse(e){let t=typeof e==`string`?Number(e):e;if(typeof t!=`number`||Number.isNaN(t))throw new Nm({path:[],code:`num.invalid`,message:`num.parse: not a number \u2014 ${String(e)}`,severity:`error`});if(!this.valid(t))throw new Nm({path:[],code:`num.out-of-range`,message:`num.parse: ${t} violates options ${JSON.stringify(this.options)}`,severity:`error`});return new W(this,t)}encode(e){return e}create(){let{min:e,max:t,whole:n}=this.options,r=0;if(e!==void 0&&r<e&&(r=e),t!==void 0&&r>t&&(r=t),n&&!Number.isInteger(r)){let e=Math.ceil(r);r=t!==void 0&&e>t?Math.floor(r):e}return r}random(e){return e(this.options.min??0,this.options.max??100,this.options.whole??!1)}compatibleType(t,n){if(!(t instanceof e))return!1;if(!n?.value)return!0;let r=this.options,i=t.options;return!(r.min!==void 0&&(i.min===void 0||i.min<r.min)||r.max!==void 0&&(i.max===void 0||i.max>r.max)||r.whole&&!i.whole)}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{min:n.min!==void 0&&r.min!==void 0?Math.min(n.min,r.min):void 0,max:n.max!==void 0&&r.max!==void 0?Math.max(n.max,r.max):void 0,whole:n.whole&&r.whole,minPrecision:n.minPrecision!==void 0&&r.minPrecision!==void 0?Math.min(n.minPrecision,r.minPrecision):void 0,maxPrecision:n.maxPrecision!==void 0&&r.maxPrecision!==void 0?Math.max(n.maxPrecision,r.maxPrecision):void 0,prefix:n.prefix===r.prefix?n.prefix:void 0,suffix:n.suffix===r.suffix?n.suffix:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Nm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.min!==void 0&&(t.min!==void 0&&e.min<t.min&&n(`num.widen.min`,`local.min ${e.min} < base.min ${t.min}`),r.min=e.min),e.max!==void 0&&(t.max!==void 0&&e.max>t.max&&n(`num.widen.max`,`local.max ${e.max} > base.max ${t.max}`),r.max=e.max),e.whole!==void 0&&(t.whole===!0&&!e.whole&&n(`num.widen.whole`,`base requires whole; local cannot remove`),r.whole=e.whole),e.minPrecision!==void 0&&(t.minPrecision!==void 0&&e.minPrecision<t.minPrecision&&n(`num.widen.minPrecision`,`minPrecision cannot decrease`),r.minPrecision=e.minPrecision),e.maxPrecision!==void 0&&(t.maxPrecision!==void 0&&e.maxPrecision>t.maxPrecision&&n(`num.widen.maxPrecision`,`maxPrecision cannot increase`),r.maxPrecision=e.maxPrecision),e.prefix!==void 0&&(r.prefix=e.prefix),e.suffix!==void 0&&(r.suffix=e.suffix),r}get(){let e=this.registry;return new Mh({key:e.num({whole:!0,min:0}),value:e.num(),loop:e.nativeExpr(`num.loop`)})}props(){let e=this.registry,t=e.num(),n=e.bool(),r=e.text(),i=e.optional(t);return{...super.props(),eq:e.method({other:t,epsilon:i},n,`num.eq`),neq:e.method({other:t,epsilon:i},n,`num.neq`),lt:e.method({other:t},n,`num.lt`),lte:e.method({other:t},n,`num.lte`),gt:e.method({other:t},n,`num.gt`),gte:e.method({other:t},n,`num.gte`),add:e.method({other:t},t,`num.add`),sub:e.method({other:t},t,`num.sub`),mul:e.method({other:t},t,`num.mul`),div:e.method({other:t},t,`num.div`),mod:e.method({other:t},t,`num.mod`),pow:e.method({other:t},t,`num.pow`),abs:e.method({},t,`num.abs`),neg:e.method({},t,`num.neg`),sign:e.method({},t,`num.sign`),sqrt:e.method({},t,`num.sqrt`),min:e.method({other:t},t,`num.min`),max:e.method({other:t},t,`num.max`),clamp:e.method({min:t,max:t},t,`num.clamp`),floor:e.method({},t,`num.floor`),ceil:e.method({},t,`num.ceil`),round:e.method({},t,`num.round`),isZero:e.method({},n,`num.isZero`),isPositive:e.method({},n,`num.isPositive`),isNegative:e.method({},n,`num.isNegative`),isInteger:e.method({},n,`num.isInteger`),isEven:e.method({},n,`num.isEven`),isOdd:e.method({},n,`num.isOdd`),toText:e.method({precision:i},r,`num.toText`),toBool:e.method({},n,`num.toBool`)}}toJSON(){return Km({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`num`+Rh(this.options,{minPrecision:1,maxPrecision:7,prefix:``,suffix:``})}valueA(){let e=this.options.whole?R.int():R.number();return this.options.min!==void 0&&(e=e.min(this.options.min)),this.options.max!==void 0&&(e=e.max(this.options.max)),e}describe(t){if(!(typeof t!=`number`||Number.isNaN(t)))return new e(this.registry,{whole:Number.isInteger(t)})}},Hg=class e extends U{constructor(e,t){super(e,{},{T:t}),this.inner=t}inner;static NAME=`optional`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e===void 0||this.inner.valid(e,t)}parse(e,t){if(e==null)return new W(this,void 0);let n=this.inner.parse(e,t);return new W(this,n.raw)}parsesExprValue(e){return this.inner.parsesExprValue(e)}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){return e===void 0?null:this.inner.encodeAs(e,t,n)}forEachNewSlot(e,t){return e!=null&&this.inner.forEachNewSlot(e,t)}async newFill(e,t,n){return e==null?e:this.inner.newFill(e,t,n)}create(){}random(e){if(!(e(0,9,!0)<3))return this.inner.random(e)}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.inner);return n.name===`null`?n:this.registry.optional(n)}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r):!n?.exact&&this.inner.compatible(t,n,r)}or(t){return t instanceof e?new e(this.registry,this.inner.or(t.inner)):this}required(){return this.inner}isOptional(){return!0}isUniversal(){return this.inner.isUniversal()}narrow(e){if(e&&Object.keys(e).length>0)throw new Nm({path:[],code:`optional.no-options`,message:`optional has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry,t=this.inner;return{...super.props(),value:e.prop(t,`optional.value`),has:e.method({},e.bool(),`optional.has`),or:e.method({fallback:t},t,`optional.or`),map:e.method({fn:e.fn({args:e.obj({value:{type:t}}),returns:e.alias(`R`)})},e.optional(e.alias(`R`)),`optional.map`,{generic:{R:e.any()}})}}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()}}}clone(){return new e(this.registry,this.inner.clone())}toCode(e,t){return this.docsPrefix(t)+`optional<${this.inner.toCode(void 0,t)}>`}valueA(e){return R.optional(this.inner.toA(e))}toNewA(e){return this.describeA(R.optional(this.inner.toNewA(e)),e)}},Ug=class e extends U{static NAME=`or`;name=e.NAME;static optionKeys=[`types`];static genericKeys=[];static from(t,n){n.registry;let r=(t.options?.types??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,{variants:t})}get variants(){return this.options.variants}valid(e,t){return this.variants.some(n=>n.valid(e,t))}parse(e,t){for(let n of this.variants)try{let r=n.parse(e,t);return new W(this,r.raw)}catch{continue}throw new Nm({path:[],code:`or.no-match`,message:`or: no variant matched (${this.variants.map(e=>e.name).join(` | `)})`,severity:`error`})}encode(e,t){let n=this.variants.find(n=>n.valid(e,t));if(!n)throw new Nm({path:[],code:`or.dump.no-match`,message:`or.dump: value does not satisfy any variant`,severity:`error`});return n.encode(e,t)}parsesExprValue(e){return this.variants.some(t=>t.parsesExprValue(e))}encodeAs(e,t,n){let r=this.variants.find(t=>t.valid(e,n));if(!r)throw new Nm({path:[],code:`or.dump.no-match`,message:`or.dump: value does not satisfy any variant`,severity:`error`});return r.encodeAs(e,t,n)}create(){return this.variants[0]?.create()??null}random(e){let t=e(0,this.variants.length-1,!0);return this.variants[t]?.random(e)??null}like(t){if(!(t instanceof e))return this;let n=t.variants.map(e=>this.registry.like(e)).filter(e=>e.name!==`null`);return n.length===0?this.registry.null():n.length===1?n[0]:this.registry.or(n)}compatibleType(e,t,n){return this.variants.some(r=>r.compatible(e,t,n))}or(t){return t instanceof e?new e(this.registry,[...this.variants,...t.variants]):new e(this.registry,[...this.variants,t])}simplify(){return this.variants.length===1?this.variants[0]:this}narrow(e){return this.options}props(){let e=super.props();if(this.variants.length===0)return e;let t=this.variants.map(e=>e.props()),n=Object.keys(t[0]).filter(e=>t.every(t=>e in t)),r={...e};for(let e of n){let n=t.map(t=>t[e].type);r[e]={type:this.registry.or(n)}}return r}get(){let e=this.variants.map(e=>e.get());if(e.some(e=>!e))return;let t=e;return new Mh({key:this.registry.and(t.map(e=>e.key)),value:this.registry.or(t.map(e=>e.value))})}call(){let e=this.variants.map(e=>e.call());if(e.some(e=>!e))return;let t=e,n=t.map(e=>e.returns).filter(e=>!!e),r=t.map(e=>e.throws).filter(e=>!!e);return new Nh({args:this.registry.and(t.map(e=>e.args)),returns:n.length===t.length?this.registry.or(n):void 0,throws:r.length>0?this.registry.or(r):void 0})}toJSON(){return{name:e.NAME,options:{types:this.variants.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.variants.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`or<${this.variants.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){return this.variants.length===0?R.never():this.variants.length===1?this.variants[0].toA(e):R.union(this.variants.map(t=>t.toA(e)))}toNewA(e){return this.variants.length===0?this.describeA(R.never(),e):this.variants.length===1?this.describeA(this.variants[0].toNewA(e),e):this.describeA(R.union(this.variants.map(t=>t.toNewA(e))),e)}},Wg=class e extends U{static NAME=`text`;name=e.NAME;static optionKeys=[`minLength`,`maxLength`,`pattern`,`flags`];static genericKeys=[];_regex;static from(t,n){return n.registry,new e(n,t.options??{})}regex(){if(this._regex)return this._regex;if(this.options.pattern)return this._regex=new RegExp(this.options.pattern,this.options.flags),this._regex}valid(e){if(typeof e!=`string`)return!1;let{minLength:t,maxLength:n}=this.options;if(t!==void 0&&e.length<t||n!==void 0&&e.length>n)return!1;let r=this.regex();return!(r&&!r.test(e))}parse(e){if(typeof e!=`string`)throw new Nm({path:[],code:`text.invalid`,message:`text.parse: expected string, got ${typeof e}`,severity:`error`});if(!this.valid(e))throw new Nm({path:[],code:`text.constraint`,message:`text.parse: value violates constraints`,severity:`error`});return new W(this,e)}encode(e){return e}create(){let e=this.options.minLength??0;return e>0?`a`.repeat(e):``}random(e){let t=e(this.options.minLength??0,this.options.maxLength??16,!0),n=``;for(let r=0;r<t;r++)n+=`abcdefghijklmnopqrstuvwxyz0123456789`[e(0,35,!0)];return n}compatibleType(t,n){if(!(t instanceof e))return!1;if(!n?.value)return!0;let r=this.options,i=t.options;return!(r.minLength!==void 0&&(i.minLength===void 0||i.minLength<r.minLength)||r.maxLength!==void 0&&(i.maxLength===void 0||i.maxLength>r.maxLength)||r.pattern&&r.pattern!==i.pattern)}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{minLength:n.minLength!==void 0&&r.minLength!==void 0?Math.min(n.minLength,r.minLength):void 0,maxLength:n.maxLength!==void 0&&r.maxLength!==void 0?Math.max(n.maxLength,r.maxLength):void 0,pattern:n.pattern===r.pattern?n.pattern:void 0,flags:n.pattern===r.pattern?n.flags:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new Nm({path:[],code:e,message:t,severity:`error`})},r={...t};return e.minLength!==void 0&&(t.minLength!==void 0&&e.minLength<t.minLength&&n(`text.widen.minLength`,`local ${e.minLength} < base ${t.minLength}`),r.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength!==void 0&&e.maxLength>t.maxLength&&n(`text.widen.maxLength`,`local ${e.maxLength} > base ${t.maxLength}`),r.maxLength=e.maxLength),e.pattern!==void 0&&(t.pattern!==void 0&&(e.pattern!==t.pattern||e.flags!==t.flags)&&n(`text.widen.pattern`,`pattern narrowing is only allowed when base has no pattern or matches exactly`),r.pattern=e.pattern,r.flags=e.flags),r}get(){let e=this.registry;return new Mh({key:e.num(),value:e.text({minLength:1,maxLength:1}),get:e.nativeExpr(`text.charAt`),loop:e.nativeExpr(`text.chars`)})}props(){let e=this.registry,t=e.text(),n=e.num(),r=e.bool(),i=e.optional(n);return{...super.props(),length:e.prop(n,`text.length`),eq:e.method({other:t},r,`text.eq`),neq:e.method({other:t},r,`text.neq`),contains:e.method({search:t},r,`text.contains`),startsWith:e.method({prefix:t},r,`text.startsWith`),endsWith:e.method({suffix:t},r,`text.endsWith`),trim:e.method({},t,`text.trim`),trimStart:e.method({},t,`text.trimStart`),trimEnd:e.method({},t,`text.trimEnd`),upper:e.method({},t,`text.upper`),lower:e.method({},t,`text.lower`),slice:e.method({start:n,end:i},t,`text.slice`),replace:e.method({search:t,replacement:t},t,`text.replace`),split:e.method({separator:t},e.list(t),`text.split`),concat:e.method({other:t},t,`text.concat`),repeat:e.method({count:n},t,`text.repeat`),indexOf:e.method({search:t,from:i},n,`text.indexOf`),lastIndexOf:e.method({search:t,from:i},n,`text.lastIndexOf`),match:e.method({pattern:t},e.list(t),`text.match`),test:e.method({pattern:t},r,`text.test`),isEmpty:e.method({},r,`text.isEmpty`),isNotEmpty:e.method({},r,`text.isNotEmpty`),toNum:e.method({},n,`text.toNum`),toBool:e.method({},r,`text.toBool`)}}toJSON(){return Km({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`text`+Rh(this.options)}valueA(){let e=R.string();return this.options.minLength!==void 0&&(e=e.min(this.options.minLength)),this.options.maxLength!==void 0&&(e=e.max(this.options.maxLength)),this.options.pattern&&(e=e.pattern(this.options.pattern,this.options.flags)),e}describe(e){return typeof e==`string`?this:void 0}},Gg=class e extends U{static NAME=`timestamp`;name=e.NAME;static optionKeys=[`min`,`max`,`utc`,`precision`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return e instanceof Date&&!Number.isNaN(e.getTime())}parse(e){let t=e instanceof Date?e:typeof e==`string`?new Date(e):new Date(NaN);if(!this.valid(t))throw new Nm({path:[],code:`timestamp.invalid`,message:`timestamp.parse: invalid: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e.toISOString()}create(){return new Date}random(e){return new Date(e(Date.UTC(2e3,0,1),Date.UTC(2050,11,31),!0))}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e,this}narrow(e){return this.options}props(){let e=this.registry,t=e.num({whole:!0}),n=e.bool(),r=e.text(),i=e.timestamp(),a=e.duration();return{...super.props(),year:e.prop(t,`timestamp.year`),month:e.prop(t,`timestamp.month`),day:e.prop(t,`timestamp.day`),hour:e.prop(t,`timestamp.hour`),minute:e.prop(t,`timestamp.minute`),second:e.prop(t,`timestamp.second`),millisecond:e.prop(t,`timestamp.millisecond`),eq:e.method({other:i},n,`timestamp.eq`),before:e.method({other:i},n,`timestamp.before`),after:e.method({other:i},n,`timestamp.after`),addDuration:e.method({duration:a},i,`timestamp.addDuration`),subDuration:e.method({duration:a},i,`timestamp.subDuration`),diff:e.method({other:i},a,`timestamp.diff`),toDate:e.method({},e.date(),`timestamp.toDate`),toEpoch:e.method({},t,`timestamp.toEpoch`),toText:e.method({format:e.optional(r)},r,`timestamp.toText`)}}toJSON(){return Km({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`timestamp`+Rh(this.options)}valueA(){return R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`).describe(`An ISO 8601 timestamp (YYYY-MM-DD HH:MM[:SS][Z]).`)}describe(e){return e instanceof Date?this:void 0}};function Kg(e){let t,n={};return Object.defineProperty(n,"elements",{enumerable:!0,get:()=>t??=e.map(e=>e.toJSON())}),n}var qg=class e extends U{static NAME=`tuple`;name=e.NAME;static optionKeys=[`elements`];static genericKeys=[];elements;static from(t,n){n.registry;let r=(t.options?.elements??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,Kg(t)),this.elements=t}valid(e,t){return!Array.isArray(e)||e.length!==this.elements.length?!1:e.every((e,n)=>e instanceof W&&e.type.valid(e.raw,t)&&Sh(this.elements[n],e.type,t))}parse(e,t){if(!Array.isArray(e)||e.length!==this.elements.length)throw new Nm({path:[],code:`tuple.invalid`,message:`tuple.parse: expected array of length ${this.elements.length}`,severity:`error`});let n=this.elements.map((n,r)=>this.registry.parseValue(e[r],n,t));return new W(this,n)}encode(e,t){return this.encodeAs(e,Oh,t)}encodeAs(e,t,n){if(!Array.isArray(e))throw new Nm({path:[],code:`tuple.invalid`,message:`tuple.encode: expected an array of cells`,severity:`error`});return e.map(e=>Eh(e,t,n))}create(){return this.elements.map(e=>new W(e,e.create()))}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<this.elements.length&&n<e.length;n++)t.slot(this.elements[n],e[n],n);return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i=0;i<e.length;i++){let a=this.elements[i];r.push(a?await a.newFill(e[i],t,n):e[i])}return r}random(e){return this.elements.map(t=>new W(t,t.random(e)))}like(t){if(!(t instanceof e)||t.elements.length!==this.elements.length)return this;let n=t.elements.map(e=>this.registry.like(e));return n.some(e=>e.name===`null`)?this.registry.null():this.registry.tuple(n)}compatibleType(t,n,r){return!(t instanceof e)||t.elements.length!==this.elements.length?!1:this.elements.every((e,i)=>e.compatible(t.elements[i],n,r))}or(t){return!(t instanceof e)||t.elements.length!==this.elements.length?this:new e(this.registry,this.elements.map((e,n)=>e.or(t.elements[n])))}narrow(e){return e.elements===void 0?this.options:{elements:e.elements}}get(){let e=this.elements.length===1?this.elements[0]:this.registry.or(this.elements),t=this.registry;return new Mh({key:t.num({whole:!0,min:0,max:this.elements.length-1}),value:e,get:t.nativeExpr(`tuple.at`),set:t.nativeExpr(`tuple.setAt`),loop:t.nativeExpr(`tuple.iterate`)})}follow(e,t){if(`key`in e&&!(`args`in e)){let t=e.key,n=t?.kind===`new`?t.value:void 0;if(typeof n==`number`&&Number.isInteger(n))return this.elements[n]}return super.follow(e,t)}props(){let e=this.registry;e.num();let t=this.elements[0]??e.any(),n=this.elements[this.elements.length-1]??e.any();return{...super.props(),length:e.prop(e.num({whole:!0,min:this.elements.length,max:this.elements.length}),`tuple.length`),first:e.prop(t,`tuple.first`),last:e.prop(n,`tuple.last`),toList:e.method({},e.list(this.elements.length===0?e.any():e.or(this.elements)),`tuple.toList`)}}toJSON(){return{name:e.NAME,options:{elements:this.elements.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.elements.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`tuple<${this.elements.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){let t=this.elements.map(t=>t.toA(e));return t.length>0?R.tuple(t):R.array(R.unknown()).max(0)}toNewA(e){let t=this.elements.map(()=>R.ref(`Expr`));return this.describeA(t.length>0?R.tuple(t):R.array(R.ref(`Expr`)).max(0),e)}},Jg=class e extends U{constructor(e,t){super(e,{},{T:t}),this.constraint=t}constraint;static NAME=`typ`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static valuesAreTypes=!0;static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e instanceof U?e.compatible(this.constraint,void 0,t)||this.constraint.compatible(e,void 0,t):!1}parse(t,n){if(t instanceof W&&t.type instanceof e)return t;if(t instanceof U){if(!this.valid(t,n))throw Error(`typ.parse: Type '${t.name}' is not compatible with ${this.constraint.toCode()}`);return new W(this,t)}if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`typ.parse: expected TypeDef or Type, got ${typeof t}`);if(!(`name`in t)||typeof t.name!=`string`)throw Error(`typ.parse: TypeDef missing 'name' field`);let r;try{r=this.registry.parse(t,n)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`typ.parse: ${t}`)}if(!this.valid(r,n))throw Error(`typ.parse: Type '${r.name}' is not compatible with ${this.constraint.toCode()}`);let i=n??this.registry,a=r.references().refs.filter(e=>i.lookup(e)===void 0);if(a.length>0)throw Error(`typ.parse: no type named ${a.join(`, `)}`);return new W(this,r)}encode(e,t){return e.toJSON()}create(){return this.constraint}random(e){return this.constraint}compatibleType(t,n,r){return t instanceof e&&this.constraint.compatible(t.constraint,n,r)}or(t){return t instanceof e?new e(this.registry,this.registry.or([this.constraint,t.constraint])):this}narrow(e){return{}}props(){return{...super.props()}}toJSON(){return{name:e.NAME,generic:{T:this.constraint.toJSON()}}}clone(){return new e(this.registry,this.constraint.clone())}toCode(e,t){return this.docsPrefix(t)+`typ<${this.constraint.toCode(void 0,t)}>`}valueA(e){let t=this.registry.compatible(this.constraint);if(t.length===0&&this.constraint.name!==`any`)return R.never();let n;if(this.constraint.name===`any`)n=R.ref(`TypeDef`);else{let e=t.map(e=>cm(this.registry,e.name));e.push(lm()),e.push(um(t.map(e=>e.name))),n=R.union(e).describe(`A gin type definition ({ "name": ..., ... }) whose type fits ${this.constraint.toCode()}.`)}return n.refine(t=>{try{return this.parse(t,e?.scope),!0}catch(e){return e instanceof Error?e.message:String(e)}})}toNewA(e){return this.describeA(this.toA(e),e)}},Yg=class e extends U{static NAME=`void`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return e===void 0}parse(e){if(e!=null)throw new Nm({path:[],code:`void.invalid`,message:`void expects undefined/null, got ${typeof e}`,severity:`error`});return new W(this,void 0)}encode(e){return null}create(){}random(e){}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new Nm({path:[],code:`void.no-options`,message:`void has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),toText:e.method({},e.text(),`void.toText`),toBool:e.method({},e.bool(),`void.toBool`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`void`}valueA(){return R.null()}};function K(e){return e.get(`this`).raw}function Xg(e){return e.get(`this`)}function q(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];return r==null?r:$g(r)?r.raw:r}function Zg(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];if($g(r))return r}function Qg(e){let t=q(e,`epsilon`);return typeof t==`number`?t:0}function $g(e){return!!e&&typeof e==`object`&&`type`in e&&`raw`in e}function e_(e,t,n,r){let i=e.get(`yield`).raw,a=t.obj({key:{type:n},value:{type:r}});return(e,t)=>i(new W(a,{key:e,value:t}))}var t_={"type.toAny":(e,t)=>G(t.any(),K(e)),"any.typeOf":(e,t)=>G(t.text(),Xg(e).type.name),"any.is":(e,t)=>G(t.bool(),!0),"any.as":(e,t)=>{let n=Xg(e);return G(t.optional(n.type),n.raw)},"any.toText":(e,t)=>G(t.text(),String(K(e))),"any.toBool":(e,t)=>G(t.bool(),!!K(e)),"any.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"any.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`))},n_={"void.toText":(e,t)=>G(t.text(),`void`),"void.toBool":(e,t)=>G(t.bool(),!1)},r_={"null.toText":(e,t)=>G(t.text(),`null`),"null.toBool":(e,t)=>G(t.bool(),!1)},i_={"bool.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"bool.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"bool.and":(e,t)=>G(t.bool(),K(e)&&q(e,`other`)),"bool.or":(e,t)=>G(t.bool(),K(e)||q(e,`other`)),"bool.xor":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"bool.not":(e,t)=>G(t.bool(),!K(e)),"bool.toText":(e,t)=>{let n=K(e),r=q(e,`trueText`),i=q(e,`falseText`);return G(t.text(),n?r??`true`:i??`false`)},"bool.toNum":(e,t)=>{let n=K(e),r=q(e,`trueValue`),i=q(e,`falseValue`);return G(t.num(),n?r??1:i??0)}},a_={"num.eq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))<=Qg(e)),"num.neq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))>Qg(e)),"num.lt":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"num.lte":(e,t)=>G(t.bool(),K(e)<=q(e,`other`)),"num.gt":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"num.gte":(e,t)=>G(t.bool(),K(e)>=q(e,`other`)),"num.add":(e,t)=>G(t.num(),K(e)+q(e,`other`)),"num.sub":(e,t)=>G(t.num(),K(e)-q(e,`other`)),"num.mul":(e,t)=>G(t.num(),K(e)*q(e,`other`)),"num.div":(e,t)=>G(t.num(),K(e)/q(e,`other`)),"num.mod":(e,t)=>G(t.num(),K(e)%q(e,`other`)),"num.pow":(e,t)=>G(t.num(),K(e)**q(e,`other`)),"num.abs":(e,t)=>G(t.num(),Math.abs(K(e))),"num.neg":(e,t)=>G(t.num(),-K(e)),"num.sign":(e,t)=>G(t.num(),Math.sign(K(e))),"num.sqrt":(e,t)=>G(t.num(),Math.sqrt(K(e))),"num.min":(e,t)=>G(t.num(),Math.min(K(e),q(e,`other`))),"num.max":(e,t)=>G(t.num(),Math.max(K(e),q(e,`other`))),"num.clamp":(e,t)=>G(t.num(),Math.min(Math.max(K(e),q(e,`min`)),q(e,`max`))),"num.floor":(e,t)=>G(t.num(),Math.floor(K(e))),"num.ceil":(e,t)=>G(t.num(),Math.ceil(K(e))),"num.round":(e,t)=>G(t.num(),Math.round(K(e))),"num.isZero":(e,t)=>G(t.bool(),Math.abs(K(e))<=Qg(e)),"num.isPositive":(e,t)=>G(t.bool(),K(e)>Qg(e)),"num.isNegative":(e,t)=>G(t.bool(),K(e)<-Qg(e)),"num.isInteger":(e,t)=>G(t.bool(),Number.isInteger(K(e))),"num.isEven":(e,t)=>G(t.bool(),K(e)%2==0),"num.isOdd":(e,t)=>G(t.bool(),Math.abs(K(e))%2==1),"num.toText":(e,t)=>{let n=q(e,`precision`),r=n==null?String(K(e)):K(e).toFixed(n);return G(t.text(),r)},"num.toBool":(e,t)=>G(t.bool(),K(e)!==0),"num.loop":async(e,t)=>{let n=K(e),r=t.num(),i=e_(e,t,r,r),a=Math.abs(Math.trunc(n)),o=n<0?-1:1;for(let e=0;e<a;e++){let t=e*o,n=Object.is(t,-0)?0:t;await i(G(r,e),G(r,n))}return G(t.void(),void 0)}},o_={"text.length":(e,t)=>G(t.num({whole:!0,min:0}),K(e).length),"text.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"text.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"text.contains":(e,t)=>G(t.bool(),K(e).includes(q(e,`search`))),"text.startsWith":(e,t)=>G(t.bool(),K(e).startsWith(q(e,`prefix`))),"text.endsWith":(e,t)=>G(t.bool(),K(e).endsWith(q(e,`suffix`))),"text.trim":(e,t)=>G(t.text(),K(e).trim()),"text.trimStart":(e,t)=>G(t.text(),K(e).trimStart()),"text.trimEnd":(e,t)=>G(t.text(),K(e).trimEnd()),"text.upper":(e,t)=>G(t.text(),K(e).toUpperCase()),"text.lower":(e,t)=>G(t.text(),K(e).toLowerCase()),"text.slice":(e,t)=>{let n=q(e,`start`),r=q(e,`end`);return G(t.text(),K(e).slice(n,r))},"text.replace":(e,t)=>{let n=q(e,`search`),r=q(e,`replacement`);return G(t.text(),K(e).split(n).join(r))},"text.split":(e,t)=>{let n=K(e).split(q(e,`separator`));return G(t.list(t.text()),n.map(e=>G(t.text(),e)))},"text.concat":(e,t)=>G(t.text(),K(e)+q(e,`other`)),"text.repeat":(e,t)=>G(t.text(),K(e).repeat(q(e,`count`))),"text.indexOf":(e,t)=>{let n=q(e,`from`);return G(t.num(),K(e).indexOf(q(e,`search`),n))},"text.lastIndexOf":(e,t)=>{let n=q(e,`from`);return G(t.num(),K(e).lastIndexOf(q(e,`search`),n))},"text.match":(e,t)=>{let n=q(e,`pattern`),r=K(e).match(new RegExp(n,`g`))??[];return G(t.list(t.text()),r.map(e=>G(t.text(),e)))},"text.test":(e,t)=>{let n=q(e,`pattern`);return G(t.bool(),new RegExp(n).test(K(e)))},"text.isEmpty":(e,t)=>G(t.bool(),K(e).length===0),"text.isNotEmpty":(e,t)=>G(t.bool(),K(e).length>0),"text.toNum":(e,t)=>G(t.num(),Number(K(e))),"text.toBool":(e,t)=>G(t.bool(),K(e).length>0),"text.charAt":(e,t)=>{let n=e.get(`key`).raw,r=K(e)[n];if(r===void 0)throw Error(`text[${n}]: index out of range`);return G(t.text({minLength:1,maxLength:1}),r)},"text.chars":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=t.text({minLength:1,maxLength:1}),a=e_(e,t,r,i);for(let e=0;e<n.length;e++)await a(G(r,e),G(i,n[e]));return G(t.void(),void 0)}},s_=e=>Xg(e).type.item,c_={"list.length":(e,t)=>G(t.num({whole:!0,min:0}),K(e).length),"list.indexGet":e=>{let t=e.get(`key`).raw,n=K(e);if(t<0||t>=n.length)throw Error(`list[${t}]: index out of range`);return n[t]},"list.indexSet":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`),i=K(e);if(n<0||n>=i.length)throw Error(`list[${n}] =: index out of range`);return i[n]=r,G(t.void(),void 0)},"list.iterate":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=e_(e,t,r,s_(e)),a=G(t.void(),void 0);for(let e=0;e<n.length;e++)await i(G(r,e),n[e]);return a},"list.at":(e,t)=>{let n=q(e,`index`),r=K(e);return n<0||n>=r.length?G(t.optional(s_(e)),void 0):G(t.optional(s_(e)),r[n].raw)},"list.push":(e,t)=>(K(e).push(Zg(e,`value`)),G(t.void(),void 0)),"list.pop":(e,t)=>{let n=K(e).pop();return G(t.optional(s_(e)),n?n.raw:void 0)},"list.shift":(e,t)=>{let n=K(e).shift();return G(t.optional(s_(e)),n?n.raw:void 0)},"list.unshift":(e,t)=>(K(e).unshift(Zg(e,`value`)),G(t.void(),void 0)),"list.insert":(e,t)=>(K(e).splice(q(e,`index`),0,Zg(e,`value`)),G(t.void(),void 0)),"list.remove":e=>K(e).splice(q(e,`index`),1)[0],"list.clear":(e,t)=>(K(e).length=0,G(t.void(),void 0)),"list.slice":e=>{let t=Xg(e).type,n=q(e,`start`),r=q(e,`end`);return G(t,K(e).slice(n,r))},"list.concat":e=>{let t=Xg(e).type,n=q(e,`other`);return G(t,K(e).concat(n))},"list.reverse":e=>{let t=Xg(e).type;return G(t,[...K(e)].reverse())},"list.join":(e,t)=>{let n=q(e,`separator`)??`,`;return G(t.text(),K(e).map(e=>String(e.raw)).join(n))},"list.indexOf":(e,t)=>{let n=Zg(e,`value`).raw,r=K(e).findIndex(e=>e.raw===n);return G(t.num(),r)},"list.contains":(e,t)=>{let n=Zg(e,`value`).raw,r=K(e);return G(t.bool(),r.some(e=>e.raw===n))},"list.unique":e=>{let t=Xg(e).type,n=new Set,r=[];for(let t of K(e))n.has(t.raw)||(n.add(t.raw),r.push(t));return G(t,r)},"list.duplicates":e=>{let t=Xg(e).type,n=new Set,r=new Set,i=[];for(let t of K(e))n.has(t.raw)?r.has(t.raw)||(r.add(t.raw),i.push(t)):n.add(t.raw);return G(t,i)},"list.map":async(e,t)=>{let n=K(e),r=Zg(e,`fn`).raw,i=s_(e),a=[],o=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++){let i=new W(o,{value:n[e],index:G(t.num(),e)});a.push(await r(i))}return G(t.list(t.any()),a)},"list.filter":async e=>{let t=Xg(e).type,n=K(e),r=Zg(e,`fn`).raw,i=[],a=t.registry.obj({value:{type:t.item},index:{type:t.registry.num()}});for(let e=0;e<n.length;e++)(await r(new W(a,{value:n[e],index:G(t.registry.num(),e)}))).raw&&i.push(n[e]);return G(t,i)},"list.find":async(e,t)=>{let n=K(e),r=Zg(e,`fn`).raw,i=s_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if((await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.optional(i),n[e].raw);return G(t.optional(i),void 0)},"list.reduce":async(e,t)=>{let n=K(e),r=Zg(e,`fn`),i=Zg(e,`initial`),a=r.raw,o=s_(e),s=i,c=t.obj({acc:{type:t.any()},value:{type:o},index:{type:t.num()}});for(let e=0;e<n.length;e++)s=await a(new W(c,{acc:s,value:n[e],index:G(t.num(),e)}));return s},"list.some":async(e,t)=>{let n=K(e),r=Zg(e,`fn`).raw,i=s_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if((await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.bool(),!0);return G(t.bool(),!1)},"list.every":async(e,t)=>{let n=K(e),r=Zg(e,`fn`).raw,i=s_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if(!(await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.bool(),!1);return G(t.bool(),!0)},"list.sort":async e=>{let t=Xg(e).type,n=[...K(e)],r=Zg(e,`fn`);if(r&&typeof r.raw==`function`){let e=r.raw,i=t.registry.obj({a:{type:t.item},b:{type:t.item}}),a=[];for(let t=0;t<n.length;t++){let r=0;for(let a=0;a<n.length;a++)t!==a&&(await e(new W(i,{a:n[t],b:n[a]}))).raw>0&&r++;a.push({index:t,key:r})}return a.sort((e,t)=>e.key-t.key),G(t,a.map(e=>n[e.index]))}return G(t,n.sort((e,t)=>{let n=e.raw,r=t.raw;return n<r?-1:+(n>r)}))},"list.isEmpty":(e,t)=>G(t.bool(),K(e).length===0),"list.isNotEmpty":(e,t)=>G(t.bool(),K(e).length>0),"list.first":(e,t)=>{let n=K(e);return G(t.optional(s_(e)),n.length>0?n[0].raw:void 0)},"list.last":(e,t)=>{let n=K(e);return G(t.optional(s_(e)),n.length>0?n[n.length-1].raw:void 0)}},l_={"list.indexSet":B.STATE,"list.push":B.STATE,"list.pop":B.STATE,"list.shift":B.STATE,"list.unshift":B.STATE,"list.insert":B.STATE,"list.remove":B.STATE,"list.clear":B.STATE},u_=e=>Xg(e).type.value,d_={"map.size":(e,t)=>G(t.num({whole:!0,min:0}),K(e).size),"map.indexGet":e=>{let t=e.get(`key`).raw,n=K(e).get(t);if(!n)throw Error(`map[${String(t)}]: key not found`);return n[1]},"map.indexSet":(e,t)=>{let n=e.get(`key`),r=e.get(`value`);return K(e).set(n.raw,[n,r]),G(t.void(),void 0)},"map.iterate":async(e,t)=>{let n=K(e),r=n.values().next().value,i=e_(e,t,r?r[0].type:t.any(),r?r[1].type:t.any());for(let[,[e,t]]of n)await i(e,t);return G(t.void(),void 0)},"map.at":(e,t)=>{let n=q(e,`key`),r=K(e).get(n);return G(t.optional(u_(e)),r?r[1].raw:void 0)},"map.has":(e,t)=>G(t.bool(),K(e).has(q(e,`key`))),"map.delete":(e,t)=>G(t.bool(),K(e).delete(q(e,`key`))),"map.clear":(e,t)=>(K(e).clear(),G(t.void(),void 0)),"map.keys":(e,t)=>{let n=K(e),r=Xg(e).type.key,i=[];for(let[,[e]]of n)i.push(e);return G(t.list(r),i)},"map.values":(e,t)=>{let n=K(e),r=Xg(e).type.value,i=[];for(let[,[,e]]of n)i.push(e);return G(t.list(r),i)},"map.isEmpty":(e,t)=>G(t.bool(),K(e).size===0),"map.isNotEmpty":(e,t)=>G(t.bool(),K(e).size>0)},f_={"map.indexSet":B.STATE,"map.delete":B.STATE,"map.clear":B.STATE},p_=e=>Xg(e).type.elements,m_={"tuple.at":e=>{let t=e.get(`key`).raw,n=K(e)[t];return n instanceof W?n:G(p_(e)[t]??G.prototype,n)},"tuple.setAt":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`);return K(e)[n]=r,G(t.void(),void 0)},"tuple.iterate":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=n.map(e=>e.type),a=e_(e,t,r,i.length===0?t.any():i.length===1?i[0]:t.or(i));for(let e=0;e<n.length;e++)await a(G(r,e),n[e]);return G(t.void(),void 0)},"tuple.length":(e,t)=>G(t.num({whole:!0}),K(e).length),"tuple.first":e=>{let t=K(e),n=p_(e),r=t[0];return r instanceof W?r:G(n[0],r)},"tuple.last":e=>{let t=K(e),n=p_(e),r=t[t.length-1];return r instanceof W?r:G(n[n.length-1],r)},"tuple.toList":(e,t)=>G(t.list(t.any()),[...K(e)])},h_={"tuple.setAt":B.STATE},g_=e=>Xg(e).type.fields,__={"object.indexGet":e=>{let t=e.get(`key`).raw,n=g_(e)[t];if(!n)throw Error(`object[${t}]: no such field`);let r=K(e)[t];return r instanceof W?r:G(n.type,r)},"object.indexSet":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`);return K(e)[n]=r,G(t.void(),void 0)},"object.iterate":async(e,t)=>{let n=K(e),r=g_(e),i=t.text(),a=Object.values(r).map(e=>e.type),o=e_(e,t,i,a.length===0?t.any():a.length===1?a[0]:t.or(a));for(let[e]of Object.entries(r)){let t=n[e];t instanceof W&&await o(G(i,e),t)}return G(t.void(),void 0)},"object.keys":(e,t)=>{let n=Object.keys(g_(e));return G(t.list(t.text()),n.map(e=>G(t.text(),e)))},"object.values":(e,t)=>{let n=K(e),r=Object.keys(g_(e)).map(e=>n[e]??G(t.any(),void 0));return G(t.list(t.any()),r)},"object.entries":(e,t)=>{let n=K(e),r=Object.keys(g_(e)).map(e=>G(t.any(),[e,n[e]?.raw]));return G(t.list(t.any()),r)},"object.has":(e,t)=>G(t.bool(),Object.hasOwn(g_(e),q(e,`key`))),"object.eq":(e,t)=>G(t.bool(),y_(Xg(e),e.get(`args`).raw)),"object.neq":(e,t)=>G(t.bool(),!y_(Xg(e),e.get(`args`).raw)),"object.toText":(e,t)=>{let n=K(e),r=g_(e),i={};for(let[e]of Object.entries(r)){let t=n[e];i[e]=t?t.type.encode(t.raw):void 0}return G(t.text(),JSON.stringify(i))}},v_={"object.indexSet":B.STATE};function y_(e,t){let n=t.other,r=n instanceof W?n.raw:n;return b_(e.raw,r)}function b_(e,t){if(e instanceof W&&(e=e.raw),t instanceof W&&(t=t.raw),e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!b_(e[n],t[n]))return!1;return!0}let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!b_(e[r],t[r]))return!1;return!0}var x_={"optional.value":e=>{let t=K(e);if(t===void 0)throw Error(`optional.value: value is undefined`);return G(Xg(e).type.inner,t)},"optional.has":(e,t)=>G(t.bool(),K(e)!==void 0),"optional.or":e=>{let t=K(e),n=Xg(e).type.inner;return t===void 0?Zg(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"optional.map":async(e,t)=>{let n=K(e),r=Xg(e).type.inner;if(n===void 0)return G(t.optional(t.any()),void 0);let i=Zg(e,`fn`).raw,a=await i(new W(t.obj({value:{type:r}}),{value:G(r,n)}));return G(t.optional(t.any()),a.raw)}},S_={"nullable.value":e=>{let t=K(e);if(t===null)throw Error(`nullable.value: value is null`);return G(Xg(e).type.inner,t)},"nullable.isNull":(e,t)=>G(t.bool(),K(e)===null),"nullable.or":e=>{let t=K(e),n=Xg(e).type.inner;return t===null?Zg(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"nullable.map":async(e,t)=>{let n=K(e),r=Xg(e).type.inner;if(n===null)return G(t.nullable(t.any()),null);let i=Zg(e,`fn`).raw,a=await i(new W(t.obj({value:{type:r}}),{value:G(r,n)}));return G(t.nullable(t.any()),a.raw)}},C_={"not.typeOf":(e,t)=>G(t.text(),Xg(e).type.name),"not.toText":(e,t)=>G(t.text(),String(K(e)))},w_={"enum.name":(e,t)=>{let n=K(e),r=Xg(e).type,i=Object.entries(r.options.values).find(([,e])=>e===n);return G(t.text(),i?i[0]:``)},"enum.value":e=>{let t=Xg(e).type;return G(t.value,K(e))},"enum.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"enum.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"enum.toText":(e,t)=>G(t.text(),String(K(e)))},T_={"date.year":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()),"date.month":(e,t)=>G(t.num({whole:!0,min:1,max:12}),K(e).getUTCMonth()+1),"date.day":(e,t)=>G(t.num({whole:!0,min:1,max:31}),K(e).getUTCDate()),"date.dayOfWeek":(e,t)=>G(t.num({whole:!0,min:0,max:6}),K(e).getUTCDay()),"date.dayOfYear":(e,t)=>{let n=K(e),r=Date.UTC(n.getUTCFullYear(),0,0);return G(t.num({whole:!0,min:1,max:366}),Math.floor((n.getTime()-r)/864e5))},"date.eq":(e,t)=>G(t.bool(),K(e).getTime()===q(e,`other`).getTime()),"date.neq":(e,t)=>G(t.bool(),K(e).getTime()!==q(e,`other`).getTime()),"date.before":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"date.after":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"date.addDays":(e,t)=>{let n=new Date(K(e));return n.setUTCDate(n.getUTCDate()+q(e,`days`)),G(t.date(),n)},"date.addMonths":(e,t)=>{let n=new Date(K(e));return n.setUTCMonth(n.getUTCMonth()+q(e,`months`)),G(t.date(),n)},"date.addYears":(e,t)=>{let n=new Date(K(e));return n.setUTCFullYear(n.getUTCFullYear()+q(e,`years`)),G(t.date(),n)},"date.diffDays":(e,t)=>G(t.num({whole:!0}),Math.round((K(e).getTime()-q(e,`other`).getTime())/864e5)),"date.diffMonths":(e,t)=>{let n=K(e),r=q(e,`other`);return G(t.num({whole:!0}),(n.getUTCFullYear()-r.getUTCFullYear())*12+(n.getUTCMonth()-r.getUTCMonth()))},"date.diffYears":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()-q(e,`other`).getUTCFullYear()),"date.toText":(e,t)=>G(t.text(),K(e).toISOString().slice(0,10))},E_={"timestamp.year":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()),"timestamp.month":(e,t)=>G(t.num({whole:!0}),K(e).getUTCMonth()+1),"timestamp.day":(e,t)=>G(t.num({whole:!0}),K(e).getUTCDate()),"timestamp.hour":(e,t)=>G(t.num({whole:!0,min:0,max:23}),K(e).getUTCHours()),"timestamp.minute":(e,t)=>G(t.num({whole:!0,min:0,max:59}),K(e).getUTCMinutes()),"timestamp.second":(e,t)=>G(t.num({whole:!0,min:0,max:59}),K(e).getUTCSeconds()),"timestamp.millisecond":(e,t)=>G(t.num({whole:!0,min:0,max:999}),K(e).getUTCMilliseconds()),"timestamp.eq":(e,t)=>G(t.bool(),K(e).getTime()===q(e,`other`).getTime()),"timestamp.before":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"timestamp.after":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"timestamp.addDuration":(e,t)=>G(t.timestamp(),new Date(K(e).getTime()+q(e,`duration`))),"timestamp.subDuration":(e,t)=>G(t.timestamp(),new Date(K(e).getTime()-q(e,`duration`))),"timestamp.diff":(e,t)=>G(t.duration(),K(e).getTime()-q(e,`other`).getTime()),"timestamp.toDate":(e,t)=>G(t.date(),new Date(K(e).toISOString().slice(0,10))),"timestamp.toEpoch":(e,t)=>G(t.num(),K(e).getTime()),"timestamp.toText":(e,t)=>G(t.text(),K(e).toISOString())},D_=864e5,O_=36e5,k_=6e4,A_=1e3,j_={"duration.init":(e,t)=>{let n=q(e,`days`)??0,r=q(e,`hours`)??0,i=q(e,`minutes`)??0,a=q(e,`seconds`)??0,o=q(e,`ms`)??0;return G(t.duration(),n*D_+r*O_+i*k_+a*A_+o)},"duration.totalSeconds":(e,t)=>G(t.num(),K(e)/1e3),"duration.totalMinutes":(e,t)=>G(t.num(),K(e)/6e4),"duration.totalHours":(e,t)=>G(t.num(),K(e)/36e5),"duration.totalDays":(e,t)=>G(t.num(),K(e)/864e5),"duration.days":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/D_)),"duration.hours":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/O_)%24),"duration.minutes":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/k_)%60),"duration.seconds":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/A_)%60),"duration.ms":(e,t)=>G(t.num({whole:!0}),K(e)%A_),"duration.toText":(e,t)=>{let n=K(e),r=Math.trunc(n/D_),i=Math.trunc(n%D_/O_),a=Math.trunc(n%O_/k_),o=Math.trunc(n%k_/A_),s=[];return r&&s.push(`${r}d`),i&&s.push(`${i}h`),a&&s.push(`${a}m`),(o||s.length===0)&&s.push(`${o}s`),G(t.text(),s.join(` `))}},M_=e=>e>>>24&255,N_=e=>e>>>16&255,P_=e=>e>>>8&255,F_=e=>(e&255)/255,I_=(e,t,n,r)=>(Math.round(e)&255)<<24|(Math.round(t)&255)<<16|(Math.round(n)&255)<<8|Math.round(r*255)&255,L_={"color.init":(e,t)=>{let n=q(e,`r`),r=q(e,`g`),i=q(e,`b`),a=q(e,`a`)??1;return G(t.color(),I_(n,r,i,a)>>>0)},"color.r":(e,t)=>G(t.num(),M_(K(e))),"color.g":(e,t)=>G(t.num(),N_(K(e))),"color.b":(e,t)=>G(t.num(),P_(K(e))),"color.a":(e,t)=>G(t.num(),F_(K(e))),"color.hue":(e,t)=>G(t.num(),R_(K(e)).h),"color.saturation":(e,t)=>G(t.num(),R_(K(e)).s),"color.lightness":(e,t)=>G(t.num(),R_(K(e)).l),"color.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"color.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"color.lighten":(e,t)=>G(t.color(),B_(K(e),q(e,`amount`))),"color.darken":(e,t)=>G(t.color(),B_(K(e),-q(e,`amount`))),"color.saturate":(e,t)=>G(t.color(),V_(K(e),q(e,`amount`))),"color.desaturate":(e,t)=>G(t.color(),V_(K(e),-q(e,`amount`))),"color.opacity":(e,t)=>G(t.color(),K(e)&4294967040|Math.round(q(e,`alpha`)*255)&255),"color.invert":(e,t)=>{let n=K(e);return G(t.color(),I_(255-M_(n),255-N_(n),255-P_(n),F_(n))>>>0)},"color.mix":(e,t)=>{let n=K(e),r=q(e,`other`),i=q(e,`weight`)??.5;return G(t.color(),I_(M_(n)*(1-i)+M_(r)*i,N_(n)*(1-i)+N_(r)*i,P_(n)*(1-i)+P_(r)*i,F_(n)*(1-i)+F_(r)*i)>>>0)},"color.complement":(e,t)=>G(t.color(),H_(K(e),180)),"color.toHex":(e,t)=>G(t.text(),`#`+K(e).toString(16).padStart(8,`0`)),"color.toRgb":(e,t)=>{let n=K(e);return G(t.text(),`rgb(${M_(n)},${N_(n)},${P_(n)})`)},"color.toHsl":(e,t)=>{let{h:n,s:r,l:i}=R_(K(e));return G(t.text(),`hsl(${Math.round(n)},${Math.round(r*100)}%,${Math.round(i*100)}%)`)},"color.toText":(e,t)=>G(t.text(),`#`+K(e).toString(16).padStart(8,`0`))};function R_(e){let t=M_(e)/255,n=N_(e)/255,r=P_(e)/255,i=Math.max(t,n,r),a=Math.min(t,n,r),o=(i+a)/2,s=0,c=0;if(i!==a){let e=i-a;switch(c=o>.5?e/(2-i-a):e/(i+a),i){case t:s=(n-r)/e+(n<r?6:0);break;case n:s=(r-t)/e+2;break;case r:s=(t-n)/e+4}s*=60}return{h:s,s:c,l:o}}function z_(e,t,n,r){let i=(1-Math.abs(2*n-1))*t,a=i*(1-Math.abs(e/60%2-1)),o=n-i/2,s=0,c=0,l=0;return e<60?[s,c,l]=[i,a,0]:e<120?[s,c,l]=[a,i,0]:e<180?[s,c,l]=[0,i,a]:e<240?[s,c,l]=[0,a,i]:e<300?[s,c,l]=[a,0,i]:[s,c,l]=[i,0,a],I_((s+o)*255,(c+o)*255,(l+o)*255,r)}function B_(e,t){let{h:n,s:r,l:i}=R_(e);return z_(n,r,Math.max(0,Math.min(1,i+t)),F_(e))>>>0}function V_(e,t){let{h:n,s:r,l:i}=R_(e);return z_(n,Math.max(0,Math.min(1,r+t)),i,F_(e))>>>0}function H_(e,t){let{h:n,s:r,l:i}=R_(e);return z_((n+t+360)%360,r,i,F_(e))>>>0}function U_(e){let t=[{impls:t_},{impls:n_},{impls:r_},{impls:i_},{impls:a_},{impls:o_},{impls:c_,effects:l_},{impls:d_,effects:f_},{impls:m_,effects:h_},{impls:__,effects:v_},{impls:x_},{impls:S_},{impls:C_},{impls:w_},{impls:T_},{impls:E_},{impls:j_},{impls:L_}];for(let n of t)for(let[t,r]of Object.entries(n.impls)){let i=n.effects?.[t]??B.NONE;e.setNative(t,r,i)}return e}var W_=class e extends $m{constructor(e,t){super(),this.type=e,this.value=t}type;value;static KIND=`new`;kind=e.KIND;static from(t,n){return new e(n.registry.parse(t.type,n),t.value).withComment(t.comment)}async evaluate(e,t){let n=this.type,r=n.init();if(this.value!==void 0){if(r){let i=r.args.parse(this.value),a=G(n,n.create()),o=t.child({this:a,args:i}),s=await r.run.evaluate(e,o);return s===void 0||s.raw===void 0?a:new W(n,s.raw)}let i=await n.newFill(this.value,e,t);if(i instanceof W)return e.registry.parseValue(i,n);let a=n.parse(i);return a.type===n?a:new W(n,a.raw)}return G(n,n.create())}typeOf(e,t){return this.type}validateWalk(e,t,n,r){return this.value===void 0&&J_(this.type)&&n.warn(`new.value.missing`,`\`new ${this.type.name}\` has no \`value\` \u2014 every field will fall to its type default (0 / "" / null). Provide a \`value\` matching the type's shape.`),this.value!==void 0&&n.at([`value`],()=>this.type.validateNewValue(this.value,e,t,n,r)),this.type}toCode(e,t={}){let n=this.type.toCode(void 0,t),r;return r=this.value===void 0?this.type.isOptional()?`undefined`:`new ${n}()`:typeof this.value==`number`||typeof this.value==`boolean`?String(this.value):typeof this.value==`string`?JSON.stringify(this.value):this.value===null?`null`:G_(this.value,e,this.type,t),this.commentPrefix(t)+r}toJSON(){return this.withCommentOn({kind:`new`,type:this.type.toJSON(),value:this.value})}toJSONCode(e=[],t=2,n=0){let r=this.type.toJSONCode([...e,`type`],t,n+1),i=this.value===void 0?void 0:(()=>{let e=JSON.stringify(this.value,null,t),r=n+1;return r>0?e.replace(/\n/g,`
105
+ `+` `.repeat(r*t)):e})(),a=i===void 0?void 0:Fm(i,{path:[...e,`value`]});return V.jsonObject([{key:`kind`,value:V.jsonString(`new`)},{key:`type`,value:r},{key:`value`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.type.clone(),this.value).withComment(this.comment)}effects(){return this.type.newEffects(this.value)}complexity(){return this.type.newComplexity(this.value)}};function G_(e,t,n,r={}){if(t&&e&&typeof e==`object`&&!Array.isArray(e)&&`kind`in e&&typeof e.kind==`string`){let n=e.kind;if(t.exprClass(n))try{return t.parseExpr(e).toCode(t,{...r,expectsValue:!0})}catch{}}let i=n?n.toCode(void 0,r):`<inferred>`;if(Array.isArray(e)){let i=n?.item,a=Bh(e.map(e=>K_(e,t,i,r)));return a.startsWith(`
106
+ `),`[${a}]`}if(e&&typeof e==`object`){let a=n?.fields,o=Object.entries(e);if(o.length===0)return`new ${i}()`;let s=Bh(o.map(([e,n])=>`${e}: ${K_(n,t,a?.[e]?.type,r)}`));return s.startsWith(`
107
+ `)?`new ${i} {${s}}`:`new ${i} { ${s} }`}return JSON.stringify(e)}function K_(e,t,n,r={}){return e===null?`null`:e===void 0?`undefined`:typeof e==`string`?JSON.stringify(e):typeof e==`number`||typeof e==`boolean`?String(e):G_(e,t,n,r)}function q_(e){if(e instanceof vg)return e;let t=e.base;return t?q_(t):void 0}function J_(e){let t=q_(e);if(!t)return!1;for(let e of Object.values(t.fields))if(!e.type.isOptional())return!0;return!1}function Y_(e,t){let n=e.call(t);if(!n)return!1;let r=n.args;if(!(r instanceof vg))return!0;for(let e of Object.values(r.fields))if(!e.type.isOptional())return!1;return!0}function X_(e,t,n,r){if(!e)return;let i=e.args;if(i instanceof vg)for(let[e,a]of Object.entries(i.fields))a.type.isOptional()||e in t||n.at(r,()=>n.error(`call.missing-arg`,`missing required argument '${e}'`))}function Z_(e,t){return t.type instanceof Sg?t.type.simplify(e.scope):t.type}function Q_(e,t){let n=e.raw;if(!n||typeof n!=`object`)return;let r=n[t];return r instanceof W?r:void 0}function $_(e){return e instanceof vg||e instanceof jg||e instanceof gg&&$_(e.base)}function ev(e,t,n){let r=[];for(let e=n;e<t.length;e++){let n=t[e];if(n instanceof nv)r.push(n.prop);else break}if(r.length===0)return``;let i=Lp(e,e=>Object.keys(e.props()),e=>{let t=[];for(let n of Object.keys(e.props())){let r=e.prop(n)?.type;r&&$_(r)&&t.push([n,r])}return t},r);if(!i||i.length===0)return``;if(i.length===1)return` \u2014 did you mean \`${i[0]}\`?`;let a=[];for(let e=0;e<n;e++){let n=t[e];if(n instanceof nv)a.push(n.prop);else{a.length=0;break}}return` \u2014 did you mean \`${[...a,...i].join(`.`)}\`?`}var tv=class{static from(e,t){if(qp(e),`prop`in e)return new nv(e.prop);let n=t.registry;if(`args`in e){let r={};for(let[i,a]of Object.entries(e.args??{}))r[i]=n.parseExpr(a,t);return new rv(r,e.generic,e.catch?n.parseExpr(e.catch,t):void 0)}if(`key`in e)return new iv(n.parseExpr(e.key,t));throw Error(`PathStep.from: unknown step shape`)}},nv=class e extends tv{constructor(e){super(),this.prop=e}prop;toJSON(){return{prop:this.prop}}clone(){return new e(this.prop)}complexity(){return 1}},rv=class e extends tv{constructor(e,t,n){super(),this.args=e,this.generic=t,this.catch_=n}args;generic;catch_;resolvedEffects;toJSON(){let e={};for(let[t,n]of Object.entries(this.args))e[t]=n.toJSON();let t={args:e};return this.generic&&(t.generic=this.generic),this.catch_&&(t.catch=this.catch_.toJSON()),t}clone(){let t={};for(let[e,n]of Object.entries(this.args))t[e]=n.clone();return new e(t,this.generic,this.catch_?.clone())}callSiteScope(e){if(!this.generic||Object.keys(this.generic).length===0)return e.scope;let t={},n=e.generic??{};for(let[r,i]of Object.entries(this.generic)){let a=e.scope.parse(i),o=n[r];if(o&&(o.name!==`alias`||o.options?.name!==r)&&!o.compatible(a))throw Error(`path: generic '${r}' binding '${a.toCode()}' does not satisfy constraint '${o.toCode()}'`);t[r]=a}return new Qm(e.scope,t)}complexity(){let e=1;for(let t of Object.values(this.args))e+=t.complexity();return this.catch_&&(e+=this.catch_.complexity()),e}async buildArgsValue(e,t,n){let r=this.callSiteScope(e),i=e.call?.(r)?.args??n.registry.obj({}),a={};for(let[e,r]of Object.entries(this.args))a[e]=await r.evaluate(n,t);return new W(i,a)}},iv=class e extends tv{constructor(e){super(),this.key=e}key;toJSON(){return{key:this.key.toJSON()}}clone(){return new e(this.key.clone())}complexity(){return 1+this.key.complexity()}},av=class e{constructor(e){this.steps=e}steps;static from(t,n){return new e(t.map(e=>tv.from(e,n)))}toJSON(){return this.steps.map(e=>e.toJSON())}toJSONCode(e=[],t=2,n=0){let r=this.steps.map((r,i)=>sv(r,[...e,i],t,n+1));return V.jsonArray(r,{path:e},n,t)}clone(){return new e(this.steps.map(e=>e.clone()))}complexity(){let e=0;for(let t of this.steps)e+=t.complexity();return e}forEachExpr(e){for(let t of this.steps)if(t instanceof rv){for(let n of Object.values(t.args))e(n);t.catch_&&e(t.catch_)}else t instanceof iv&&e(t.key)}toCode(e,t={}){return this.toGinCode(e,t).toString()}toGinCode(e,t={},n=[]){if(this.steps.length===0)return new V(``);let r=new V(``);for(let i=0;i<this.steps.length;i++){let a=this.steps[i],o=[...n,`path`,i];if(a instanceof nv){let e=i===0?a.prop:`.${a.prop}`;r=i===0?Fm(e,{path:o}):H`${r}${Fm(e,{path:o})}`}else if(a instanceof rv){let n=Object.entries(a.args),i;if(n.length===0)i=new V(`()`);else{let r=n.map(([n,r])=>{let i=[...o,`args`,n];return H`${n}: ${r.toGinCode(e,{...t,expectsValue:!0},i)}`});i=Bh(r.map(e=>e.toString())).startsWith(`
108
+ `)?H`({\n ${Im(r,`,
109
+ `)}\n})`:H`({ ${Im(r,`, `)} })`}if(r=H`${r}${Fm(i,{path:o})}`,a.catch_){let n=a.catch_.toGinCode(e,{...t,expectsValue:!0},[...o,`catch`]);r=H`${r}.catch((error) => ${n})`}}else if(a instanceof iv){let n=a.key.toGinCode(e,{...t,expectsValue:!0},[...o,`key`]);r=H`${r}${Fm(H`[${n}]`,{path:o})}`}}return r}async walk(e,t,n={mode:`get`}){if(this.steps.length===0)throw Error(`Path.walk: empty path`);let r=()=>G(t.registry.bool(),!1),i=()=>G(t.registry.bool(),!0),a=null,o=0;for(;o<this.steps.length;){let s=this.steps[o],c=o===this.steps.length-1;if(n.mode===`set`&&a!==null&&ov(a)&&!(s instanceof rv))return r();if(s instanceof nv){if(a===null){let t=e.get(s.prop);if(t===void 0)throw Error(`path: unknown variable '${s.prop}'${Pp(s.prop,e.names())}`);a=t,o++;continue}let r=a.type.prop(s.prop);if(!r){let e=n.mode===`get`?Q_(a,s.prop):void 0;if(e){a=e,o++;continue}throw Error(`path: no prop '${s.prop}' on type '${a.type.name}'${ev(a.type,this.steps,o)}`)}let l=Z_(a.type,r),u=this.steps[o+1],d=u instanceof rv;if(d&&l.call()){let c=await u.buildArgsValue(l,e,t);if(o+1===this.steps.length-1&&n.mode===`set`)return await r.invokeMethodSet(a,s.prop,c,n.setValue,e,t,l),i();try{a=await r.invokeMethod(a,s.prop,c,e,t,l)}catch(n){if(n instanceof ph&&u.catch_){let r=e.child({error:n.error});a=await u.catch_.evaluate(t,r)}else throw n}o+=2;continue}if(!d&&Y_(l)){let u=await new rv({},void 0,void 0).buildArgsValue(l,e,t);if(c&&n.mode===`set`)return await r.invokeMethodSet(a,s.prop,u,n.setValue,e,t,l),i();a=await r.invokeMethod(a,s.prop,u,e,t,l),o++;continue}if(c&&n.mode===`set`)return await r.write(a,s.prop,n.setValue,e,t),i();a=await r.read(a,s.prop,e,t,l),o++}else if(s instanceof iv){if(a===null)throw Error(`path: [key] cannot be the first step`);let r=a.type.get();if(!r)throw Error(`path: type '${a.type.name}' has no indexed access`);let l=await s.key.evaluate(t,e);if(c&&n.mode===`set`)return await r.indexWrite(a,l,n.setValue,e,t),i();a=await r.indexRead(a,l,e,t),o++}else if(s instanceof rv){if(a===null)throw Error(`path: (args) cannot be the first step`);let r=a.raw,l=a.type,u=l.call(),d=await s.buildArgsValue(l,e,t);if(c&&n.mode===`set`){if(!u?.set)throw Error(`path: call on type '${l.name}' has no call.set`);let r=u.set,a=async i=>{let o=new W(l,a);return await r.evaluate(t,e.child({args:i,value:n.setValue,recurse:o})),G(t.registry.void(),void 0)};return await a(d),i()}try{if(typeof r==`function`)a=await r(d);else if(u?.get){let n=u.get,r=async i=>{let a=new W(l,r);try{return await n.evaluate(t,e.child({args:i,recurse:a}))}catch(e){if(e instanceof dh)return e.value??G(t.registry.void(),void 0);throw e}};a=await r(d)}else throw Error(`path: value of type '${l.name}' is not callable`)}catch(n){if(n instanceof ph&&s.catch_){let r=e.child({error:n.error});a=await s.catch_.evaluate(t,r)}else throw n}o++}else throw Error(`path: unknown step at index ${o}`)}return a}typeOf(e,t){if(this.steps.length===0)return e.registry.any();let n=null,r=0;for(;r<this.steps.length;){let i=this.steps[r];if(i instanceof nv){if(n===null){n=t.get(i.prop)??e.registry.any(),r++;continue}let a=n.prop(i.prop);if(!a)return e.registry.any();let o=Z_(n,a),s=this.steps[r+1];if(s instanceof rv&&o.call()){let t=s.callSiteScope(o),i=o.call(t)?.returns;n=i?.simplify(t)??i??e.registry.any(),r+=2;continue}if(!(s instanceof rv)&&Y_(o)){n=o.call()?.returns??e.registry.any(),r++;continue}n=o,r++}else if(i instanceof iv)n=n?.get()?.value??e.registry.any(),r++;else if(i instanceof rv){if(n){let t=i.callSiteScope(n),r=n.call(t)?.returns;n=r?.simplify(t)??r??e.registry.any()}else n=e.registry.any();r++}else r++}return n??e.registry.any()}validateWalk(e,t,n,r,i=`get`){if(this.steps.length===0)return n.error(`path.empty`,`path is empty`),e.registry.any();if(i===`set`&&this.steps.length===1&&this.steps[0]instanceof nv)return e.registry.any();let a=null,o=0;for(;o<this.steps.length;){let s=this.steps[o],c=o===this.steps.length-1;if(s instanceof nv){if(a===null){let r=t.get(s.prop);r?a=r:(n.at([`path`,o],()=>n.error(`var.unknown`,`unknown variable '${s.prop}'${Pp(s.prop,[...t.keys()])}`)),a=e.registry.any()),o++;continue}let l=a.prop(s.prop);if(!l){n.at([`path`,o],()=>n.error(`prop.unknown`,`no prop '${s.prop}' on type '${a.name}'${ev(a,this.steps,o)}`)),a=e.registry.any(),o++;continue}let u=Z_(a,l),d=this.steps[o+1];if(d instanceof rv&&u.call()){for(let[i,a]of Object.entries(d.args))n.at([`path`,o+1,`args`,i],()=>a.validateWalk(e,t,n,r));d.catch_&&n.at([`path`,o+1,`catch`],()=>d.catch_.validateWalk(e,t,n,r));let c=d.callSiteScope(u),l=u.call(c);X_(l,d.args,n,[`path`,o+1]),i===`set`&&o+1===this.steps.length-1&&(l?.set||n.at([`path`,o+1],()=>n.error(`set.call.no-set`,`method '${s.prop}' has no call.set`))),d.resolvedEffects=l?.effects()??0;let f=l?.returns;a=f?.simplify(c)??f??e.registry.any(),o+=2;continue}if(!(d instanceof rv)&&Y_(u)){a=u.call()?.returns??e.registry.any(),o++;continue}i===`set`&&c&&!l.set&&l.get&&!u.call()&&n.at([`path`,o],()=>n.error(`set.prop.computed`,`prop '${s.prop}' is computed (read-only); cannot assign to it`));let f=i===`get`?u.call():void 0;if(f&&!Y_(u)){n.at([`path`,o],()=>n.error(`call.uncalled`,`method '${s.prop}' needs arguments \u2014 add an {args:{\u2026}} step to call it`)),a=f.returns??e.registry.any(),o++;continue}a=u,o++}else if(s instanceof iv){n.at([`path`,o,`key`],()=>s.key.validateWalk(e,t,n,r));let l=a?.get();i===`set`&&c?l?.set||n.at([`path`,o],()=>n.error(`set.index.no-set`,`type '${a?.name??`?`}' has no index set`)):l?.get||n.at([`path`,o],()=>n.error(`index.unsupported`,`type '${a?.name??`?`}' has no indexed access`)),a=l?.value??e.registry.any(),o++}else if(s instanceof rv){for(let[i,a]of Object.entries(s.args))n.at([`path`,o,`args`,i],()=>a.validateWalk(e,t,n,r));if(a){let t=s.callSiteScope(a),r=a.call(t);X_(r,s.args,n,[`path`,o]),i===`set`&&c&&(r?.set||n.at([`path`,o],()=>n.error(`set.call.no-set`,`call on type '${a?.name??`?`}' has no call.set`))),s.resolvedEffects=r?.effects()??0;let l=r?.returns;a=l?.simplify(t)??l??e.registry.any()}else s.resolvedEffects=0,a=e.registry.any();o++}else o++}return a??e.registry.any()}};function ov(e){return e.raw===null||e.raw===void 0}function sv(e,t,n,r){if(e instanceof nv)return V.jsonObject([{key:`prop`,value:V.jsonString(e.prop)}],{path:t},r,n);if(e instanceof rv){let i=Object.entries(e.args).map(([e,i])=>({key:e,value:i.toJSONCode([...t,`args`,e],n,r+2)})),a=[{key:`args`,value:V.jsonObject(i,{path:[...t,`args`]},r+1,n)}];return e.generic&&a.push({key:`generic`,value:JSON.stringify(e.generic,null,n).replace(/\n/g,`
110
+ `+` `.repeat(r*n))}),e.catch_&&a.push({key:`catch`,value:e.catch_.toJSONCode([...t,`catch`],n,r+1)}),V.jsonObject(a,{path:t},r,n)}return e instanceof iv?V.jsonObject([{key:`key`,value:e.key.toJSONCode([...t,`key`],n,r+1)}],{path:t},r,n):new V(JSON.stringify(e.toJSON(),null,n))}var cv=class e extends $m{constructor(e){super(),this.path=e}path;static KIND=`get`;kind=e.KIND;static from(t,n){return new e(av.from(t.path,n)).withComment(t.comment)}async evaluate(e,t){return this.path.walk(t,e,{mode:`get`})}typeOf(e,t){return this.path.typeOf(e,t)}validateWalk(e,t,n,r){return this.path.validateWalk(e,t,n,r,`get`)}toGinCode(e,t={},n=[]){let r=this.path.toGinCode(e,t,n);return Fm(H`${this.commentPrefix(t)}${r}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`get`,path:this.path.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.path.toJSONCode([...e,`path`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`get`)},{key:`path`,value:r},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.path.clone()).withComment(this.comment)}forEachChild(e){this.path.forEachExpr(t=>e(t,`inherit`))}effects(){let e=[];this.path.forEachExpr(t=>{e.push(t.effects())});for(let t of this.path.steps)t instanceof rv&&t.resolvedEffects!==void 0&&e.push(t.resolvedEffects);return Pm(...e)}complexity(){return this.path.complexity()}},lv=class e extends $m{constructor(e,t){super(),this.path=e,this.value=t}path;value;static KIND=`set`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){return new e(av.from(t.path,n),n.registry.parseExpr(t.value,n)).withComment(t.comment)}async evaluate(e,t){let n=await this.value.evaluate(e,t);return this.path.steps.length===1&&this.path.steps[0]instanceof nv?(t.set(this.path.steps[0].prop,n),G(e.registry.bool(),!0)):this.path.walk(t,e,{mode:`set`,setValue:n})}typeOf(e,t){return e.registry.bool()}validateWalk(e,t,n,r){let i=n.at(`value`,()=>this.value.validateWalk(e,t,n,r)),a=this.path.validateWalk(e,t,n,r,`set`);return a.name!==`any`&&!a.compatible(i)&&n.at(`value`,()=>n.warn(`set.type-mismatch`,`value type '${i.name}' not compatible with target '${a.name}'`)),e.registry.bool()}toGinCode(e,t={},n=[]){let r=this.path.toGinCode(e,t,n),i=this.value.toGinCode(e,{...t,expectsValue:!0},[...n,`value`]);return Fm(H`${this.commentPrefix(t)}${r} = ${i}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`set`,path:this.path.toJSON(),value:this.value.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.path.toJSONCode([...e,`path`],t,n+1),i=this.value.toJSONCode([...e,`value`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`set`)},{key:`path`,value:r},{key:`value`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.path.clone(),this.value.clone()).withComment(this.comment)}forEachChild(e){this.path.forEachExpr(t=>e(t,`inherit`)),e(this.value,`inherit`)}effects(){let e=B.STATE|this.value.effects();this.path.forEachExpr(t=>{e|=t.effects()});for(let t of this.path.steps)t instanceof rv&&t.resolvedEffects!==void 0&&(e|=t.resolvedEffects);return e}complexity(){return this.path.complexity()+this.value.complexity()}},uv=class e extends $m{constructor(e,t){super(),this.vars=e,this.body=t}vars;body;static KIND=`define`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.vars.map(e=>({name:e.name,type:e.type?r.parse(e.type,n):void 0,value:r.parseExpr(e.value,n)}));return new e(i,r.parseExpr(t.body,n)).withComment(t.comment)}async evaluate(e,t){let n=t.child();for(let t of this.vars){let r=await t.value.evaluate(e,n);n.vars.set(t.name,r)}return this.body.evaluate(e,n)}typeOf(e,t){let n=new Map(t);for(let t of this.vars){let r=t.type??rh(e,t.value,n);n.set(t.name,r)}return rh(e,this.body,n)}validateWalk(e,t,n,r){let i=new Map(t);for(let t=0;t<this.vars.length;t++){let a=this.vars[t];n.at([`vars`,t,`name`],()=>sh(a.name,i,n));let o=n.at([`vars`,t,`value`],()=>oh(e,a.value,i,n,r));if(a.type&&!o.isUniversal()&&!a.type.compatible(o)){let e=dv(a.type),r=dv(o),i=o.name===`alias`?` (hint: '${r}' is an unbound generic \u2014 either bind it via \`generic: {${r}: ...}\` on the call site, pass \`output: typ<...>\`, or omit the declared type so the alias flows through)`:``;n.at([`vars`,t,`value`],()=>n.error(`define.var.type-mismatch`,`var '${a.name}' value type '${r}' not compatible with declared '${e}'${i}`))}i.set(a.name,a.type??o)}return n.at(`body`,()=>oh(e,this.body,i,n,r))}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i={...t,expectsValue:!0},a={...t,expectsValue:!1},o=this.vars.map((r,a)=>{let o=r.type?H`: ${r.type.toGinCode(void 0,t,[...n,`vars`,a,`type`])}`:``,s=r.value.toGinCode(e,i,[...n,`vars`,a,`value`]),c=H`let ${r.name}${o} = ${s};`;return c.text.split(`
111
+ `,1)[0].length<=80?c:H`let ${r.name}${o} =\n ${s.indent(` `)};`});if(r){let r=this.body.toGinCode(e,i,[...n,`body`]),a=o.map(e=>H` ${e}`),s=H` return ${r.indent(` `)};`,c=Lm([...a,s]);return Fm(H`${this.commentPrefix(t)}(() => {\n${c}\n})()`,{path:n,expr:this})}let s=this.body.kind,c=this.body.toGinCode(e,a,[...n,`body`]),l=s===`if`||s===`switch`||s===`loop`||s===`block`?c:H`${c};`;return Fm(H`${this.commentPrefix(t)}${Lm([...o,l])}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`define`,vars:this.vars.map(e=>{let t={name:e.name,value:e.value.toJSON()};return e.type&&(t.type=e.type.toJSON()),t}),body:this.body.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.vars.map((r,i)=>{let a=[...e,`vars`,i],o=r.value.toJSONCode([...a,`value`],t,n+3),s=r.type?r.type.toJSONCode([...a,`type`],t,n+3):void 0;return V.jsonObject([{key:`name`,value:V.jsonString(r.name)},{key:`value`,value:o},{key:`type`,value:s}],{path:a},n+2,t)}),i=this.body.toJSONCode([...e,`body`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`define`)},{key:`vars`,value:V.jsonArray(r,{path:[...e,`vars`]},n+1,t)},{key:`body`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.vars.map(e=>({name:e.name,type:e.type?.clone(),value:e.value.clone()})),this.body.clone()).withComment(this.comment)}forEachChild(e){for(let t of this.vars)e(t.value,`inherit`);e(this.body,`inherit`)}effects(){let e=this.body.effects();for(let t of this.vars)e|=t.value.effects();return e}complexity(){let e=1+this.body.complexity();for(let t of this.vars)e+=1+t.value.complexity();return e}};function dv(e){try{return e.toCode()}catch{return e.name}}var fv=class e extends $m{constructor(e){super(),this.lines=e}lines;static KIND=`block`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(t.lines.map(e=>r.parseExpr(e,n))).withComment(t.comment)}async evaluate(e,t){let n=G(e.registry.void(),void 0);for(let r of this.lines)n=await r.evaluate(e,t);return n}typeOf(e,t){return this.lines.length===0?e.registry.void():rh(e,this.lines[this.lines.length-1],t)}validateWalk(e,t,n,r){let i=e.registry.void();for(let a=0;a<this.lines.length;a++)i=n.at(a,()=>oh(e,this.lines[a],t,n,r));return i}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1;if(this.lines.length===0)return Fm(r?`undefined`:``,{path:n,expr:this});if(this.lines.length===1)return Fm(this.lines[0].toGinCode(e,t,[...n,0]),{path:n,expr:this});let i=this.commentPrefix(t);return Fm(r?H`${i}(() => {\n${Lm(this.lines.map((r,i)=>{let a=i===this.lines.length-1,o=r.toGinCode(e,{...t,expectsValue:a},[...n,i]).indent(` `);return a?H` return ${o};`:H` ${o};`}))}\n})()`:H`${i}${Lm(this.lines.map((r,i)=>{let a=r.kind,o=r.toGinCode(e,{...t,expectsValue:!1},[...n,i]);return a===`if`||a===`switch`||a===`loop`||a===`block`?o:H`${o};`}))}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`block`,lines:this.lines.map(e=>e.toJSON())})}toJSONCode(e=[],t=2,n=0){let r=this.lines.map((r,i)=>r.toJSONCode([...e,i],t,n+2));return V.jsonObject([{key:`kind`,value:V.jsonString(`block`)},{key:`lines`,value:V.jsonArray(r,{path:[...e,`lines`]},n+1,t)},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.lines.map(e=>e.clone())).withComment(this.comment)}forEachChild(e){for(let t of this.lines)e(t,`inherit`)}effects(){let e=B.NONE;for(let t of this.lines)e|=t.effects();return e}complexity(){let e=1;for(let t of this.lines)e+=t.complexity();return e}},pv=class e extends $m{constructor(e,t,n){super(),this.action=e,this.value=t,this.error=n}action;value;error;static KIND=`flow`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(t.action,t.value?r.parseExpr(t.value,n):void 0,t.error?r.parseExpr(t.error,n):void 0).withComment(t.comment)}async evaluate(e,t){switch(this.action){case`break`:throw new lh;case`continue`:throw new uh;case`return`:throw new dh(this.value?await this.value.evaluate(e,t):void 0);case`exit`:throw new fh(this.value?await this.value.evaluate(e,t):void 0);case`throw`:throw this.error?new ph(await this.error.evaluate(e,t)):Error("flow.throw requires `error`")}}typeOf(e,t){return e.registry.void()}validateWalk(e,t,n,r){return this.action!==`break`&&this.action!==`continue`||r.inLoop||n.error(`flow.outside-loop`,`${this.action} used outside a loop`),this.action===`return`&&!r.inLambda&&n.warn(`flow.outside-lambda`,`return used outside a lambda`),this.action===`throw`&&!this.error&&n.error(`flow.throw.no-error`,"throw requires an `error` expression"),this.value&&n.at(`value`,()=>oh(e,this.value,t,n,r)),this.error&&n.at(`error`,()=>oh(e,this.error,t,n,r)),e.registry.void()}toGinCode(e,t={},n=[]){let r=this.commentPrefix(t),i={...t,expectsValue:!0},a;switch(this.action){case`break`:a=new V(`break`);break;case`continue`:a=new V(`continue`);break;case`return`:a=this.value?H`return ${this.value.toGinCode(e,i,[...n,`value`])}`:new V(`return`);break;case`throw`:a=this.error?H`throw ${this.error.toGinCode(e,i,[...n,`error`])}`:new V(`throw`);break;case`exit`:a=this.value?H`exit ${this.value.toGinCode(e,i,[...n,`value`])}`:new V(`exit`);break;default:a=new V(``)}return Fm(H`${r}${a}`,{path:n,expr:this})}toJSONCode(e=[],t=2,n=0){let r=this.value?this.value.toJSONCode([...e,`value`],t,n+1):void 0,i=this.error?this.error.toJSONCode([...e,`error`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`flow`)},{key:`action`,value:V.jsonString(this.action)},{key:`value`,value:r},{key:`error`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}toJSON(){let e={kind:`flow`,action:this.action};return this.value&&(e.value=this.value.toJSON()),this.error&&(e.error=this.error.toJSON()),this.withCommentOn(e)}clone(){return new e(this.action,this.value?.clone(),this.error?.clone()).withComment(this.comment)}forEachChild(e){this.value&&e(this.value,`inherit`),this.error&&e(this.error,`inherit`)}effects(){return B.STATE|(this.value?.effects()??B.NONE)|(this.error?.effects()??B.NONE)}complexity(){return 1+(this.value?.complexity()??0)+(this.error?.complexity()??0)}};function mv(e){return e.replace(/\n/g,`
112
+ `)}function hv(e,t=`inherit`){if(e instanceof pv)return e.action===`throw`||e.action===`exit`?e:e.action===`return`?t===`lambda`?void 0:e:e.action===`break`||e.action===`continue`?t===`loop`?void 0:e:void 0;let n;return e.forEachChild((e,r)=>{if(n)return;let i=hv(e,r===`inherit`?t:r);i&&(n=i)}),n}var gv=class e extends $m{constructor(e,t){super(),this.ifs=e,this.otherwise=t}ifs;otherwise;static KIND=`if`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.ifs.map(e=>({condition:r.parseExpr(e.condition,n),body:r.parseExpr(e.body,n)}));return new e(i,t.else?r.parseExpr(t.else,n):void 0).withComment(t.comment)}async evaluate(e,t){for(let n of this.ifs)if((await n.condition.evaluate(e,t)).raw)return n.body.evaluate(e,t);return this.otherwise?this.otherwise.evaluate(e,t):G(e.registry.void(),void 0)}typeOf(e,t){let n=this.ifs.map(n=>rh(e,n.body,t));return this.otherwise&&n.push(rh(e,this.otherwise,t)),n.length===1?n[0]:e.registry.or(n)}validateWalk(e,t,n,r){let i=e.registry.bool(),a=[];for(let o=0;o<this.ifs.length;o++){let s=this.ifs[o],c=n.at([`ifs`,o,`condition`],()=>oh(e,s.condition,t,n,r));if(!i.compatible(c)){let e;try{e=c.toCode()}catch{e=c.name}n.at([`ifs`,o,`condition`],()=>n.warn(`if.condition.type`,`if condition should be bool, got '${e}' (did you forget to call a method?)`))}a.push(n.at([`ifs`,o,`body`],()=>oh(e,s.body,t,n,r)))}for(let e=0;e<this.ifs.length;e++)this.ifs[e].body.effects()===B.NONE&&n.at([`ifs`,e,`body`],()=>n.warn(`if.branch.no-effect`,"if branch body has no observable effect — when this branch matches, nothing happens. Either give it a `set`/`flow`/native call, or drop the branch entirely"));return this.otherwise&&(a.push(n.at(`else`,()=>oh(e,this.otherwise,t,n,r))),this.otherwise.effects()===B.NONE&&n.at(`else`,()=>n.warn(`if.else.no-effect`,"else arm has no observable effect — `else` is optional; OMIT it entirely when its only purpose is producing a placeholder value"))),a.length===1?a[0]:e.registry.or(a)}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i=this.ifs.some(e=>!!hv(e.body))||(this.otherwise?!!hv(this.otherwise):!1),a=this.commentPrefix(t),o={...t,expectsValue:!0};if(r&&!i){if(this.ifs.length===1&&this.otherwise){let t=this.ifs[0];return Fm(H`${a}(${t.condition.toGinCode(e,o,[...n,`ifs`,0,`condition`])} ? ${t.body.toGinCode(e,o,[...n,`ifs`,0,`body`])} : ${this.otherwise.toGinCode(e,o,[...n,`else`])})`,{path:n,expr:this})}let t=H``;for(let r=0;r<this.ifs.length;r++){let i=this.ifs[r],a=r===0?`if`:`else if`,s=i.condition.toGinCode(e,o,[...n,`ifs`,r,`condition`]),c=i.body.toGinCode(e,o,[...n,`ifs`,r,`body`]);t=H`${t}${r===0?``:`
113
+ `} ${a} (${s}) return ${c.indent(` `)};`}let r=``;return this.otherwise&&(r=H`\n return ${this.otherwise.toGinCode(e,o,[...n,`else`]).indent(` `)};`),Fm(H`${a}(() => {\n${t}${r}\n})()`,{path:n,expr:this})}let s=H``;for(let r=0;r<this.ifs.length;r++){let i=this.ifs[r],a=r===0?`if`:`else if`,c=r===0?``:` `,l=i.condition.toGinCode(e,o,[...n,`ifs`,r,`condition`]),u=i.body.renderStatementBodyRich(e,t,[...n,`ifs`,r,`body`]);s=H`${s}${c}${a} (${l}) ${u}`}if(this.otherwise){let r=this.otherwise.renderStatementBodyRich(e,t,[...n,`else`],!0);s=H`${s} else ${r}`}return Fm(H`${a}${s}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`if`,ifs:this.ifs.map(e=>({condition:e.condition.toJSON(),body:e.body.toJSON()})),else:this.otherwise?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.ifs.map((r,i)=>{let a=[...e,`ifs`,i];return V.jsonObject([{key:`condition`,value:r.condition.toJSONCode([...a,`condition`],t,n+3)},{key:`body`,value:r.body.toJSONCode([...a,`body`],t,n+3)}],{path:a},n+2,t)}),i=this.otherwise?this.otherwise.toJSONCode([...e,`else`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`if`)},{key:`ifs`,value:V.jsonArray(r,{path:[...e,`ifs`]},n+1,t)},{key:`else`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.ifs.map(e=>({condition:e.condition.clone(),body:e.body.clone()})),this.otherwise?.clone()).withComment(this.comment)}forEachChild(e){for(let t of this.ifs)e(t.condition,`inherit`),e(t.body,`inherit`);this.otherwise&&e(this.otherwise,`inherit`)}effects(){let e=B.NONE;for(let t of this.ifs)e|=t.condition.effects()|t.body.effects();return this.otherwise&&(e|=this.otherwise.effects()),e}complexity(){let e=1;for(let t of this.ifs)e+=t.condition.complexity()+t.body.complexity();return this.otherwise&&(e+=this.otherwise.complexity()),e}},_v=class e extends $m{constructor(e,t,n){super(),this.value=e,this.cases=t,this.otherwise=n}value;cases;otherwise;static KIND=`switch`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(r.parseExpr(t.value,n),t.cases.map(e=>({equals:e.equals.map(e=>r.parseExpr(e,n)),body:r.parseExpr(e.body,n)})),t.else?r.parseExpr(t.else,n):void 0).withComment(t.comment)}async evaluate(e,t){let n=await this.value.evaluate(e,t);for(let r of this.cases)for(let i of r.equals)if((await i.evaluate(e,t)).raw===n.raw)return r.body.evaluate(e,t);return this.otherwise?this.otherwise.evaluate(e,t):G(e.registry.void(),void 0)}typeOf(e,t){let n=this.cases.map(n=>rh(e,n.body,t));return this.otherwise&&n.push(rh(e,this.otherwise,t)),n.length===0?e.registry.void():n.length===1?n[0]:e.registry.or(n)}validateWalk(e,t,n,r){let i=n.at(`value`,()=>oh(e,this.value,t,n,r)),a=[];for(let o=0;o<this.cases.length;o++){let s=this.cases[o];for(let a=0;a<s.equals.length;a++){let c=n.at([`cases`,o,`equals`,a],()=>oh(e,s.equals[a],t,n,r));i.compatible(c)||n.at([`cases`,o,`equals`,a],()=>n.warn(`switch.case.type`,`case value type '${c.name}' not compatible with switch value '${i.name}'`))}a.push(n.at([`cases`,o,`body`],()=>oh(e,s.body,t,n,r))),s.body.effects()===B.NONE&&n.at([`cases`,o,`body`],()=>n.warn(`switch.case.no-effect`,"switch case body has no observable effect — when this case matches, nothing happens. Either give it a `set`/`flow`/native call, or drop the case"))}return this.otherwise&&(a.push(n.at(`else`,()=>oh(e,this.otherwise,t,n,r))),this.otherwise.effects()===B.NONE&&n.at(`else`,()=>n.warn(`switch.else.no-effect`,`switch default has no observable effect — OMIT it instead of carrying a placeholder fallback`))),a.length===0?e.registry.void():a.length===1?a[0]:e.registry.or(a)}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i=this.cases.some(e=>!!hv(e.body))||(this.otherwise?!!hv(this.otherwise):!1),a={...t,expectsValue:!0},o=this.value.toGinCode(e,a,[...n,`value`]),s=this.commentPrefix(t);if(r&&!i){let t=Lm(this.cases.map((t,r)=>H`${Lm(t.equals.map((t,i)=>H` case ${t.toGinCode(e,a,[...n,`cases`,r,`equals`,i])}:`))}\n return ${t.body.toGinCode(e,a,[...n,`cases`,r,`body`]).indent(` `)};`)),r=``;return this.otherwise&&(r=H`\n default:\n return ${this.otherwise.toGinCode(e,a,[...n,`else`]).indent(` `)};`),Fm(H`${s}(() => {\n switch (${o}) {\n${t}${r}\n }\n})()`,{path:n,expr:this})}let c=(n,r)=>{let i=n.kind;return n instanceof pv?H`${n.toGinCode(e,{...t,expectsValue:!1},r)};`:i===`block`||i===`if`||i===`switch`||i===`loop`?n.toGinCode(e,{...t,expectsValue:!1},r):H`${n.toGinCode(e,{...t,expectsValue:!0},r)};`},l=Lm(this.cases.map((t,r)=>{let i=Lm(t.equals.map((t,i)=>H` case ${t.toGinCode(e,a,[...n,`cases`,r,`equals`,i])}:`)),o=[...n,`cases`,r,`body`];return H`${i}\n ${c(t.body,o).indent(` `)}${t.body instanceof pv?``:`
114
+ break;`}`})),u=``;return this.otherwise&&(u=H`\n default:\n ${c(this.otherwise,[...n,`else`]).indent(` `)}`),Fm(H`${s}switch (${o}) {\n${l}${u}\n}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`switch`,value:this.value.toJSON(),cases:this.cases.map(e=>({equals:e.equals.map(e=>e.toJSON()),body:e.body.toJSON()})),else:this.otherwise?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.value.toJSONCode([...e,`value`],t,n+1),i=this.cases.map((r,i)=>{let a=[...e,`cases`,i],o=r.equals.map((e,r)=>e.toJSONCode([...a,`equals`,r],t,n+4));return V.jsonObject([{key:`equals`,value:V.jsonArray(o,{path:[...a,`equals`]},n+3,t)},{key:`body`,value:r.body.toJSONCode([...a,`body`],t,n+3)}],{path:a},n+2,t)}),a=this.otherwise?this.otherwise.toJSONCode([...e,`else`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`switch`)},{key:`value`,value:r},{key:`cases`,value:V.jsonArray(i,{path:[...e,`cases`]},n+1,t)},{key:`else`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.value.clone(),this.cases.map(e=>({equals:e.equals.map(e=>e.clone()),body:e.body.clone()})),this.otherwise?.clone()).withComment(this.comment)}forEachChild(e){e(this.value,`inherit`);for(let t of this.cases){for(let n of t.equals)e(n,`inherit`);e(t.body,`inherit`)}this.otherwise&&e(this.otherwise,`inherit`)}effects(){let e=this.value.effects();for(let t of this.cases){for(let n of t.equals)e|=n.effects();e|=t.body.effects()}return this.otherwise&&(e|=this.otherwise.effects()),e}complexity(){let e=1+this.value.complexity();for(let t of this.cases){for(let n of t.equals)e+=n.complexity();e+=t.body.complexity()}return this.otherwise&&(e+=this.otherwise.complexity()),e}},vv=class e extends $m{constructor(e,t,n,r,i){super(),this.over=e,this.body=t,this.keyName=n,this.valueName=r,this.parallel=i}over;body;keyName;valueName;parallel;static KIND=`loop`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.parallel?{concurrent:t.parallel.concurrent?r.parseExpr(t.parallel.concurrent,n):void 0,rate:t.parallel.rate?r.parseExpr(t.parallel.rate,n):void 0}:void 0;return new e(r.parseExpr(t.over,n),r.parseExpr(t.body,n),t.key,t.value,i).withComment(t.comment)}async evaluate(e,t){let n=await this.over.evaluate(e,t),r=n.type.get();if(!(r?.loop||r?.loopDynamic))throw Error(`loop: type '${n.type.name}' has no loop or loopDynamic defined on its GetSet`);let i=this.keyName??`key`,a=this.valueName??`value`,o=this.parallel?.concurrent?Number((await this.parallel.concurrent.evaluate(e,t)).raw):void 0,s=this.parallel?.rate?Number((await this.parallel.rate.evaluate(e,t)).raw):void 0,c=o!==void 0||s!==void 0;if(r.loopDynamic){let r=e.registry.num({whole:!0,min:0});if(!c){let o=n,s=0;for(;o.raw;){await t.checkpoint();let n=t.child({[i]:G(r,s),[a]:o});try{await this.body.evaluate(e,n)}catch(e){if(e instanceof lh)break;if(!(e instanceof uh))throw e}s++,o=await this.over.evaluate(e,t)}return G(e.registry.void(),void 0)}let l=new Set,u=o??1/0,d=!1,f=0,p=0,m=async()=>{if(d)return!1;await t.checkpoint();let n=await this.over.evaluate(e,t);if(!n.raw)return!1;if(s&&s>0){let e=Date.now()-f;e<s&&await new Promise(t=>setTimeout(t,s-e)),f=Date.now()}let o=t.child({[i]:G(r,p),[a]:n}),c=(async()=>{try{await this.body.evaluate(e,o)}catch(e){if(e instanceof uh)return;if(e instanceof lh){d=!0;return}throw e}})().finally(()=>l.delete(c));return l.add(c),p++,!0},h=Number.isFinite(u)?u:1;for(;l.size<h&&await m(););for(;l.size>0;)for(await Promise.race(l);!d&&l.size<h&&await m(););return G(e.registry.void(),void 0)}let l=r.loop;if(!l)throw Error(`loop: type '${n.type.name}' has no loop ExprDef on its GetSet`);if(!c)return await yv(l,t,e,n,async(n,r)=>{let o=t.child({[i]:n,[a]:r});try{return await this.body.evaluate(e,o)}catch(t){if(t instanceof uh)return G(e.registry.void(),void 0);throw t}}),G(e.registry.void(),void 0);let u=new Set,d=o??1/0,f=!1,p=0;return await yv(r.loop,t,e,n,async(n,r)=>{if(f)return G(e.registry.void(),void 0);if(s&&s>0){let e=Date.now()-p;e<s&&await new Promise(t=>setTimeout(t,s-e)),p=Date.now()}for(;u.size>=d;)await Promise.race(u);let o=t.child({[i]:n,[a]:r}),c=(async()=>{try{await this.body.evaluate(e,o)}catch(e){if(e instanceof uh)return;if(e instanceof lh){f=!0;return}throw e}})().finally(()=>u.delete(c));return u.add(c),G(e.registry.void(),void 0)}),await Promise.all(u),G(e.registry.void(),void 0)}typeOf(e,t){return e.registry.void()}validateWalk(e,t,n,r){let i=n.at(`over`,()=>oh(e,this.over,t,n,r)),a=i.get();if(a?.loop||a?.loopDynamic||n.error(`loop.not-iterable`,`type '${i.name}' has no loop defined`),this.parallel?.concurrent){let i=n.at([`parallel`,`concurrent`],()=>oh(e,this.parallel.concurrent,t,n,r));e.registry.num().compatible(i)||n.at([`parallel`,`concurrent`],()=>n.error(`loop.parallel.concurrent.type`,`parallel.concurrent must be a number, got '${i.name}'`))}if(this.parallel?.rate){let i=n.at([`parallel`,`rate`],()=>oh(e,this.parallel.rate,t,n,r)),a=e.registry.num().compatible(i),o=e.registry.duration().compatible(i);!a&&!o&&n.at([`parallel`,`rate`],()=>n.error(`loop.parallel.rate.type`,`parallel.rate must be a number or duration, got '${i.name}'`))}this.keyName===void 0?t.has(`key`)&&n.error(`loop.key.shadow`,`loop's default 'key' is already in scope from an enclosing loop — set the \`key\` field on this loop to a distinct name (e.g. "i", "j", "outerKey") so the inner loop doesn't shadow the outer iteration index`):n.at(`key`,()=>sh(this.keyName,t,n)),this.valueName===void 0?t.has(`value`)&&n.error(`loop.value.shadow`,`loop's default 'value' is already in scope from an enclosing loop — set the \`value\` field on this loop to a distinct name (e.g. "v", "row", "outerValue") so the inner loop doesn't shadow the outer iteration value`):n.at(`value`,()=>sh(this.valueName,t,n));let o=a?.key??e.registry.any(),s=a?.value??e.registry.any(),c=new Map(t);return c.set(this.keyName??`key`,o),c.set(this.valueName??`value`,s),n.at(`body`,()=>oh(e,this.body,c,n,{...r,inLoop:!0})),this.body.effects()===B.NONE&&n.at(`body`,()=>n.warn(`loop.body.no-effect`,"loop body has no observable effect — the iteration's computed value is discarded. Add a `set` to accumulate into an outer var, a `flow` to control iteration, or invoke a side-effecting native (e.g. `fns.log`, `fns.fetch`)")),e.registry.void()}toCode(e,t={}){let n=t.expectsValue??!1,r={...t,expectsValue:!0},i={...t,expectsValue:!1},a=this.over.toCode(e,r),o=this.keyName??`key`,s=this.valueName??`value`,c=``;t.includeComments!==!1&&(this.parallel?.concurrent&&(c+=`/* parallel.concurrent: ${this.parallel.concurrent.toCode(e,r)} */ `),this.parallel?.rate&&(c+=`/* parallel.rate: ${this.parallel.rate.toCode(e,r)} */ `));let l=(()=>{let t=this.body.kind;if(t===`flow`)return`${this.body.toCode(e,i)};`;if(t===`block`){let t=this.body.toCode(e,i);return t.startsWith(`{`)?t.slice(1,-1).trim():t}return t===`if`||t===`switch`||t===`loop`?this.body.toCode(e,i):`${this.body.toCode(e,i)};`})(),u=`${c}for (const [${o}, ${s}] of ${a}) {
115
+ ${mv(l)}
116
+ }`,d=this.commentPrefix(t);return n?d+`(() => { ${u}; return undefined; })()`:d+u}toJSON(){let e={kind:`loop`,over:this.over.toJSON(),body:this.body.toJSON()};return this.keyName!==void 0&&(e.key=this.keyName),this.valueName!==void 0&&(e.value=this.valueName),this.parallel&&(e.parallel={concurrent:this.parallel.concurrent?.toJSON(),rate:this.parallel.rate?.toJSON()}),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.over.toJSONCode([...e,`over`],t,n+1),i=this.body.toJSONCode([...e,`body`],t,n+1),a=this.parallel?V.jsonObject([{key:`concurrent`,value:this.parallel.concurrent?.toJSONCode([...e,`parallel`,`concurrent`],t,n+2)},{key:`rate`,value:this.parallel.rate?.toJSONCode([...e,`parallel`,`rate`],t,n+2)}],{path:[...e,`parallel`]},n+1,t):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`loop`)},{key:`over`,value:r},{key:`body`,value:i},{key:`key`,value:this.keyName===void 0?void 0:V.jsonString(this.keyName)},{key:`value`,value:this.valueName===void 0?void 0:V.jsonString(this.valueName)},{key:`parallel`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.over.clone(),this.body.clone(),this.keyName,this.valueName,this.parallel?{concurrent:this.parallel.concurrent?.clone(),rate:this.parallel.rate?.clone()}:void 0).withComment(this.comment)}forEachChild(e){e(this.over,`inherit`),e(this.body,`loop`),this.parallel?.concurrent&&e(this.parallel.concurrent,`inherit`),this.parallel?.rate&&e(this.parallel.rate,`inherit`)}effects(){return this.over.effects()|this.body.effects()|(this.parallel?.concurrent?.effects()??B.NONE)|(this.parallel?.rate?.effects()??B.NONE)}complexity(){return 6+this.over.complexity()+this.body.complexity()+(this.parallel?.concurrent?.complexity()??0)+(this.parallel?.rate?.complexity()??0)}};async function yv(e,t,n,r,i){let a=n.registry,o=new W(a.fn({args:a.obj({key:{type:a.any()},value:{type:a.any()}}),returns:a.void()}),async e=>{let t=e.raw;if(!t)throw Error(`yield: missing args`);return await s.checkpoint(),i(t.key,t.value)}),s=t.child({this:r,yield:o});try{await e.evaluate(n,s)}catch(e){if(!(e instanceof lh))throw e}}var bv=class e extends $m{constructor(e,t,n){super(),this.fnType=e,this.body=t,this.constraint=n}fnType;body;constraint;static KIND=`lambda`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=r.parse(t.type,n),a=Cv(n,i),o=r.parseExpr(t.body,a),s=t.constraint?r.parseExpr(t.constraint,a):void 0;return new e(i,o,s).withComment(t.comment)}async evaluate(e,t){let n=this.fnType,r=this.body,i=t,a=this.constraint,o=async t=>{await i.checkpoint();let s=new W(n,o),c=i.child({args:t,recurse:s});if(a&&(await a.evaluate(e,c)).raw!==!0)throw Error(`lambda constraint failed: ${a.toCode(e.registry,{expectsValue:!0})}`);try{return await r.evaluate(e,c)}catch(t){if(t instanceof dh)return t.value??new W(e.registry.void(),void 0);throw t}};return new W(n,o)}typeOf(e,t){return this.fnType}validateWalk(e,t,n,r){let i=this.fnType.call(),a=new Map(t);a.set(`args`,i?.args??e.registry.any());let o=n.at(`body`,()=>oh(e,this.body,a,n,{...r,inLambda:!0}));if(i?.returns&&!i.returns.compatible(o)&&n.at(`body`,()=>n.warn(`lambda.returns.type`,`body type '${o.name}' not compatible with declared returns '${i.returns.name}'`)),this.constraint){let t=e.registry.bool(),i=n.at(`constraint`,()=>oh(e,this.constraint,a,n,{...r,inLambda:!0}));t.compatible(i)||n.at(`constraint`,()=>n.warn(`lambda.constraint.type`,`constraint must return bool, got '${i.name}'`))}return this.fnType}toGinCode(e,t={},n=[]){let r=this.fnType.call(),i={...t,expectsValue:!0},a=this.commentPrefix(t),o=`(${xv(r?.args,t)})${r?.returns?`: ${r.returns.toCode(void 0,t)}`:``}`,s=this.body.toGinCode(e,i,[...n,`body`]),c=s.text,l;return l=this.constraint?H`${o} => {\n if (!(${Sv(this.constraint.toGinCode(e,i,[...n,`constraint`]))})) throw new Error('constraint');\n return ${s.indent(` `)};\n}`:c.includes(`
117
+ `)?H`${o} => {\n ${s.indent(` `)}\n}`:H`${o} => ${s}`,Fm(a?H`${a}${l}`:l,{path:n,expr:this})}toCode(e,t={}){return this.toGinCode(e,t).toString()}toJSON(){return this.withCommentOn({kind:`lambda`,type:this.fnType.toJSON(),body:this.body.toJSON(),constraint:this.constraint?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.fnType.toJSONCode([...e,`type`],t,n+1),i=this.body.toJSONCode([...e,`body`],t,n+1),a=this.constraint?this.constraint.toJSONCode([...e,`constraint`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`lambda`)},{key:`type`,value:r},{key:`body`,value:i},{key:`constraint`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.fnType.clone(),this.body.clone(),this.constraint?.clone()).withComment(this.comment)}forEachChild(e){e(this.body,`lambda`),this.constraint&&e(this.constraint,`lambda`)}effects(){return B.NONE}complexity(){return 10+this.body.complexity()+(this.constraint?.complexity()??0)}};function xv(e,t){if(!e||e.name===`void`||e.name===`any`)return``;let n=e.fields;if(!n)return`args: ${e.toCode(void 0,t)}`;let r=Object.entries(n);return r.length===0?``:r.map(([e,n])=>{let r=n.type.isOptional?.()??!1,i=r&&typeof n.type.required==`function`?n.type.required():n.type;return`${n.docs&&t.includeComments!==!1?`/* ${n.docs} */ `:``}${e}${r?`?`:``}: ${i.toCode(void 0,t)}`}).join(`, `)}function Sv(e){return e.text.includes(`
118
+ `)?new V(e.text.replace(/\n\s*/g,` `),e.spans):e}function Cv(e,t){let n=new Qm(e),r=t.call();if(r?.types)for(let[e,t]of Object.entries(r.types))n.bind(e,t);return n}var wv=class e extends $m{constructor(e,t){super(),this.template=e,this.params=t}template;params;static KIND=`template`;kind=e.KIND;static from(t,n){let r=n.registry,i=t.template,a=i&&typeof i==`object`&&`kind`in i?r.parseExpr(i,n):r.parseExpr({kind:`new`,type:{name:`text`},value:String(i)},n),o=t.params?r.parseExpr(t.params,n):void 0;return new e(a,o).withComment(t.comment)}async evaluate(e,t){let n=await this.template.evaluate(e,t),r=String(n.raw),i;this.params&&(i=(await this.params.evaluate(e,t)).raw);let a=r.replace(/\{(\w+)\}/g,(e,n)=>{if(i&&Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];return e==null?``:e instanceof W?String(e.raw??``):String(e)}let r=t.get(n);return r===void 0?``:r instanceof W?String(r.raw??``):String(r)});return G(e.registry.text(),a)}typeOf(e,t){return e.registry.text()}validateWalk(e,t,n,r){let i=e.registry.text(),a=n.at(`template`,()=>oh(e,this.template,t,n,r));i.compatible(a)||n.at(`template`,()=>n.warn(`template.template.type`,`template should resolve to text, got '${a.name}'`));let o,s=!1;if(this.params){let i=n.at(`params`,()=>oh(e,this.params,t,n,r));if(i.name===`any`)s=!0;else if(i.name===`obj`||i.name===`iface`){let e=i.props(),t=Object.entries(e).filter(([,e])=>!e.type.call()).map(([e])=>e);o=new Set(t)}else n.at(`params`,()=>n.warn(`template.params.type`,`template params should be an object, got '${i.name}'`)),s=!0}let c=this.template instanceof W_&&typeof this.template.value==`string`?this.template.value:void 0;if(c!==void 0){let e=new Set,r=/\{(\w+)\}/g,i;for(;(i=r.exec(c))!==null;){let r=i[1];if(e.has(r))continue;e.add(r);let a=o?.has(r)??!1,c=t.has(r);s?c||n.error(`template.placeholder.unresolved`,`placeholder '{${r}}' isn't a scope variable; either define '${r}' in scope or pass a typed obj as \`params\` so it can be checked`):!a&&!c&&n.error(`template.placeholder.unresolved`,this.params?`placeholder '{${r}}' is not a key of \`params\` (keys: [${[...o??[]].join(`, `)||`none`}]) and not a scope variable`:`placeholder '{${r}}' does not match any scope variable; either \`define ${r} = ...\` first or pass it via \`params\``)}}return e.registry.text()}toCode(e,t={}){let n=this.commentPrefix(t),r=this.template instanceof W_&&typeof this.template.value==`string`?this.template.value:void 0;if(r===void 0){let r=e.toCode(this.template,{...t,expectsValue:!0});return this.params?`${n}template(${r}, ${e.toCode(this.params,{...t,expectsValue:!0})})`:`${n}template(${r})`}let i=this.params?Tv(this.params,e):void 0;return`${n}${`\`${r.replace(/\{(\w+)\}/g,(e,t)=>{if(i&&Object.prototype.hasOwnProperty.call(i,t)){let e=i[t];return e.length>64?`\${
119
+ `+e+`
120
+ }`:"${"+e+`}`}return"${"+t+`}`}).replace(/`/g,"\\`")}\``}`}toJSON(){return this.withCommentOn({kind:`template`,template:this.template.toJSON(),...this.params?{params:this.params.toJSON()}:{}})}toJSONCode(e=[],t=2,n=0){let r=this.template.toJSONCode([...e,`template`],t,n+1),i=this.params?this.params.toJSONCode([...e,`params`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`template`)},{key:`template`,value:r},{key:`params`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.template.clone(),this.params?.clone()).withComment(this.comment)}forEachChild(e){e(this.template,`inherit`),this.params&&e(this.params,`inherit`)}effects(){return this.template.effects()|(this.params?.effects()??B.NONE)}complexity(){return 1+this.template.complexity()+(this.params?.complexity()??0)}};function Tv(e,t){if(!(e instanceof W_))return;let n=e.value;if(!n||typeof n!=`object`||Array.isArray(n))return;let r={};for(let[e,i]of Object.entries(n))if(typeof i==`string`)r[e]=JSON.stringify(i);else if(typeof i==`number`||typeof i==`boolean`)r[e]=String(i);else if(i===null)r[e]=`null`;else if(i&&typeof i==`object`&&`kind`in i&&typeof i.kind==`string`&&t.exprClass(i.kind))try{r[e]=t.parseExpr(i).toCode(t,{expectsValue:!0})}catch{return}else return;return r}var Ev=class e extends $m{constructor(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){super(),this.id=e,this.type=t,this.resolvedEffects=n}id;type;resolvedEffects;static KIND=`native`;kind=e.KIND;static from(t,n){return new e(t.id,t.type?n.registry.parse(t.type,n):void 0,n.registry.nativeEffects(t.id)).withComment(t.comment)}async evaluate(e,t){let n=e.registry.getNative(this.id);if(!n)throw Error(`native: no impl registered for '${this.id}'`);let r=await n(t,e.registry);return r instanceof W?r:G(this.type??e.registry.any(),r)}typeOf(e,t){return this.type??e.registry.any()}validateWalk(e,t,n,r){return e.registry.getNative(this.id)||n.warn(`native.unknown`,`native impl '${this.id}' is not registered`),this.type??e.registry.any()}toCode(e,t={}){return this.commentPrefix(t)+`/* native: ${this.id} */`}toJSON(){let e={kind:`native`,id:this.id};return this.type&&(e.type=this.type.toJSON()),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.type?this.type.toJSONCode([...e,`type`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`native`)},{key:`id`,value:V.jsonString(this.id)},{key:`type`,value:r},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.id,this.type?.clone(),this.resolvedEffects).withComment(this.comment)}effects(){return this.resolvedEffects}complexity(){return 1}},Dv=[`props`,`get`,`call`,`init`],Ov=class{classes=new Map;namedTypes=new Map;natives=new Map;nativeEffectsMap=new Map;exprClasses=new Map;augments=new Map;_version=0;get version(){return this._version}parent=void 0;get registry(){return this}define(e){return this.classes.set(e.NAME,e),this._version++,this}register(e){return this.namedTypes.set(e.name,e),this._version++,this}scope(e){return new Qm(this,{...e})}augment(e,t){this._version++;let n={props:t.props?jh.fromMap(t.props,this):void 0,get:t.get?Mh.from(t.get,this):void 0,call:t.call?Nh.from(t.call,this):void 0,init:t.init?Ph.from(t.init,this):void 0},r=this.augments.get(e);return r?(this.augments.set(e,{props:n.props?{...r.props??{},...n.props}:r.props,get:r.get??n.get,call:r.call??n.call,init:r.init??n.init}),this):(this.augments.set(e,{props:n.props?{...n.props}:void 0,get:n.get,call:n.call,init:n.init}),this)}augmentation(e){return this.augments.get(e)}lookup(e){if(this.namedTypes.has(e))return this.namedTypes.get(e);let t=this.classes.get(e);if(t)return t.from({name:e},this)}localLookup(e){}setNative(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){return this.natives.set(e,t),this.nativeEffectsMap.set(e,n),this}getNative(e){return this.natives.get(e)}nativeEffects(e){let t=this.nativeEffectsMap.get(e);return t===void 0?B.STATE|B.SYSTEM|B.EXTERNAL:t}defineExpr(e){return this.exprClasses.set(e.KIND,e),this._version++,this}exprClass(e){return this.exprClasses.get(e)}typeClasses(){return Array.from(this.classes.values())}typeClass(e){return this.classes.get(e)}namedTypeList(){return Array.from(this.namedTypes.values())}exprClassList(){return Array.from(this.exprClasses.values())}typeNameCandidates(){return[...this.typeClasses().map(e=>e.NAME),...this.namedTypeList().map(e=>e.name)]}parseExpr(e,t=this){if(e==null)return;if(e instanceof $m)return e;if(typeof e!=`object`||!(`kind`in e))throw Error(`registry.parseExpr: expected ExprDef with kind, got ${typeof e}`);let n=e,r=this.exprClasses.get(n.kind);if(!r)throw Error(`registry.parseExpr: unknown expr kind '${n.kind}'`);return r.from(n,t)}toCode(e,t){return(e instanceof $m?e:this.parseExpr(e)).toCode(this,t)}toGinCode(e,t){return(e instanceof $m?e:this.parseExpr(e)).toGinCode(this,t,[])}toJSONCode(e,t=2){return(e instanceof $m?e:this.parseExpr(e)).toJSONCode([],t)}validate(e){let t=new Mm,n=new Set,r=(r,i)=>{if(n.has(r))return;n.add(r);let a=i.validate(e);for(let e of a.list)t.list.push({...e,path:[r,...e.path]})};for(let[e,t]of this.namedTypes)r(e,t);for(let e of this.augments.keys()){let t=this.lookup(e);t&&r(e,t)}return t}parseValue(e,t,n=this){if(e instanceof W)return this.checkSlot(e,t,n);if(t?.parsesExprValue(n)&&this.exprShaped(e))return t.parse(e,n);if(e&&typeof e==`object`&&`type`in e&&`value`in e&&this.typeDefShaped(e.type)){let r=e.kind;if(typeof r==`string`&&this.exprClass(r))throw TypeError(`registry.parseValue: this node is an EXPRESSION (kind:'${r}'), not a value envelope \u2014 an Expr only evaluates inside a program (\`Engine.run\`/\`Engine.evaluate\`); a bare \`parse\` takes data. Drop the \`kind\` to mean the literal ${JSON.stringify(e.type)} value.`+(t?` (This slot is declared \`${t.toCode()}\`.)`:``));return this.checkSlot(this.parse(e.type,n).parse(e.value,n),t,n)}if(!t)throw TypeError(`registry.parseValue: expected Value or JSONValue, got ${typeof e}`);return t.parse(e,n)}typeDefShaped(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&typeof e.name==`string`}exprShaped(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e.kind;return typeof t==`string`&&!!this.exprClass(t)}checkSlot(e,t,n){if(!t||Sh(t,e.type,n))return e;throw TypeError(`registry.parseValue: this slot is declared \`${t.toCode()}\` but the value carries \`${e.type.toCode()}\``)}parse(e,t=this){if(!e||typeof e!=`object`)throw Error(`registry.parse: expected object, got ${typeof e}`);if(e instanceof U)throw Error(`registry.parse: expected a serialized TypeDef, got a LIVE ${e.constructor.name} instance (\`${e.name}\`) \u2014 pass \`type.toJSON()\`, or use the type as it stands.`);let n=e;if(!am(n.name))throw Error(`registry.parse: type 'name' must match ${im}, got ${JSON.stringify(n.name)}`);if(n.extends!==void 0&&!am(n.extends))throw Error(`registry.parse: type 'extends' must match ${im}, got ${JSON.stringify(n.extends)}`);if(n.satisfies){for(let e of n.satisfies)if(!am(e))throw Error(`registry.parse: 'satisfies' entries must match ${im}, got ${JSON.stringify(e)}`)}let r=n.extends??n.name;Up(n,this.namedTypes.has(r)?void 0:this.classes.get(r),n.extends===void 0,this);let i=this.parseInner(n,t);if(n.satisfies&&n.satisfies.length>0)for(let e of n.satisfies){let r=t.lookup(e)??this.lookup(e);if(!r)throw Error(`registry.parse: satisfies references unknown interface '${e}'${Pp(e,this.typeNameCandidates())}`);if(!r.compatible(i))throw Error(`registry.parse: type '${n.name}' claims to satisfy '${e}' but does not structurally match`)}return i}isUseSiteDef(e){return e.generic===void 0&&e.options===void 0?!1:[`extends`,`satisfies`,`init`,`props`,`get`,`call`,`constraint`].every(t=>e[t]===void 0)}boundAboveRegistry(e,t){for(let n=t;n&&n!==this;n=n.parent)if(n.localLookup(e)!==void 0)return!0;return!1}parseGenericArgs(e,t){return Object.fromEntries(Object.entries(e.generic??{}).map(([e,n])=>[e,this.parse(n,t)]))}useSiteAlias(e,t){return new Sg(t,e.options===void 0?{name:e.name}:{name:e.name,options:e.options},this.parseGenericArgs(e,t))}applyUse(e,t,n,r){let i=e;return Object.keys(t).length>0&&i instanceof gg&&(i=i.specialize(t)),n!==void 0&&Object.keys(n).length>0&&!pg(i.narrow(n),i.options)&&(i=new gg(this,i,{name:i.name,docs:i.docs,options:n,generic:i instanceof gg?i.local.generic:void 0,useSite:!0},i instanceof gg&&i.bindings?i.scope:void 0,r)),i}nearBuiltin(e){return e[0]===e[0]?.toLowerCase()&&Pp(e,this.typeClasses().map(e=>e.NAME))!==``}isBareNameDef(e){for(let t of[`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`])if(e[t]!==void 0)return!1;return!0}parseInner(e,t){if(e.extends){let n=t.lookup(e.extends)??this.lookup(e.extends);if(!n)throw Error(`registry.parse: extends references unknown type '${e.extends}'${Pp(e.extends,this.typeNameCandidates())}`);let r=this.classes.get(e.extends),i=e.generic!==void 0&&Object.keys(e.generic).length>0,a=r&&!i?Dv.filter(t=>e[t]!==void 0&&(r.consumes??[]).includes(t)):[];if(r&&a.length>0){let n={name:e.extends,...a.includes(`props`)?{props:e.props}:{},...a.includes(`get`)?{get:e.get}:{},...a.includes(`call`)?{call:e.call}:{},...a.includes(`init`)?{init:e.init}:{}},i=r.from(n,t),o={...e};delete o.extends;for(let e of a)delete o[e];return new gg(this,i,this.buildLocal(o,t))}return new gg(this,n,this.buildLocal(e,t))}if(this.isBareNameDef(e)){let n=t;for(;n&&n!==this;){if(n.localLookup(e.name)!==void 0)return new Sg(t,{name:e.name});n=n.parent}if(this.namedTypes.has(e.name))return this.namedTypes.get(e.name);let r=this.classes.get(e.name);return r?r.from(e,t):new Sg(t,{name:e.name})}let n=this.isUseSiteDef(e);if(n&&this.boundAboveRegistry(e.name,t))return this.useSiteAlias(e,t);if(this.namedTypes.has(e.name)){let r=this.namedTypes.get(e.name);return n?this.applyUse(r,this.parseGenericArgs(e,t),e.options,t):e.generic&&r instanceof gg?r.specialize(this.parseGenericArgs(e,t)):r}let r=this.classes.get(e.name);if(!r){if(n&&!this.nearBuiltin(e.name))return this.useSiteAlias(e,t);throw Error(`registry.parse: unknown type '${e.name}'${Pp(e.name,this.typeNameCandidates())}`)}let i=new Set(r.consumes??[]),a=Dv.filter(t=>e[t]!==void 0&&!i.has(t));if(a.length===0)return r.from(e,t);let o={...e};for(let e of a)delete o[e];let s=r.from(o,t),c={name:e.name,docs:e.docs,props:a.includes(`props`)&&e.props?jh.fromMap(e.props,t):void 0,get:a.includes(`get`)&&e.get?Mh.from(e.get,t):void 0,call:a.includes(`call`)&&e.call?Nh.from(e.call,t):void 0,init:a.includes(`init`)&&e.init?Ph.from(e.init,t):void 0};return new gg(this,s,c)}getTypesFor(e){let t=this.lookup(e);if(!t)return[];let n=[];for(let e of this.namedTypes.values())if(e!==t)try{t.compatible(e)&&n.push(e)}catch{}for(let[r,i]of this.classes){if(r===e)continue;let a;try{a=i.from({name:r},this)}catch{continue}try{t.compatible(a)&&n.push(a)}catch{}}return n}buildLocal(e,t){let n=e.generic?Object.fromEntries(Object.entries(e.generic).map(([e,n])=>[e,this.parse(n,t)])):void 0;return{name:e.name,docs:e.docs,options:e.options,generic:n,props:e.props?jh.fromMap(e.props,t):void 0,get:e.get?Mh.from(e.get,t):void 0,call:e.call?Nh.from(e.call,t):void 0,init:e.init?Ph.from(e.init,t):void 0,constraint:e.constraint?this.parseExpr(e.constraint,t):void 0}}any(){return new _g(this,{})}void(){return new Yg(this,{})}null(){return new zg(this,{})}bool(e){return new Cg(this,e??{})}num(e){return new Vg(this,e??{})}text(e){return new Wg(this,e??{})}list(e,t){return new Ng(this,e,t??{})}map(e,t){return new Lg(this,e,t)}tuple(e){return new qg(this,[...e])}obj(e){return new vg(this,e)}field(e,t){return{type:e,docs:t?.docs,default:t?.default===void 0?void 0:this.parseExpr(t.default)}}optional(e){return new Hg(this,e)}nullable(e){return new Bg(this,e)}not(e){return new Rg(this,e)}or(e){return new Ug(this,[...e])}and(e){return new bg(this,[...e])}enum(e,t){return kv(e)?new Dg(this,this.text(),{values:Object.fromEntries(e.map(e=>[e,e]))}):new Dg(this,t??this.text(),{values:e})}literal(e,t){if(e instanceof U)return new Mg(this,e,t);let n=this.primitiveOf(e);return new Mg(this,n,e)}primitiveOf(e){switch(typeof e){case`string`:return this.text();case`number`:return this.num();case`boolean`:return this.bool()}}date(e){return new Tg(this,e??{})}timestamp(e){return new Gg(this,e??{})}duration(){return new Eg(this,{})}color(e){return new wg(this,e??{})}fn(e){return new Ag(this,{args:e.args,returns:e.returns,throws:e.throws,get:e.call},e.generic??{})}iface(e){return new jg(this,{props:e.props?jh.fromMap(e.props,this):{},get:e.get?Mh.from(e.get,this):void 0,call:e.call?Nh.from(e.call,this):void 0})}alias(e){return new Sg(this,{name:e})}typ(e){return new Jg(this,e)}compatible(e){let t=[],n=new Set,r=e=>{n.has(e.name)||(n.add(e.name),t.push(e))};for(let t of this.typeClasses()){let n;try{n=t.from({name:t.NAME},this)}catch{continue}if(!(n.isUniversal()&&e.name!==t.NAME))try{n.compatible(e)&&r(n)}catch{continue}}for(let t of this.namedTypeList())try{t.compatible(e)&&r(t)}catch{continue}return t}like(e){let t=this.compatible(e).map(t=>t.like(e));return t.length===0?this.null():t.length===1?t[0]:this.or(t)}extend(e,t){let n=typeof e==`string`?this.lookup(e)??(()=>{throw Error(`extend: unknown base '${e}'`)})():e;return new gg(this,n,t)}nativeExpr(e){return this.parseExpr({kind:`native`,id:e})}prop(e,t,n){return Av(new jh({type:e,get:this.nativeExpr(t),docs:n}))}method(e,t,n,r){return Av(new jh({type:this.fn({args:this.obj(e),returns:t,generic:r?.generic}),get:this.nativeExpr(n),docs:r?.docs}))}};function kv(e){return Array.isArray(e)}function Av(e){if(!jv(e))throw Error(`registry: a computed prop must carry a get expression`);return e}function jv(e){return e.get!==void 0}var Mv=[_g,Yg,zg,Cg,Vg,Wg,Ng,Lg,qg,vg,Hg,Bg,Rg,Ug,bg,Dg,Mg,Ag,jg,Jg,Tg,Gg,Eg,wg],Nv=[W_,cv,lv,uv,fv,gv,_v,vv,bv,wv,pv,Ev];function Pv(){let e=new Ov;for(let t of Mv)e.define(t);for(let t of Nv)e.defineExpr(t);return U_(e),e}var Fv={$Exit:{code:"/** gin `flow: exit` — unwinds to the outermost exported function, whose result becomes `value`. */\nclass $Exit {\n constructor(readonly value: unknown) {}\n}"},$Throw:{code:"/** gin `flow: throw` — a thrown gin value; a call step's `catch` handler receives `error`. */\nclass $Throw extends Error {\n constructor(readonly error: unknown) { super(typeof error === 'string' ? error : 'gin throw'); }\n}"},$str:{code:"/** Template placeholder text — `null`/`undefined` read as the empty string. */\nfunction $str(v: unknown): string {\n return v === undefined || v === null ? '' : String(v);\n}"},$template:{code:`/** A template whose text is only known at run time: \`{name}\` reads \`params.name\`. */
121
+ function $template(tmpl: string, params: Record<string, unknown> | undefined): string {
122
+ return tmpl.replace(/\\{(\\w+)\\}/g, (_, name: string) =>
123
+ params && Object.prototype.hasOwnProperty.call(params, name) ? $str(params[name]) : '');
124
+ }`,deps:[`$str`]},$typeOf:{code:`/** The gin type name of a run-time value (\`any.typeOf\`). */
125
+ function $typeOf(v: unknown): string {
126
+ if (v === undefined) return 'void';
127
+ if (v === null) return 'null';
128
+ if (typeof v === 'number') return 'num';
129
+ if (typeof v === 'string') return 'text';
130
+ if (typeof v === 'boolean') return 'bool';
131
+ if (typeof v === 'function') return 'fn';
132
+ if (v instanceof Date) return 'timestamp';
133
+ if (v instanceof Map) return 'map';
134
+ if (Array.isArray(v)) return 'list';
135
+ return 'obj';
136
+ }`},$deepEq:{code:`/** Structural equality (\`obj.eq\`). */
137
+ function $deepEq(a: unknown, b: unknown): boolean {
138
+ if (a === b) return true;
139
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
140
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
141
+ if (Array.isArray(a) && Array.isArray(b)) {
142
+ if (a.length !== b.length) return false;
143
+ for (let i = 0; i < a.length; i++) if (!$deepEq(a[i], b[i])) return false;
144
+ return true;
145
+ }
146
+ const ak = Object.keys(a as object);
147
+ const bk = Object.keys(b as object);
148
+ if (ak.length !== bk.length) return false;
149
+ for (const k of ak) if (!$deepEq((a as any)[k], (b as any)[k])) return false;
150
+ return true;
151
+ }`},$objText:{code:`/** \`obj.toText\` — the declared fields as JSON. */
152
+ function $objText(o: Record<string, unknown>, fields: readonly string[]): string {
153
+ const out: Record<string, unknown> = {};
154
+ for (const f of fields) out[f] = o[f];
155
+ return JSON.stringify(out);
156
+ }`},$numEq:{code:"/** `num.eq` — equal within `epsilon` (default 0). */\nfunction $numEq(a: number, b: number, epsilon?: number): boolean {\n return Math.abs(a - b) <= (typeof epsilon === 'number' ? epsilon : 0);\n}"},$numText:{code:"/** `num.toText` — fixed to `precision` digits when given. */\nfunction $numText(n: number, precision?: number): string {\n return precision != null ? n.toFixed(precision) : String(n);\n}"},$optValue:{code:`/** \`optional.value\` — the value, or a throw when there is none. */
157
+ function $optValue<T>(v: T | undefined): T {
158
+ if (v === undefined) throw new Error('optional.value: value is undefined');
159
+ return v;
160
+ }`},$nullValue:{code:`/** \`nullable.value\` — the value, or a throw when it is null. */
161
+ function $nullValue<T>(v: T | null): T {
162
+ if (v === null) throw new Error('nullable.value: value is null');
163
+ return v;
164
+ }`},$charAt:{code:`/** \`text[i]\` — throws out of range. */
165
+ function $charAt(s: string, i: number): string {
166
+ const ch = s[i];
167
+ if (ch === undefined) throw new Error(\`text[\${i}]: index out of range\`);
168
+ return ch;
169
+ }`},$listGet:{code:"/** `list[i]` — throws out of range. */\nfunction $listGet<T>(xs: T[], i: number): T {\n if (i < 0 || i >= xs.length) throw new Error(`list[${i}]: index out of range`);\n return xs[i]!;\n}"},$listSet:{code:"/** `list[i] = v` — throws out of range. */\nfunction $listSet<T>(xs: T[], i: number, v: T): void {\n if (i < 0 || i >= xs.length) throw new Error(`list[${i}] =: index out of range`);\n xs[i] = v;\n}"},$listAt:{code:`/** \`list.at\` — the element, or undefined out of range. */
170
+ function $listAt<T>(xs: T[], i: number): T | undefined {
171
+ return i < 0 || i >= xs.length ? undefined : xs[i];
172
+ }`},$duplicates:{code:`/** \`list.duplicates\` — each value seen more than once, in first-repeat order. */
173
+ function $duplicates<T>(xs: T[]): T[] {
174
+ const seen = new Set<T>();
175
+ const dupes = new Set<T>();
176
+ const out: T[] = [];
177
+ for (const v of xs) {
178
+ if (seen.has(v)) { if (!dupes.has(v)) { dupes.add(v); out.push(v); } }
179
+ else seen.add(v);
180
+ }
181
+ return out;
182
+ }`},$sortNatural:{code:"/** `list.sort` without a comparator — a sorted copy by `<`. */\nfunction $sortNatural<T>(xs: T[]): T[] {\n return [...xs].sort((a: any, b: any) => a < b ? -1 : a > b ? 1 : 0);\n}"},$map:{code:`function $map<T, R>(xs: T[], fn: (args: { value: T; index: number }) => R): R[] {
183
+ const out: R[] = [];
184
+ for (let i = 0; i < xs.length; i++) out.push(fn({ value: xs[i]!, index: i }));
185
+ return out;
186
+ }`},$mapAsync:{code:`async function $mapAsync<T, R>(xs: T[], fn: (args: { value: T; index: number }) => R | Promise<R>): Promise<R[]> {
187
+ const out: R[] = [];
188
+ for (let i = 0; i < xs.length; i++) out.push(await fn({ value: xs[i]!, index: i }));
189
+ return out;
190
+ }`},$filter:{code:`function $filter<T>(xs: T[], fn: (args: { value: T; index: number }) => boolean): T[] {
191
+ const out: T[] = [];
192
+ for (let i = 0; i < xs.length; i++) if (fn({ value: xs[i]!, index: i })) out.push(xs[i]!);
193
+ return out;
194
+ }`},$filterAsync:{code:`async function $filterAsync<T>(xs: T[], fn: (args: { value: T; index: number }) => boolean | Promise<boolean>): Promise<T[]> {
195
+ const out: T[] = [];
196
+ for (let i = 0; i < xs.length; i++) if (await fn({ value: xs[i]!, index: i })) out.push(xs[i]!);
197
+ return out;
198
+ }`},$find:{code:`function $find<T>(xs: T[], fn: (args: { value: T; index: number }) => boolean): T | undefined {
199
+ for (let i = 0; i < xs.length; i++) if (fn({ value: xs[i]!, index: i })) return xs[i];
200
+ return undefined;
201
+ }`},$findAsync:{code:`async function $findAsync<T>(xs: T[], fn: (args: { value: T; index: number }) => boolean | Promise<boolean>): Promise<T | undefined> {
202
+ for (let i = 0; i < xs.length; i++) if (await fn({ value: xs[i]!, index: i })) return xs[i];
203
+ return undefined;
204
+ }`},$some:{code:`function $some<T>(xs: T[], fn: (args: { value: T; index: number }) => boolean): boolean {
205
+ for (let i = 0; i < xs.length; i++) if (fn({ value: xs[i]!, index: i })) return true;
206
+ return false;
207
+ }`},$someAsync:{code:`async function $someAsync<T>(xs: T[], fn: (args: { value: T; index: number }) => boolean | Promise<boolean>): Promise<boolean> {
208
+ for (let i = 0; i < xs.length; i++) if (await fn({ value: xs[i]!, index: i })) return true;
209
+ return false;
210
+ }`},$every:{code:`function $every<T>(xs: T[], fn: (args: { value: T; index: number }) => boolean): boolean {
211
+ for (let i = 0; i < xs.length; i++) if (!fn({ value: xs[i]!, index: i })) return false;
212
+ return true;
213
+ }`},$everyAsync:{code:`async function $everyAsync<T>(xs: T[], fn: (args: { value: T; index: number }) => boolean | Promise<boolean>): Promise<boolean> {
214
+ for (let i = 0; i < xs.length; i++) if (!(await fn({ value: xs[i]!, index: i }))) return false;
215
+ return true;
216
+ }`},$reduce:{code:`function $reduce<T, R>(xs: T[], fn: (args: { acc: R; value: T; index: number }) => R, initial: R): R {
217
+ let acc = initial;
218
+ for (let i = 0; i < xs.length; i++) acc = fn({ acc, value: xs[i]!, index: i });
219
+ return acc;
220
+ }`},$reduceAsync:{code:`async function $reduceAsync<T, R>(xs: T[], fn: (args: { acc: R; value: T; index: number }) => R | Promise<R>, initial: R): Promise<R> {
221
+ let acc = initial;
222
+ for (let i = 0; i < xs.length; i++) acc = await fn({ acc, value: xs[i]!, index: i });
223
+ return acc;
224
+ }`},$sort:{code:`function $sort<T>(xs: T[], fn: (args: { a: T; b: T }) => number): T[] {
225
+ const ranked = xs.map((v, i) => {
226
+ let key = 0;
227
+ for (let j = 0; j < xs.length; j++) if (i !== j && fn({ a: v, b: xs[j]! }) > 0) key++;
228
+ return { v, key };
229
+ });
230
+ ranked.sort((x, y) => x.key - y.key);
231
+ return ranked.map((r) => r.v);
232
+ }`},$sortAsync:{code:`async function $sortAsync<T>(xs: T[], fn: (args: { a: T; b: T }) => number | Promise<number>): Promise<T[]> {
233
+ const ranked: Array<{ v: T; key: number }> = [];
234
+ for (let i = 0; i < xs.length; i++) {
235
+ let key = 0;
236
+ for (let j = 0; j < xs.length; j++) if (i !== j && (await fn({ a: xs[i]!, b: xs[j]! })) > 0) key++;
237
+ ranked.push({ v: xs[i]!, key });
238
+ }
239
+ ranked.sort((x, y) => x.key - y.key);
240
+ return ranked.map((r) => r.v);
241
+ }`},$mapGet:{code:"/** `map[key]` — throws when the key is missing. */\nfunction $mapGet<K, V>(m: Map<K, V>, k: K): V {\n if (!m.has(k)) throw new Error(`map[${String(k)}]: key not found`);\n return m.get(k)!;\n}"},$parallel:{code:`/** A \`parallel\` loop: at most \`concurrent\` bodies at once, starts at least \`rate\` ms apart. */
242
+ async function $parallel<K, V>(
243
+ items: Iterable<[K, V]>,
244
+ concurrent: number | undefined,
245
+ rate: number | undefined,
246
+ body: (key: K, value: V) => unknown | Promise<unknown>,
247
+ ): Promise<void> {
248
+ const limit = concurrent && concurrent > 0 ? concurrent : Infinity;
249
+ const running = new Set<Promise<unknown>>();
250
+ let last = 0;
251
+ for (const [k, v] of items) {
252
+ while (running.size >= limit) await Promise.race(running);
253
+ if (rate) {
254
+ const wait = last + rate - Date.now();
255
+ if (wait > 0) await new Promise((r) => setTimeout(r, wait));
256
+ last = Date.now();
257
+ }
258
+ const p: Promise<unknown> = Promise.resolve().then(() => body(k, v)).finally(() => running.delete(p));
259
+ running.add(p);
260
+ }
261
+ await Promise.all(running);
262
+ }`},$date:{code:`/** gin \`date\` / \`timestamp\` natives (all UTC). */
263
+ const $date = {
264
+ dayOfYear(d: Date): number {
265
+ return Math.floor((d.getTime() - Date.UTC(d.getUTCFullYear(), 0, 0)) / 86_400_000);
266
+ },
267
+ addDays(d: Date, n: number): Date { const x = new Date(d); x.setUTCDate(x.getUTCDate() + n); return x; },
268
+ addMonths(d: Date, n: number): Date { const x = new Date(d); x.setUTCMonth(x.getUTCMonth() + n); return x; },
269
+ addYears(d: Date, n: number): Date { const x = new Date(d); x.setUTCFullYear(x.getUTCFullYear() + n); return x; },
270
+ diffDays(a: Date, b: Date): number { return Math.round((a.getTime() - b.getTime()) / 86_400_000); },
271
+ diffMonths(a: Date, b: Date): number {
272
+ return (a.getUTCFullYear() - b.getUTCFullYear()) * 12 + (a.getUTCMonth() - b.getUTCMonth());
273
+ },
274
+ toDate(d: Date): Date { return new Date(d.toISOString().slice(0, 10)); },
275
+ };`},$duration:{code:`/** gin \`duration\` (milliseconds) natives. */
276
+ const $duration = {
277
+ init(a: { days?: number; hours?: number; minutes?: number; seconds?: number; ms?: number }): number {
278
+ return (a.days ?? 0) * 86_400_000 + (a.hours ?? 0) * 3_600_000 + (a.minutes ?? 0) * 60_000
279
+ + (a.seconds ?? 0) * 1_000 + (a.ms ?? 0);
280
+ },
281
+ toText(ms: number): string {
282
+ const days = Math.trunc(ms / 86_400_000);
283
+ const hours = Math.trunc((ms % 86_400_000) / 3_600_000);
284
+ const mins = Math.trunc((ms % 3_600_000) / 60_000);
285
+ const secs = Math.trunc((ms % 60_000) / 1_000);
286
+ const parts: string[] = [];
287
+ if (days) parts.push(\`\${days}d\`);
288
+ if (hours) parts.push(\`\${hours}h\`);
289
+ if (mins) parts.push(\`\${mins}m\`);
290
+ if (secs || parts.length === 0) parts.push(\`\${secs}s\`);
291
+ return parts.join(' ');
292
+ },
293
+ };`},$color:{code:`/** gin \`color\` natives — a color is a packed 0xRRGGBBAA number. */
294
+ const $color = {
295
+ r: (c: number) => (c >>> 24) & 0xff,
296
+ g: (c: number) => (c >>> 16) & 0xff,
297
+ b: (c: number) => (c >>> 8) & 0xff,
298
+ a: (c: number) => (c & 0xff) / 255,
299
+ pack(r: number, g: number, b: number, a: number): number {
300
+ return (((Math.round(r) & 0xff) << 24) | ((Math.round(g) & 0xff) << 16)
301
+ | ((Math.round(b) & 0xff) << 8) | (Math.round(a * 255) & 0xff)) >>> 0;
302
+ },
303
+ init(a: { r: number; g: number; b: number; a?: number }): number {
304
+ return $color.pack(a.r, a.g, a.b, a.a ?? 1);
305
+ },
306
+ hsl(c: number): { h: number; s: number; l: number } {
307
+ const r = $color.r(c) / 255, g = $color.g(c) / 255, b = $color.b(c) / 255;
308
+ const max = Math.max(r, g, b), min = Math.min(r, g, b);
309
+ const l = (max + min) / 2;
310
+ let h = 0, s = 0;
311
+ if (max !== min) {
312
+ const d = max - min;
313
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
314
+ switch (max) {
315
+ case r: h = (g - b) / d + (g < b ? 6 : 0); break;
316
+ case g: h = (b - r) / d + 2; break;
317
+ case b: h = (r - g) / d + 4; break;
318
+ }
319
+ h *= 60;
320
+ }
321
+ return { h, s, l };
322
+ },
323
+ fromHsl(h: number, s: number, l: number, a: number): number {
324
+ const c = (1 - Math.abs(2 * l - 1)) * s;
325
+ const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
326
+ const m = l - c / 2;
327
+ let r1 = 0, g1 = 0, b1 = 0;
328
+ if (h < 60) [r1, g1, b1] = [c, x, 0];
329
+ else if (h < 120) [r1, g1, b1] = [x, c, 0];
330
+ else if (h < 180) [r1, g1, b1] = [0, c, x];
331
+ else if (h < 240) [r1, g1, b1] = [0, x, c];
332
+ else if (h < 300) [r1, g1, b1] = [x, 0, c];
333
+ else [r1, g1, b1] = [c, 0, x];
334
+ return $color.pack((r1 + m) * 255, (g1 + m) * 255, (b1 + m) * 255, a);
335
+ },
336
+ lighten(c: number, amount: number): number {
337
+ const { h, s, l } = $color.hsl(c);
338
+ return $color.fromHsl(h, s, Math.max(0, Math.min(1, l + amount)), $color.a(c));
339
+ },
340
+ saturate(c: number, amount: number): number {
341
+ const { h, s, l } = $color.hsl(c);
342
+ return $color.fromHsl(h, Math.max(0, Math.min(1, s + amount)), l, $color.a(c));
343
+ },
344
+ complement(c: number): number {
345
+ const { h, s, l } = $color.hsl(c);
346
+ return $color.fromHsl((h + 180 + 360) % 360, s, l, $color.a(c));
347
+ },
348
+ opacity(c: number, alpha: number): number {
349
+ return (c & 0xffffff00) | (Math.round(alpha * 255) & 0xff);
350
+ },
351
+ invert(c: number): number {
352
+ return $color.pack(255 - $color.r(c), 255 - $color.g(c), 255 - $color.b(c), $color.a(c));
353
+ },
354
+ mix(a: number, b: number, weight?: number): number {
355
+ const w = weight ?? 0.5;
356
+ return $color.pack(
357
+ $color.r(a) * (1 - w) + $color.r(b) * w,
358
+ $color.g(a) * (1 - w) + $color.g(b) * w,
359
+ $color.b(a) * (1 - w) + $color.b(b) * w,
360
+ $color.a(a) * (1 - w) + $color.a(b) * w,
361
+ );
362
+ },
363
+ toHex: (c: number) => '#' + c.toString(16).padStart(8, '0'),
364
+ toRgb: (c: number) => \`rgb(\${$color.r(c)},\${$color.g(c)},\${$color.b(c)})\`,
365
+ toHsl(c: number): string {
366
+ const { h, s, l } = $color.hsl(c);
367
+ return \`hsl(\${Math.round(h)},\${Math.round(s * 100)}%,\${Math.round(l * 100)}%)\`;
368
+ },
369
+ };`}},Iv=new Set(`any.unknown.never.object.string.number.boolean.symbol.bigint.undefined.null.void.true.false.this.keyof.typeof.infer.is.asserts.readonly.unique.type.interface.enum.class.function.let.const.var.new.in.of.as.extends.implements.namespace.module.declare.abstract.async.await.yield.import.export.default.return.if.else.for.while.do.switch.case.break.continue.try.catch.finally.throw.delete.instanceof.super.with.debugger.package.private.protected.public.static.global.require.Array.ArrayBuffer.ArrayLike.AsyncGenerator.AsyncIterable.AsyncIterator.Atomics.Awaited.BigInt.BigInt64Array.BigUint64Array.Boolean.Capitalize.ConstructorParameters.DataView.Date.Error.EvalError.Exclude.Extract.Float32Array.Float64Array.Function.Generator.Infinity.InstanceType.Int16Array.Int32Array.Int8Array.Intl.Iterable.IterableIterator.Iterator.JSON.Lowercase.Map.Math.NaN.NonNullable.Number.Object.Omit.OmitThisParameter.Parameters.Partial.Pick.Promise.PromiseLike.PropertyKey.Proxy.RangeError.Readonly.ReadonlyArray.ReadonlyMap.ReadonlySet.Record.ReferenceError.Reflect.RegExp.Required.ReturnType.Set.SharedArrayBuffer.String.Symbol.SyntaxError.TemplateStringsArray.ThisParameterType.ThisType.TypeError.URIError.Uint16Array.Uint32Array.Uint8Array.Uint8ClampedArray.Uncapitalize.Uppercase.WeakMap.WeakRef.WeakSet.globalThis.console.eval.arguments`.split(`.`));function Lv(e){return/^[A-Za-z_][\w$]*$/.test(e)&&!Iv.has(e)&&!(e in Fv)}function Rv(e){let t=e.replace(/[^\w]/g,`_`);return/^[A-Za-z_]/.test(t)||(t=`_`+t),Lv(t)?t:`${t}_`}var zv=class{taken=new Set;types=new Map;data=new Map;constructor(e,t){let n=e.namedTypeList().filter(e=>e instanceof gg&&!e.local.useSite).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of n)Lv(e.name)&&!this.taken.has(e.name)&&this.claim(this.types,e.name,e.name);for(let e of n)this.types.has(e.name)||this.type(e.name);for(let e of n){let n=!1;try{n=t(e)}catch{n=!1}n&&this.dataName(e.name)}}claim(e,t,n){let r=n;for(let e=2;this.taken.has(r);e++)r=`${n.replace(/_$/,``)}_${e}`;return this.taken.add(r),e.set(t,r),r}type(e){return this.types.get(e)??this.claim(this.types,e,Rv(e))}dataName(e){return this.data.get(e)??this.claim(this.data,e,`${this.type(e)}Data`)}fresh(e){return this.claim(new Map,e,Rv(e))}},Bv=(e,t)=>e===void 0||e===`undefined`||e===`null`?t:/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false)$/.test(e)?e:`(${e} ?? ${t})`,J=(e,t)=>e.arg(t)??`undefined`,Vv=e=>t=>`(${t.self()} ${e} ${J(t,`other`)})`,Hv=(e,...t)=>n=>`${e}(${[n.self(),...t.map(e=>J(n,e))].join(`, `)})`,Uv=(e,...t)=>n=>`${n.self()}.${e}(${t.map(e=>J(n,e)).join(`, `)})`,Wv=e=>t=>`${t.self()}.${e}`,Gv=e=>t=>`void ${e(t)}`,Kv=(e,...t)=>{let n=t.map(t=>e.arg(t));for(;n.length>0&&n[n.length-1]===void 0;)n.pop();return n.map(e=>e??`undefined`).join(`, `)},qv=(e,...t)=>n=>{let r=n.fn(`fn`),i=t.map(e=>J(n,e));return r?r.sync?`${n.helper(`$`+e)}(${[n.self(),r.code,...i].join(`, `)})`:n.aw(`${n.helper(`$`+e+`Async`)}(${[n.self(),r.code,...i].join(`, `)})`):`${n.helper(`$`+e)}(${[n.self(),`undefined as any`,...i].join(`, `)})`},Jv=e=>t=>{let n=t.once(),r=t.fn(`fn`);if(!r)return n;let i=`(${r.code})({ value: ${n} })`;return`(${n} === ${e} ? ${e} : ${r.sync?i:t.aw(i)})`},Yv={"type.toAny":e=>e.self(),"any.typeOf":e=>{let t=e.staticTypeName();return t===void 0?`${e.helper(`$typeOf`)}(${e.self()})`:(e.discard(),JSON.stringify(t))},"any.is":e=>{let t=e.guard();return t?`${t}(${e.self()})`:(e.discard(),`true`)},"any.as":e=>{let t=e.guard();if(!t)return e.self();let n=e.once();return`(${t}(${n}) ? ${n} : undefined)`},"any.toText":e=>`String(${e.self()})`,"any.toBool":e=>`Boolean(${e.self()})`,"any.eq":Vv(`===`),"any.neq":Vv(`!==`),"void.toText":e=>(e.discard(),`"void"`),"void.toBool":e=>(e.discard(),`false`),"null.toText":e=>(e.discard(),`"null"`),"null.toBool":e=>(e.discard(),`false`),"not.typeOf":e=>`${e.helper(`$typeOf`)}(${e.self()})`,"not.toText":e=>`String(${e.self()})`,"bool.eq":Vv(`===`),"bool.neq":Vv(`!==`),"bool.and":Vv(`&&`),"bool.or":Vv(`||`),"bool.xor":Vv(`!==`),"bool.not":e=>`!${e.self()}`,"bool.toText":e=>{let t=e.arg(`trueText`),n=e.arg(`falseText`);return t===void 0&&n===void 0?`String(${e.self()})`:`(${e.self()} ? ${Bv(t,`"true"`)} : ${Bv(n,`"false"`)})`},"bool.toNum":e=>{let t=e.arg(`trueValue`),n=e.arg(`falseValue`);return`(${e.self()} ? ${Bv(t,`1`)} : ${Bv(n,`0`)})`},"num.eq":e=>e.arg(`epsilon`)===void 0?`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.neq":e=>e.arg(`epsilon`)===void 0?`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.lt":Vv(`<`),"num.lte":Vv(`<=`),"num.gt":Vv(`>`),"num.gte":Vv(`>=`),"num.add":Vv(`+`),"num.sub":Vv(`-`),"num.mul":Vv(`*`),"num.div":Vv(`/`),"num.mod":Vv(`%`),"num.pow":Vv(`**`),"num.abs":Hv(`Math.abs`),"num.neg":e=>`(-${e.self()})`,"num.sign":Hv(`Math.sign`),"num.sqrt":Hv(`Math.sqrt`),"num.min":Hv(`Math.min`,`other`),"num.max":Hv(`Math.max`,`other`),"num.clamp":e=>`Math.min(Math.max(${e.self()}, ${J(e,`min`)}), ${J(e,`max`)})`,"num.floor":Hv(`Math.floor`),"num.ceil":Hv(`Math.ceil`),"num.round":Hv(`Math.round`),"num.isZero":e=>`(Math.abs(${e.self()}) <= 0)`,"num.isPositive":e=>`(${e.self()} > 0)`,"num.isNegative":e=>`(${e.self()} < 0)`,"num.isInteger":Hv(`Number.isInteger`),"num.isEven":e=>`(${e.self()} % 2 === 0)`,"num.isOdd":e=>`(Math.abs(${e.self()}) % 2 === 1)`,"num.toText":e=>e.arg(`precision`)===void 0?`String(${e.self()})`:`${e.helper(`$numText`)}(${e.self()}, ${e.arg(`precision`)})`,"num.toBool":e=>`(${e.self()} !== 0)`,"text.length":Wv(`length`),"text.eq":Vv(`===`),"text.neq":Vv(`!==`),"text.contains":Uv(`includes`,`search`),"text.startsWith":Uv(`startsWith`,`prefix`),"text.endsWith":Uv(`endsWith`,`suffix`),"text.trim":Uv(`trim`),"text.trimStart":Uv(`trimStart`),"text.trimEnd":Uv(`trimEnd`),"text.upper":Uv(`toUpperCase`),"text.lower":Uv(`toLowerCase`),"text.slice":e=>`${e.self()}.slice(${Kv(e,`start`,`end`)})`,"text.replace":e=>`${e.self()}.split(${J(e,`search`)}).join(${J(e,`replacement`)})`,"text.split":Uv(`split`,`separator`),"text.concat":Vv(`+`),"text.repeat":Uv(`repeat`,`count`),"text.indexOf":e=>`${e.self()}.indexOf(${Kv(e,`search`,`from`)})`,"text.lastIndexOf":e=>`${e.self()}.lastIndexOf(${Kv(e,`search`,`from`)})`,"text.match":e=>`(${e.self()}.match(new RegExp(${J(e,`pattern`)}, "g")) ?? [] as string[])`,"text.test":e=>`new RegExp(${J(e,`pattern`)}).test(${e.self()})`,"text.isEmpty":e=>`(${e.self()}.length === 0)`,"text.isNotEmpty":e=>`(${e.self()}.length > 0)`,"text.toNum":Hv(`Number`),"text.toBool":e=>`(${e.self()}.length > 0)`,"list.length":Wv(`length`),"list.at":e=>`${e.helper(`$listAt`)}(${e.self()}, ${J(e,`index`)})`,"list.push":Gv(Uv(`push`,`value`)),"list.pop":Uv(`pop`),"list.shift":Uv(`shift`),"list.unshift":Gv(Uv(`unshift`,`value`)),"list.insert":e=>`void ${e.self()}.splice(${J(e,`index`)}, 0, ${J(e,`value`)})`,"list.remove":e=>`${e.self()}.splice(${J(e,`index`)}, 1)[0]!`,"list.clear":e=>`void (${e.self()}.length = 0)`,"list.slice":e=>`${e.self()}.slice(${Kv(e,`start`,`end`)})`,"list.concat":Uv(`concat`,`other`),"list.reverse":e=>`[...${e.self()}].reverse()`,"list.join":e=>`${e.self()}.map(String).join(${Bv(e.arg(`separator`),`","`)})`,"list.indexOf":Uv(`indexOf`,`value`),"list.contains":e=>`(${e.self()}.indexOf(${J(e,`value`)}) !== -1)`,"list.unique":e=>`[...new Set(${e.self()})]`,"list.duplicates":e=>`${e.helper(`$duplicates`)}(${e.self()})`,"list.map":qv(`map`),"list.filter":qv(`filter`),"list.find":qv(`find`),"list.reduce":qv(`reduce`,`initial`),"list.some":qv(`some`),"list.every":qv(`every`),"list.sort":e=>e.arg(`fn`)===void 0?`${e.helper(`$sortNatural`)}(${e.self()})`:qv(`sort`)(e),"list.isEmpty":e=>`(${e.self()}.length === 0)`,"list.isNotEmpty":e=>`(${e.self()}.length > 0)`,"list.first":e=>`${e.self()}[0]`,"list.last":e=>`${e.self()}.at(-1)`,"map.size":Wv(`size`),"map.at":Uv(`get`,`key`),"map.has":Uv(`has`,`key`),"map.delete":Uv(`delete`,`key`),"map.clear":Gv(Uv(`clear`)),"map.keys":e=>`[...${e.self()}.keys()]`,"map.values":e=>`[...${e.self()}.values()]`,"map.isEmpty":e=>`(${e.self()}.size === 0)`,"map.isNotEmpty":e=>`(${e.self()}.size > 0)`,"object.keys":e=>(e.discard(),JSON.stringify(e.fields())),"object.values":e=>{let t=e.once();return`[${e.fields().map(e=>Qv(t,e)).join(`, `)}]`},"object.entries":e=>{let t=e.once();return`[${e.fields().map(e=>`[${JSON.stringify(e)}, ${Qv(t,e)}] as [string, unknown]`).join(`, `)}]`},"object.has":e=>(e.discard(),`(${JSON.stringify(e.fields())} as string[]).includes(${J(e,`key`)})`),"object.eq":e=>`${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.neq":e=>`!${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.toText":e=>`${e.helper(`$objText`)}(${e.self()} as any, ${JSON.stringify(e.fields())})`,"tuple.length":Wv(`length`),"tuple.first":e=>`${e.self()}[0]`,"tuple.last":e=>{let t=e.once();return`${t}[${t}.length - 1]`},"tuple.toList":e=>`[...${e.self()}]`,"optional.value":e=>`${e.helper(`$optValue`)}(${e.self()})`,"optional.has":e=>`(${e.self()} !== undefined)`,"optional.or":e=>{let t=e.once();return`(${t} !== undefined ? ${t} : ${J(e,`fallback`)})`},"optional.map":Jv(`undefined`),"nullable.value":e=>`${e.helper(`$nullValue`)}(${e.self()})`,"nullable.isNull":e=>`(${e.self()} === null)`,"nullable.or":e=>{let t=e.once();return`(${t} !== null ? ${t} : ${J(e,`fallback`)})`},"nullable.map":Jv(`null`),"enum.name":e=>{let t=ey(e.selfType),n={};for(let[e,r]of Object.entries(t?.options.values??{}))n[String(r)]=e;return`((${JSON.stringify(n)} as Record<string, string>)[String(${e.self()})] ?? "")`},"enum.value":e=>e.self(),"enum.eq":Vv(`===`),"enum.neq":Vv(`!==`),"enum.toText":e=>`String(${e.self()})`,"date.year":Uv(`getUTCFullYear`),"date.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"date.day":Uv(`getUTCDate`),"date.dayOfWeek":Uv(`getUTCDay`),"date.dayOfYear":e=>`${e.helper(`$date`)}.dayOfYear(${e.self()})`,"date.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"date.neq":e=>`(${e.self()}.getTime() !== ${J(e,`other`)}.getTime())`,"date.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"date.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"date.addDays":e=>`${e.helper(`$date`)}.addDays(${e.self()}, ${J(e,`days`)})`,"date.addMonths":e=>`${e.helper(`$date`)}.addMonths(${e.self()}, ${J(e,`months`)})`,"date.addYears":e=>`${e.helper(`$date`)}.addYears(${e.self()}, ${J(e,`years`)})`,"date.diffDays":e=>`${e.helper(`$date`)}.diffDays(${e.self()}, ${J(e,`other`)})`,"date.diffMonths":e=>`${e.helper(`$date`)}.diffMonths(${e.self()}, ${J(e,`other`)})`,"date.diffYears":e=>`(${e.self()}.getUTCFullYear() - ${J(e,`other`)}.getUTCFullYear())`,"date.toText":e=>`${e.self()}.toISOString().slice(0, 10)`,"timestamp.year":Uv(`getUTCFullYear`),"timestamp.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"timestamp.day":Uv(`getUTCDate`),"timestamp.hour":Uv(`getUTCHours`),"timestamp.minute":Uv(`getUTCMinutes`),"timestamp.second":Uv(`getUTCSeconds`),"timestamp.millisecond":Uv(`getUTCMilliseconds`),"timestamp.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"timestamp.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"timestamp.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"timestamp.addDuration":e=>`new Date(${e.self()}.getTime() + ${J(e,`duration`)})`,"timestamp.subDuration":e=>`new Date(${e.self()}.getTime() - ${J(e,`duration`)})`,"timestamp.diff":e=>`(${e.self()}.getTime() - ${J(e,`other`)}.getTime())`,"timestamp.toDate":e=>`${e.helper(`$date`)}.toDate(${e.self()})`,"timestamp.toEpoch":Uv(`getTime`),"timestamp.toText":Uv(`toISOString`),"duration.init":e=>`${e.helper(`$duration`)}.init(${e.self()})`,"duration.totalSeconds":e=>`(${e.self()} / 1000)`,"duration.totalMinutes":e=>`(${e.self()} / 60000)`,"duration.totalHours":e=>`(${e.self()} / 3600000)`,"duration.totalDays":e=>`(${e.self()} / 86400000)`,"duration.days":e=>`Math.trunc(${e.self()} / 86400000)`,"duration.hours":e=>`(Math.trunc(${e.self()} / 3600000) % 24)`,"duration.minutes":e=>`(Math.trunc(${e.self()} / 60000) % 60)`,"duration.seconds":e=>`(Math.trunc(${e.self()} / 1000) % 60)`,"duration.ms":e=>`(${e.self()} % 1000)`,"duration.toText":e=>`${e.helper(`$duration`)}.toText(${e.self()})`,"color.init":e=>`${e.helper(`$color`)}.init(${e.self()})`,"color.hue":e=>`${e.helper(`$color`)}.hsl(${e.self()}).h`,"color.saturation":e=>`${e.helper(`$color`)}.hsl(${e.self()}).s`,"color.lightness":e=>`${e.helper(`$color`)}.hsl(${e.self()}).l`,"color.eq":Vv(`===`),"color.neq":Vv(`!==`),"color.lighten":e=>`${e.helper(`$color`)}.lighten(${e.self()}, ${J(e,`amount`)})`,"color.darken":e=>`${e.helper(`$color`)}.lighten(${e.self()}, -${J(e,`amount`)})`,"color.saturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, ${J(e,`amount`)})`,"color.desaturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, -${J(e,`amount`)})`,"color.opacity":e=>`${e.helper(`$color`)}.opacity(${e.self()}, ${J(e,`alpha`)})`,"color.invert":e=>`${e.helper(`$color`)}.invert(${e.self()})`,"color.mix":e=>`${e.helper(`$color`)}.mix(${e.self()}, ${Kv(e,`other`,`weight`)})`,"color.complement":e=>`${e.helper(`$color`)}.complement(${e.self()})`,"color.toHex":e=>`${e.helper(`$color`)}.toHex(${e.self()})`,"color.toRgb":e=>`${e.helper(`$color`)}.toRgb(${e.self()})`,"color.toHsl":e=>`${e.helper(`$color`)}.toHsl(${e.self()})`,"color.toText":e=>`${e.helper(`$color`)}.toHex(${e.self()})`};for(let e of[`color.r`,`color.g`,`color.b`,`color.a`]){let t=e.slice(-1);Yv[e]=e=>`${e.helper(`$color`)}.${t}(${e.self()})`}var Xv={"list.indexGet":e=>`${e.helper(`$listGet`)}(${e.self}, ${e.key})`,"text.charAt":e=>`${e.helper(`$charAt`)}(${e.self}, ${e.key})`,"map.indexGet":e=>`${e.helper(`$mapGet`)}(${e.self}, ${e.key})`,"object.indexGet":e=>`(${e.self} as any)[${e.key}]`,"tuple.at":e=>`${e.self}[${e.key}]`},Zv={"list.indexSet":e=>`${e.helper(`$listSet`)}(${e.self}, ${e.key}, ${e.value})`,"map.indexSet":e=>`${e.self}.set(${e.key}, ${e.value})`,"object.indexSet":e=>`(${e.self} as any)[${e.key}] = ${e.value}`,"tuple.setAt":e=>`${e.self}[${e.key}] = ${e.value}`};function Qv(e,t){return $v(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function $v(e){return/^[A-Za-z_$][\w$]*$/.test(e)}function ey(e){let t=e;for(let e=0;e<10&&t;e++){if(t instanceof Dg)return t;t=t.base}}var ty=class extends Error{constructor(e){super(`gin \u2192 TypeScript: ${e.length} problem${e.length===1?``:`s`}
370
+ - ${e.join(`
371
+ - `)}`),this.problems=e,this.name=`TypeScriptExportError`}problems},ny=class{constructor(e){this.ctxAllowed=e}ctxAllowed;awaited=!1;loops=[]},ry=new Set(`break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.export.extends.false.finally.for.function.if.import.in.instanceof.new.null.return.super.switch.this.throw.true.try.typeof.var.void.while.with.as.implements.interface.let.package.private.protected.public.static.yield.await.async.undefined.arguments.eval.ctx.args.self.Promise.Math.Number.String.Boolean.Date.Map.Set.Array.Object.JSON.Error.RegExp`.split(`.`)),iy=/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false|null|undefined)$/,ay=class{constructor(e,t={}){this.engine=e,this.registry=e.registry,this.opt={types:t.types??`referenced`,includeComments:t.includeComments??!0,prelude:t.prelude??`separate`,async:t.async??`always`,export:t.export??!1,scope:t.scope??{}},this.names=new zv(this.registry,e=>this.splits(this.decl(e)))}engine;registry;types=new Map;helpers=new Map;problems=new Set;opt;names;defined=new Set;makers=new Map;guards=new Map;used=new Set;ctxVars=new Map;usesExit=!1;get always(){return this.opt.async===`always`}get exp(){return this.opt.export?`export `:``}problem(e){this.problems.add(e)}check(){if(this.problems.size>0)throw new ty([...this.problems])}uniq(e){let t=e.replace(/[^\w$]/g,`_`);/^[A-Za-z_$]/.test(t)||(t=`_`+t),(/^make[A-Z]/.test(t)||/^is[A-Z]/.test(t)||t.startsWith(`$`))&&(t=`_`+t);let n=ry.has(t)||this.used.has(t)?`${t}_1`:t;for(let e=2;this.used.has(n);e++)n=`${t}_${e}`;return this.used.add(n),n}tsName(e){return this.names.type(e)}helper(e){if(this.helpers.has(e))return e;let t=Fv[e];if(!t)throw Error(`gin \u2192 TypeScript: no prelude helper '${e}'`);for(let e of t.deps??[])this.helper(e);return this.helpers.set(e,t.code),e}ref(e,t={generics:new Set}){if(e instanceof Sg){let n=e.options.name;if(t.generics.has(n))return n;let r=e.simplify();if(r!==e&&!(r instanceof Sg))return this.ref(r,t);let i=this.registry.lookup(n);return i&&!(i instanceof Sg)?this.ref(i,t):`any`}if(e instanceof gg)return this.namedRef(e,t);if(e instanceof _g)return`any`;if(e instanceof Yg)return`void`;if(e instanceof zg)return`null`;if(e instanceof Cg)return`boolean`;if(e instanceof Vg||e instanceof Eg||e instanceof wg)return`number`;if(e instanceof Wg)return`string`;if(e instanceof Tg||e instanceof Gg)return`Date`;if(e instanceof Ng)return Cy(this.ref(e.item,t));if(e instanceof Lg)return`Map<${this.ref(e.key,t)}, ${this.ref(e.value,t)}>`;if(e instanceof qg)return`[${e.elements.map(e=>this.ref(e,t)).join(`, `)}]`;if(e instanceof Hg)return Sy([this.ref(e.inner,t),`undefined`]);if(e instanceof Bg)return Sy([this.ref(e.inner,t),`null`]);if(e instanceof Ug)return Sy(e.variants.map(e=>this.ref(e,t)));if(e instanceof bg)return e.parts.map(e=>xy(this.ref(e,t))).join(` & `)||`unknown`;if(e instanceof Dg){let t=Object.values(e.options.values).map(e=>JSON.stringify(e));return t.length?t.join(` | `):`never`}if(e instanceof Mg)return JSON.stringify(e.literal);if(e instanceof Ag){let n=e.call();return n?this.fnSig(n,t,`unknown`,e.generic):`(...args: any[]) => any`}if(e instanceof vg)return this.objLiteralType(Object.entries(e.fields),t);if(e instanceof jg){let n=this.members(Object.entries(e._props),t,void 0);return e._call&&n.push(`(${this.params(e._call.args,t)}): ${this.returns(e._call,t,`unknown`)}`),by(n)}return e instanceof Rg||e instanceof Jg?`unknown`:`any`}decl(e){let t=this.registry.lookup(e.name);return t instanceof gg&&t.name===e.name?t:e}namedRef(e,t,n=!1){if(e.local.useSite)return e.original instanceof gg?this.namedRef(e.original,t,n):this.ref(e.original,t);let r=this.decl(e);this.define(r);let i=n&&this.splits(r)?this.dataName(r):this.tsName(r.name),a=Object.keys(r.generic??{});if(a.length===0)return i;let o=a.map(n=>{let r=e.generic?.[n];return r&&!U.isGenericPlaceholder(n,r)?this.ref(r,t):t.generics.has(n)?n:`any`});return o.every(e=>e===`any`)?i:`${i}<${o.join(`, `)}>`}define(e){if(this.defined.has(e.name))return;this.defined.add(e.name);let t=this.maker(e);this.declaration(e,t)}surface(e){let t=e.definitionProps();return Object.entries(t).map(([e,t])=>[e,jh.from(t)])}definitionCall(e){return e.definitionCall()}splits(e){if(!cy(e.base))return!1;if(this.definitionCall(e)||this.surface(e).some(([,e])=>sy(e)))return!0;let t=e.original;return t instanceof gg&&!t.local.useSite&&this.splits(this.decl(t))}carriedMembers(e){let t=new Map,n=new Set;for(let r=e;r instanceof gg&&!r.local.useSite;r=r.original)for(let[e,i]of this.surface(this.decl(r)))n.has(e)||(n.add(e),sy(i)&&(!i.get||i.get instanceof Ev)&&t.set(e,i));return[...t]}dataName(e){return this.names.dataName(e.name)}declaration(e,t){if(this.opt.types===`none`)return;let n=this.tsName(e.name),r=e.generic??{},i={generics:new Set(Object.keys(r))},a=this.genericParams(r,i);if(!this.splits(e)){this.types.set(n,this.singleDeclaration(e,t));return}let o=Object.keys(r).length?`<${Object.keys(r).join(`, `)}>`:``,s=e.original,c=s instanceof gg&&!s.local.useSite,l=this.surface(e),u=this.members(l.filter(([,e])=>!sy(e)),i,t),d=this.members(l.filter(([,e])=>sy(e)),i,t),f=this.definitionCall(e);f&&d.push(`(${this.params(f.args,i)}): ${this.returns(f,i,`unknown`)}`);let p=this.dataName(e),m=[];c&&m.push(this.namedRef(s,i,!0)),(u.length||m.length===0)&&m.push(by(u));let h=[`The stored fields of ${n}${t?` \u2014 what \`${t.name}\` takes`:``}.`];this.types.set(p,`${this.docBlock(h)}${this.exp}type ${p}${a} = ${m.join(` & `)};`);let ee=[];c&&ee.push(this.namedRef(s,i)),ee.push(`${p}${o}`),d.length&&ee.push(by(d)),this.types.set(n,`${this.docBlock(this.typeDocs(e))}${this.exp}type ${n}${a} = ${ee.join(` & `)};`)}typeDocs(e){let t=[];return e.docs&&t.push(e.docs),e.local.options&&Object.keys(e.local.options).length>0&&t.push(`gin: ${e.base.toCode(void 0,{includeComments:!1})}`),e.local.constraint&&t.push(`constraint: ${e.local.constraint.toCode(this.registry,{expectsValue:!0,includeComments:!1})}`),t}singleDeclaration(e,t){let n=this.tsName(e.name),r=e.generic??{},i={generics:new Set(Object.keys(r))},a=this.genericParams(r,i),o=this.typeDocs(e),s=e.original,c=s instanceof gg&&!s.local.useSite,l=cy(e.base),u=this.definitionCall(e),d=l||c?this.members(this.surface(e),i,t):[];u&&d.push(`(${this.params(u.args,i)}): ${this.returns(u,i,`unknown`)}`);let f;if(c){let e=this.ref(s,i);f=d.length?`${e} & ${by(d)}`:e}else l?f=by(d):(f=this.ref(e.base,i),d.length&&(f=`${xy(f)} & ${by(d)}`));return`${this.docBlock(o)}${this.exp}type ${n}${a} = ${f};`}genericParams(e,t){let n=Object.keys(e);return n.length===0?``:`<${n.map(n=>{let r=e[n];if(U.isGenericPlaceholder(n,r))return`${n} = any`;let i=this.ref(r,t);return`${n} extends ${i} = ${i}`}).join(`, `)}>`}members(e,t,n){let r=[];for(let[i,a]of e){let e=$v(i)?i:JSON.stringify(i),o=[];a.docs&&o.push(a.docs);let s=a.type.call(),c=n?.members.get(i);if(s&&(a.get||a.type instanceof Ag)){let n=c?c.async===!1?`sync`:`async`:this.hostMemberKind(a);r.push(`${this.docLine(o)}${e}: ${this.fnSig(s,t,n,a.type.generic)}`);continue}if(a.get){let n=this.ref(a.type,t);r.push(`${this.docLine(o)}readonly ${e}: ${c?.async===!0?`Promise<${n}>`:n}`);continue}let l=a.type.isOptional(),u=l?a.type.required():a.type,d=_y(u);d&&o.push(d),r.push(`${this.docLine(o)}${e}${l?`?`:``}: ${this.ref(u,t)}`)}return r}hostMemberKind(e){return this.always?`async`:e.get instanceof Ev&&!Yv[e.get.id]?e.get.effects()&(B.EXTERNAL|B.SYSTEM)?`async`:`sync`:e.get instanceof Ev?`sync`:`unknown`}objLiteralType(e,t){return by(this.members(e,t,void 0))}fnSig(e,t,n,r){let i=Object.keys(r??{}),a=i.length?{generics:new Set([...t.generics,...i])}:t;return`${i.length?this.genericParams(r,a):``}(${this.params(e.args,a)}) => ${this.returns(e,a,n)}`}returns(e,t,n){let r=e.returns?this.ref(e.returns,t):`any`;return n===`sync`?r:n===`async`||this.always?`Promise<${r}>`:`${xy(r)} | Promise<${r}>`}params(e,t){if(e instanceof vg){let n=Object.entries(e.fields);return n.length===0?``:`args${n.every(([,e])=>e.type.isOptional()||e.default!==void 0)?`?`:``}: ${this.objLiteralType(n,t)}`}return e instanceof _g||e instanceof Yg?``:`args: ${this.ref(e,t)}`}defParams(e,t){let n=this.params(e,t);return n.startsWith(`args?:`)?`args:${n.slice(6)} = {}`:n}docBlock(e){if(!this.opt.includeComments||e.length===0)return``;let t=e.flatMap(e=>e.split(`
372
+ `));return t.length===1?`/** ${Ty(t[0])} */
373
+ `:`/**
374
+ ${t.map(e=>` * ${Ty(e)}`).join(`
375
+ `)}
376
+ */
377
+ `}docLine(e){return!this.opt.includeComments||e.length===0?``:`/** ${Ty(e.join(` · `).replace(/\n/g,` `))} */ `}maker(e){if(this.makers.has(e.name))return this.makers.get(e.name)??void 0;let t=e.definitionProps(),n=Object.entries(t).map(([e,t])=>[e,jh.from(t)]).filter(([,e])=>e.get&&!(e.get instanceof Ev)),r=e.original instanceof gg&&!e.original.local.useSite?this.maker(this.decl(e.original)):void 0;if(n.length===0&&!r){this.makers.set(e.name,null);return}if(!cy(e.base)){this.problem(`type '${e.name}': members written in gin on a non-object type are not supported`),this.makers.set(e.name,null);return}let i={name:`make${this.tsName(e.name)}`,members:new Map(r?.members??[])};for(let[e,t]of n)i.members.set(e,{kind:t.type.call()?`method`:`computed`,async:`pending`});this.makers.set(e.name,i);let a=e.generic??{},o={generics:new Set(Object.keys(a))},s=this.genericParams(a,o),c=Object.keys(a).length?`<${Object.keys(a).join(`, `)}>`:``,l=`${this.tsName(e.name)}${c}`;this.define(e);let u=new Set(this.used);this.used.clear();let d=`self`,f=[];f.push(r?`const ${d} = ${r.name}(data) as ${l};`:`const ${d} = data as ${l};`);for(let[t,r]of n){let n=new ny(!1),a=[],s=new Map([[`this`,{ts:d,type:e}]]),c=r.type.call();if(c){let e=this.uniq(t);s.set(`args`,{ts:`args`,type:c.args}),s.set(`recurse`,{ts:e,type:r.type}),this.stmt(r.get,s,n,a,{kind:`return`});let l=this.always||n.awaited;i.members.set(t,{kind:`method`,async:l});let u=this.defParams(c.args,o);f.push(`${Qv(d,t)} = ${l?`async `:``}function ${e}(${u}) {`),f.push(...vy(a),`};`)}else this.stmt(r.get,s,n,a,{kind:`return`}),i.members.set(t,{kind:`computed`,async:n.awaited}),f.push(`Object.defineProperty(${d}, ${JSON.stringify(t)}, {`),f.push(` get: ${n.awaited?`async `:``}() => {`,...vy(vy(a)),` },`),f.push(` enumerable: false,`,` configurable: true,`,`});`)}f.push(`return ${d};`),this.used.clear();for(let e of u)this.used.add(e);let p=this.members(this.carriedMembers(e),o,i),m=`${this.dataName(e)}${c}${p.length?` & ${by(p)}`:``}`,h=[`/** Attach ${e.name}'s gin-written members to its data. */`,`${this.exp}function ${i.name}${s}(data: ${m}): ${l} {`,...vy(f),`}`].join(`
378
+ `);return this.helpers.set(i.name,h),this.declaration(e,i),i}guard(e){let t=this.ref(e),n=t,r=this.guards.get(n);if(r)return r;let i=e instanceof gg?`$is${this.tsName(this.decl(e).name)}`:`$is_${Oy(t)}`;this.guards.set(n,i);let a=this.checkExpr(e,`v`,0,!0);return this.helpers.set(i,`function ${i}(v: unknown): v is ${t} {
379
+ return ${a};
380
+ }`),i}checkExpr(e,t,n,r=!1){let i=`x${n}`;if(e instanceof Sg){let r=e.simplify();return r===e?`true`:this.checkExpr(r,t,n)}if(e instanceof gg)return r?this.checkExpr(e.base,t,n):`${this.guard(e)}(${t})`;if(e instanceof Vg||e instanceof Eg||e instanceof wg)return`typeof ${t} === "number"`;if(e instanceof Wg)return`typeof ${t} === "string"`;if(e instanceof Cg)return`typeof ${t} === "boolean"`;if(e instanceof zg)return`${t} === null`;if(e instanceof Yg)return`${t} === undefined`;if(e instanceof Tg||e instanceof Gg)return`${t} instanceof Date`;if(e instanceof Ag)return`typeof ${t} === "function"`;if(e instanceof Lg)return`${t} instanceof Map`;if(e instanceof Ng){let r=this.checkExpr(e.item,i,n+1);return r===`true`?`Array.isArray(${t})`:`(Array.isArray(${t}) && ${t}.every((${i}: unknown) => ${r}))`}if(e instanceof qg){let r=e.elements.map((e,r)=>this.checkExpr(e,`${t}[${r}]`,n+1));return`(Array.isArray(${t}) && ${t}.length === ${e.elements.length}${r.map(e=>` && ${e}`).join(``)})`}if(e instanceof Hg)return`(${t} === undefined || ${this.checkExpr(e.inner,t,n)})`;if(e instanceof Bg)return`(${t} === null || ${this.checkExpr(e.inner,t,n)})`;if(e instanceof Ug)return`(${e.variants.map(e=>this.checkExpr(e,t,n)).join(` || `)})`;if(e instanceof bg)return`(${e.parts.map(e=>this.checkExpr(e,t,n)).join(` && `)})`;if(e instanceof Dg)return`${JSON.stringify(Object.values(e.options.values))}.includes(${t} as any)`;if(e instanceof Mg)return`${t} === ${JSON.stringify(e.literal)}`;if(e instanceof vg||e instanceof jg){let r=e instanceof vg?Object.entries(e.fields):Object.entries(e._props),i=[`typeof ${t} === "object"`,`${t} !== null`];for(let[e,a]of r){if(a.get||a.type.call())continue;let r=`(${t} as any)${$v(e)?`.`+e:`[${JSON.stringify(e)}]`}`;i.push(a.type.isOptional()?`(${r} === undefined || ${this.checkExpr(a.type.required(),r,n+1)})`:this.checkExpr(a.type,r,n+1))}return`(${i.join(` && `)})`}return`true`}exportFunction(e,t){this.ctxVars=new Map,this.usesExit=!1,(!$v(t)||ry.has(t))&&this.problem(`'${t}' is not usable as a function name`);let n=t;this.used.add(t);let r=new ny(!0),i=[],a=[],o=``;if(e instanceof bv){let t=e.fnType.call(),s={generics:new Set(Object.keys(e.fnType.generic??{}))},c=new Map([[`args`,{ts:`args`,type:t?.args??this.registry.obj({})}],[`recurse`,{ts:n,type:e.fnType}]]);e.constraint&&this.constraint(e.constraint,c,r,i),this.stmt(e.body,c,r,i,{kind:`return`}),a=[(t?this.defParams(t.args,s):``)||`args: {} = {}`],t?.returns&&(o=this.ref(t.returns,s))}else this.stmt(e,new Map,r,i,{kind:`return`});let s=this.always||r.awaited;if(this.ctxVars.size>0){let e=this.names.fresh(`${Dy(t)}Ctx`),n=[...this.ctxVars].map(([e,t])=>{let n=this.engine.getGlobal(e),r=n?.docs?[n.docs]:[];return`${this.docLine(r)}${$v(e)?e:JSON.stringify(e)}: ${this.ref(t)}`});this.types.set(e,`${this.docBlock([`Free variables ${t} reads (engine globals and run extras).`])}${this.exp}type ${e} = ${by(n)};`),a.push(`ctx: ${e}`)}let c=i;if(this.usesExit){let e=this.helper(`$Exit`);c=[`try {`,...vy(i),`} catch ($exit) {`,` if ($exit instanceof ${e}) return $exit.value as any;`,` throw $exit;`,`}`]}let l=o?`: ${s?`Promise<${o}>`:o}`:``;return[`${e.comment?this.docBlock([e.comment]):``}${this.exp}${s?`async `:``}function ${n}(${a.join(`, `)})${l} {`,...vy(c),`}`].join(`
381
+ `)}constraint(e,t,n,r){let i=this.val(e,t,n,r),a=JSON.stringify(`lambda constraint failed: ${e.toCode(this.registry,{expectsValue:!0,includeComments:!1})}`);r.push(`if (${i.code} !== true) throw new Error(${a});`)}stmt(e,t,n,r,i){if(e.comment&&this.opt.includeComments&&r.push(...e.comment.split(`
382
+ `).map(e=>`// ${e}`)),e instanceof fv){if(e.lines.length===0)return this.finish(`undefined`,r,i,!0);e.lines.forEach((a,o)=>this.stmt(a,t,n,r,o===e.lines.length-1?i:{kind:`discard`}));return}if(e instanceof uv){let a=this.defineVars(e,t,n,r);return this.stmt(e.body,a,n,r,i)}if(e instanceof gv)return this.ifStmt(e,t,n,r,i);if(e instanceof _v)return this.switchStmt(e,t,n,r,i);if(e instanceof vv){this.loop(e,t,n,r),i.kind===`assign`&&r.push(`${i.name} = undefined;`);return}if(e instanceof pv)return this.flow(e,t,n,r);if(e instanceof lv)return this.set(e,t,n,r),this.finish(`true`,r,i,!0);let a=this.val(e,t,n,r);this.finish(a.code,r,i,a.pure)}finish(e,t,n,r){n.kind===`return`?e!==`undefined`&&t.push(`return ${wy(e)};`):n.kind===`assign`?t.push(`${n.name} = ${wy(e)};`):r||t.push(`${wy(e)};`)}defineVars(e,t,n,r){let i=new Map(t);for(let t of e.vars){let e=this.val(t.value,i,n,r),a=this.uniq(t.name),o=t.type??e.type,s=t.type?`: ${this.ref(t.type)}`:``;r.push(`let ${a}${s} = ${wy(e.code)};`),i.set(t.name,{ts:a,type:o,sync:e.sync})}return i}ifStmt(e,t,n,r,i){let a=(r,o)=>{if(r>=e.ifs.length){e.otherwise&&this.stmt(e.otherwise,t,n,o,i);return}let s=e.ifs[r],c=this.val(s.condition,t,n,o),l=[];this.stmt(s.body,t,n,l,i),o.push(`if (${wy(c.code)}) {`,...vy(l),`}`);let u=[];a(r+1,u),u.length!==0&&(u[0].startsWith(`if (`)&&yy(u)?(o[o.length-1]=`} else ${u[0]}`,o.push(...u.slice(1))):(o[o.length-1]=`} else {`,o.push(...vy(u),`}`)))};a(0,r)}switchStmt(e,t,n,r,i){let a=this.spill(this.val(e.value,t,n,r),r,`sw`),o=[];if(e.cases.forEach((e,r)=>{let s=[],c=e.equals.map(e=>this.val(e,t,n,s).code);s.length&&this.problem(`switch: a case value that needs statements is not supported`);let l=[];this.stmt(e.body,t,n,l,i);let u=c.length?c.map(e=>`${a} === ${e}`).join(` || `):`false`;o.push(`${r===0?`if`:`} else if`} (${u}) {`,...vy(l))}),e.otherwise){let a=[];if(this.stmt(e.otherwise,t,n,a,i),o.length===0){r.push(...a);return}o.push(`} else {`,...vy(a))}o.length&&r.push(...o,`}`)}flow(e,t,n,r){let i=n.loops[n.loops.length-1];switch(e.action){case`break`:i===`for`?r.push(`break;`):this.problem(i===`parallel`?`flow: break inside a parallel loop is not supported`:`flow: break outside a loop`);return;case`continue`:i===`for`?r.push(`continue;`):i===`parallel`?r.push(`return;`):this.problem(`flow: continue outside a loop`);return;case`return`:{i===`parallel`&&this.problem(`flow: return inside a parallel loop is not supported`);let a=e.value?this.val(e.value,t,n,r).code:void 0;r.push(a&&a!==`undefined`?`return ${wy(a)};`:`return;`);return}case`exit`:{let i=e.value?this.val(e.value,t,n,r).code:`undefined`;this.usesExit=!0,r.push(`throw new ${this.helper(`$Exit`)}(${wy(i)});`);return}case`throw`:{let i=e.error?this.val(e.error,t,n,r).code:`undefined`;r.push(`throw new ${this.helper(`$Throw`)}(${wy(i)});`);return}}}loop(e,t,n,r){let i=this.registry.any(),a=this.typeOfExpr(e.over,t),o=a.get(),s=o?.loop instanceof Ev?o.loop.id:void 0,c=e.keyName??`key`,l=e.valueName??`value`,u=this.uniq(c),d=this.uniq(l),f=new Map(t);if(f.set(c,{ts:u,type:o?.key??i}),f.set(l,{ts:d,type:o?.value??i}),e.parallel)return this.parallelLoop(e,t,n,r,f,s,u,d,!!o?.loopDynamic);let p=[];if(n.loops.push(`for`),this.stmt(e.body,f,n,p,{kind:`discard`}),n.loops.pop(),o?.loopDynamic){let i=[],a=this.val(e.over,t,n,i);r.push(`for (let ${u} = 0; ; ${u}++) {`,...vy(i),` const ${d} = ${wy(a.code)};`,` if (!${d}) break;`,...vy(p),`}`);return}let m=this.spill(this.val(e.over,t,n,r),r,`over`);switch(s){case`list.iterate`:case`tuple.iterate`:r.push(`for (let ${u} = 0; ${u} < ${m}.length; ${u}++) {`,` const ${d} = ${m}[${u}];`,...vy(p),`}`);return;case`text.chars`:r.push(`for (let ${u} = 0; ${u} < ${m}.length; ${u}++) {`,` const ${d} = ${m}[${u}]!;`,...vy(p),`}`);return;case`map.iterate`:r.push(`for (const [${u}, ${d}] of ${m}) {`,...vy(p),`}`);return;case`num.loop`:{let e=this.uniq(`count`);r.push(`for (let ${u} = 0, ${e} = Math.abs(Math.trunc(${m})); ${u} < ${e}; ${u}++) {`,` const ${d} = ${m} < 0 ? -${u} : ${u};`,...vy(p),`}`);return}case`object.iterate`:{let e=JSON.stringify(uy(a));r.push(`for (const ${u} of ${e}) {`,` const ${d} = (${m} as any)[${u}];`,` if (${d} === undefined) continue;`,...vy(p),`}`);return}default:this.problem(`loop: iterating '${a.toCode()}' is not supported (only built-in iterables)`)}}parallelLoop(e,t,n,r,i,a,o,s,c){if(c){this.problem(`loop: a parallel while-loop is not supported`);return}let l=e.parallel?.concurrent?this.val(e.parallel.concurrent,t,n,r).code:`undefined`,u=e.parallel?.rate?this.val(e.parallel.rate,t,n,r).code:`undefined`,d=this.typeOfExpr(e.over,t),f=this.spill(this.val(e.over,t,n,r),r,`over`),p;switch(a){case`list.iterate`:case`tuple.iterate`:p=`${f}.entries()`;break;case`text.chars`:p=`${f}.split("").entries()`;break;case`map.iterate`:p=f;break;case`num.loop`:p=`Array.from({ length: Math.abs(Math.trunc(${f})) }, (_, i) => [i, ${f} < 0 ? -i : i] as [number, number])`;break;case`object.iterate`:p=`${JSON.stringify(uy(d))}.map((f) => [f, (${f} as any)[f]] as [string, any]).filter((e) => e[1] !== undefined)`;break;default:this.problem(`loop: iterating '${d.toCode()}' is not supported (only built-in iterables)`);return}let m=[],h=new ny(n.ctxAllowed);h.loops.push(`parallel`),this.stmt(e.body,i,h,m,{kind:`discard`}),n.awaited=!0,r.push(`await ${this.helper(`$parallel`)}(${p}, ${l}, ${u}, async (${o}, ${s}) => {`,...vy(m),`});`)}val(e,t,n,r){if(e instanceof W_)return this.newValue(e,t,n,r);if(e instanceof cv)return this.path(e.path.steps,t,n,r);if(e instanceof lv)return this.set(e,t,n,r),{code:`true`,type:this.registry.bool(),pure:!0};if(e instanceof bv)return this.lambda(e,t,n);if(e instanceof wv)return this.template(e,t,n,r);if(e instanceof fv){if(e.lines.length===0)return{code:`undefined`,type:this.registry.void(),pure:!0};for(let i of e.lines.slice(0,-1))this.stmt(i,t,n,r,{kind:`discard`});return this.val(e.lines[e.lines.length-1],t,n,r)}if(e instanceof uv)return this.val(e.body,this.defineVars(e,t,n,r),n,r);if(e instanceof gv)return this.ifValue(e,t,n,r);if(e instanceof _v||e instanceof vv){let i=this.uniq(`v`);return r.push(`let ${i};`),this.stmt(e,t,n,r,{kind:`assign`,name:i}),{code:i,type:this.typeOfExpr(e,t),pure:!0}}return e instanceof pv?(this.flow(e,t,n,r),{code:`undefined as never`,type:this.registry.void(),pure:!0}):e instanceof Ev?(this.problem(`native '${e.id}' used directly as an expression is not supported`),{code:`undefined as any`,type:this.registry.any(),pure:!0}):(this.problem(`expression kind '${e.kind}' is not supported`),{code:`undefined as any`,type:this.registry.any(),pure:!0})}ifValue(e,t,n,r){let i=[],a=e.ifs.map(e=>{let r=[],a=this.val(e.condition,t,n,r),o=[],s=this.val(e.body,t,n,o);return i.push(r,o),{cb:r,c:a,bb:o,v:s}}),o=[],s=e.otherwise?this.val(e.otherwise,t,n,o):void 0;i.push(o);let c=this.typeOfExpr(e,t);if(i.every(e=>e.length===0)){let e=s?s.code:`undefined`;for(let t=a.length-1;t>=0;t--)e=`${a[t].c.code} ? ${a[t].v.code} : ${e}`;return{code:`(${e})`,type:c,pure:a.every(e=>e.c.pure&&e.v.pure)&&(s?.pure??!0)}}let l=this.uniq(`v`);r.push(`let ${l};`);let u=(e,t)=>{if(e>=a.length){s&&t.push(...o,`${l} = ${wy(s.code)};`);return}let n=a[e];t.push(...n.cb,`if (${wy(n.c.code)}) {`,...vy([...n.bb,`${l} = ${wy(n.v.code)};`]),`}`);let r=[];u(e+1,r),r.length&&(t[t.length-1]=`} else {`,t.push(...vy(r),`}`))};return u(0,r),{code:l,type:c,pure:!0}}template(e,t,n,r){let i=this.registry.text(),a=e.params?this.val(e.params,t,n,r):void 0,o=a?this.spill(a,r,`params`):void 0,s=e.template instanceof W_&&typeof e.template.value==`string`?e.template.value:void 0;if(s===void 0){let a=this.val(e.template,t,n,r);return{code:`${this.helper(`$template`)}(${a.code}, ${o??`undefined`} as any)`,type:i,pure:!1}}let c=a?dy(a.type):void 0,l="`",u=0;for(let e of s.matchAll(/\{(\w+)\}/g)){l+=Ey(s.slice(u,e.index)),u=e.index+e[0].length;let r=e[1],i;if(o&&c?.has(r))i={code:Qv(o,r),type:c.get(r)};else if(o&&!c)i={code:`(${o} as any)[${JSON.stringify(r)}]`,type:this.registry.any()};else{let e=this.lookup(r,t,n);e&&(i={code:e.ts,type:e.type})}i&&(l+="${"+(py(i.type)?i.code:`${this.helper(`$str`)}(${i.code})`)+`}`)}return l+=Ey(s.slice(u))+"`",{code:l,type:i,pure:!0}}lambda(e,t,n){let r=e.fnType.call(),i={generics:new Set(Object.keys(e.fnType.generic??{}))},a=this.uniq(`recurse`),o=new ny(n.ctxAllowed),s=new Map(t);s.set(`args`,{ts:`args`,type:r?.args??this.registry.obj({})}),s.set(`recurse`,{ts:a,type:e.fnType});let c=[];e.constraint&&this.constraint(e.constraint,s,o,c),this.stmt(e.body,s,o,c,{kind:`return`});let l=this.always||o.awaited,u=r?this.defParams(r.args,i):``,d=r?.returns?`: ${l?`Promise<${this.ref(r.returns,i)}>`:this.ref(r.returns,i)}`:``,f=Object.keys(e.fnType.generic??{}).length?this.genericParams(e.fnType.generic,i):``,p=c.some(e=>RegExp(`\\b${a.replace(/\$/g,`\\$`)}\\b`).test(e)),m;if(p)m=[`${l?`async `:``}function ${a}${f}(${u})${d} {`,...vy(c),`}`].join(`
383
+ `);else if(c.length===1&&c[0].startsWith(`return `)&&!c[0].includes(`
384
+ `)){let e=c[0].slice(7,-1);e.startsWith(`{`)&&(e=`(${e})`),m=`${l?`async `:``}${f}(${u})${d} => ${e}`}else m=[`${l?`async `:``}${f}(${u})${d} => {`,...vy(c),`}`].join(`
385
+ `);return{code:`(${m})`,type:e.fnType,pure:!0,sync:!l}}newValue(e,t,n,r){let i=e.type,a=i.init();if(e.value!==void 0&&a){let t=a.run instanceof Ev?a.run.id:void 0;if(t!==`duration.init`&&t!==`color.init`)return this.problem(`new ${i.toCode()}: a constructor written in gin is not supported`),{code:`undefined as any`,type:i,pure:!0};let n=this.literal(a.args.parse(e.value).toLogical(),a.args);return{code:`${this.helper(t===`duration.init`?`$duration`:`$color`)}.init(${n})`,type:i,pure:!0}}if(e.value===void 0){let e=this.construct(i,this.literal(new W(i,i.create()).toLogical(),i));return{code:e,type:i,pure:!e.startsWith(`make`)}}let o=this.fill(e.value,i,t,n,r);return{code:o.code,type:i,pure:o.pure}}fill(e,t,n,r,i){let a=e instanceof $m?e:Ah(e,t.scope??this.registry);if(a){let e=this.val(a,n,r,i);return{code:e.code,pure:e.pure}}if(!hy(e,this.registry))try{let n=this.construct(t,this.literal(t.parse(e).toLogical(),t));return{code:n,pure:!n.startsWith(`make`)}}catch(e){return this.problem(`new ${t.toCode()}: ${e instanceof Error?e.message:String(e)}`),{code:`undefined as any`,pure:!0}}if(t instanceof Sg)return this.fill(e,t.simplify(),n,r,i);if(t instanceof Hg||t instanceof Bg)return e===void 0?{code:`undefined`,pure:!0}:e===null?{code:`null`,pure:!0}:this.fill(e,t.inner,n,r,i);let o=e=>this.ordered(e.map(([e,t,i])=>a=>{let o=this.fill(t,i,n,r,a);return{code:o.code,pure:o.pure,key:e}}),i);if(t instanceof Ng&&Array.isArray(e))return{code:`[${o(e.map(e=>[void 0,e,t.item])).map(e=>e.code).join(`, `)}]`,pure:!1};if(t instanceof qg&&Array.isArray(e))return{code:`[${o(e.map((e,n)=>[void 0,e,t.elements[n]??this.registry.any()])).map(e=>e.code).join(`, `)}] as ${this.ref(t)}`,pure:!1};if(t instanceof Lg&&Array.isArray(e)){let n=[];for(let r of e){let[e,i]=Array.isArray(r)?r:[r?.key,r?.value];n.push([void 0,e,t.key],[void 0,i,t.value])}let r=o(n),i=[];for(let e=0;e<r.length;e+=2)i.push(`[${r[e].code}, ${r[e+1].code}]`);return{code:`new Map<${this.ref(t.key)}, ${this.ref(t.value)}>([${i.join(`, `)}])`,pure:!1}}let s=ly(t);if(s&&e&&typeof e==`object`&&!Array.isArray(e)){let a=e,c=[],l=[];for(let[e,t]of s)e in a?c.push([e,a[e],t.type]):t.default&&l.push([e,t.default]);let u=o(c);for(let[e,t]of l)u.push({key:e,code:this.val(t,n,r,i).code});let d=u.map(e=>`${$v(e.key)?e.key:JSON.stringify(e.key)}: ${e.code}`);return{code:this.construct(t,`{ ${d.join(`, `)} }`),pure:!1}}return this.problem(`new ${t.toCode()}: payload shape not supported`),{code:`undefined as any`,pure:!0}}construct(e,t){let n=e instanceof gg&&!e.local.useSite?this.decl(e):void 0;if(n){this.define(n);let e=this.carriedMembers(n).map(([e])=>e);e.length&&this.problem(`new ${n.name}: its host member${e.length>1?`s`:``} ${e.join(`, `)} cannot be supplied in TypeScript \u2014 build the value on the host (\`make${this.tsName(n.name)}\` / \`${this.dataName(n)}\`) and pass it in`);let r=this.maker(n);if(r)return`${r.name}(${t})`}return t.startsWith(`[`)||t.startsWith(`{`)||n?`(${t} as ${this.ref(e)})`:t}literal(e,t){if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`number`)return Object.is(e,-0)?`-0`:Number.isFinite(e)?String(e):e>0?`Infinity`:e<0?`-Infinity`:`NaN`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(e instanceof Date)return`new Date(${JSON.stringify(e.toISOString())})`;let n=t instanceof gg?t.base:t instanceof Hg||t instanceof Bg?t.inner:t;if(e instanceof Map){let t=n instanceof Lg?n.key:this.registry.any(),r=n instanceof Lg?n.value:this.registry.any(),i=[...e].map(([e,n])=>`[${this.literal(e,t)}, ${this.literal(n,r)}]`);return`new Map<${this.ref(t)}, ${this.ref(r)}>([${i.join(`, `)}])`}if(Array.isArray(e)){if(n instanceof qg)return`[${e.map((e,t)=>this.literal(e,n.elements[t]??this.registry.any())).join(`, `)}]`;let t=n instanceof Ng?n.item:this.registry.any();return`[${e.map(e=>this.literal(e,t)).join(`, `)}]`}if(typeof e==`object`){let n=new Map(ly(t)??[]);return`{ ${Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${$v(e)?e:JSON.stringify(e)}: ${this.literal(t,n.get(e)?.type??this.registry.any())}`).join(`, `)} }`}return`undefined`}set(e,t,n,r){let i=e.path.steps,a=this.val(e.value,t,n,r);if(i.length===1&&i[0]instanceof nv){let e=i[0].prop,o=this.lookup(e,t,n);if(!o){this.problem(`set: unknown variable '${e}'`);return}r.push(`${o.ts} = ${wy(a.code)};`);return}let o=iy.test(a.code)?a.code:this.spill(a,r,`value`),s=i[i.length-1];if(s instanceof rv){this.problem(`set: assigning through a method call is not supported`);return}let c=this.path(i.slice(0,-1),t,n,r);if(s instanceof nv){let e=c.type.prop(s.prop);if(e?.set){this.problem(`set: prop '${s.prop}' has a gin setter, which is not supported`);return}if(e?.get&&!e.type.call()){this.problem(`set: prop '${s.prop}' is computed and cannot be assigned`);return}r.push(`${Qv(c.code,s.prop)} = ${o};`)}else if(s instanceof iv){let e=this.val(s.key,t,n,r).code,i=c.type.get(),a=i?.set instanceof Ev?i.set.id:void 0,l=a?Zv[a]:void 0;if(!l){this.problem(`set: indexed assignment on '${c.type.toCode()}' is not supported`);return}r.push(`${l({self:c.code,key:e,value:o,helper:e=>this.helper(e)})};`)}}lookup(e,t,n){let r=t.get(e);if(r)return r;let i=this.engine.getGlobal(e),a=this.opt.scope[e]??i?.type;if(a)return n.ctxAllowed?(this.ctxVars.set(e,a),{ts:Qv(`ctx`,e),type:a}):(this.problem(`'${e}' is read inside a gin-written member, where only this / args / recurse are in scope`),{ts:`undefined as any`,type:a})}path(e,t,n,r){let i;for(let a=0;a<e.length;a++){let o=e[a];if(o instanceof nv){if(!i){let e=this.lookup(o.prop,t,n);e?i={code:e.ts,type:e.type,pure:!0,sync:e.sync}:(this.problem(`unknown variable '${o.prop}'`),i={code:`undefined as any`,type:this.registry.any(),pure:!0});continue}this.touch(i.type);let s=i.type.prop(o.prop);if(!s){this.problem(`no prop '${o.prop}' on '${i.type.toCode()}' (the TypeScript export dispatches on the static type)`),i={code:Qv(i.code,o.prop),type:this.registry.any(),pure:!1};continue}let c=s.type instanceof Sg?s.type.simplify(i.type.scope):s.type,l=e[a+1];if(l instanceof rv&&c.call()){i=this.invoke(i,o.prop,s,c,l,t,n,r),a++;continue}if(!(l instanceof rv)&&oy(c)){i=this.invoke(i,o.prop,s,c,new rv({}),t,n,r);continue}i=this.readProp(i,o.prop,s,c,n,r)}else{if(!i)return this.problem(`path: must start with a variable`),{code:`undefined as any`,type:this.registry.any(),pure:!0};if(o instanceof iv){this.touch(i.type);let e=i,a=[],s=this.val(o.key,t,n,a),c=a.length||!s.pure?this.spill(e,r,`recv`):e.code;r.push(...a);let l=e.type.get(),u=l?.get instanceof Ev?l.get.id:void 0,d=u?Xv[u]:void 0;d||this.problem(`indexing '${e.type.toCode()}' is not supported`),i={code:d?d({self:c,key:s.code,helper:e=>this.helper(e)}):`undefined as any`,type:l?.value??this.registry.any(),pure:!1}}else if(o instanceof rv){let e=i.type,a=e.scope;try{a=o.callSiteScope(e)}catch(e){this.problem(String(e instanceof Error?e.message:e))}let s=e.call(a);s?.get&&this.problem(`calling a '${e.toCode()}' value implemented in gin is not supported`);let{recv:c,args:l}=this.orderedArgs(i,o.args,t,n,r),u=`${c}(${gy(l,s)})`;i.sync!==!0&&(u=this.aw(u,n));let d=s?.returns?.simplify(a)??s?.returns??this.registry.any();i=o.catch_?this.withCatch(u,o.catch_,d,t,n,r):{code:u,type:d,pure:!1}}}}return i??{code:`undefined as any`,type:this.registry.any(),pure:!0}}touch(e){e instanceof gg&&!e.local.useSite&&this.define(this.decl(e))}readProp(e,t,n,r,i,a){let o=n.get instanceof Ev?n.get.id:void 0,s=o?Yv[o]:void 0;if(s)return{code:s(this.nativeCtx(e,{},void 0,i,a)),type:r,pure:e.pure};let c=Qv(e.code,t);return n.get&&this.memberAsync(e.type,t,n,`computed`)&&(c=this.aw(c,i)),{code:c,type:r,pure:e.pure&&!n.get}}invoke(e,t,n,r,i,a,o,s){let c=r.scope;try{c=i.callSiteScope(r)}catch(e){this.problem(String(e instanceof Error?e.message:e))}let l=r.call(c),u=l?.returns?.simplify(c)??l?.returns??this.registry.any(),d=n.get instanceof Ev?n.get.id:void 0,f=d?Yv[d]:void 0,{recv:p,args:m}=this.orderedArgs(e,i.args,a,o,s),h;if(f){let t=i.generic?.T?this.registry.parse(i.generic.T,c):void 0;h=f(this.nativeCtx({...e,code:p},m,t,o,s))}else h=`${Qv(p,t)}(${gy(m,l)})`,this.memberAsync(e.type,t,n,`method`)&&(h=this.aw(h,o));return i.catch_?this.withCatch(h,i.catch_,u,a,o,s):{code:h,type:u,pure:!!f&&e.pure&&Object.values(m).every(e=>e.pure)&&!(d&&my(d))}}memberAsync(e,t,n,r){if(n.get&&!(n.get instanceof Ev)){let n=e instanceof gg?this.decl(e):void 0,i=this.findMember(n,t);return i?i.async!==!1:r===`method`}return r!==`computed`&&this.hostMemberKind(n)!==`sync`}findMember(e,t){for(let n=e;n instanceof gg;n=n.original){let e=this.makers.get(this.decl(n).name)?.members.get(t);if(e)return e}}orderedArgs(e,t,n,r,i){let a=Object.entries(t).map(([e,t])=>{let i=[];return{k:e,r:this.val(t,n,r,i),buf:i}}),o=a.some(e=>e.buf.length>0||!e.r.pure),s=o&&!iy.test(e.code)?this.spill(e,i,`recv`):e.code,c={};for(let e of a)i.push(...e.buf),c[e.k]=o&&!e.r.pure&&e.r.sync===void 0?{...e.r,code:this.spill(e.r,i,e.k),pure:!0}:e.r;return{recv:s,args:c}}ordered(e,t){let n=e.map(e=>{let t=[];return{r:e(t),buf:t}}),r=n.reduce((e,t,n)=>t.buf.length?n:e,-1);return n.map((e,n)=>{if(t.push(...e.buf),n<r&&!e.r.pure&&!iy.test(e.r.code)){let n=this.uniq(`slot`);return t.push(`const ${n} = ${wy(e.r.code)};`),{...e.r,code:n,pure:!0}}return e.r})}nativeCtx(e,t,n,r,i){let a=e.code,o={};for(let[e,n]of Object.entries(t))o[e]=n.code;return{self:()=>a,once:()=>($v(a)||(a=this.spill({...e,code:a},i,`recv`)),a),discard:()=>{e.pure||i.push(`${wy(a)};`)},arg:e=>o[e],argOnce:e=>{let n=o[e];return n===void 0||$v(n)?n:(o[e]=this.spill({...t[e],code:n},i,e),o[e])},fn:e=>{let n=t[e];if(n)return{code:n.code,sync:!this.always&&n.sync===!0}},helper:e=>this.helper(e),aw:e=>this.aw(e,r),selfType:e.type,fields:()=>uy(e.type),guard:()=>n?this.guard(n):void 0,staticTypeName:()=>fy(e.type)}}withCatch(e,t,n,r,i,a){let o=this.uniq(`result`),s=this.uniq(`e`),c=this.uniq(`error`),l=this.helper(`$Throw`);a.push(`let ${o};`,`try {`,` ${o} = ${wy(e)};`,`} catch (${s}) {`,` if (!(${s} instanceof ${l})) throw ${s};`);let u=[`const ${c} = ${s}.error as any;`],d=new Map(r);d.set(`error`,{ts:c,type:this.registry.any()});let f=this.val(t,d,i,u);return u.push(`${o} = ${wy(f.code)};`),a.push(...vy(u),`}`),{code:o,type:n,pure:!0}}aw(e,t){return t.awaited=!0,`(await ${e})`}spill(e,t,n){if($v(e.code)||iy.test(e.code))return e.code;let r=this.uniq(n);return t.push(`const ${r} = ${wy(e.code)};`),r}typeOfExpr(e,t){let n=new Map;for(let[e,t]of this.engine.getGlobals())n.set(e,t.type);for(let[e,t]of Object.entries(this.opt.scope))n.set(e,t);for(let[e,r]of t)n.set(e,r.type);try{return e.typeOf(this.engine,n)}catch{return this.registry.any()}}};function oy(e){let t=e.call();return t?t.args instanceof vg?Object.values(t.args.fields).every(e=>e.type.isOptional()):!0:!1}function sy(e){return!!e.get||e.type instanceof Ag}function cy(e){return e instanceof vg||e instanceof jg||e instanceof gg&&cy(e.base)}function ly(e){if(e instanceof vg)return Object.entries(e.fields);if(e instanceof jg)return Object.entries(e._props);if(e instanceof gg){let t=ly(e.base);if(!t)return;let n=new Map(t);for(let[t,r]of Object.entries(e.local.props??{}))n.set(t,jh.from(r));return[...n]}}function uy(e){return(ly(e)??[]).filter(([,e])=>!e.get&&!e.type.call()).map(([e])=>e)}function dy(e){let t=ly(e);if(t)return new Map(t.filter(([,e])=>!e.get).map(([e,t])=>[e,t.type]))}function fy(e){if(!(e instanceof _g||e instanceof Ug||e instanceof bg||e instanceof Rg||e instanceof Sg||e instanceof Hg||e instanceof Bg))return e.name}function py(e){let t=e instanceof gg?e.base:e;return t instanceof Wg||t instanceof Vg||t instanceof Cg||t instanceof Dg}function my(e){return/\.(push|pop|shift|unshift|insert|remove|clear|delete|indexSet|setAt)$/.test(e)}function hy(e,t){return e instanceof $m?!0:!e||typeof e!=`object`?!1:!Array.isArray(e)&&typeof e.kind==`string`&&t.exprClass(e.kind)?!0:Object.values(e).some(e=>hy(e,t))}function gy(e,t){let n=Object.entries(e);return n.length===0?(t?.args instanceof vg?Object.values(t.args.fields):[]).some(e=>!e.type.isOptional()&&e.default===void 0)?`{} as any`:``:`{ ${n.map(([e,t])=>e===t.code?e:`${$v(e)?e:JSON.stringify(e)}: ${wy(t.code)}`).join(`, `)} }`}function _y(e){let t=e.options;if(t&&typeof t==`object`&&Object.keys(t).length!==0&&(e instanceof Vg||e instanceof Wg||e instanceof Ng||e instanceof Tg||e instanceof Gg))return`gin: ${e.toCode(void 0,{includeComments:!1})}`}function vy(e){return e.flatMap(e=>e.split(`
386
+ `)).map(e=>e&&` ${e}`)}function yy(e){return e[e.length-1]===`}`}function by(e){if(e.length===0)return`{}`;let t=`{ ${e.join(`; `)} }`;return t.length<=80&&!t.includes(`
387
+ `)&&!t.includes(`/**`)?t:`{
388
+ ${vy(e.map(e=>`${e};`)).join(`
389
+ `)}
390
+ }`}function xy(e){return e.includes(`=>`)||e.includes(` | `)||e.includes(` & `)?`(${e})`:e}function Sy(e){let t=[];for(let n of e.map(e=>e.includes(`=>`)?`(${e})`:e))t.includes(n)||t.push(n);return t.join(` | `)}function Cy(e){return/^[\w$.]+(<.*>)?$/.test(e)&&!e.includes(` `)?`${e}[]`:`Array<${e}>`}function wy(e){if(!e.startsWith(`(`)||!e.endsWith(`)`))return e;let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===`(`)t++;else if(r===`)`){if(t--,t===0&&n<e.length-1)return e}else if(r===`"`||r==="`"||r===`'`)return e}return e.slice(1,-1)}function Ty(e){return e.replace(/\*\//g,`*\\/`)}function Ey(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function Dy(e){let t=e.replace(/[^\w$]+(.)/g,(e,t)=>t.toUpperCase());return t.charAt(0).toUpperCase()+t.slice(1)}function Oy(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)>>>0;return t.toString(36)}function ky(e,t,n={}){let r=e.registry.parseExpr(t),i=new ay(e,n),a=n.name??`main`,o=i.exportFunction(r,a);i.helpers.has(a)&&i.problem(`function name '${a}' is also the name of a helper the code needs \u2014 pick another`),i.check();let s=new Map(i.helpers);return n.prelude===`inline`&&s.size>0&&(o=`${[...s.values()].join(`
391
+
392
+ `)}
393
+
394
+ ${o}`,s.clear()),{code:o,types:new Map(i.types),helpers:s,functions:[a]}}var Ay=class{constructor(e){this.registry=e}registry;globals=new Map;registerGlobal(e,t){return this.globals.set(e,t),this}getGlobal(e){return this.globals.get(e)}getGlobals(){return this.globals}parse(e){if(!e||typeof e!=`object`||!(`kind`in e))throw Error(`engine.parse: expected ExprDef with kind, got ${typeof e}`);return e}createRootScope(e,t){let n=new nh(null,void 0,t);for(let[e,t]of this.globals)n.vars.set(e,G(t.type,t.value));if(e)for(let[t,r]of Object.entries(e))n.vars.set(t,r);return n}async run(e,t,n){let r=n?new cg(n):void 0;r?.check();let i=this.createRootScope(t,r);try{return await this.evaluate(e,i)}catch(e){if(e instanceof fh)return e.value??G(this.registry.void(),void 0);throw e}}typeOf(e,t){let n=t??this.globalTypeScope();return rh(this,e,n)}validate(e,t,n){let r=t??this.globalTypeScope();return ah(this,e,r,n)}toCode(e,t){return this.registry.toCode(e,t)}toGinCode(e,t){return this.registry.toGinCode(e,t)}toJSONCode(e,t=2){return this.registry.toJSONCode(e,t)}toTypeScript(e,t){return ky(this,e,t)}globalTypeScope(){let e=new Map;for(let[t,n]of this.globals)e.set(t,n.type);return e}async evaluate(e,t){return(e instanceof $m?e:this.registry.parseExpr(e)).evaluate(this,t)}async validateValue(e,t){let n=new Mm,r=e.type.constraints();if(r.length===0)return n;let i=t??this.createRootScope();for(let t=0;t<r.length;t++){let a=r[t],o=i.child({this:e});try{(await a.evaluate(this,o)).raw!==!0&&n.at(`constraint[${t}]`,()=>n.error(`constraint.failed`,`value failed constraint: ${a.toCode(this.registry,{expectsValue:!0})}`))}catch(e){n.at(`constraint[${t}]`,()=>n.error(`constraint.threw`,`constraint threw: ${e.message}`))}}return n}};function jy(e){return new Ay(e)}var My=`^[a-z]\\S*$`,Ny=`A fn's name, as your tools spell it.`;function Py(e){if(e.name!==`text`)return!1;let t=e.options;return typeof t==`object`&&!!t&&`pattern`in t&&t.pattern===`^[a-z]\\S*$`}var Fy=R.string().pattern(My).describe(Ny);function Iy(e){return R.codec(Fy,{decode:t=>e.fn(t)??Error(`${t} names no fn: write a fn's name as your tools spell it.`),encode:t=>e.name(t)})}var Ly=new WeakMap,Ry=0;function zy(e){if(e===void 0)return 0;let t=Ly.get(e);return t===void 0&&Ly.set(e,t=++Ry),t}var By=Am.declare().dynamic((e,t,n)=>({...Tm(e,n),FnName:t===void 0?Fy:Iy(t)}),{key:(e,t,n)=>`${km(e,n)}|${zy(t)}`,cacheSize:4}),Vy={result:e=>By.result(e)},Hy=e=>Py(e)?R.ref(`FnName`):void 0;function Uy(e,t={}){return e.toA({...t.scope===void 0?{}:{scope:t.scope},...t.includeDocs===void 0?{}:{includeDocs:t.includeDocs},...t.unknownKeys===void 0?{}:{unknownKeys:t.unknownKeys},override:Hy})}function Wy(e,t={}){return Vy.result(Uy(e,t))}var Gy=new WeakMap,Ky=new WeakMap;function qy(e,t){let n=t.unknownKeys??`strip`,r=Gy;t.scope!==void 0&&(r=Ky.get(t.scope)??new WeakMap,Ky.set(t.scope,r));let i=r.get(e)??new Map;r.set(e,i);let a=i.get(n);if(a!==void 0)return a;let o=Wy(e,{...t,includeDocs:`none`});return i.set(n,o),o}function Jy(e,t={}){return qy(e,t).bind(e.registry)}function Yy(e){return e.map(String).join(`.`)}function Xy(e,t,n={}){let r=Jy(e,n).render(Xl).parse(t,{inPlace:!1,...n.repair===void 0?{}:{repair:n.repair},...n.label===void 0?{}:{label:n.label}});return r.ok?{ok:!0,value:r.value}:{ok:!1,problems:r.issues.map(e=>({path:Yy(e.codePath),message:e.message})),message:r.message}}var Zy=v().regex(/^[a-z][A-Za-z0-9_-]{0,63}$/).brand(),Qy=`[A-Za-z0-9](?:[A-Za-z0-9-]|_(?![_.]|$))*`,$y=RegExp(`^${Qy}(?:\\.${Qy})*$`),eb=v().regex($y,"a fn name is letters, digits, `_` and `-` in dot-separated parts, each starting with a letter or digit, with no `__` and no part ending in `_`");function tb(e){if(!$y.test(e))return e.includes(`__`)?`${e} holds \`__\`, which separates the parts of the name the model calls it by: write one \`_\``:/(?:^|\.)_|_(?:\.|$)/.test(e)?`a part of ${e} starts or ends with \`_\`: start each part with a letter or digit and end it with no \`_\``:`${e} is not a fn name: letters, digits, \`_\` and \`-\` in dot-separated parts, each starting with a letter or digit`}function nb(e){let{system:t,local:n}=Nl(e);return`${t}__${n.replaceAll(`.`,`__`)}`}function rb(e){return e.length===64&&/_x[0-9a-f]{8}$/.test(e)}function ib(e){return nb(e).length>64}function ab(e){if(rb(e))return;let t=e.indexOf(`__`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+2).split(`__`).join(`.`);if(!Al.test(n)||!$y.test(r))return;let i=I.safeParse(`${n}/${r}`);return i.success&&!ib(i.data)&&nb(i.data)===e?i.data:void 0}function ob(e,t){let n=I.safeParse(e);if(n.success)return n.data;let r=t?.(e);return r===void 0?e.includes(`--`)?sb(e)??ab(e):ab(e)??sb(e):r}function sb(e){if(e.length>=64)return;let t=I.safeParse(e.replace(`__`,`/`).replaceAll(`--`,`.`));if(t.success)return t.data.replaceAll(`/`,`__`).replaceAll(`.`,`--`).replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,64)===e?t.data:void 0}S({model:Zy,fn:I,until:N}),S({model:Zy,fn:I,system:F});var cb=I.describe(Ny),lb=v().min(1).regex(/^\S+$/,`a type's name, with no spaces`);Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);var ub=/^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i;function db(e){try{let{protocol:t}=new URL(e);return t===`http:`||t===`https:`}catch{return!1}}var fb=v().regex(ub,`expected an http or https URL`).refine(db,`expected an http or https URL`);function pb(e){return fb.safeParse(e).success}var mb=`outsideImages`,hb=E([`ask`,`always`]),gb=S({value:hb,setBy:M.optional(),updatedAt:N.optional()}),_b=`https`,vb={der:`/harness-ca.crt`,pem:`/harness-ca.pem`},yb=E([`own`,`files`]),bb=S({on:b(),source:yb,setBy:M.optional(),updatedAt:N.optional(),fingerprint:v().optional(),authorityName:v().optional(),host:v(),links:x(v())}),xb=v().regex(/^(?:\*|[a-z*][a-z0-9*-]*\/[A-Za-z0-9_*][A-Za-z0-9_.*-]*)$/,`an agent's name (crm/reviewer) or a pattern (hub/chat*, crm/*, *)`).refine(e=>!e.includes(`**`),`write one *`),Sb=S({into:x(xb).min(1),order:y().int().min(0).max(1e3).default(100),requires:x(I).default([]),mode:E([`tools`,`static`]).optional(),replaces:x(I).optional()}),Cb=C([D(`none`),S({detail:E([`full`,`summary`]).default(`full`),maxTokens:y().int().min(1).optional()})]),wb=S({target:xb,agents:x(I)}),Tb=E([`approved`,`pending`,`declined`]);S({context:I,system:F,title:v(),inject:Sb,fns:x(I),targets:x(wb),agents:x(I),review:Tb,off:b(),dynamic:b()}),S({hook:I,system:F,explains:v(),review:Tb});var Eb=S({section:E([`context`,`hooks`]),name:I,title:v(),change:E([`added`,`changed`,`removed`]),tokens:y().int().min(0).optional(),targets:x(wb),agents:x(I),replaces:x(I).optional()});S({agent:I,context:I,on:b(),order:y().int().min(0).max(1e3).optional(),by:M,at:N});var Db=E([`off`,`pending`,`declined`,`system-off`,`fns-unusable`,`mode`,`replaced`,`no-fit`]),Ob=S({agent:I,context:I,source:w(`type`,[S({type:D(`context`)}),S({type:D(`hook`),hook:I})]),system:F,via:xb,title:v(),detail:E([`full`,`summary`]),text:v(),tokens:y().int().min(0),order:y().int(),on:b(),leftOut:S({why:Db,reason:v()}).optional(),switched:S({by:M,at:N}).optional()}),kb=S({injections:x(Ob),targets:x(wb)}),Ab=S({agent:I,context:I,on:b().optional(),order:y().int().min(0).max(1e3).nullable().optional()}),jb=[`listed`,`signature`,`full`],Mb=E(jb),Nb=S({fn:I,detail:Mb}),Pb=S({type:D(`tools`)}),Fb=E([`auto`,`native`,`text`]),Ib=E([`system-end`,`tail`]),Lb=w(`type`,[Pb,S({type:D(`static`),protocol:Fb.default(`auto`),placement:Ib.default(`system-end`),loadDetail:Mb.default(`full`)})]),Rb=E(Lb.options.map(e=>e.shape.type.value));E([`find`,`find_ctx`,`inspect`,`load`,`unload`,`run`]);var zb=S({fn:v().min(1).describe(`The fn to run, by its qualified name (fs/read).`),args:T(v(),Zc()).default({}).describe(`Its args, as its card shows them.`),on:L.optional().describe(`For a system with several machines connected, which one runs it (laptop).`)}),Bb=S({type:D(`plain`)}),Vb=S({type:D(`suggest`),topN:y().int().min(0).default(6),autoInject:S({tokens:y().int().min(0),items:y().int().min(0)}).optional()}),Hb=E([`embedding`,`words`,`turnsAgo`,`age`,`selectedBefore`,`used`]),Ub=S({weight:y().min(0),target:y().optional(),k:y().positive().optional()}),Wb=E([`perMessage`,`perIteration`]),Gb=[`history`,`context`,`fns`],Kb=E(Gb),qb=T(Kb,y().min(0)),Jb=w(`type`,[Bb,Vb,S({type:D(`graph`),metrics:bc(Hb,Ub).default({}),spread:S({damping:y().min(0).max(.95).default(.5),hops:y().int().min(0).max(4).default(2)}).prefault({}),floorExchanges:y().int().min(0).default(1),shares:qb.default({history:.45,context:.35,fns:.2}),threshold:y().min(0).default(.15),evaluate:Wb.default(`perMessage`)})]),Yb=E(Jb.options.map(e=>e.shape.type.value)),Xb=S({contextWindow:y().int().min(256).optional(),maxOutputTokens:y().int().min(16).optional(),reasoningTokens:y().int().min(0).optional(),charsPerToken:y().min(1).max(8).optional()}),Zb=Xb.keyof();Zb.options;var Qb=Xb.required(),$b=E([`admin`,`probe`,`model-info`,`default`]),ex=S({model:v(),limits:Qb,sources:T(Zb,$b),ratio:y()});S({model:v(),limits:Xb,setBy:M,updatedAt:N}),S({model:v(),ratio:y().min(.5).max(2),samples:y().int().min(0),updatedAt:N});var tx=S({asked:y().int().min(0),got:y().int().min(0)}),nx=S({window:y().int().min(0),output:y().int().min(0),reasoning:y().int().min(0),margin:y().int().min(0),fixed:y().int().min(0),pools:T(Kb,tx),estimate:y().int().min(0),cut:x(S({what:v(),why:v()}))}),rx=S({name:I,detail:Mb,activation:y().min(0)}),ix=S({tokens:y().int().min(0),items:x(S({name:I,detail:E([`full`,`summary`,`listed`]),tokens:y().int().min(0)})),leftOut:x(S({name:I,why:Db,reason:v()})),rebuilt:S({added:x(I),dropped:x(I)}).optional()}),ax=S({contextor:Yb,mode:Rb,context:x(rx),fns:x(rx),linear:y().int().min(0),earlier:x(y().int().min(0)),budget:nx,injected:ix.optional()}),ox=S({session:j,text:v().min(1),model:v().min(1).optional(),count:x(v()).max(200).optional()}),sx=S({agent:I,model:v(),window:y().int().min(0),maxTokens:y().int().min(0),estimate:y().int().min(0),system:v(),tools:x(S({name:v(),description:v(),parameters:Zc(),tokens:y().int().min(0)})),messages:x(S({role:v(),content:v(),tokens:y().int().min(0)})),parts:S({instructions:v(),injected:v(),context:v(),guide:v(),tokens:S({instructions:y().int(),injected:y().int(),context:y().int(),guide:y().int(),system:y().int()})}),counts:x(y().int().min(0)),report:ax}),cx=S({turn:al,items:x(rx),at:N}),lx=[`none`,`read`,`write`,`delete`,`auto`],ux=E(lx),dx=S({name:v().optional(),sheetName:v().optional(),sheetIndex:y().int().nonnegative().optional(),headers:x(v()),rows:x(x(v()))});E([`empty`,`boolean`,`integer`,`number`,`date`,`text`]);var fx=E([`file`,`folder`,`link`,`other`]);S({entries:x(S({name:v(),location:v(),kind:fx,type:v().optional(),size:y().nonnegative().optional(),modifiedAt:y().optional()})),truncated:b(),total:y().int().nonnegative()});var px={converter:v(),from:v(),title:v().optional(),metadata:T(v(),sc()).optional()},mx=w(`kind`,[S({kind:D(`markdown`),...px,text:v()}),S({kind:D(`text`),...px,text:v()}),S({kind:D(`code`),...px,language:v(),text:v()}),S({kind:D(`pages`),...px,pages:x(v())}),S({kind:D(`table`),...px,tables:x(dx)})]),hx=mx.options.map(e=>e.shape.kind.value),gx=/^(?:true|false|yes|no)$/i,_x=/^[-+]?\d{1,15}$/,vx=/^[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)?(?:\.\d+)?(?:e[-+]?\d+)?%?$/i,yx=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[-+]\d{2}:?\d{2})?)?$|^\d{1,2}\/\d{1,2}\/\d{2,4}$/;function bx(e){return gx.test(e)?`boolean`:_x.test(e)?`integer`:/\d/.test(e)&&vx.test(e)?`number`:yx.test(e)&&!Number.isNaN(Date.parse(e))?`date`:`text`}function xx(e,t){return e===`empty`||e===t?t:e===`integer`&&t===`number`||e===`number`&&t===`integer`?`number`:`text`}function Sx(e){let t=Math.max(e.headers.length,...e.rows.map(e=>e.length));return Array.from({length:t},(t,n)=>{let r=`empty`;for(let t of e.rows){let e=(t[n]??``).trim();e!==``&&(r=xx(r,bx(e)))}return r})}var Cx=Wc([v().regex(/^[a-z][a-z0-9+.-]*$/),`://`,v()]),wx=v().min(1).brand(),Tx=`^[0-9a-f]{64}$`,Ex=new RegExp(Tx),Dx=S({hash:v().regex(Ex),size:y().int().min(0),mime:v()});S({content:Dx,mime:v(),finalUrl:v(),status:y().int(),rendered:b(),title:v().optional()});var Ox=S({uri:Cx,name:v(),description:v(),index:E([`all`,`on-read`,`none`]),ignore:x(v()),watch:b()}),kx=S({uri:Cx,name:v(),type:E([`folder`,`file`,`page`,`record`,`other`]),mime:v().optional(),format:v().optional(),size:y().int().min(0).optional(),modifiedAt:N.optional(),version:v()}),Ax=S({uri:Cx.optional(),raw:v(),kind:E([`child`,`import`,`link`,`embed`,`external`]),title:v().optional()}),jx=E([`links`,`text`,`bytes`]),Mx=C([S({inline:v()}),S({ref:Dx})]),Nx=S({stat:kx,links:x(Ax).optional(),text:Mx.optional(),bytes:Dx.optional()});E(hx);var Px=[`description`,`ocr`,`transcript`,`thumbnail`];E(Px);var Fx=E([...hx,...Px]),Ix=S({key:wx,path:x(v()),title:v(),start:y().int().min(0),end:y().int().min(0),embedText:v().optional(),form:Fx.optional()}),Lx=S({uri:Cx,change:E([`added`,`changed`,`removed`]),version:v().optional()}),Rx=S({format:v().optional(),mime:v().optional(),glob:v().optional(),form:Fx.optional()}),zx=C([S({resource:Cx,section:wx.optional(),title:v().optional()}),S({url:fb,title:v()}),S({file:Dx,title:v()}),S({run:A,title:v()})]),Bx=S({uri:Cx,section:wx.optional(),title:v(),preview:v(),rank:y()}),Vx=Gi();function Hx(e,t){return Vx.add(e,{why:t}),e}function Ux(e){let t=e;for(;t!==void 0;){if(Vx.has(t))return!0;t=t instanceof Tc||t instanceof jc||t instanceof Nc||t instanceof kc||t instanceof Vc?t.unwrap():void 0}return!1}function Wx(e){let t=e.shape;return Object.entries(t).filter(([,e])=>Ux(e)).map(([e])=>e)}var Gx=new WeakMap;function Kx(e,t){return Gx.set(e,{schema:t}),e}var qx=w(`to`,[S({to:D(`session`),session:j}),S({to:D(`user`),user:M}),S({to:D(`everyone`)})]),Jx=E([`live`,`snapshot`]),Yx=w(`type`,[S({type:D(`system`)}),S({type:D(`memory`),scope:qx,author:M,run:A.optional()}),S({type:D(`resource`),uri:Cx,section:wx.optional(),version:v(),copy:Jx})]),Xx=[`system`,`memory`,`resource`],Zx=S({full:y().int().min(0),summary:y().int().min(0)}),Qx=E([`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`mentions`,`about`,`learned`]),$x=[`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`about`],eS=E($x),tS=w(`kind`,[S({kind:D(`context`),name:I}),S({kind:D(`fn`),name:cb}),S({kind:D(`type`),name:I}),S({kind:D(`resource`),uri:Cx,section:wx.optional()})]),nS=[`fn`,`context`,`resource`,`type`],rS=S({to:tS,relation:eS,weight:y().min(0).max(1).default(.5)}),iS=E([`declared`,`mentioned`,`resource`,`learned`,`authored`]),aS=S({from:I,to:tS,toKey:v(),relation:Qx,weight:y().min(0).max(1),source:iS,uses:y().min(0).optional(),by:M.optional(),updatedAt:N}),oS=S({weight:y().min(0).max(2).optional(),summary:v().optional(),tags:x(v().min(1)).optional(),fns:x(cb).optional(),suggestFns:x(cb).optional(),inject:Hx(Sb.optional(),`a model never writes text that lands in later prompts`),command:v().regex(/^[a-z][a-z0-9-]*$/).optional(),visible:Il.optional(),suggest:Il.optional(),parent:I.optional()}),sS=S({text:v().min(1),title:v().optional(),scope:E([`session`,`user`,`everyone`]).default(`session`),about:x(tS).optional()}).extend(oS.shape),cS=oS.keyof().exclude(oS.keyof().options.filter(e=>Wx(oS).includes(e))),lS=sS.omit({scope:!0}).partial().extend({name:I,clear:Kx(x(oS.keyof()).optional(),x(cS).optional())}),uS=S({uri:Cx,sections:x(wx).optional(),copy:Jx.default(`live`)}).extend(oS.omit({summary:!0,parent:!0}).shape),dS=S({created:x(I),updated:x(I),links:y().int().min(0)}),fS={maxDepth:3,maxDecisions:256,maxTokens:8e3};y().int().min(1).max(65535).default({hub:4300,web:4310,mockHub:4320}.hub);function pS(e){return e.split(`/`).filter((e,t)=>t!==0||e!==``).map(e=>e.startsWith(`:`)?{t:`param`,k:e.slice(1)}:{t:`lit`,v:e})}function mS(e){return`/`+e.map(e=>e.t===`param`?`:${e.k}`:e.v).join(`/`)}function hS(e,t){return`/`+e.map(e=>{if(e.t===`lit`)return e.v;let n=t[e.k];if(n===void 0)throw Error(`path is missing a value for ":${e.k}"`);return encodeURIComponent(String(n))}).join(`/`)}function gS(e){return e.filter(e=>e.t===`param`).map(e=>e.k)}var _S=class extends Error{status;code;data;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.data=r,this.name=`ApiError`}},vS=()=>{let e=globalThis.navigator;return typeof e?.onLine==`boolean`?e.onLine:void 0};function yS(e={}){let t=new Set,n=e.initial??(vS()===!1?`offline`:`online`),r=e=>{if(e!==n){n=e;for(let n of[...t])n(e)}},i=e=>(t.add(e),()=>void t.delete(e)),a=()=>{},o=globalThis;if((e.browser??!0)&&typeof o.addEventListener==`function`&&typeof o.removeEventListener==`function`){let e=()=>r(`online`),t=()=>r(`offline`);o.addEventListener(`online`,e),o.addEventListener(`offline`,t),a=()=>{o.removeEventListener(`online`,e),o.removeEventListener(`offline`,t)}}return{get status(){return n},subscribe:i,whenOnline:(e,t)=>new Promise((r,a)=>{if(n===`online`){r();return}if(e?.aborted){a(e.reason);return}let o=null,s=t=>{l(),o&&clearTimeout(o),e?.removeEventListener(`abort`,c),t()};function c(){s(()=>a(e.reason))}let l=i(e=>{e===`online`&&s(r)});t?.timeout!==void 0&&(o=setTimeout(()=>s(r),t.timeout)),e?.addEventListener(`abort`,c,{once:!0})}),report:r,dispose:()=>{a(),a=()=>{}}}}var bS=e=>{if(Array.isArray(e))return e.map(bS);if(e&&typeof e==`object`){let t={};for(let n of Object.keys(e).sort())t[n]=bS(e[n]);return t}return e},xS=e=>JSON.stringify(bS(e))??`null`,SS=e=>{try{return JSON.stringify(e)!==void 0}catch{return!1}},CS=(e,t)=>({get:n=>e.getItem(t+n)??void 0,set:(n,r)=>e.setItem(t+n,r),delete:n=>{let r=t+n,i=e.getItem(r)!==null;return e.removeItem(r),i},keys:function*(){for(let n=0;n<e.length;n++){let r=e.key(n);r!==null&&r.startsWith(t)&&(yield r.slice(t.length))}}}),wS=(e,t)=>{if(typeof e==`object`)return e;if(e!==`memory`)try{let n=e===`local`?globalThis.localStorage:globalThis.sessionStorage;if(n)return CS(n,t)}catch{}let n=new Map;return{get:e=>n.get(e),set:(e,t)=>void n.set(e,t),delete:e=>n.delete(e),keys:()=>n.keys()}};function TS(e={}){let t=e.max??500,n=e.ttl??0,r=e.now??Date.now,i=wS(e.store??`memory`,e.prefix??`ayepi:cache:`),a=new Map;for(let e of i.keys())a.set(e,!0);let o=e=>{a.delete(e),a.set(e,!0)},s=e=>{let t=i.get(e);if(t!==void 0)try{return JSON.parse(t)}catch{i.delete(e);return}},c=e=>(a.delete(e),i.delete(e)),l=()=>{for(;a.size>t;)c(a.keys().next().value)};return{read:e=>{let t=s(e);if(!t)return;let n=r();if(t.exp&&n>=t.exp){if(!t.stale||n>=t.stale){c(e);return}return o(e),{value:t.v,stale:!0}}return o(e),{value:t.v,stale:!1}},write:(e,t,a)=>{if(!SS(t))return;let s=a?.ttl??n,c=s>0?r()+s:0,u={v:t,exp:c,stale:c&&a?.staleWhileRevalidate?c+a.staleWhileRevalidate:0,tags:a?.tags??[]};i.set(e,JSON.stringify(u)),o(e),l()},remove:e=>void c(e),removeWhere:e=>{let t=0;for(let n of[...i.keys()])e(n)&&c(n)&&(t+=1);return t},invalidateTags:e=>{if(e.length===0)return 0;let t=new Set(e),n=0;for(let e of[...i.keys()]){let r=s(e);r&&r.tags.some(e=>t.has(e))&&c(e)&&(n+=1)}return n},clear:()=>{for(let e of[...i.keys()])i.delete(e);a.clear()}}}function ES(e={},t=yS()){let n=new Map,r=t=>{let r=t??e.store??`memory`,i=n.get(r);return i||(i=TS({...e,store:r}),n.set(r,i)),i};return{cacheFor:r,invalidateTags:e=>{r(void 0);for(let t of n.values())t.invalidateTags(e)},connectivity:t}}var DS=class extends Error{constructor(e=`caller rate limit exceeded`){super(e),this.name=`CallerRateLimited`}},OS=`\0`,kS=e=>new DOMException(e,`AbortError`),AS=e=>{let t=e.filter(e=>e!==void 0);if(t.length===1)return t[0];let n=new AbortController,r=()=>{n.abort();for(let e of t)e.removeEventListener(`abort`,r)};for(let e of t){if(e.aborted)return n.abort(),n.signal;e.addEventListener(`abort`,r,{once:!0})}return n.signal},jS=(e,t)=>new Promise((n,r)=>{if(t.aborted){r(kS(`aborted`));return}let i=()=>{clearTimeout(a),r(kS(`aborted`))},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e);t.addEventListener(`abort`,i,{once:!0})}),MS=(e,t)=>t.reduceRight((e,t)=>t(e),e),NS=(e,t,n)=>e===void 0?[]:typeof e==`function`?e(t,n):e,PS=(e,t)=>n=>async(r,i)=>{t.n+=1,e.onStart?.(r.data);try{let t=await n(r,i);return e.onSuccess?.(t,r.data),t}catch(t){throw e.onError?.(t,r.data),t}finally{--t.n,e.onSettled?.(r.data)}},FS=(e,t,n)=>r=>async(i,a)=>{t!==`success`&&n.invalidateTags(NS(e,i.data,void 0));let o=await r(i,a);return t!==`start`&&n.invalidateTags(NS(e,i.data,o)),o},IS=(e,t,n)=>r=>async(i,a)=>{let o=n(i.data),s=n=>t.write(o,n,{ttl:e.ttl,staleWhileRevalidate:e.staleWhileRevalidate,tags:NS(e.tags,i.data,n)}),c=t.read(o);if(c&&!c.stale)return c.value;if(c&&c.stale)return r(i,a).then(s).catch(()=>{}),c.value;let l=await r(i,a);return s(l),l},LS=e=>{let t=new Map;return n=>(r,i)=>{let a=e(r.data),o=t.get(a);if(o)return o;let s=n(r,i).finally(()=>t.delete(a));return t.set(a,s),s}},RS=()=>{let e=null;return t=>(n,r)=>{e?.abort(kS(`superseded`));let i=new AbortController;e=i;let a=AS([r,i.signal]);return new Promise((e,r)=>{a.addEventListener(`abort`,()=>r(kS(`superseded`)),{once:!0}),t(n,a).then(e,r)}).finally(()=>{e===i&&(e=null)})}},zS=e=>{let t=e.onLimit??`wait`,n=e.window/e.limit,r=e.limit,i=Date.now(),a=()=>{let t=Date.now(),n=(t-i)/e.window*e.limit;n>0&&(r=Math.min(e.limit,r+n),i=t)};return e=>async(i,o)=>{if(a(),r<1){if(t===`throw`||t===`drop`)throw new DS;await jS((1-r)*n,o),a()}return--r,e(i,o)}},BS=e=>{let t=e.attempts??3,n=e.base??200,r=e.factor??2,i=e.max??3e4,a=e.jitter??.5;return e=>async(o,s)=>{let c;for(let l=1;l<=t;l+=1)try{return await e(o,s)}catch(e){if(c=e,l>=t)break;await jS(Math.min(i,n*r**(l-1))*(1-a*Math.random()),s)}throw c}},VS=e=>e instanceof _S&&e.status===0&&e.code===`DISCONNECTED`,HS=(e,t)=>{let n=e.maxRetries??1/0,r=e.backoff??1e3;return i=>async(a,o)=>{let s=e.timeout===void 0?1/0:Date.now()+e.timeout,c=0;for(;;)try{return await i(a,o)}catch(e){if(!VS(e)||c>=n)throw e;let i=s-Date.now();if(i<=0)throw e;c+=1,await t.connectivity.whenOnline(o,{timeout:Math.min(r,i)})}}},US=(e,t)=>{let n=null,r=[],i=0;return a=>{let o=t=>{n&&=(clearTimeout(n),null);let o=r;r=[],i=0;let s=o.map(e=>e.call.data);a(e.accumulate?{data:e.accumulate(s),opts:o[o.length-1].call.opts}:o[o.length-1].call,t).then(t=>{let n=e.spread?e.spread(t,s):null;o.forEach((e,r)=>e.resolve(n?n[r]:t))},e=>o.forEach(t=>t.reject(e)))};return t.push(()=>{n&&=(clearTimeout(n),null);let e=r;r=[],i=0;for(let t of e)t.reject(kS(`cancelled`))}),(t,a)=>new Promise((s,c)=>{let l=Date.now();r.length===0&&(i=l),r.push({call:t,resolve:s,reject:c});let u=e.leading&&n===null&&r.length===1;n&&clearTimeout(n);let d=e.maxWait!==void 0&&l-i>=e.maxWait;if(u||d){o(a);return}let f=e.maxWait===void 0?e.wait:Math.min(e.wait,i+e.maxWait-l);n=setTimeout(()=>o(a),f)})}};function WS(e,t,n,r,i){if(t.items||t.itemsIn||t.streamIn!==null||t.streamOut!==null)return{call:(...e)=>n(...e),cancel:()=>{},invalidate:()=>{},pending:0};let a=t.p.length>0||t.q.length>0||t.hasBody||t.f.length>0,o=i.cache===!0||i.cache===void 0||i.cache===!1?{}:i.cache,s=e=>o.key?o.key(e):xS(e),c=t=>`${e}${OS}${s(t)}`,l=i.cache?r.cacheFor(o.store):null,u={n:0},d=[],f=new AbortController,p=(e,t)=>{let r={...e.opts??{},signal:t};return Promise.resolve(a?n(e.data,r):n(r))},m=[];if((i.onStart||i.onSuccess||i.onError||i.onSettled)&&m.push(PS(i,u)),i.invalidates&&m.push(FS(i.invalidates,i.invalidateOn??`success`,r)),l&&m.push(IS(o,l,c)),i.dedupe&&m.push(LS(c)),i.lastOnly&&m.push(RS()),i.debounce!==void 0){let e=typeof i.debounce==`number`?{wait:i.debounce}:i.debounce;m.push(US(e,d))}i.rateLimit&&m.push(zS(i.rateLimit)),i.retry&&m.push(BS(i.retry));let h=t.sideEffects===!1||t.sideEffects===void 0&&t.method===`GET`,ee=i.replay===!1?null:i.replay===void 0?h?{}:null:typeof i.replay==`object`?i.replay:{};ee&&(h||ee.force)&&m.push(HS(ee,r)),(i.onOnline||i.onOffline)&&r.connectivity.subscribe(e=>e===`online`?i.onOnline?.():i.onOffline?.());let te=MS(p,m);return{call:(...e)=>{let t=a?e[0]:void 0,n=a?e[1]:e[0],r=AS([n?.signal,f.signal]);return te({data:t,opts:n},r)},cancel:()=>{f.abort(kS(`cancelled`)),f=new AbortController;for(let e of d)e()},invalidate:()=>void l?.removeWhere(t=>t.startsWith(`${e}${OS}`)),get pending(){return u.n}}}function GS(e){try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}}function KS(e){let{id:t,...n}=e;return JSON.stringify({rid:typeof t==`string`?t:null,...n})}function qS(e){let{rid:t,...n}=e;return JSON.stringify(typeof t==`string`?{id:t,...n}:n)}function JS(e,t){return JSON.stringify({id:e,$status:0,$code:`DISCONNECTED`,$error:t})}function YS(e){return`$status`in e||e.end===!0}var XS=class{#e=new Set;add(e){this.#e.add(e)}settle(e){typeof e.id==`string`&&YS(e)&&this.#e.delete(e.id)}fail(e,t){let n=[...this.#e];this.#e.clear();for(let r of n)e(JS(r,t))}},ZS={$status:501,$code:`NOT_SERVED`,$error:`this client serves no spec`};function QS(e,t){let n=e.rid;typeof n==`string`&&typeof e.type==`string`&&t(JSON.stringify({rid:n,...ZS}))}var $S=class{app;send;request;#e=null;constructor(e,t,n){this.app=e,this.send=t,this.request=n}receive(e){let t=this.#e??this.#t();this.app.ws.message(t,qS(e))}drop(){let e=this.#e;e&&(this.#e=null,this.app.ws.close(e))}#t(){let e=this.app.ws.open(t=>{let n=GS(t);n&&this.#e===e&&this.send(KS(n))},this.request());return this.#e=e,e}},eC=new Set([101,204,205,304]);function tC(e,t,n,r,i,a){return new Promise((o,s)=>{if(i?.aborted){s(new DOMException(`The operation was aborted.`,`AbortError`));return}let c=new XMLHttpRequest;c.open(e,t,!0),c.responseType=`arraybuffer`;for(let[e,t]of Object.entries(n))c.setRequestHeader(e,t);c.upload.onprogress=e=>{e.lengthComputable&&a({loaded:e.loaded,total:e.total})};let l=()=>c.abort(),u=()=>i?.removeEventListener(`abort`,l);c.onload=()=>{u();let e=eC.has(c.status)?null:c.response;o(new Response(e,{status:c.status,statusText:c.statusText}))},c.onerror=()=>{u(),s(TypeError(`Network request failed`))},c.onabort=()=>{u(),s(new DOMException(`The operation was aborted.`,`AbortError`))},i?.addEventListener(`abort`,l,{once:!0}),c.send(r)})}function nC(e){return!!e&&typeof e.parse==`function`}function rC(e){let t=iC(e);return t?t():e}function iC(e){let t=e[Symbol.for(`ayepi.manifest`)];return typeof t==`function`?t:void 0}function aC(e){return typeof e==`number`&&e>=200&&e<300}var oC={400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,409:`Conflict`,410:`Gone`,422:`Unprocessable Entity`,429:`Too Many Requests`,500:`Internal Server Error`,502:`Bad Gateway`,503:`Service Unavailable`};function sC(e){let t=Number(e.$status);return new _S(t,typeof e.$code==`string`?e.$code:`ERROR`,typeof e.$error==`string`?e.$error:oC[t]??`Request failed with status ${t}`,e.data)}function cC(e){let t=rC(e.manifest),n=e.fetchImpl??(e=>fetch(e)),r=yS(),i=ES(e.cache,r);e.ws?.onState?.(e=>r.report(e===`open`?`online`:`offline`));let a=()=>typeof e.headers==`function`?e.headers():e.headers??{},o=t=>e.unauthorized!==void 0&&Object.keys(t).some(e=>e.toLowerCase()===`authorization`),s=null,c=()=>{let t=e.unauthorized;return t?(s??=t().catch(()=>!1).finally(()=>{s=null}),s):Promise.resolve(!1)},l=t=>e.validate?.endpoints[t]?.cfg,u=(e,t)=>{let n=l(e);return n?.response?n.response.parse(t):t},d=(e,t)=>{let n=l(e);return n&&nC(n.streamOut)?n.streamOut.parse(t):t},f=(e,t,n)=>{let r=l(e)?.responses?.[t];return r?r.parse(n):n},p=0,m=new Map,h=new Map,ee=new Map,te=new Map,ne=new Map,re=(t,n,r)=>{r&&o(a())&&ne.set(t,n),e.ws?.send(n)},ie=e=>{let t=te.get(e);t&&(te.delete(e),t())},ae=(t,n,r)=>{if(!n)return;let i=()=>{te.delete(t),ne.delete(t),r(n.reason)&&e.ws?.send(JSON.stringify({id:t,abort:!0}))};n.aborted?i():(n.addEventListener(`abort`,i,{once:!0}),te.set(t,()=>n.removeEventListener(`abort`,i)))},oe=e=>JSON.stringify(e??{},Object.keys(e??{}).sort());if(e.ws){let t=e.ws,n=e=>t.send(e),r=e.serve?new $S(e.serve,n,()=>new Request(new URL(e.baseUrl,`http://peer.invalid/`))):null;r&&t.onState?.(e=>{e!==`open`&&r.drop()}),t.onMessage(e=>{let i=GS(e);if(!i)return;if(`rid`in i){r?r.receive(i):QS(i,n);return}if(typeof i.id!=`string`){if(typeof i.type==`string`){let e=`${i.type}|${oe(i.params)}`;for(let t of ee.get(e)??[])t(i.data)}return}let a=i.id,o=ne.get(a);ne.delete(a),o!==void 0&&i.$status===401?c().then(e=>{(m.has(a)||h.has(a))&&(e?t.send(o):se(a,i))}):se(a,i)})}function se(e,t){let n=`$status`in t&&!aC(t.$status);if(h.has(e)){let r=h.get(e);`chunk`in t?r.push(t.chunk):t.end===!0?(h.delete(e),ie(e),r.end()):n&&(h.delete(e),ie(e),r.fail(sC(t)))}else if(m.has(e)){let r=m.get(e);m.delete(e),ie(e),n?r.reject(sC(t)):r.resolve(t.data)}}function ce(){let e=[],t=!1,n,r=null;return{push(t){e.push(t),r?.()},end(){t=!0,r?.()},fail(e){n=e,t=!0,r?.()},async*iterate(){for(;;)if(e.length>0)yield e.shift();else{if(n!==void 0)throw n;if(t)return;await new Promise(e=>r=e),r=null}}}}function le(t,n){let r=typeof n==`function`?n():n;(async()=>{try{for await(let n of r)e.ws.send(JSON.stringify({id:t,chunk:n}));e.ws.send(JSON.stringify({id:t,end:!0}))}catch{e.ws.send(JSON.stringify({id:t,end:!0}))}})()}function ue(e,t,n){return JSON.stringify(t.ws===null?{id:e,type:t.path,method:t.method,data:n}:{id:e,type:t.ws,data:n})}function de(t,n,r,i,a){if(!e.ws){let e=Error(`no websocket transport configured`);if(!n.items)return Promise.reject(e);throw e}let o=`c${++p}`;if(n.items){let e=ce();return h.set(o,e),ae(o,a,t=>h.delete(o)?(e.fail(t),!0):!1),re(o,ue(o,n,r),!n.itemsIn),n.itemsIn&&le(o,i),(async function*(){for await(let n of e.iterate())yield d(t,n)})()}let s=new Promise((e,t)=>{m.set(o,{resolve:e,reject:t}),ae(o,a,e=>{let t=m.get(o);return t?(m.delete(o),t.reject(e),!0):!1}),re(o,ue(o,n,r),!1)});return n.itemsIn&&le(o,i),s.then(e=>n.multi?e:u(t,e))}function fe(t,n){if(!e.ws)return Promise.reject(Error(`no websocket transport configured`));let r=`c${++p}`;return new Promise((e,i)=>{m.set(r,{resolve:e,reject:i}),ae(r,n,e=>{let t=m.get(r);return t?(m.delete(r),t.reject(e),!0):!1}),re(r,JSON.stringify({id:r,...t}),!0)})}function g(e,t){if(e.b===`raw`)return{p:{},q:{},b:t,f:{}};let n={},r={},i={},a={},o=new Set(e.p),s=new Set(e.q),c=new Set(e.b??[]),l=new Set(e.f);for(let[e,u]of Object.entries(t??{}))if(o.has(e))n[e]=u;else if(s.has(e))r[e]=u;else if(c.has(e))i[e]=u;else if(l.has(e))a[e]=u;else throw Error(`key "${e}" does not belong to endpoint data`);return{p:n,q:r,b:e.hasBody?i:void 0,f:a}}function pe(t,n,r){let i=hS(pS(t.path),n),a=new URL(i.slice(1),e.baseUrl.endsWith(`/`)?e.baseUrl:e.baseUrl+`/`);for(let[e,t]of Object.entries(r))if(t!==void 0){if(Array.isArray(t))for(let n of t)a.searchParams.append(e,String(n));else a.searchParams.set(e,String(t))}return a}function me(e){let t=(typeof e==`function`?e():e)[Symbol.asyncIterator](),n=new TextEncoder;return new ReadableStream({async pull(e){let{done:r,value:i}=await t.next();if(r)return e.close();e.enqueue(n.encode(JSON.stringify(i)+`
395
+ `))},async cancel(){await t.return?.(void 0)}})}async function he(e,t,i,s=!1){let{p:l,q:u,b:d,f}=g(e,t),p=i?.stream,m=pe(e,l,u),h={...a(),...i?.headers??{}},ee=null,te=!1;if(e.streamIn)h[`content-type`]=e.streamIn,e.itemsIn?(ee=me(p),te=!0):(ee=p,te=p instanceof ReadableStream);else if(e.f.length>0){let e=new FormData;d!==void 0&&e.set(`body`,JSON.stringify(d));for(let[t,n]of Object.entries(f))if(n!==void 0){if(Array.isArray(n))for(let r of n)e.append(t,r);else e.set(t,n)}ee=e}else if(e.hasBody){if(e.bodyEnc===`urlencoded`){h[`content-type`]=`application/x-www-form-urlencoded`;let e=new URLSearchParams;for(let[t,n]of Object.entries(d??{}))if(n!==void 0){if(Array.isArray(n))for(let r of n)e.append(t,String(r));else e.set(t,String(n))}ee=e.toString()}else h[`content-type`]=`application/json`,ee=JSON.stringify(d)}let ne={method:e.method,headers:h,body:ee,signal:i?.signal};te&&(ne.duplex=`half`);let re=i?.onUploadProgress,ie;try{ie=re&&!e.streamIn&&!e.streamOut&&typeof XMLHttpRequest<`u`?await tC(e.method,m.toString(),h,ee,i?.signal,re):await n(new Request(m,ne))}catch(e){throw e instanceof TypeError?(r.report(`offline`),new _S(0,`DISCONNECTED`,`network request failed`)):e}if(r.report(`online`),ie.status===401&&!s&&e.streamIn===null&&o(h)&&await c())return await ie.body?.cancel().catch(()=>{}),he(e,t,i,!0);if(!ie.ok){let e=await ie.json().catch(()=>({})),t=e?.error;throw new _S(ie.status,t?.code??`ERROR`,t?.message,e)}return ie}async function ge(e,t,n,r){let i=await he(t,n,r);if(t.streamOut)return i.body??new ReadableStream({start:e=>e.close()});if(t.multi)return{status:i.status,data:f(e,i.status,await i.json())};if(i.status!==204)return u(e,await i.json())}async function*_e(e,t,n,r){let i=await he(t,n,r);if(!i.body)return;let a=t.streamOut===`text/event-stream`,o=a?`
396
+
397
+ `:`
398
+ `,s=t=>{let n=a?t.split(`
399
+ `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(`
400
+ `):t;if(n.trim())return d(e,JSON.parse(n))},c=i.body.getReader(),l=new TextDecoder,u=``;try{for(;;){let{done:e,value:t}=await c.read();if(e)break;u+=l.decode(t,{stream:!0});let n;for(;(n=u.indexOf(o))>=0;){let e=u.slice(0,n);u=u.slice(n+o.length);let t=s(e);t!==void 0&&(yield t)}}u+=l.decode();let e=s(u);e!==void 0&&(yield e)}finally{await c.cancel().catch(()=>{})}}function ve(n,...r){let i=t.endpoints[n];if(!i)return Promise.reject(Error(`unknown endpoint "${n}"`));let a=i.p.length>0||i.q.length>0||i.hasBody||i.f.length>0||i.streamIn!==null,o=a?r[0]:void 0,s=a?r[1]:r[0],c=s?.transport??(e.prefer===`ws`&&!i.httpOnly&&e.ws?`ws`:`http`);if(c===`ws`&&i.httpOnly){let e=Error(`endpoint "${n}" is http-only`);if(i.items)throw e;return Promise.reject(e)}return i.items||i.itemsIn?c===`ws`?de(n,i,o,s?.stream,s?.signal):i.items?_e(n,i,o,s):ge(n,i,o,s):c===`ws`?fe(i.ws===null?{type:i.path,method:i.method,data:o}:{type:i.ws,data:o},s?.signal).then(e=>i.multi?e:u(n,e)):ge(n,i,o,s)}function ye(e,...n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);if(r.method!==`GET`)throw Error(`url() requires a GET endpoint; "${e}" is ${r.method}`);let{p:i,q:a}=g(r,n[0]);return pe(r,i,a).toString()}function be(n,...r){let i=t.events[n];if(!i)throw Error(`unknown event "${n}"`);if(!e.ws)throw Error(`no websocket transport configured`);let a=i.hasParams?r[0]:void 0,o=i.hasParams?r[1]:r[0],s=`${i.ws}|${oe(a)}`,c=ee.get(s);return c||ee.set(s,c=new Set),c.add(o),fe({sub:i.ws,params:a}),()=>{c.delete(o),c.size===0&&fe({unsub:i.ws,params:a})}}function xe(e,n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);return WS(e,r,(...t)=>ve(e,...t),i,n??{})}return{call:ve,on:be,url:ye,caller:xe,connection:{get status(){return r.status},subscribe:e=>r.subscribe(e)}}}var lC={initial:500,max:3e4,factor:2,jitter:!0},uC={interval:3e4,timeout:1e4};function dC(e,t={}){let n=t.WebSocket??globalThis.WebSocket;if(!n)throw Error(`wsTransport: no WebSocket implementation available; pass opts.WebSocket`);let r=n,i=t.whileDisconnected??`fail`,a={...lC,...t.backoff},o=t.heartbeat===!1?null:{...uC,...t.heartbeat??{}},s=t.maxRetries??1/0,c=null,l=`closed`,u=null,d=0,f=!1,p=!1,m=null,h=null,ee=null,te=[],ne=new Map,re=new XS,ie=new Set,ae=e=>{if(e!==l){l=e,t.onStateChange?.(e);for(let t of[...ie])t(e)}},oe=e=>u?.(e),se=e=>JSON.stringify(e??{},Object.keys(e??{}).sort());function ce(){re.fail(oe,`connection closed`)}function le(){h&&clearInterval(h),ee&&clearTimeout(ee),h=ee=null}function ue(){o&&(le(),h=setInterval(()=>{l===`open`&&c&&(c.send(JSON.stringify({ping:!0})),ee&&clearTimeout(ee),ee=setTimeout(()=>c?.close(),o.timeout))},o.interval))}function de(e){let t=null;try{t=JSON.parse(e)}catch{oe(e);return}t&&t.pong===!0?ee&&=(clearTimeout(ee),null):(t&&re.settle(t),oe(e))}function fe(){if(p)return;f=!0,d=0,ae(`open`);for(let e of ne.values())c?.send(e);let e=te.splice(0);for(let t of e)c?.send(t);ue()}function g(){le(),c=null,ce(),p?ae(`closed`):pe()}function pe(){if(p)return;if(d>=s){ae(`closed`);return}let e=Math.min(a.max,a.initial*a.factor**+d),t=a.jitter?e/2+e/2*Math.random():e;d++,ae(`connecting`),m=setTimeout(me,t)}function me(){if(p||c)return;m&&=(clearTimeout(m),null),ae(`connecting`);let n;try{n=new r(typeof e==`function`?e():e,typeof t.protocols==`function`?t.protocols():t.protocols)}catch(e){t.onError?.(e),pe();return}c=n;let i=!1,a=()=>{c===n&&g()};n.addEventListener(`open`,()=>{i=!0,fe()}),n.addEventListener(`message`,e=>de(String(e.data))),n.addEventListener(`close`,a),n.addEventListener(`error`,e=>{t.onError?.(e),i||a()})}function he(e){let t={};try{t=JSON.parse(e)}catch{}typeof t.sub==`string`?ne.set(`${t.sub}|${se(t.params)}`,e):typeof t.unsub==`string`&&ne.delete(`${t.unsub}|${se(t.params)}`),typeof t.id==`string`&&typeof t.type==`string`&&re.add(t.id);let n=typeof t.sub==`string`||typeof t.unsub==`string`;l===`open`&&c?c.send(e):`rid`in t||(me(),n||(!f||i===`queue`?te.push(e):typeof t.id==`string`&&oe(JS(t.id,`not connected`))))}return{send:he,onMessage(e){u=e},connect:me,reconnect(){if(p)return;let e=c;c=null,le(),ce(),e?.close(),d=0,me()},close(){p=!0,m&&clearTimeout(m),m=null,le(),ce(),c?.close(),c=null,ae(`closed`)},get state(){return l},onState(e){return ie.add(e),()=>void ie.delete(e)}}}function fC(e,t,n){return{kind:`endpoint`,cfg:e,mws:t,prefixes:n}}function pC(e){return fC(e,[],[])}function Y(e){for(let[t,n]of Object.entries(e.endpoints)){let e=n.cfg;if(e.streamIn&&(e.body||e.files))throw Error(`endpoint "${t}": streamIn excludes body/files`);if(e.files&&`body`in e.files)throw Error(`endpoint "${t}": "body" is reserved as the multipart JSON field name`);if(e.streamOut&&e.response)throw Error(`endpoint "${t}": streamOut excludes response`);if(e.responses&&e.response)throw Error(`endpoint "${t}": responses (multi-status) excludes response`);if(e.responses&&e.streamOut)throw Error(`endpoint "${t}": responses excludes streamOut`);if(e.streamEncoding&&!(e.streamOut instanceof ws))throw Error(`endpoint "${t}": streamEncoding requires a typed (schema) streamOut`);if(e.bodyEncoding===`urlencoded`&&!(e.body instanceof dc))throw Error(`endpoint "${t}": urlencoded bodies must be z.object(...)`);if(e.download&&typeof e.streamOut!=`string`)throw Error(`endpoint "${t}": download requires a raw (content-type) streamOut`);for(let n of[`params`,`query`,`headers`,`cookies`]){let r=e[n];if(r&&!(r instanceof dc))throw Error(`endpoint "${t}": ${n} must be a z.object(...)`)}_C(t,n)}let t;return Object.defineProperty(e,mC,{value:()=>t??=hC(e),enumerable:!1,configurable:!0}),e}var mC=Symbol.for(`ayepi.manifest`);function hC(e){let t=Object.entries(e.endpoints).map(([e,t])=>_C(e,t));return{endpoints:Object.fromEntries(t.map(e=>[e.name,{method:e.method,path:e.path,ws:e.ws,httpOnly:e.httpOnly,streamIn:e.streamInCt,itemsIn:e.itemsIn,streamOut:e.streamOutCt,items:e.items,p:e.p,q:e.q,b:e.bRaw?`raw`:e.b,f:e.f,hasBody:!!e.def.cfg.body,hasHeaders:!!e.def.cfg.headers,multi:e.multi,bodyEnc:e.bodyEnc,sideEffects:e.def.cfg.sideEffects}])),events:Object.fromEntries(Object.entries(e.events??{}).map(([e,t])=>[e,{ws:t.ws??e,hasParams:!!t.params}]))}}function gC(e){return e&&e instanceof dc?Object.keys(e.shape):null}function _C(e,t){let n=t.cfg,r=TC(t.mws),i=t=>{throw Error(`endpoint "${e}": ${t}`)},a=new Map;for(let e of r)e.paramKey&&e.paramSchema&&a.set(e.paramKey,e.paramSchema);let o=new Map,s=(e,t)=>{for(let n of e.keys)(a.has(n)||o.has(n))&&i(`param ":${n}" is declared more than once (${t})`),o.set(n,e.schemas[n])};for(let e of t.prefixes)typeof e!=`string`&&s(e,`prefix path`);let c=typeof n.path==`object`&&n.path!==null?n.path:null;c&&s(c,`endpoint path`);let l=gC(n.params)??[];for(let e of l)(a.has(e)||o.has(e))&&i(`param ":${e}" is declared more than once (params schema)`);let u=new Set([...a.keys(),...o.keys(),...l]),d=[];for(let e of t.prefixes)d.push(...typeof e==`string`?pS(e):e.parts);if(c)d.push(...c.parts);else if(typeof n.path==`string`)d.push(...pS(n.path));else{d.push({t:`lit`,v:e});let t=new Set(gS(d));for(let e of u)t.has(e)||d.push({t:`param`,k:e})}let f=gS(d),p=new Set(f);f.length!==p.size&&i(`path positions a param more than once: ${mS(d)}`);for(let e of f)u.has(e)||i(`path references undeclared param ":${e}"`);for(let e of u)p.has(e)||i(`declared param ":${e}" has no position in path ${mS(d)}`);let m=[...u],h=gC(n.query)??[],ee=n.body?gC(n.body):null,te=!!n.body&&ee===null,ne=Object.keys(n.files??{}),re=new Map;for(let[e,t]of[[`path`,m],[`query`,h],[`body`,ee??[]],[`files`,ne]])for(let n of t){let t=re.get(n);t&&i(`key "${n}" appears in both ${t} and ${e} — kinds must be disjoint`),re.set(n,e)}te&&(m.length>0||h.length>0||ne.length>0)&&i(`a non-object body is the entire data payload — params/query/files are not allowed alongside it`);let ie=n.streamIn instanceof ws,ae=typeof n.streamIn==`string`?n.streamIn:ie?`application/x-ndjson`:null,oe=n.streamOut instanceof ws,se=oe&&n.streamEncoding===`sse`,ce=typeof n.streamOut==`string`?n.streamOut:oe?se?`text/event-stream`:`application/x-ndjson`:null,le=!!(n.httpOnly||typeof n.streamIn==`string`||typeof n.streamOut==`string`||ne.length>0);return{name:e,def:t,method:n.method??`POST`,parts:d,path:mS(d),ws:n.ws??null,wsEligible:!le,httpOnly:le,streamInCt:ae,itemsIn:ie,streamOutCt:ce,items:oe,sse:se,multi:!!(n.responses&&Object.keys(n.responses).length>0),bodyEnc:n.body?n.bodyEncoding??`json`:null,p:m,q:h,b:ee,bRaw:te,f:ne,loaders:a,tplSchemas:o,chain:r}}function vC(){return{}}function yC(e){return()=>{throw Error(`middleware "${e}" has no implementation — bind it with implement(api).middleware(def, impl)`)}}function bC(e,t,n,r,i,a){let o={kind:`middleware`,name:e,requires:t,optional:n,paramKey:r,paramSchema:i,doc:a,run:yC(e),with(...e){return xC([o,...e],[])},path(e){return xC([o],[e])},endpoint(e){return xC([o],[]).endpoint(e)},group(e){return xC([o],[]).group(e)}};return o}function xC(e,t){return{kind:`stack`,mws:e,prefixes:t,with(...n){return xC([...e,...n],t)},path(n){return xC(e,[...t,n])},endpoint(n){return fC(n,e,t)},group(n){let r={};for(let[i,a]of Object.entries(n))r[i]=fC(a,e,t);return r}}}function X(...e){return xC([...e],[])}function SC(e,t){return bC(e,t?.requires??[],t?.optional??[],void 0,void 0,t?.doc)}function CC(e,t,n){return bC(e,n?.requires??[],n?.optional??[],e,t,n?.doc)}var wC=Object.assign(SC,{loader:CC});function TC(e){let t=new Set,n=[],r=(e,i)=>{if(!t.has(e)){if(i.has(e))throw Error(`middleware cycle involving "${e.name}"`);i.add(e);for(let t of e.requires)r(t,i);i.delete(e),t.add(e),n.push(e)}};for(let t of e)r(t,new Set);let i=new Map(n.map((e,t)=>[e,t]));return[...n].sort((e,t)=>e.optional.includes(t)?1:t.optional.includes(e)?-1:i.get(e)-i.get(t))}function EC(...e){let t={},n={};for(let r of e){for(let[e,n]of Object.entries(r.endpoints)){if(Object.hasOwn(t,e))throw Error(`mergeSpecs: endpoint "${e}" is in more than one spec`);t[e]=n}for(let[e,t]of Object.entries(r.events??{})){if(Object.hasOwn(n,e))throw Error(`mergeSpecs: event "${e}" is in more than one spec`);n[e]=t}}return Y({endpoints:t,events:n})}var DC=new WeakMap;function OC(e,t){return DC.set(e._zod.def,{source:t}),e}function kC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var AC=class e extends U{static NAME=`record`;name=e.NAME;static optionKeys=[];static genericKeys=[`V`];static from(t,n){let r=t.generic?.V;return new e(n,r===void 0?n.registry.any():n.parse(r))}static toA(){return R.object({name:R.literal(e.NAME),generic:R.object({V:R.ref(`TypeDef`)}).optional()}).describe(`A record: an object with any text keys, each value a V.`)}constructor(e,t){super(e,{},{V:t})}get value(){let e=this.generic.V;if(e===void 0)throw Error(`record has no value type`);return e}valid(e,t){return kC(e)&&Object.values(e).every(e=>{try{return this.value.parse(e,t),!0}catch{return!1}})}parse(e,t){if(!kC(e))throw new Nm({path:[],code:`record.invalid`,message:`record.parse: expected an object of values by key`,severity:`error`});for(let[n,r]of Object.entries(e))try{this.value.parse(r,t)}catch(e){throw new Nm({path:[n],code:`record.value`,message:`record.parse: ${n}: ${e instanceof Error?e.message:String(e)}`,severity:`error`})}return new W(this,e)}encode(e){return e}create(){return{}}random(e){return{}}compatibleType(t){return t instanceof e&&this.value.compatibleType(t.value)}or(t){return t instanceof e&&this.value.compatibleType(t.value)?this:t}narrow(){return{}}toJSON(){return{name:e.NAME,generic:{V:this.value.toJSON()}}}clone(){return new e(this.scope,this.value)}toCode(e,t){return`${this.docsPrefix(t)}record<${this.value.toCode(void 0,t)}>`}valueA(e){return R.record(this.value.toA(e))}toNewA(){return R.record(R.ref(`Expr`))}};function jC(e){return e.typeClass(AC.NAME)===void 0&&e.define(AC),e}function MC(){return jC(Pv())}var NC;function PC(){return NC??=MC(),NC}var FC=Vy.result(`TypeDef`),IC=Vy.result(`Expr`);function LC(e){return()=>{let{description:t,...n}=e(PC()).render(Xl).jsonSchema;return n}}function RC(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zC(e){return RC(e)&&`name`in e&&typeof e.name==`string`}var Z=OC(Jc(zC,{message:`Expected a gin type definition ({ name, ... }).`}),LC(e=>FC.bind(e,void 0,{namedRefs:!0})));function BC(e){return zC(e)}var VC=OC(Jc(BC,{message:`Expected a gin object type definition ({ name: "obj", props: { ... } }).`}),LC(e=>Wy(e.typ(e.obj({}))).bind(e,void 0,{namedRefs:!0})));function HC(e){return RC(e)&&`kind`in e&&typeof e.kind==`string`}var UC=OC(Jc(HC,{message:`Expected a gin expression ({ kind, ... }).`}),LC(e=>IC.bind(e,void 0,{namedRefs:!0}))),WC=new Set(`id.uuid.guid.url.uri.api.json.csv.tsv.xml.html.css.yaml.sql.pdf.svg.png.jpg.ip.dns.http.https.ssh.tls.ssl.tcp.udp.vpn.os.cpu.gpu.ram.ui.ux.ai.llm.sku.sms.otp.jwt.utc.iso.gmt.ssn.vat.faq.crm.rgb.db.mime.ttl.oauth.sso.mfa`.split(`.`)),GC=new Map([[`ctx`,`context`]]);function KC(e,t){let n=e.toLowerCase();if(WC.has(n))return n.toUpperCase();let r=GC.get(n);return r===void 0?n.endsWith(`s`)&&WC.has(n.slice(0,-1))?`${n.slice(0,-1).toUpperCase()}s`:t?e:n:t?ZC(r):r}function qC(e){return ZC((/[\s._/:-]/.test(e)&&!/[a-z]/.test(e)?e.toLowerCase():e).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[\s._/:-]+/).filter(e=>e!==``).map((e,t)=>KC(e,t===0)).join(` `))||e}function JC(e){return e.label??qC(e.name)}function YC(e){return qC(Nl(e).local)}function XC(e){return/^[A-Z][a-z]/.test(e)?`${e.charAt(0).toLowerCase()}${e.slice(1)}`:e}function ZC(e){return e===``?e:`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function QC(e,t){let n=e.replace(/\s+/g,` `).trim();if(n.length<=t)return n;let r=n.slice(0,t-1),i=r.lastIndexOf(` `);return`${i>t*.6?r.slice(0,i):r}…`}var $C=[`path`,`file`,`uri`,`query`,`command`,`url`,`name`,`title`,`text`,`pattern`,`message`];function ew(e,t=60){if(e==null)return``;if(typeof e==`string`)return QC(e,t);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e))return e.length===0?``:`${e.length} item${e.length===1?``:`s`}`;let n=$C.map(t=>e[t]).find(e=>typeof e==`string`&&e!==``);if(typeof n==`string`)return QC(n,t);for(let[n,r]of Object.entries(e))if(typeof r==`string`||typeof r==`number`||typeof r==`boolean`)return QC(`${n}: ${String(r)}`,t);return``}var tw=[`active`,`retry`,`done`,`failed`],nw=E(tw),rw=S({one:v().min(1),many:v().min(1)}),iw=S({active:rw,retry:rw,done:rw,failed:rw}),aw=S({phase:nw,one:v(),many:v()}),ow={active:{one:`{fn}…`,many:`{fn} ×{n}…`},retry:{one:`Retrying {fn}…`,many:`Retrying {fn} ×{n}…`},done:{one:`{fn} done`,many:`{fn} ×{n} done`},failed:{one:`{fn} failed`,many:`{fn} ×{n} failed`}};function sw(e,t){switch(e){case`queued`:case`running`:case`waiting`:return t>1?`retry`:`active`;case`invalid-input`:return`retry`;case`done`:return`done`;case`failed`:return`failed`;case`awaiting-approval`:case`paused`:case`cancelled`:case`undone`:return}}var cw=60,lw=3,uw=/\{([^{}|]+)(?:\|([^{}]*))?\}/g;function dw(e,t,n){for(let r of e){if(r===void 0)continue;let e=pw(r[t].one,n,!1),i=pw(r[t].many,n,!0);if(e!==void 0&&i!==void 0)return{phase:t,one:e,many:i}}let r=ow[t];return{phase:t,one:pw(r.one,n,!1)??r.one,many:pw(r.many,n,!0)??r.many}}function fw(e,t){return t===1?e.one:e.many.replaceAll(`{n}`,String(t))}function pw(e,t,n){let r=[],i=e.replace(uw,(e,i,a)=>{let o=mw(i.trim(),t,n);return o===void 0?a===void 0?(r.push(i),e):a:o});return r.length>0?void 0:ZC(i.replace(/…{2,}/g,`…`))}function mw(e,t,n){if(e===`fn`)return XC(YC(t.fn));if(e===`n`)return n?`{n}`:void 0;let[r,...i]=e.split(`.`),a=r===`args`?t.args:r===`output`?t.output:void 0;return a===void 0?void 0:gw(hw(a,i))}function hw(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=Array.isArray(n)?n[Number(e)]:n[e]}return n}function gw(e){if(e!=null){if(typeof e==`string`)return e===``?void 0:vw(e);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e)){let t=e.map(gw).filter(e=>e!==void 0);if(t.length===0)return;let n=t.slice(0,lw),r=t.length-n.length;return _w(r>0?[...n,`${r} more`]:n)}for(let t of[`title`,`name`,`id`]){let n=e[t];if(typeof n==`string`&&n!==``)return vw(n)}}}function _w(e){return e.length<=2?e.join(` and `):`${e.slice(0,-1).join(`, `)} and ${e.at(-1)??``}`}function vw(e){let t=e.split(`
401
+ `)[0]??``;return t.length>cw?`${t.slice(0,59)}…`:t}var yw=E([`system-needs-config`,`system-disconnected`,`system-removed`,`kind-missing`,`kind-system-disconnected`,`dep-unavailable`,`disabled`,`held`,`paused`,`role-unset`]),bw=C([D(!0),S({unavailable:yw,detail:v()})]),xw=S({code:E([...yw.options,`no-such-fn`,`not-a-name`,`other-system`,`not-for-model`,`connect-account`]),reason:v().min(1),system:F.optional()}),Sw=xw.extend({fn:v()}),Cw=xw.extend({name:v()}),ww=S({id:M,name:v(),email:v(),role:E([`admin`,`member`]),groups:x(S({id:M,name:v()})),timeZone:v(),locale:v()}),Tw=S({now:N,timeZone:v(),local:v()}),Ew=S({name:v(),instance:L,boot:v(),from:S({system:v(),fn:I,run:A}).optional()}),Dw=S({id:A,fn:I,parent:A.optional(),turn:al,session:j.optional(),user:ww,time:Tw,system:Ew,caller:M,attempt:y().int().min(1),priority:Fl,watched:b().optional(),inChat:b().optional()}),Ow=S({timeZone:v(),locale:v(),now:N}),kw=E([`card`,`message`,`hidden`]),Aw=S({cancel:b(),pause:b(),undo:b(),background:b()}),jw=Aw.pick({cancel:!0,pause:!0,background:!0}),Mw=S({timeout:kl.optional(),retries:y().int().min(0).optional(),cost:P.optional()}),Nw=w(`type`,[S({type:D(`none`)}),S({type:D(`linear`)}),S({type:D(`steps`),steps:T(v(),v())})]),Pw=E([`pending`,`active`,`done`,`failed`,`skipped`]),Fw=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({steps:T(v(),S({status:Pw,detail:v().optional()}))})]),Iw=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({step:v(),status:Pw,detail:v().optional()})]),Lw=[`retry`,`caller`,`fatal`],Rw=S({class:E(Lw),message:v(),code:v().optional(),data:O.optional()}),zw=E([`json`,`schema`,`validation`,`unavailable`,`result`]),Bw=S({path:v(),message:v()}),Vw=S({path:v(),repair:E([`json-string`])});function Hw(e){return e.path===``?e.message:`${e.path}: ${e.message}`}var Uw=S({source:zw,problems:x(Bw).min(1),raw:v().optional(),blocked:xw.optional()}),Ww=[`awaiting-approval`,`queued`,`running`,`waiting`,`paused`,`done`,`invalid-input`,`failed`,`cancelled`,`undone`],Gw=E(Ww),Kw={"awaiting-approval":!1,queued:!1,running:!1,waiting:!1,paused:!1,done:!0,"invalid-input":!0,failed:!0,cancelled:!0,undone:!0},qw={"awaiting-approval":`Needs approval`,queued:`Queued`,running:`Running`,waiting:`Waiting`,paused:`Paused`,done:`Done`,"invalid-input":`Thinking harder`,failed:`Failed`,cancelled:`Cancelled`,undone:`Undone`};function Jw(e){return Kw[e]}function Yw(e){return!Kw[e]}var Xw=Ww.filter(Jw),Zw=Ww.filter(Yw),Qw=w(`type`,[S({type:D(`status`),status:Gw,text:aw.optional()}),S({type:D(`progress`),progress:Fw}),S({type:D(`allowed`),operations:jw}),S({type:D(`cost`),cost:P,total:P}),S({type:D(`background`)})]),$w=w(`status`,[S({status:D(`done`),result:O,undo:O.optional(),cost:P.optional(),expose:x(Nb).optional()}),S({status:D(`invalid-input`),invalid:Uw,undo:O.optional(),cost:P.optional()}),S({status:D(`paused`),resume:O,cost:P.optional()}),S({status:D(`failed`),error:Rw,undo:O.optional(),cost:P.optional()}),S({status:D(`cancelled`),partial:O.optional(),undo:O.optional(),cost:P.optional(),error:Rw.optional()})]),eT=w(`status`,[S({status:D(`done`),result:O}),S({status:D(`failed`),error:Rw}),S({status:D(`cancelled`),error:Rw.optional()}),S({status:D(`background`),run:A})]),tT=w(`status`,[S({status:D(`undone`),summary:v()}),S({status:D(`failed`),error:Rw}),S({status:D(`gone`)})]),nT=w(`ok`,[S({ok:D(!0),value:O}),S({ok:D(!1),error:Rw})]),rT=S({cost:P,time:kl,limitedBy:v()}),iT=mx,aT=S({hash:v().regex(Ex),kind:Fx,converter:v().min(1),content:Dx,chars:y().int().min(0),tokens:y().int().min(0),call:Tl.optional(),createdAt:N}),oT=S({kind:Fx,model:v().optional(),estimate:y().min(0).optional()}),sT=w(`from`,[S({from:D(`system`),system:F,served:E([`bytes`,`text`]).optional()}),S({from:D(`upload`),by:M}),S({from:D(`web`),url:fb,finalUrl:fb.optional(),fetchedAt:N,rendered:b()}),S({from:D(`run`),run:A,fn:I})]),cT=[`system`,`upload`,`web`,`run`],lT=E([`auto`,`always`,`never`]),uT=`hub://resources/`,dT=[`document`,`code`,`image`,`table`,`audio`,`video`,`web`,`data`,`archive`,`folder`,`other`],fT=E(dT),pT={markdown:`document`,text:`document`,pdf:`document`,docx:`document`,pptx:`document`,rtf:`document`,odt:`document`,notebook:`document`,html:`web`,json:`data`,jsonl:`data`,yaml:`data`,toml:`data`,xml:`data`,ini:`data`,csv:`table`,tsv:`table`,excel:`table`,ods:`table`,image:`image`,svg:`image`,mermaid:`image`,audio:`audio`,video:`video`,zip:`archive`,folder:`folder`,...Object.fromEntries(`typescript.javascript.jsx.tsx.vue.python.ruby.go.rust.java.c.cpp.csharp.php.swift.kotlin.scala.css.scss.less.shell.sql.dockerfile.graphql.lua.r.dart`.split(`.`).map(e=>[e,`code`]))};function mT(e,t){let n=e===void 0?void 0:pT[e];if(n!==void 0)return n;let r=t?.split(`/`)[0];return r===`image`||r===`audio`||r===`video`?r:`other`}var hT=E([`type`,`source`,`path`,`date`]),gT=S({value:v(),label:v(),count:y().int().min(0)}),_T=zl.extend({search:v().optional(),system:F.optional(),family:fT.optional(),source:E(cT).optional(),under:v().optional(),form:Fx.optional(),missing:Fx.optional(),group:hT.optional(),in:v().optional()}),vT=S({uri:Cx}),yT=S({uri:Cx,section:wx.optional()}),bT=S({image:Cx,question:v().trim().min(1).max(2e3),page:y().int().min(1).optional()}),xT=S({answer:v(),model:v(),image:S({id:Cx,name:v()})}),ST=S({uri:Cx,form:C([Fx,D(`raw`)]).optional(),section:wx.optional(),offset:y().int().min(0).optional(),maxChars:y().int().min(1).max(2e5).optional(),rows:S({table:v(),from:y().int().min(0),to:y().int().min(0)}).optional()}),CT=S({uri:Cx,form:C([Fx,D(`raw`)]),text:v(),offset:y().int().min(0),total:y().int().min(0),truncated:b(),partial:v().optional(),note:v().optional(),forms:x(Fx),offers:x(oT)}),wT=C([S({url:fb,render:lT.optional(),name:v().optional(),folder:v().min(1).optional()}),S({content:Dx,name:v().min(1),path:v().optional()})]),TT=C([S({model:v().min(1)}),S({category:v().min(1)}),S({auto:S({cost:y().min(0).optional(),speed:y().min(0).optional(),accuracy:y().min(0).optional()})})]),ET=S({id:v(),name:v(),arguments:v(),invalid:v().optional()}),DT=S({type:E([`text`,`image`,`file`,`audio`,`video`]),content:v(),format:v().optional(),name:v().optional()}),OT=S({role:E([`system`,`user`,`assistant`,`tool`]),content:C([v(),x(DT)]),name:v().optional(),toolCallId:v().optional(),toolCalls:x(ET).optional(),refusal:v().optional(),tokens:y().int().optional()}),kT=S({input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional()}),AT=E([`stop`,`length`,`tool_calls`,`content_filter`,`refusal`]),jT=S({content:v().optional(),reasoning:v().optional(),toolCallNamed:ET.optional(),toolCallArguments:ET.optional(),toolCallMore:ET.optional(),toolCall:ET.optional(),finishReason:AT.optional(),refusal:v().optional(),usage:kT.optional()}),MT=C([b(),y().positive()]),NT=E([`summary`,`list`,`markers`,`full`]),PT=C([NT,S({detail:NT.optional(),maxErrors:y().int().min(0).optional(),maxChars:y().int().min(0).optional(),suggestions:b().optional(),expected:b().optional(),context:y().int().min(0).optional(),depth:y().int().min(0).optional(),header:b().optional()})]),FT=S({name:v(),description:v().optional(),parameters:O,strict:MT.optional(),errorFormat:PT.optional()}),IT=C([D(`text`),D(`json`),S({schema:O,strict:MT,errorFormat:PT.optional(),schemaDelivery:E([`auto`,`structured`,`json`,`prompt`]).optional()})]),LT=S({messages:x(OT),temperature:y().optional(),maxTokens:y().int().optional(),stop:x(v()).optional(),tools:x(FT).optional(),toolChoice:C([E([`auto`,`none`,`required`]),S({tool:v()})]).optional(),responseFormat:IT.optional(),errorFormat:PT.optional()}),RT=S({run:A.optional(),request:LT,model:TT.optional(),stream:b()}),zT=w(`type`,[S({type:D(`chunk`),chunk:jT}),S({type:D(`done`),usage:kT,cost:P,interaction:ll,model:v()}),S({type:D(`error`),message:v(),kind:E([`model`,`tool`,`limit`,`provider`])})]),BT=S({id:v().min(1),text:v().min(1),score:y().min(0).max(1)}),VT=S({run:A,question:v().min(1),candidates:x(BT).min(1).max(50),max:y().int().min(1).max(20)}),HT=w(`by`,[S({by:D(`decision`),picked:x(S({id:v(),why:v().optional()})),note:v().optional(),call:Tl.optional()}),S({by:D(`off`)}),S({by:D(`failed`),message:v()})]),UT=w(`type`,[S({type:D(`predicate`),instructions:v().min(1)}),S({type:D(`choice`),instructions:v().min(1),choices:T(v(),v())}),S({type:D(`score`),instructions:v().min(1),levels:x(v()).min(1)})]),WT=C([v().min(1),x(OT).min(1)]),GT=T(v().min(1),UT),KT=y().min(0).max(1),qT=w(`type`,[S({type:D(`predicate`),probability:KT}),S({type:D(`choice`),choice:v(),probabilities:T(v(),KT),confidence:KT}),S({type:D(`score`),score:y(),probabilities:x(KT),confidence:KT}),S({type:D(`refusal`)})]),JT=T(v(),qT),YT=.5,XT=[`chat`,`embed`,`image`,`transcribe`,`speech`,`decide`];E(XT);var ZT=E([`yes`,`no`,`unknown`]),QT=S({modality:D(`chat`),input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional(),caching:ZT.optional()}),$T=S({modality:D(`embed`),texts:y().int().min(0),characters:y().int().min(0),images:y().int().min(1).optional(),tokens:y().int().min(0).optional(),dimensions:y().int().min(1)}),eE=S({modality:D(`image`),images:y().int().min(0),size:v().optional()}),tE=S({modality:D(`transcribe`),seconds:y().min(0),bytes:y().int().min(0)}),nE=S({modality:D(`speech`),characters:y().int().min(0),seconds:y().min(0).optional()}),rE=S({modality:D(`decide`),questions:y().int().min(0),characters:y().int().min(0),images:y().int().min(0).optional(),tokens:y().int().min(0).optional()});w(`modality`,[QT,$T,eE,tE,nE,rE]);var iE=E([`mp3`,`wav`,`ogg`]),aE=E([`running`,`done`,`failed`,`aborted`]),oE=S({id:Tl,provider:v(),model:v(),run:A.optional(),turn:al.optional(),session:j.optional(),system:F.optional(),fn:I.optional(),purpose:v().optional(),interaction:ll.optional(),cost:P,status:aE,error:v().optional(),priority:Fl.optional(),sent:y().int().min(0),received:y().int().min(0),queued:kl,firstByte:kl.optional(),total:kl.optional(),startedAt:N,endedAt:N.optional()}),sE=e=>S({modality:e.shape.modality,units:e}),cE=w(`modality`,[sE(QT),sE($T),sE(eE),sE(tE),sE(nE),sE(rE)]),lE=e=>oE.extend(e.shape),uE=w(`modality`,[lE(cE.options[0]),lE(cE.options[1]),lE(cE.options[2]),lE(cE.options[3]),lE(cE.options[4]),lE(cE.options[5])]),dE=w(`modality`,[S({modality:D(`embed`),texts:x(v()).min(1),model:TT.optional()}),S({modality:D(`image`),prompt:v().min(1),model:TT.optional(),size:v().optional(),count:y().int().min(1).max(10).optional()}),S({modality:D(`transcribe`),audio:Dx,model:TT.optional(),language:v().optional()}),S({modality:D(`speech`),text:v().min(1),model:TT.optional(),voice:v().optional(),format:iE.optional()}),S({modality:D(`decide`),input:WT,questions:GT,model:TT.optional()})]).and(S({run:A.optional()})),fE=w(`modality`,[S({modality:D(`embed`),vectors:x(x(y()))}),S({modality:D(`image`),images:x(Dx)}),S({modality:D(`transcribe`),text:v(),segments:x(S({start:y().min(0),end:y().min(0),text:v()})).optional()}),S({modality:D(`speech`),audio:Dx}),S({modality:D(`decide`),answers:JT})]).and(S({call:Tl,cost:P,model:v()})),pE=E([`chat`,`transcribe`,`dictate`,`speak`,`describe`,`ocr`,`decide`]),mE={chat:`chat`,transcribe:`hearing`,dictate:`hearing`,speak:`audio`,describe:`vision`,ocr:`vision`,decide:`decision`},hE=S({model:TT,provider:Sl.optional()}),gE=w(`engine`,[S({engine:D(`browser`)}),hE.extend({engine:D(`model`)})]),_E=[`browser`,`model`],vE=pE.exclude([`dictate`,`decide`]),yE=hE.extend({role:D(`decide`),threshold:y().min(0).max(1).default(YT)}),bE=w(`role`,[S({role:D(`dictate`),engine:gE,language:v().optional()}),yE,hE.extend({role:vE,language:v().optional()})]);S({choice:bE,setBy:M,updatedAt:N});var xE=C([S({model:v(),provider:v()}),S({problem:v()})]),SE=S({role:pE,choice:bE.optional(),from:E([`setting`,`env`,`none`]),resolved:xE.optional()}),CE=[`done`,`invalid-input`,`failed`,`cancelled`],wE=T(E(CE),y().int().min(0));function TE(){return{done:0,"invalid-input":0,failed:0,cancelled:0}}function EE(e){return CE.reduce((t,n)=>t+e[n],0)}var DE=v().regex(/^\d{4}-\d{2}-\d{2}$/),OE=[50,100,250,500,1e3,2500,5e3,1e4,3e4,6e4,3e5],kE=S({count:y().int().min(0),sum:kl,max:kl,histogram:x(y().int().min(0)).length(OE.length+1)}),AE=S({fn:I,system:F,day:DE,outcomes:wE,queued:kE,approval:kE,ran:kE,cost:P,tokens:y().int().min(0),retries:y().int().min(0),modelCalls:y().int().min(0),updatedAt:N}),jE=S({fn:I,system:F,from:DE,to:DE,runs:y().int().min(0),outcomes:wE,p50:kl.optional(),p95:kl.optional(),averageQueued:kl.optional(),averageCost:P,cost:P,tokens:y().int().min(0),retries:y().int().min(0),lastRunAt:N.optional()}),ME=S({fn:cb.optional(),system:F.optional(),days:y().int().min(1).max(365).optional()}),NE=E([`private`,`shared`,`public`]),PE={private:`Only me`,shared:`Me and chosen people`,public:`Everyone`},FE=S({owner:M,visibility:NE,with:x(M)});E([`system`,`fn`,`context`,`root`,`connection`]);var IE=w(`kind`,[S({kind:D(`system`),system:F}),S({kind:D(`fn`),fn:I}),S({kind:D(`context`),context:I}),S({kind:D(`root`),uri:v().min(1)}),S({kind:D(`connection`),connection:Ol})]);function LE(e){switch(e.kind){case`system`:return`system:${e.system}`;case`fn`:return`fn:${e.fn}`;case`context`:return`context:${e.context}`;case`root`:return`root:${e.uri}`;case`connection`:return`connection:${e.connection}`}}S({key:v(),target:IE,sharing:FE,scoped:b().optional(),setBy:M,updatedAt:N});var RE=S({target:IE,sharing:FE,editable:b()}),zE=S({multiUser:b()}),BE=FE.omit({owner:!0}),VE=S({run:A,fn:k,share:BE}),HE=S({run:A,fns:x(k).max(1e3)}),UE=S({source:E([`fn`,`context`,`system`,`person`,`group`,`model`,`resource`,`type`,`kind`]),text:v().optional(),values:x(v()).max(200).optional(),limit:y().int().min(1).max(50).optional()}),WE=S({value:v(),label:v(),hint:v().optional(),icon:v().optional(),missing:b().optional()}),GE=E([`shared`,`person`]),KE=v().regex(/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/),qE=T(KE,v()),JE=S({kind:D(`none`)}),YE=S({kind:D(`bearer`),per:GE,token:v().min(1).optional()}),XE=S({kind:D(`headers`),per:GE,names:x(KE).min(1),values:qE.optional()}),ZE=w(`kind`,[JE,YE,XE,S({kind:D(`oauth`),per:GE,scopes:x(v().min(1)).optional(),clientId:v().min(1).optional(),clientSecret:v().min(1).optional()})]),QE=w(`kind`,[JE,YE,XE]),$E=w(`kind`,[JE,YE.omit({token:!0}),XE.omit({values:!0})]),eD=[`auth.token`,`auth.values`],tD=[`auth.token`,`auth.values`,`auth.clientSecret`];function nD(e){if(e.kind===`oauth`)return`oauth`;if(e.kind!==`none`&&e.per!==`shared`)return`form`}var rD=C([S({token:v().min(1)}),S({headers:qE}),S({accessToken:v().min(1),refreshToken:v().min(1).optional(),tokenType:v().default(`Bearer`),clientId:v().min(1).optional()})]),iD=S({on:b(),ask:b()}),aD=w(`flow`,[S({flow:D(`oauth`)}),S({flow:D(`form`),form:Z})]),oD=S({flow:aD.optional(),share:b().default(!1),title:v().min(1)}),sD=v().regex(Al).brand();fc({name:sD,label:v().min(1),auth:ZE,baseUrl:Ls().optional(),privateTo:M.optional()});var cD=C([sD,S({arg:k})]),lD=S({title:v(),description:v(),icon:v().optional(),how:aD,settings:Z,fns:T(k,iD),scope:E([`system`,`instance`,`key`]).optional(),keys:S({type:I}).optional(),defaults:iD.optional()}),uD=E([`pending`,`connected`,`expired`,`failed`]),dD=S({label:v(),detail:v().optional(),choices:T(v(),x(WE)).optional()}),fD=S({id:Ol,system:F,instance:L.optional(),key:sD.optional(),owner:M,status:uD,account:dD.optional(),credentials:bl.optional(),expiresAt:N.optional(),settings:O,fns:T(k,iD),share:BE,problem:v().optional(),createdAt:N,updatedAt:N}).omit({credentials:!0}),pD=S({system:F,decl:lD,ready:b(),connections:x(fD),instances:x(S({instance:L,label:v(),connect:oD})).optional(),keys:x(S({key:sD,label:v(),connect:oD,host:v().optional()})).optional()}),mD=S({id:Ol,owner:M,credentials:O,settings:O}),hD=S({connection:Ol,owner:M,redirect:Ls(),state:v(),instance:L.optional(),key:sD.optional()}),gD=S({connection:Ol,owner:M,instance:L.optional(),key:sD.optional(),redirect:Ls(),answer:C([S({params:T(v(),v())}),S({form:O})])}),_D=C([S({account:dD,credentials:O,expiresAt:N.optional()}),S({problem:v()})]),vD=S({connection:Ol,update:C([S({credentials:O,expiresAt:N.optional()}),S({expired:v()})])}),yD=S({connection:Ol,settings:O.optional(),fns:T(k,iD).optional(),share:BE.optional()}),bD=[`embedding`,`imageEmbedding`],xD=S({input:P,output:P,cached:P.optional(),cacheWrite:P.optional()}),SD=S({id:v().min(1),name:v().optional(),capabilities:x(v()),contextWindow:y().int().min(1),maxOutput:y().int().min(1).optional(),pricing:xD,caching:b(),dimensions:y().int().min(1).optional(),maxInput:y().int().min(1).optional(),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}).refine(e=>!bD.some(t=>e.capabilities.includes(t))||e.dimensions!==void 0,{message:`An embedding model says how many dimensions its vectors have.`,path:[`dimensions`]}),CD=S({name:k,description:v(),models:x(SD),runtime:D(!0).optional(),instance:L.optional()}),wD=S({provider:k,model:v(),request:LT,stream:b(),run:A.optional()}),TD=w(`type`,[S({type:D(`chunk`),chunk:jT}),S({type:D(`done`),usage:kT}),S({type:D(`error`),message:v(),kind:E([`model`,`limit`,`provider`,`auth`])})]),ED=S({id:v().min(1),contextWindow:y().int().min(1).optional(),maxOutput:y().int().min(1).optional(),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}),DD=S({provider:k}),OD=w(`listed`,[S({listed:D(!0),models:x(ED)}),S({listed:D(!1)})]),kD=S({provider:k,model:v(),input:WT,questions:GT}),AD=S({answers:JT,tokens:y().int().min(0).optional()}),jD=S({image:v().regex(/^(https?:|data:)/,`an http(s) or data URL`),mimeType:v().optional()}),MD=C([v(),jD]),ND=S({provider:k,model:v(),inputs:x(MD).min(1)}),PD=S({vectors:x(x(y())),tokens:y().int().min(0).optional()});function FD(e){return S({provider:D(`aws`),region:v().min(1),auth:w(`kind`,[S({kind:D(`keys`),accessKeyId:v().min(1),secretAccessKey:e,sessionToken:e.optional()}),S({kind:D(`apiKey`),apiKey:e})]),profilePrefix:v().optional()})}var ID=S({input:b(),output:b()}),LD=C([S({ok:D(!0)}),S({ok:D(!1),reason:v().min(1)})]),RD=C([S({ok:D(!0)}),S({ok:D(!1),action:E([`retry`,`stop`]),reason:v().min(1)})]),zD=w(`phase`,[S({phase:D(`input`),run:Dw,fn:v(),args:O}),S({phase:D(`output`),run:Dw,fn:v(),args:O,result:O,attempt:y().int().min(1)})]),BD=C([RD,LD]),VD=S({kind:E([`builtin`,`dynamic-import`,`dynamic-require`,`eval`,`new-function`]),line:y().int().min(1),detail:v(),code:v()}),HD=S({size:y().int().min(0),builtins:x(v()),concerns:x(VD),urls:x(v()),hosts:x(v())}),UD=E([`passed`,`failed`,`skipped`]),WD=S({file:v().min(1),name:v().min(1),status:UD,duration:kl,real:b().optional(),error:v().max(4e3).optional()}),GD=[`phone`,`desktop`],KD=E(GD);E([`empty`,`loading`,`error`,`typical`,`long`]);var qD=S({component:v().min(1),state:v().min(1),viewport:KD,theme:E([`light`,`dark`]),image:Dx}),JD=S({scan:HD,tests:S({system:F,version:v().min(1),ranAt:N,duration:kl,passed:y().int().min(0),failed:y().int().min(0),skipped:y().int().min(0),cases:x(WD).max(500),more:y().int().min(0).optional(),previews:x(qD).max(200).optional()}).optional()}),YD=E([`ai`,`embed`,`resources`,`fns`,`search`,`decide`,`approvals`,`connections`,`settings`,`state`,`data`,`runs`]),XD=S({roles:x(pE).optional(),models:x(v().min(1)).optional(),perRun:P.optional(),perDay:P.optional()}),ZD=S({read:x(v().min(1)),write:x(v().min(1))}),QD=S({hub:x(YD),models:XD.optional(),secrets:x(v().min(1)).optional(),calls:x(C([I,F])).optional(),network:x(v().min(1)).optional(),files:ZD.optional()}),$D=S({component:v().min(1),mode:E([`replace`,`beside`])}),eO=[`installed`,`live`],tO=E(eO),nO=[`text`,`integer`,`number`,`boolean`,`date`,`datetime`,`time`,`uuid`,`json`,`binary`],rO=E(nO),iO=E([`group`,`measure`,`attribute`]),aO=S({name:k,label:v().min(1),accepts:x(rO).min(1),required:b(),many:b(),min:y().int().min(1).optional(),role:E([`group`,`measure`]).optional()}),oO=w(`rule`,[S({rule:D(`distinct`),channel:k,max:y().int().min(1)}),S({rule:D(`non-negative`),channel:k}),S({rule:D(`bounded`),channel:k}),S({rule:D(`distinct-columns`),channels:x(k).min(2)}),S({rule:D(`links`),from:k,to:k})]),sO=E([`window`,`top-n`,`partition`,`aggregate`]),cO=S({name:k,label:v().min(1),whole:D(!0).optional(),needs:x(k).optional()}),lO=S({claim:D(`range`),channel:k}),uO=E([`floor`,`structural`,`encoded`,`time-encoded`]),dO=E([`temporal-key`,`low-cardinality`,`enum-key`,`high-null`,`many-categories`]),fO=S({channels:x(aO).min(1),rows:S({min:y().int().min(0),max:y().int().min(1).optional()}),whole:b(),rules:x(oO).default([]),size:sO.optional(),styles:x(cO).min(1).default([{name:`default`,label:`Default`}]),claims:x(lO).default([]),priority:S({band:uO,terms:x(dO)}).default({band:`structural`,terms:[]}),pageSize:y().int().min(1).max(500).optional()}),pO=S({name:k,description:v(),data:Z}),mO=S({registry:I,name:k,label:v().min(1),description:v().optional(),icon:v().optional(),shape:fO.optional()}),hO=mO.extend({system:F}),gO=S({name:v().min(1),label:v().optional(),kind:rO,nullable:b(),type:Z.optional(),ref:I.optional(),role:iO.optional(),key:b().optional(),editable:b().optional()}),_O=S({column:v().min(1),dir:E([`asc`,`desc`])}),vO=S({fn:I,args:T(v(),O),keys:x(v().min(1))}),yO=S({columns:x(gO),rows:x(x(O)),offset:y().int().min(0),limit:y().int().min(1).optional(),total:y().int().min(0).optional(),truncated:b(),sort:x(_O),write:S({affected:y().int().min(0)}).optional(),records:S({type:I,id:v().min(1)}).optional(),drill:vO.optional()}),bO=S({flag:E([`delete-fns`,`write-fns`,`runs`,`injects`,`effects`,`capabilities`,`secrets`,`hosts`,`files`,`calls`,`models`]),line:v().min(1),items:x(v().min(1)),lead:v().min(1).optional(),tail:v().min(1).optional()}),xO=S({section:v().min(1),added:y().int().min(0),changed:y().int().min(0),removed:y().int().min(0)}),SO=E([`widened`,`narrowed`,`changed`,`added`]),CO=S({line:v(),counts:x(xO),flags:x(bO),grants:SO.optional(),config:E([`added`,`changed`,`removed`]).optional()}),wO=E([`gitignored`,`env`,`key`,`credential`,`token`,`secret-content`,`runs-code`,`unknown-path`]),TO=E([`allow`,`ask`,`refuse`]),EO=E([`ask`,`refuse`]),DO=w(`type`,[S({type:D(`glob`),glob:v().min(1)}),S({type:D(`content`),pattern:v().min(1)}),S({type:D(`gitignored`)})]);S({name:v().min(1),kind:wO,match:DO,except:x(v().min(1)).optional(),read:TO,write:EO,why:v().min(1)});var OO=S({path:v().min(1),kind:wO,rule:v().min(1),access:E([`read`,`write`]),action:E([`allow`,`ask`,`refuse`]),why:v().min(1),certain:b()}),kO=S({flags:x(OO)}),AO=w(`type`,[S({type:D(`text`),text:v()}),S({type:D(`code`),language:v(),code:v(),title:v().optional()}),S({type:D(`table`),title:v(),table:yO}),S({type:D(`type-diff`),name:v(),before:Z.optional(),after:Z.optional(),changes:x(v()),breaks:x(S({fn:v(),why:v()}))}),S({type:D(`flags`),flags:x(OO).min(1)})]),jO=S({kind:D(`system-install`),system:F,instance:L,version:v().min(1),manifestHash:v().min(1),bundleHash:v().min(1),sourceHash:v().min(1),host:Wl,source:v().min(1).optional(),grants:QD.optional(),replaces:S({version:v().min(1),manifestHash:v().min(1)}).optional()}),MO=w(`kind`,[jO]),NO=S({title:v().min(1),parts:x(AO),irreversible:b(),subject:MO.optional(),checks:JD.optional(),summary:CO.optional()}),PO=E([`person`,`admins`]),FO=S({preview:b(),remember:b(),approver:PO.optional()}),IO=S({run:A,fn:k,args:O,user:ww,kind:jl.optional(),payload:O.optional()}),LO=S({run:A,fn:k,args:O,user:ww,deadline:N}),RO=S({problems:x(Bw)}),zO=S({type:Z,into:k,label:v().min(1).max(80).optional()}),BO=S({fn:k,args:O,key:v().min(1),parent:A.optional(),approver:PO,for:M.optional(),chat:j.optional(),ask:zO.optional(),preview:NO}).refine(e=>e.parent!==void 0||e.approver===`admins`||e.for!==void 0,{message:"A run proposed outside a run waits for an admin, or for the person named in `for`.",path:[`approver`]}),VO=S({by:M,preview:NO}),HO=S({run:A,subject:jO}),UO=S({token:v().min(1),expiresAt:N}),WO=S({run:A,approval:pl}),GO=v().regex(/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/),KO=x(GO),qO=`•••• kept`;S({$secret:bl,json:D(!0).optional()});var JO=v().regex(/^[a-z][a-z0-9-]{0,39}$/,`a page segment is lowercase letters, digits and dashes, starting with a letter (at most 40)`),YO=E([`main`,`hidden`]),XO=E([`everyone`,`admin`]),ZO=S({segment:JO,title:v().trim().min(1).max(40),description:v().optional(),icon:v().min(1).optional(),nav:YO.default(`main`),access:XO.default(`everyone`),component:v().min(1)});function QO(e){let t=new Set;return e.flatMap(e=>t.has(e.segment)?[`page ${e.segment} is declared twice`]:(t.add(e.segment),[]))}var $O=x(ZO).superRefine((e,t)=>{for(let n of QO(e))t.addIssue({code:`custom`,message:n})}),ek=ZO.extend({system:F,client:S({url:v().min(1),hash:v().min(1)})}),tk=`http://127.0.0.1:11434`;function nk(e){return w(`provider`,[S({provider:D(`openai`),apiKey:e,baseURL:Ls().optional()}),S({provider:D(`openrouter`),apiKey:e}),S({provider:D(`ollama`),baseURL:Ls().default(tk),contextWindow:y().int().min(256).optional(),decisionModels:x(v().min(1)).optional()}),FD(e)])}var rk=nk(bl),ik=E(rk.options.map(e=>e.shape.provider.value));S({id:Sl,config:rk,createdAt:N}),S({id:bl,name:v(),owner:M,ciphertext:v(),createdAt:N});var ak=S({id:xl,name:v(),description:v(),models:x(v())}),ok=w(`scope`,[S({scope:D(`hub`)}),S({scope:D(`group`),group:M}),S({scope:D(`user`),user:M}),S({scope:D(`session`),session:j}),S({scope:D(`turn`),turn:al}),S({scope:D(`system`),system:F}),S({scope:D(`fn`),fn:I}),S({scope:D(`model`),model:v()})]),sk=E([`hub`,`group`,`user`,`session`,`turn`]),ck=w(`scope`,[S({scope:D(`hub`)}),S({scope:D(`group`),group:M}),S({scope:D(`user`),user:M}),S({scope:D(`session`),session:j}),S({scope:D(`turn`),turn:al})]),lk=S({id:ml,target:ok,period:C([S({window:kl}),D(`all-time`),D(`per-turn`)]),maxCost:P,maxTokens:y().int().optional(),maxCalls:y().int().optional(),maxTime:kl.optional(),share:E([`pooled`,`each`]).optional(),onLimit:E([`wait`,`refuse`,`ask`]),setBy:M}),uk=S({id:hl,target:ck,default:Fl.optional(),max:Fl.optional(),setBy:M}),dk=S({priority:Fl,priorityFrom:S({default:sk,cappedBy:sk.optional()}),turn:S({cost:P,time:kl}),budgets:x(S({rule:ml,scope:ok,remaining:P})),limitedBy:ml.optional()});S({id:gl,budgets:x(ml),estimate:P,createdAt:N,settled:S({cost:P,at:N}).optional()}),S({id:_l,at:N,cost:P,tokens:y().int().min(0),actor:M,system:F.optional(),session:j.optional(),fn:I,model:v().optional(),llmCall:ll.optional(),modelCall:Tl.optional(),run:A});var fk=E([`chat`,`admin`,`disconnected`,`needs-config`,`held`,`removed`]),pk=S({prompt:x(S({name:F,label:v(),description:v(),summary:v().optional()})),on:x(F),off:x(S({name:F,why:fk}))}),mk=S({name:F,reason:v(),label:v().optional(),description:v().optional()}),hk=RegExp(`(\\d+)`,`g`);function gk(e,t=[]){let n=new Map(t.map(e=>[e.index,e.number]));return e.replace(hk,(e,t)=>{let r=n.get(Number(t));return r===void 0?``:`[${r}]`})}function _k(e){let t=e.trim().replace(/^\$\.?/,``);if(t===``)return[];let n=[],r=/\[\s*(?:"([^"]*)"|'([^']*)'|(\d+))\s*\]|([^.[\]]+)/y,i=0;for(;i<t.length;){if(t[i]===`.`){i+=1;continue}r.lastIndex=i;let e=r.exec(t);if(e===null)return;n.push(e[1]??e[2]??e[3]??e[4]??``),i=r.lastIndex}return n}function vk(e){try{return O.parse(JSON.parse(e))}catch{return}}function yk(e,t){let n=_k(t);if(n===void 0)return;let r=e;for(let e of n){let t=typeof r==`string`?vk(r):r;if(Array.isArray(t)){if(!/^\d+$/.test(e))return;let n=t[Number(e)];if(n===void 0)return;r=n}else if(typeof t==`object`&&t){if(!Object.hasOwn(t,e))return;let n=t[e];if(n===void 0)return;r=n}else return}return{value:r}}var bk=S({index:y().int().min(1),number:y().int().min(1),tool:v(),path:v(),note:v()}),xk=E([`result`,`reply`]),Sk=bk.extend({run:A.optional(),fn:I.optional(),found:xk.optional(),value:O.optional(),large:D(!0).optional(),problem:v().optional()}),Ck=S({prompt:b(),on:b()}),wk=y().int().min(0).max(3),Tk=S({agent:I,model:TT.optional(),mode:Lb.optional(),contextor:Jb.optional(),fnMode:ux.optional(),systems:C([x(F),D(`all`)]),instructions:v().optional(),citations:b().optional()}),Ek=Tk.partial(),Dk=x(S({label:v().trim().min(1).max(40).optional(),settings:Ek})).min(2).max(4),Ok=S({turn:al,variant:wk,label:v()}),kk=S({variant:wk,label:v(),settings:Ek,session:j,turn:al}),Ak=S({run:A,fn:I}),jk=S({variant:wk,effects:x(Ak)}),Mk=S({variant:wk,label:v(),effects:x(Ak).min(1)}),Nk=S({variants:x(kk).min(2).max(4),reserved:P,chosen:wk.optional(),chosenBy:M.optional(),chosenAt:N.optional(),discarded:x(jk)}),Pk=S({field:v(),type:v(),before:O.optional(),after:O.optional()}),Fk=S({id:A,fn:I,fnVersion:v(),kind:jl,system:F,instance:L.optional(),parent:A.optional(),root:A,turn:al,session:j.optional(),key:v(),actor:M,caller:M,connection:Ol.optional(),llmCall:ll.optional(),toolCallId:v().optional(),args:O,repairs:x(Vw).optional(),test:b().optional(),status:Gw,text:aw.optional(),outcome:$w.optional(),progress:Fw.optional(),allowed:jw,cost:P,totalCost:P,priority:Fl,background:b(),attempt:y().int().min(1),errors:x(S({attempt:y().int(),error:Rw,cost:P,at:N})),undo:O.optional(),resume:O.optional(),stateChanges:x(Pk),tokens:y().int().min(0).optional(),createdAt:N,approvedAt:N.optional(),startedAt:N.optional(),endedAt:N.optional()}),Ik=Fk.pick({id:!0,fn:!0,status:!0,cost:!0,totalCost:!0,startedAt:!0,endedAt:!0}),Lk=S({session:j,system:F,name:v(),type:v(),def:Z,value:O,version:y().int().min(1),updatedBy:C([S({run:A}),S({delivery:sl})]),updatedAt:N}).pick({name:!0,type:!0}).extend({value:O.optional()}),Rk=E([`queued`,`delivered`,`done`,`failed`,`expired`]),zk=S({id:sl,system:F,kind:C([S({action:v(),input:O}),S({form:A,value:O})]),session:j,actor:M,run:A.optional(),status:Rk,result:O.optional(),error:Rw.optional(),attempts:y().int().min(0),createdAt:N,deliveredAt:N.optional(),doneAt:N.optional(),expiresAt:N.optional()}).pick({id:!0,status:!0,result:!0,error:!0}),Bk=S({id:cl,run:A,handler:v(),args:O,decl:S({description:v(),args:Z,returns:Z}),answerer:C([S({user:M}),S({system:F,run:A})]),status:E([`pending`,`answered`,`failed`]),result:O.optional(),createdAt:N}),Vk=E([`running`,`done`,`failed`,`cancelled`,`paused`,`undone`]),Hk=S({transcript:y().int().min(0),tools:x(I),context:x(I),selection:cx.optional(),suggested:x(I).optional(),announcedSystems:pk.optional(),citationsTold:Ck.optional()});S({id:al,session:j.optional(),message:ol.optional(),actor:M,user:ww,time:Tw,client:Ow.optional(),root:A.optional(),status:Vk,limits:dk,cost:P,errors:C([S({max:y().int().min(1)}),D(`feed-back`)]),start:Hk.optional(),compare:Nk.optional(),createdAt:N,continuedAt:N.optional(),endedAt:N.optional()});var Uk=E([`queued`,`streaming`,`done`,`failed`,`aborted`]),Wk=S({content:v(),reasoning:v().optional(),toolCalls:x(jT.shape.toolCall.unwrap()).optional(),finishReason:jT.shape.finishReason.unwrap(),refusal:v().optional()}),Gk=S({id:ll,turn:al,run:A,session:j.optional(),system:F.optional(),iteration:y().int().min(0),provider:v(),model:v(),request:LT,response:Wk.optional(),usage:kT.optional(),cost:P,status:Uk,error:v().optional(),priority:Fl,selection:ax.optional(),modelCall:Tl.optional(),queuedAt:N,startedAt:N.optional(),firstTokenAt:N.optional(),endedAt:N.optional()}),Kk=Kc(()=>S({run:Ik,llmCalls:x(Gk.pick({id:!0,model:!0,cost:!0,status:!0})),children:x(Kk)})),qk=S({turn:al,undone:x(S({run:A,fn:I,summary:v()})),failed:x(S({run:A,fn:I,error:Rw})),notUndoable:x(S({run:A,fn:I})),kept:x(Mk).optional(),session:S({messages:y().int().min(0),unloaded:x(I),reloaded:x(I)}).optional()});S({run:A,turn:al,session:j.optional(),iteration:y().int().min(0),priority:Fl}),S({run:A,priority:Fl});var Jk=[`system`,`instance`,`fn`,`context`,`type`,`kind`,`resource`,`root`,`component`,`registry`,`command`,`provider`],Yk=E(Jk),Xk=[`brings`,`names`,`loads`,`next`,`reads`,`writes`,`calls`,`uses`,`kind`,`creates`,`updates`,`removes`,`refers`,`renders`,`contributes`,`belongs`],Zk=E(Xk),Qk=[...eO,`pending`];E(Qk);var $k=E([`text`,`enum`,`number`,`date`,`boolean`]);E([`is`,`isNot`,`in`,`notIn`,`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`,`contains`]);var eA={text:[`contains`,`is`,`isNot`,`in`,`notIn`,`empty`,`notEmpty`],enum:[`is`,`isNot`,`in`,`notIn`,`empty`,`notEmpty`],number:[`gt`,`gte`,`lt`,`lte`,`between`,`is`,`isNot`,`empty`,`notEmpty`],date:[`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`],boolean:[`is`]},tA={is:`is`,isNot:`is not`,in:`in`,notIn:`not in`,gt:`>`,gte:`≥`,lt:`<`,lte:`≤`,between:`between`,empty:`is empty`,notEmpty:`is not empty`,contains:`contains`},nA=C([v(),y(),b()]),rA=E([`usd`,`ms`,`tokens`,`bytes`,`count`]);S({label:v(),type:$k,sortable:b(),filterable:b(),values:x(v()).readonly().optional(),dynamic:b().optional(),unit:rA.optional()});var iA=v().min(1),aA=w(`op`,[S({field:iA,op:E([`is`,`isNot`,`gt`,`gte`,`lt`,`lte`,`contains`]),value:nA}),S({field:iA,op:E([`in`,`notIn`]),values:x(nA).min(1)}),S({field:iA,op:D(`between`),from:nA,to:nA}),S({field:iA,op:E([`empty`,`notEmpty`])})]),oA=S({field:iA,dir:E([`asc`,`desc`])}),sA=zl.extend({text:v().optional(),filters:x(aA).max(20).optional(),sort:x(oA).max(3).optional()}),cA=(e,t={})=>({label:e,type:`text`,sortable:!0,filterable:!0,...t}),lA=(e,t)=>({label:e,type:`enum`,sortable:!0,filterable:!0,values:t}),uA=e=>({label:e,type:`enum`,sortable:!0,filterable:!0,dynamic:!0}),dA=(e,t)=>({label:e,type:`number`,sortable:!0,filterable:!0,unit:t}),fA=e=>({label:e,type:`date`,sortable:!0,filterable:!0}),pA=e=>({label:e,type:`boolean`,sortable:!1,filterable:!0}),mA=e=>({...e,sortable:!1}),hA=[`resources`,`fns`,`runs`,`modelCalls`,`llmCalls`,`sessions`,`contexts`,`notifications`,`systems`,`types`,`graph`,`users`,`groups`],gA=E(hA),_A={resources:{fields:{name:cA(`Name`),system:uA(`System`),family:lA(`Type`,dT),source:lA(`Source`,cT),forms:{...lA(`Forms`,Fx.options),sortable:!1},size:dA(`Size`,`bytes`),seenAt:fA(`Seen`),modifiedAt:fA(`Modified`)},defaultSort:[{field:`seenAt`,dir:`desc`}]},fns:{fields:{name:cA(`Name`),system:uA(`System`),kind:uA(`Kind`),available:pA(`Available`),paused:pA(`Paused`),disabled:pA(`Disabled`),runs:dA(`Runs`,`count`),failures:dA(`Failures`,`count`),averageCost:dA(`Avg cost`,`usd`),averageTime:dA(`Avg time`,`ms`),lastRunAt:fA(`Last run`),updatedAt:fA(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},runs:{fields:{fn:uA(`Fn`),system:uA(`System`),status:lA(`Status`,Ww),session:uA(`Session`),actor:uA(`By`),cost:dA(`Cost`,`usd`),duration:dA(`Duration`,`ms`),createdAt:fA(`Started`),endedAt:fA(`Ended`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},modelCalls:{fields:{modality:lA(`Modality`,XT),model:uA(`Model`),provider:uA(`Provider`),system:uA(`System`),status:lA(`Status`,aE.options),session:uA(`Session`),cost:dA(`Cost`,`usd`),tokens:dA(`Tokens`,`tokens`),duration:dA(`Duration`,`ms`),createdAt:fA(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},llmCalls:{fields:{model:uA(`Model`),system:uA(`System`),status:lA(`Status`,Uk.options),session:uA(`Session`),cost:dA(`Cost`,`usd`),tokens:dA(`Tokens`,`tokens`),duration:dA(`Duration`,`ms`),createdAt:fA(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},sessions:{fields:{title:cA(`Title`),agent:uA(`Agent`),status:lA(`Status`,[`idle`,`running`,`paused`]),archived:pA(`Archived`),createdAt:fA(`Created`),updatedAt:fA(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},contexts:{fields:{name:cA(`Name`),system:uA(`System`),origin:lA(`Origin`,Xx),tags:uA(`Tag`),disabled:pA(`Off`),stale:pA(`Stale`),tokens:dA(`Tokens`,`tokens`),updatedAt:fA(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},notifications:{fields:{kind:uA(`Kind`),read:pA(`Read`),createdAt:fA(`Received`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},systems:{fields:{name:cA(`Name`),status:uA(`Status`),version:cA(`Version`),instances:dA(`Instances`,`count`),fns:dA(`Fns`,`count`),context:dA(`Context`,`count`),types:dA(`Types`,`count`),parts:dA(`Other parts`,`count`),pending:dA(`Pending changes`,`count`),refusals:dA(`Refusals`,`count`),lastSeenAt:fA(`Last seen`)},defaultSort:[{field:`name`,dir:`asc`}]},types:{fields:{name:cA(`Name`),system:uA(`System`),instance:uA(`Instance`),references:dA(`Refers to`,`count`),updatedAt:fA(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},graph:{fields:{name:mA(cA(`Name`)),system:mA(uA(`System`)),nodeKind:mA(lA(`Item`,Jk)),edgeKind:mA(lA(`Link`,Xk)),fnKind:mA(uA(`Fn kind`)),mode:mA(uA(`Mode`)),effect:mA(uA(`Effect on`)),visibility:mA(lA(`Visible to`,Il.options)),stage:mA(lA(`Stage`,Qk)),on:pA(`On`)},defaultSort:[]},users:{fields:{name:cA(`Name`),email:cA(`Email`),role:lA(`Role`,[`admin`,`member`]),disabled:pA(`Disabled`),createdAt:fA(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]},groups:{fields:{name:cA(`Name`),createdAt:fA(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]}};function vA(e,t){return t.sort!==void 0&&t.sort.length>0?t.sort:_A[e].defaultSort}var yA=S({value:nA,label:v().optional(),count:y().int().min(0)}),bA=S({list:gA,field:iA,prefix:v().optional(),limit:y().int().min(1).max(50).optional()}),xA=S({list:gA,query:sA.default({})}),SA=Rl(Zc()).extend({sort:x(oA),total:y().int().min(0).optional(),partial:D(!0).optional().describe(`More rows than the hub reads at once: more may match; narrow the filters for a full answer.`)}),CA=il.record,wA=S({shape:E([`table`,`value`]),owner:E([`shared`,`person`]),writers:D(`admins`).optional(),search:S({text:x(v().min(1)),embed:b()})}),TA=S({id:CA,type:I,value:O,owner:M.optional(),title:v(),version:y().int().min(1),createdAt:N,updatedAt:N,updatedBy:M.optional(),updatedBySystem:F.optional(),run:A.optional()}),EA=S({id:v().min(1),record:CA,type:I,number:y().int().min(1),change:E([`created`,`updated`,`removed`]),value:O,by:M.optional(),bySystem:F.optional(),run:A.optional(),at:N}),DA=S({type:I,query:sA.optional(),search:v().min(1).optional(),run:A.optional()}),OA=Rl(TA),kA=DA.extend({query:sA.omit({cursor:!0,limit:!0}).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(500).optional()}),AA=S({type:I,id:CA,run:A.optional()}),jA=S({type:I,id:CA.optional(),value:O,expect:y().int().min(1).optional(),run:A.optional(),owner:M.optional()}),MA=S({type:I,id:CA,set:T(v().min(1),O).refine(e=>Object.keys(e).length>0,`set at least one field`),expect:y().int().min(1).optional(),run:A.optional()}),NA=S({type:I,id:CA,run:A.optional()}),PA=zl.extend({type:I,id:CA}),FA=Rl(EA),IA=S({type:I,system:F,description:v(),storage:wA,records:y().int().min(0),updatedAt:N.optional()}),LA=zl.extend({text:v().optional(),system:F.optional()}),RA=Rl(IA),zA=`general`,BA=S({name:k,title:v().min(1),description:v().min(1)});function VA(e){for(let t of e.matchAll(uw)){let n=(t[1]??``).trim();if(!n.startsWith(`args.`))return`the claim "${e}" uses {${n}}: a claim reads only its call's args ({args.path})`}}var HA=v().min(1).max(500).superRefine((e,t)=>{let n=VA(e);n!==void 0&&t.addIssue({code:`custom`,message:n})}),UA=S({fn:k,args:O,user:ww,caller:A,session:j.optional()}),WA=S({claims:x(v().min(1))});function GA(e){return e==null||e===``?[]:typeof e==`string`?[e]:typeof e==`number`||typeof e==`boolean`?[String(e)]:Array.isArray(e)?e.flatMap(e=>Array.isArray(e)?[JSON.stringify(e)]:GA(e)):[JSON.stringify(e)]}function KA(e,t){let n=[],r=[],i=0;for(let a of e.matchAll(uw)){n.push(e.slice(i,a.index)),i=a.index+a[0].length;let[o,...s]=(a[1]??``).trim().split(`.`),c=o===`args`?GA(hw(t,s)):[],l=a[2],u=c.length>0?c:l===void 0?[]:[l];if(u.length===0)return[];r.push(u)}n.push(e.slice(i));let a=[n[0]??``];return r.forEach((e,t)=>{let r=n[t+1]??``;a=a.flatMap(t=>e.map(e=>`${t}${e}${r}`))}),a}function qA(e,t){return[...new Set(e.flatMap(e=>KA(e,t)))]}var JA=S({label:v(),plural:v().optional(),icon:v().optional(),color:v().optional(),title:v().optional(),subtitle:v().optional()}),YA=S({name:k,description:v(),def:Z,display:JA,methods:x(k),instance:L.optional(),audience:BE.optional(),meta:T(v(),O).optional(),records:wA.optional()}),XA=E([`user-wins`,`union`,`intersect`,`most-restrictive`]),ZA=E([`self`,`fns`]),QA=S({name:k,description:v(),type:Z,appliesTo:x(Ll),merge:XA,editableBy:x(ZA)}),$A=S({name:k,description:v(),data:Z}),ej=S({name:k,description:v(),applicability:v(),payload:Z,approveChanges:b(),status:iw.optional(),estimates:b().optional(),approval:FO.optional()}),tj=S({description:v(),args:Z,returns:Z,required:b()}),nj=w(`to`,[S({to:D(`instance`),instance:L}),S({to:D(`any`)})]),rj=S({args:O,result:O.optional(),note:v().optional()}),ij=E([`read`,`write`,`delete`]),aj=E([`fns`,`types`,`context`,`resources`,`kinds`,`components`,`examples`,`approvals`,`secrets`,`connections`,`records`]),oj=[`create`,`update`,`remove`],sj=E(oj),cj=S({thing:aj,action:sj,kind:jl.optional()}).refine(e=>e.kind===void 0||e.thing===`fns`,{message:`only fns have a kind`,path:[`kind`]}),lj=E([`resources`]),uj=S({mode:ij.optional(),reads:x(I).optional(),writes:x(I).optional(),free:b().optional(),registry:x(cj).optional(),keeps:x(lj).min(1).optional()}),dj=S({language:v().min(1),code:v()}),fj=S({every:kl.min(1e3)}),pj=E([`developer`,`admin`,`reference`]),mj=S({deps:x(I)}),hj=S({name:k,description:v(),instructions:v().optional(),kind:jl,payload:O.optional(),readable:dj.optional(),args:Z,returns:Z,deps:x(I),handlers:T(v(),tj),progress:Nw,status:iw.optional(),operations:Aw,undo:Z.optional(),resume:Z.optional(),state:Z.optional(),form:Z.optional(),display:kw,limits:Mw,visibility:Il,tags:x(v()),niche:pj.optional(),examples:x(rj).optional(),validate:ID.optional(),approval:FO.optional(),routing:nj.optional(),connectKey:cD.optional(),effects:uj.optional(),promptExamples:y().int().min(0).max(20).optional(),group:k.optional(),flags:b().optional(),roles:x(pE).optional(),live:fj.optional(),parallelClaims:x(HA).optional(),dynamicClaims:b().optional(),check:mj.optional()}),gj=S({name:v(),hint:v(),required:b()}),_j=S({to:I,when:v().min(1).max(200)}),vj=S({name:k,title:v().min(1).optional(),description:v(),content:v().optional(),command:S({name:v(),args:x(gj)}).optional(),imports:x(I),fns:x(I),suggestFns:x(I),suggest:Il,visible:Il,inject:Sb.optional(),tags:x(v()),niche:pj.optional(),weight:y().min(0).max(2).optional(),summary:v().optional(),parent:I.optional(),next:I.optional(),choices:x(_j).optional(),links:x(rS).optional()}),yj=S({name:k,description:v(),explains:v().min(1).max(2e3).optional(),order:y(),timeout:kl}),bj=S({name:k,title:v(),description:v(),target:Z,of:I.optional()}),xj=S({name:k,description:v(),match:Rx}),Sj=S({name:k,description:v(),input:Z,returns:Z,state:Z.optional(),expires:kl.optional()}),Cj=[`message`,`run`,`resources`,`system`,`fns`],wj=E(Cj),Tj=S({entry:v(),hash:v(),files:x(S({path:v(),size:y().int().min(0),hash:v()}))}),Ej=E([`types`,`settings`,`attachments`,`kinds`,`fns`,`context`,`hooks`,`mentions`,`sectioners`,`actions`]),Dj={types:x(YA),settings:x(QA),attachments:x($A),kinds:x(ej),fns:x(hj),context:x(vj),hooks:x(yj),mentions:x(bj),sectioners:x(xj),actions:x(Sj)},Oj=S({name:F,version:v(),description:v(),about:v().optional(),hash:v(),...Dj,events:x(wj),resources:b(),client:Tj.optional(),config:Z,requires:x(F),providers:x(CD).optional(),connect:lD.optional(),registries:x(pO).optional(),contributes:x(mO).optional(),configSecrets:KO.optional(),runtime:bc(Ej,x(k)).optional(),grants:QD.optional(),configComponent:$D.optional(),pages:$O.optional(),groups:x(BA).optional()}),kj=S({hash:v(),upsert:S(Dj).partial(),remove:bc(Ej,x(k)),lists:Oj.pick({providers:!0,registries:!0,contributes:!0}).optional(),roots:D(!0).optional()}),Aj=S({added:x(I),updated:x(I),removed:x(I),refused:x(S({name:v(),problems:x(v())}))}),jj=S({args:Z,returns:Z,description:v(),mode:ij}),Mj=S({args:Z,returns:Z,deps:x(I),types:x(I).optional(),refs:x(v()).optional(),operations:Aw,handlers:T(v(),tj).optional(),progress:Nw.optional(),status:iw.optional(),limits:Mw.optional(),display:kw.optional(),approval:FO.optional(),effects:uj.optional(),readable:dj.optional(),connectKey:sD.optional(),parallelClaims:x(HA).optional(),examples:x(rj).min(1)});function Nj(e){return e===`native`||e.startsWith(`hub/`)}function Pj(e){return Nj(e.kind)&&(e.examples??[]).length===0}var Fj=S({session:j,turn:al,text:v(),user:ww,time:Tw}),Ij=y(),Lj=S({label:v(),mode:ij,blocked:v().optional(),args:v().optional(),returns:v().optional(),instructions:v().optional(),examples:x(rj).optional(),moreExamples:y().int().positive().optional()}),Rj={toolset:Rb.optional()},zj=w(`type`,[S({type:D(`text`),tag:v(),text:v()}),S({type:D(`suggest-context`),...Rj,items:x(S({context:I,title:v().optional(),why:v().optional(),score:Ij.optional()}))}),S({type:D(`suggest-fns`),...Rj,items:x(S({fn:I,why:v().optional(),score:Ij.optional(),card:Lj.optional()}))}),S({type:D(`load`),context:x(I).optional(),fns:x(I).optional()})]),Bj=S({label:v(),hint:v().optional(),icon:v().optional(),target:O}),Vj=S({title:v(),subtitle:v().optional(),fields:x(S({label:v(),value:v()})).optional(),body:v().optional(),open:zx.optional(),value:O.optional()});vj.omit({name:!0,content:!0}).extend({key:k,summary:v().min(1).max(300),imports:x(I).default([]),fns:x(I).default([]),suggestFns:x(I).default([]),suggest:Il.default(`both`),visible:Il.default(`both`),tags:x(v()).default([])}).strict();var Hj=E([`header`,`duplicate-key`,`broken-link`,`cycle`,`missing-summary`]);S({file:v().min(1),line:y().int().min(1),column:y().int().min(1),code:Hj,message:v().min(1)});var Uj=S({loaded:x(I),fns:x(I),fnsRefused:x(Sw),refused:x(S({context:v(),reason:v().min(1),closest:x(I)})),cards:v()}),Wj=S({context:x(v().min(1)).min(1),guidance:v().min(1).max(4e3),maxDepth:y().int().min(0).max(10).default(fS.maxDepth),maxDecisions:y().int().min(1).max(4096).default(fS.maxDecisions),maxTokens:y().int().min(1).max(1e6).default(fS.maxTokens),metadataOnly:b().default(!1)}),Gj=E([`start`,`import`,`choice`]),Kj=S({name:I,title:v().optional(),description:v(),depth:y().int().min(0),via:Gj,from:I.optional(),probability:y().min(0).max(1).optional(),tokens:y().int().min(0),content:v().optional()}),qj=E([`declined`,`max-tokens`,`max-decisions`,`max-depth`,`unavailable`,`failed`]),Jj=S({context:v(),from:I.optional(),depth:y().int().min(0),reason:qj,probability:y().min(0).max(1).optional()}),Yj=E([`complete`,`max-depth`,`max-decisions`,`max-tokens`,`failed`]),Xj=Uj.extend({crawled:x(Kj),skipped:x(Jj),stop:S({reason:Yj,detail:v().optional()}),depth:y().int().min(0),decisions:y().int().min(0),tokens:y().int().min(0),calls:x(Tl),metadataOnly:b()}),Zj=S({loaded:x(I),refused:x(Sw),cards:v()});C([Zj.strict(),Uj.strict(),Xj.strict()]);var Qj=S({expiresIn:kl.nullable().optional()}),$j=S({id:Dl,secret:v().min(32),expiresAt:N.optional()}),eM=$j.pick({id:!0,secret:!0}),tM=S({id:Dl,system:F,instance:L,secretHash:v(),previousHash:v().optional(),createdBy:M,createdAt:N,expiresAt:N.optional(),lastUsedAt:N.optional(),uses:y().int().min(0),revokedAt:N.optional()}).omit({secretHash:!0,previousHash:!0}),nM=E([`pairing`,`needs-config`,`connected`,`disconnected`,`removed`]),rM=C([S({path:v()}),S({package:v(),version:v()}),S({git:v(),ref:v()}),S({zip:v().regex(Ex),file:v()})]),iM=S({policy:E([`always`,`on-failure`,`never`]),backoff:kl,maxPerHour:y().int().min(1)}),aM=E([`installing`,`stopped`,`starting`,`running`,`crashed`,`disabled`]),oM=S({name:F,instance:L,source:rM,dir:v(),command:S({run:v(),args:x(v()),env:T(v(),v()),cwd:v().optional()}),version:v(),goodVersion:v().optional(),autoStart:b(),restart:iM,status:aM,pid:y().int().optional(),lastExit:S({code:y().int(),at:N,output:v()}).optional(),installedBy:M,installedAt:N}),sM=S({functions:b(),renderers:b(),context:b().optional()}),cM=S({value:O,version:y().int().min(1),setBy:M,setAt:N}),lM=S({keyFingerprint:v().optional(),publicKey:v().optional(),config:cM.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional()}),uM=E([`one`,`many`]),dM=S({name:F,description:v(),about:v().optional(),status:nM,enabled:sM,version:v(),manifestHash:v(),defaultInstance:L.optional(),actor:M,stage:tO.optional(),instances:uM.optional()}).extend(lM.shape),fM=S({id:ul,name:F,keyFingerprint:v(),publicKey:v(),version:v(),address:v(),method:E([`code`,`token`]),code:v().optional(),replaces:F.optional(),description:v().optional(),instance:L.optional(),configType:Z.optional(),configSecrets:KO.optional(),status:E([`pending`,`approved`,`rejected`,`expired`]),createdAt:N,expiresAt:N});S({id:dl,name:F.optional(),tokenHash:v(),createdBy:M,expiresAt:N,usedAt:N.optional(),autoPair:Qj.optional(),boundTo:S({instance:L,manifestHash:v().min(1),host:Wl,run:A}).optional()}),S({system:F,manifest:Oj,importedAt:N});var pM=jE.pick({averageCost:!0,averageQueued:!0,p95:!0,lastRunAt:!0}).extend({outcomes:wE.default(TE),averageTime:kl,tokens:jE.shape.tokens.default(0)}),mM=E([`contract`,`runtime`]),hM=S({name:I,system:F,decl:hj,version:v(),origin:mM,addedBy:M.optional(),available:bw,paused:b(),disabled:b(),stats:pM,updatedAt:N});S({name:I,system:F,decl:ej});var gM=YA.omit({name:!0,methods:!0}).extend({name:I,system:F,references:x(I),declaredBy:mM.optional(),version:v().optional(),updatedAt:N}),_M=S({types:x(gM),missing:x(I)}),vM=vj.extend({alwaysFor:x(I).optional()}),yM=S({name:I,system:F,origin:Yx.optional(),declaredBy:mM.optional(),version:v().optional(),decl:vM,tokens:Zx.optional(),disabled:b().optional(),systemOff:b().optional(),mentions:S({context:x(I),fns:x(I)}),stale:b(),updatedAt:N});function bM(e){return e.disabled===!0||e.systemOff===!0}var xM=[`kinds`,`commands`,`mentions`,`hooks`,`actions`,`settings`,`attachments`,`embedders`,`sectioners`,`providers`,`registries`,`components`,`examples`],SM=E(xM),CM=S({section:SM,name:v().min(1),about:v(),origin:mM,version:v(),visibility:Il.optional(),owner:I.optional(),decl:O,on:b().optional()}),wM=S({system:F}),TM=S({parts:x(CM),more:bc(SM,y().int().min(0))});function EM(e){return wC(e?.name??`otel`,{requires:e?.requires??[]})}var DM=v().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/),OM=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,kM=e=>e!==``&&e!==`.`&&e!==`..`&&!OM.test(e),AM=v().min(1).refine(e=>!e.includes(`\\`)&&!e.includes(`:`)&&e.split(`/`).every(kM),`A package path is relative, uses forward slashes and stays inside the package.`),jM=S({childProcess:b(),workers:b()});S({format:D(1),name:F,version:DM,description:v(),protocol:y().int().min(1),server:S({entry:AM,external:T(v(),v()).default({}),node:v().optional()}),client:S({entry:AM}).optional(),instances:uM.default(`one`),files:T(AM,v().regex(Ex)).optional(),permissions:jM.partial().optional()});var MM=S({state:v(),data:v(),cache:v()}),NM=S({host:Wl,path:v().min(1),bundleHash:v().min(1),approval:pl}),PM=S({system:F,instance:L,description:v(),status:nM,keyFingerprint:v(),publicKey:v(),version:v(),manifestHash:v(),config:cM.optional(),installed:oM.optional(),host:NM.optional(),dirs:MM.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional(),connect:oD.optional()}),FM=S({instance:L,description:v(),online:b(),config:O,types:x(S({name:I,description:v()}))}),IM=S({pairing:ul,description:v(),instance:L,configType:Z.optional(),configSecrets:KO.optional()});S({format:D(1),system:F,instance:L,version:v(),exportedAt:N,exportedBy:M,withSecrets:b()});var LM=S({system:F,instance:L,description:v().optional(),config:O}),RM=S({at:N,stream:E([`stdout`,`stderr`,`hub`]),text:v()}),zM=S({meaning:b(),items:y().int().min(0),pending:y().int().min(0),embedding:b(),retrying:b(),lastError:S({at:N,message:v()}).optional()}),BM=C([ik,I]),VM=S({id:v(),provider:BM,name:v(),contextWindow:y().int().min(0).optional(),pricing:S({input:P,output:P}).optional(),capabilities:x(v()),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}),HM=VM.extend({tier:E([`flagship`,`efficient`,`legacy`,`experimental`]),maxOutputTokens:y().int().min(1).optional(),roles:x(pE)}),UM=lk.extend({spent:P}),WM=S({setting:I,system:F,decl:QA}),GM=Gk.omit({request:!0,response:!0}),KM=w(`kind`,[S({kind:D(`budget`),id:ml}),S({kind:D(`priority`),id:hl}),S({kind:D(`policy`),id:fl}),S({kind:D(`category`),id:xl}),S({kind:D(`provider`),id:Sl})]),qM=S({uri:Cx,system:F,stat:kx,links:x(Ax),indexedVersion:v().optional(),sectioner:I.optional(),source:sT.optional(),raw:Dx.optional(),forms:x(Fx).optional(),primary:Fx.optional(),seenAt:N});S({id:Cl,match:Rx,sectioner:I,setBy:M}),S({uri:Cx,from:v(),to:v(),added:x(wx),changed:x(wx),removed:x(wx)});var JM=E([`fn`,`context`,`section`,`message`,`type`,`example`,`record`,`contextSection`,`image`]);S({kind:JM,key:v(),system:F.optional(),text:v(),hash:v(),vectorHash:v().optional(),embedder:I,updatedAt:N,parent:v().optional(),image:v().optional()});var YM=E([`words`,`meaning`,`both`]);S({kind:JM,key:v(),rank:y().min(0).max(1),similarity:y().min(-1).max(1).optional(),matched:YM.optional(),parent:v().optional(),text:v()});var XM=E([`approval-needed`,`input-needed`,`config-needed`,`message`,`replied`,`turn-finished`,`turn-failed`,`pairing-requested`,`system-disconnected`,`spend-limit`,`system-paused`,`system-notice`,`system-message`]),ZM=S({system:F,segment:v().min(1),path:x(v().min(1)).optional(),query:T(v(),v()).optional()}).strict(),QM=C([S({session:j}),S({approval:pl}),S({pairing:ul}),S({run:A}),S({system:F}),S({page:ZM})]),$M=E([`ok`,`failed`,`info`]),eN=S({label:v().min(1).max(24),link:QM}),tN=S({id:vl,user:M,reason:XM,title:v(),body:v(),link:QM,read:b(),pushed:b(),resolved:v().optional(),tone:$M.optional(),also:eN.optional(),key:v().min(1).max(200).optional(),createdAt:N}),nN=S({id:yl,user:M,endpoint:Ls(),keys:S({p256dh:v(),auth:v()}),device:v(),createdAt:N}),rN=il.fnExample;rj.extend({id:rN,fn:I,system:F,source:E([`decl`,`added`,`runtime`]),key:v().min(1).max(200).optional(),order:y().int().min(0),text:v(),addedBy:M.optional(),createdAt:N});var iN=S({fn:k,upsert:x(rj.extend({key:v().min(1).max(200)})),remove:x(v().min(1).max(200))}),aN=S({fn:cb,query:v().optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(50).optional()}),oN=S({fn:I,items:x(rj.extend({id:rN,rank:y().optional()})),total:y().int().min(0),next:y().int().min(0).optional()}),sN=E([`text`,`semantic`,`hybrid`]),cN=[`session`,`user`,`everyone`],lN=E([`fn`,`context`]),uN=S({text:v().optional(),match:sN.optional(),items:x(lN).min(1).optional(),kinds:x(C([D(`native`),I])).min(1).optional(),systems:x(F).min(1).optional(),instance:L.optional(),visibility:E([`mine`,`shared`,`public`]).optional(),types:S({reads:x(lb).optional(),writes:x(lb).optional()}).optional(),modes:x(ij).min(1).optional(),effects:x(S({thing:aj,action:sj.optional(),kind:v().min(1).optional()})).min(1).optional(),names:x(I).min(1).max(100).optional(),filters:x(aA).max(20).optional(),off:b().optional(),scopes:x(E(cN)).min(1).optional(),available:b().optional(),niches:x(pj).min(1).optional(),order:E([`rank`,`name`]).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(100).optional()}),dN=uN.omit({items:!0,match:!0,filters:!0,off:!0,scopes:!0}).extend({kinds:uN.shape.kinds.describe("Leave `kinds` out unless the person asks for a kind of fn by name: you can't know how a fn was made, and a search by what it does finds every kind."),names:x(cb).min(1).max(100).optional().describe(`Only these fns, by name, spelled as your tools and search hits spell them: to look up fns whose names you know. Leave it out to search by what a fn does.`),types:S({reads:x(lb).optional(),writes:x(lb).optional()}).optional().describe("Only fns that read (`reads`) or write (`writes`) any of these types: a table's name (`tasks`), or a type's name exactly as a result gave it. Leave it out unless you know the type.")}),fN=S({text:uN.shape.text,systems:uN.shape.systems,origins:x(E(Xx)).min(1).optional(),scopes:uN.shape.scopes,tags:x(v().min(1)).min(1).max(20).optional(),names:uN.shape.names,niches:uN.shape.niches,order:uN.shape.order,offset:uN.shape.offset,limit:uN.shape.limit}),pN=S({key:wx,path:x(v()),title:v()}),mN=S({item:lN,name:I,system:F,description:v(),kind:v().optional(),mode:ij.optional(),signature:v().optional(),effects:v().optional(),instance:L.optional(),rank:y().optional(),similarity:y().optional(),matched:YM.optional(),section:pN.optional(),niche:pj.optional(),available:b(),blocked:xw.optional(),inPrompt:E([`injected`,`loaded`]).optional(),exact:D(!0).optional()}),hN=mN.pick({rank:!0,similarity:!0,matched:!0,section:!0}),gN=yM.extend({found:hN.optional()}),_N=S({item:lN,by:E([`decision`,`llm`]),dropped:x(S({name:I,note:v().optional()})),calls:x(Tl).min(1).optional(),failed:v().optional(),action:D(`load`).optional()}),vN=S({fns:x(I),context:x(I),note:v()}),yN=S({items:x(mN),next:y().int().min(0).optional(),filtered:x(_N).optional(),loaded:vN.optional(),missing:S({names:x(I).min(1),note:v()}).optional()}),bN=S({min:P,typical:P,max:P,basis:E([`free`,`history`,`payload`,`unknown`]),runs:y().int().min(0)}),xN=S({runs:y().int().min(0),typical:kl,slow:kl,longest:kl}),SN=S({fn:I,kind:v(),mode:ij,reads:x(I),writes:x(I),uses:x(I),free:b(),registry:x(cj),cost:bN,times:xN.optional(),longRunning:b(),notice:v().optional()}),CN=S({kind:v().min(1),payload:O,args:O.optional(),history:bN.optional()}),wN=S({estimate:bN.optional()}),TN=S({model:hE.optional(),messages:y().int().min(0).max(20).default(4)}),EN=S({value:TN,setBy:M.optional(),updatedAt:N.optional()}),DN=S({entries:x(w(`type`,[S({type:D(`log`),at:N,level:E([`debug`,`info`,`warn`,`error`]),message:v().max(4e3),fields:T(v(),O).optional()}),S({type:D(`traffic`),at:N,method:v().max(16),endpoint:v().max(300),status:y().int(),duration:kl})])).min(1).max(500),page:v().max(300).optional()}),ON=S({uri:Cx,written:y().int().min(0)});SN.pick({fn:!0,kind:!0,mode:!0,reads:!0,writes:!0,uses:!0,free:!0}).extend({registry:x(cj).optional(),system:F,instance:L.optional(),updatedAt:N}),S({fn:I,type:I,use:E([`read`,`write`])}),S({fn:I,type:I,kind:jl,system:F}),S({fn:I,to:I,link:E([`dep`,`kind`,`role`]),system:F}),S({fn:I,uses:I}),S({id:v(),fn:I,number:y().int().min(1),decl:hj,savedBy:M.optional(),savedAt:N}),S({id:v(),type:I,number:y().int().min(1),decl:YA,instance:L.optional(),savedAt:N});var kN={fns:`fns`,types:`types`,context:`context`,resources:`resources`,kinds:`kinds`,components:`components`,examples:`examples`,approvals:`runs awaiting approval`,secrets:`secrets`,connections:`connections`,records:`records`},AN={create:`Creates`,update:`Updates`,remove:`Removes`};function jN(e){let t=[];for(let n of oj){let r=new Map;for(let t of e){if(t.action!==n)continue;let e=r.has(t.thing)?r.get(t.thing):new Set;e===void 0||t.kind===void 0?r.set(t.thing,void 0):(e.add(t.kind),r.set(t.thing,e))}if(r.size===0)continue;let i=[...r.entries()].map(([e,t])=>t===void 0||t.size===0?kN[e]:`${kN[e]} (${[...t].sort().join(`, `)})`);t.push(`${AN[n]} ${i.join(`, `)}.`)}return t.length===0?void 0:t.join(` `)}var MN=il.refusal,NN=[`fns`,`context`,`types`,`roots`,...xM],PN=E(NN),FN=S({section:PN,name:v().min(1)});FN.extend({system:F,by:M,at:N});var IN=S({version:v(),hash:v().min(1),grants:QD,runtime:x(FN),by:M,at:N}),LN=S({section:C([PN,E([`grants`,`config`])]),name:v().min(1),change:E([`added`,`changed`,`removed`]),origin:mM,before:O.optional(),after:O.optional()}),RN=LN.pick({section:!0,name:!0}),zN=RN.extend({change:LN.shape.change,origin:mM,version:v(),by:M,at:N}),BN=S({version:v(),hash:v().min(1),by:mM,changes:x(LN),since:N});S({system:F,live:IN.optional(),pending:BN.optional(),checks:JD.optional(),declined:x(zN).optional(),updatedAt:N});var VN=S({mode:ij,effects:v().optional(),reads:x(I),writes:x(I),deps:x(I),cost:P.optional(),free:b().optional()}),HN=S({name:v().min(1),before:VN.optional(),after:VN.optional()}),UN=BN.extend({summary:CO,fns:x(HN),injections:x(Eb).default([])}),WN=[`stage`,`effects`,`mode`,`types`,`capability`,`models`,`budget`,`secrets`,`calls`,`network`,`files`,`visibility`],GN=E(WN),KN=S({id:MN,system:F,instance:L,rule:GN,attempt:v().min(1),detail:v().min(1),run:A.optional(),fn:I.optional(),at:N}),qN=S({instance:Wl,rule:GN.extract([`network`,`files`]),attempt:v().min(1).max(1e3),detail:v().min(1).max(2e3)}),JN=S({system:F.optional(),rule:GN.optional(),cursor:v().optional(),limit:y().int().min(1).max(200).optional()}),YN=S({items:x(KN),next:v().optional()}),XN=S({system:F,stage:tO,manifest:Oj,facts:x(SN),checks:JD.optional(),live:IN.optional(),pending:UN.optional(),declined:x(zN).default([]),off:x(FN),refusals:S({total:y().int().min(0),last:x(KN).max(10)}),previewUrls:T(v(),v()).optional(),clientApproved:b().optional()}),ZN=S({system:F,hash:v().min(1),off:x(FN).default([])}),QN=S({system:F,hash:v().min(1),approve:x(RN).default([]),decline:x(RN).default([]),off:x(FN).default([])}).refine(e=>e.approve.length+e.decline.length>0,{message:`approve or decline at least one change`,path:[`approve`]}),$N=S({hash:v(),waiting:y().int().min(0)}),eP=C([S({preview:NO,contract:Oj.optional(),ask:zO.optional()}),S({refused:v().min(1)})]),tP=S({fn:I,args:O,instance:L.optional()}),nP=il.mentionRequest,rP=S({request:nP,query:v(),roots:x(Cx).max(20).optional(),limit:y().int().min(1).max(50)}),iP=S({hits:x(Bx)}),aP=2e3,oP=S({kind:I,changedSince:N.optional(),cursor:v().optional(),limit:y().int().min(1).max(100).optional()}),sP=S({items:x(S({fn:I,kind:I,owner:M,title:v(),version:y().int().min(1),payload:O,removed:b(),updatedAt:N})),cursor:v().optional()}),cP=S({fn:I,args:O,key:v().min(1).max(200),priority:Fl.extract([`background`,`interactive`]).optional(),maxSpend:P.positive().optional()}),lP=S({run:A,turn:al,status:Gw}),uP=S({title:v().min(1).max(120),body:v().max(aP),tone:$M.optional(),link:QM.optional(),also:eN.optional(),key:v().min(1).max(136).optional()}),dP=`Harness`,fP=`hub.name`,pP=v().trim().min(1).max(40).refine(e=>!/[\r\n]/.test(e),{message:`One line only.`}),mP=S({name:pP,source:E([`setting`,`env`,`default`]),version:v()}),hP=S({name:pP.nullable()}),gP=[`off`,`text`,`model`];E(gP);var _P=w(`use`,[S({use:D(`off`)}),S({use:D(`text`)}),S({use:D(`model`),embedder:I})]),vP={use:`text`},yP=S({text:b(),images:b(),crossModal:b()}).extend({embedder:I,name:v(),dimensions:y().int().min(1)}),bP=w(`space`,[S({space:D(`none`),reason:v()}),S({space:D(`shared`),embedder:I}),S({space:D(`own`),embedder:I,crossModal:b()})]),xP=S({value:_P,setBy:M.optional(),updatedAt:N.optional(),text:I,options:x(yP),state:bP}),SP={id:M,name:v(),about:v(),createdAt:N,disabled:b()},CP=E([`admin`,`member`]),wP=S({...SP,kind:D(`user`),email:v(),role:CP,timeZone:v().optional()}),TP=w(`kind`,[wP,S({...SP,kind:D(`group`)}),S({...SP,kind:D(`agent`),fn:I}),S({...SP,kind:D(`system`),system:F}),S({...SP,kind:D(`mcp`),mcp:El})]),EP=wP.pick({id:!0,kind:!0,name:!0,email:!0,role:!0,timeZone:!0});S({group:M,user:M,addedBy:M,addedAt:N,provider:v().optional()}),S({user:M,kind:E([`password`,`passkey`]),secretHash:v(),createdAt:N}),S({id:wl,user:M,version:y().int().min(1),refreshHash:v(),rotatedHashes:x(v()).optional(),device:v(),createdAt:N,lastSeenAt:N,actingAs:M.optional()}),S({actor:M,session:wl,version:y().int().min(1)});var DP=S({setting:I,actor:M,value:O,setBy:M,run:A.optional(),updatedAt:N}),OP=C([S({actor:M}),S({group:M}),S({kind:Ll}),S({everyone:D(!0)})]),kP=S({fn:v().optional(),system:F.optional(),kind:jl.optional(),tags:x(v()).optional(),when:UC.optional(),via:I.optional()}),AP=w(`by`,[S({by:D(`turn-user`)}),S({by:D(`actor`),actor:M}),S({by:D(`group`),group:M,quorum:y().int().min(1).optional()}),S({by:D(`admins`)}),S({by:D(`judge`),fn:I}),S({by:D(`hub`)})]);S({fn:I,args:O,actor:M}),S({approve:b(),reason:v()});var jP=w(`effect`,[S({effect:D(`allow`)}),S({effect:D(`deny`),reason:v()}),S({effect:D(`ask`),approver:AP})]),MP=S({id:fl,description:v(),subject:OP,target:kP,decision:jP,priority:y().int(),expiresAt:N.optional(),createdBy:M,createdAt:N,yields:b().optional()}),NP=E([`once`,`session`,`always`]),PP=S({id:pl,run:A,fn:I,policy:fl.optional(),approver:AP,status:E([`pending`,`approved`,`denied`,`expired`]),decisions:x(S({by:M,approve:b(),remember:NP,reason:v().optional(),at:N})),createdAt:N,preview:NO.optional(),proposed:b().optional(),ask:zO.optional(),variant:Ok.optional()}),FP=v().regex(/^[a-z0-9][a-z0-9-]{0,31}$/,`lower case letters, digits and dashes, starting with a letter or digit`),IP=S({role:v().min(1).default(`groups`).describe(`The claim whose values pick the role (default "groups").`),admin:x(v().min(1)).default([]).describe(`Values of the role claim that make an admin.`),member:x(v().min(1)).optional().describe(`When given, values of the role claim one of which (or an admin value) is needed to sign in.`),groups:v().min(1).optional().describe(`The claim whose values are hub group names to sync the person into.`)}),LP=S({id:FP,label:v().min(1).max(60),issuer:Ls(),clientId:v().min(1),clientSecret:v().min(1).optional(),scope:v().min(1).default(`openid email profile`),userinfo:b().default(!0),claims:IP.prefault({})});x(LP).refine(e=>new Set(e.map(e=>e.id)).size===e.length,`each provider needs its own id`);var RP=v().trim().toLowerCase().regex(/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,`a domain such as example.com`),zP=w(`mode`,[S({mode:D(`invite`)}),S({mode:D(`domains`),domains:x(RP).min(1).max(50)}),S({mode:D(`anyone`)})]),BP=`signInPolicy`,VP=S({limit:y().int().min(1).max(1e5),window:y().int().min(1e3).max(864e5)}),HP=S({account:VP,address:VP}),UP=`signInLimits`,WP=S({proxies:y().int().min(0).max(5)}),GP=`proxyTrust`;S({issuer:v(),sub:v(),provider:FP,user:M,email:v().optional(),linkedAt:N,lastSignInAt:N});var KP=LP.pick({id:!0,label:!0}),qP=S({providers:x(LP.omit({clientSecret:!0}).extend({confidential:b()})),policy:zP,breakGlass:EP.optional(),callbackUrl:v(),limits:HP,proxy:WP}),JP=S({ok:b(),detail:v()}),YP=S({provider:FP,ok:b(),discovery:JP,keys:JP,checkedAt:N}),XP=E([`linked`,`email`,`new`,`none`]),ZP=S({allowed:b(),reason:v(),link:XP,user:EP.optional(),role:CP.optional(),groups:x(v()),unknownGroups:x(v())}),QP=S({id:v(),provider:FP,at:N,problem:v().optional(),subject:v().optional(),email:v().optional(),emailVerified:b(),claims:T(v(),O),outcome:ZP.optional()}),$P=S({provider:FP,label:v(),email:v().optional(),lastSignInAt:N}),eF=EP.extend({disabled:b(),createdAt:N,breakGlass:b(),password:b(),identities:x($P),groups:x(S({id:M,name:v(),synced:b()}))}),tF=S({id:M,name:v(),about:v(),createdAt:N,members:y().int().min(0)}),nF=S({user:M,name:v().trim().min(1).max(120).optional(),role:CP.optional(),disabled:b().optional()}),rF=S({group:M,user:M,member:b()});function iF(e){return`/auth/sso/${encodeURIComponent(e)}/start`}var aF=`harness_sso_handoff`,oF=E([`score`,`decision`,`graph`]),sF=E([`below-threshold`,`top-n`,`declined`,`budget`,`rule`,`failed`]),cF={"below-threshold":`Score under the threshold`,"top-n":`Others scored higher`,declined:`The decision model declined it`,budget:`No room in the token budget`,rule:`Hidden by a rule`,failed:`Decision model failed; the score decided`},lF=[`suggest`,`load`],uF=E(lF);function dF(e){return e.by===`none`?`suggest`:e.action??`suggest`}var fF=E([`loaded`,`budget`,`blocked`]),pF={loaded:`Loaded for the turn`,budget:`No room to load it, so suggested`,blocked:`Can't be loaded now, so suggested`},mF=w(`used`,[S({used:D(!0),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),note:v().optional(),load:fF.optional()}),S({used:D(!1),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),reason:sF,note:v().optional()})]),hF=S({by:oF,threshold:y().optional(),calls:x(Tl).min(1).optional(),action:D(`load`).optional(),items:x(mF)}),gF=S({messages:y().int().min(1).max(20).default(3),candidates:y().int().min(1).max(50).default(20),cap:y().int().min(0).max(20).default(6),floor:y().min(0).max(1).default(.2)}),_F=[`decision`,`llm`,`none`];E(_F);var vF=w(`by`,[S({by:D(`none`)}),gF.extend({by:D(`decision`),model:hE.optional(),action:uF.optional()}),gF.extend({by:D(`llm`),model:hE,action:uF.optional()})]),yF={by:`none`},bF=gF.extend({enabled:b(),model:hE.optional()});function xF(e){let{enabled:t,model:n,...r}=e;return t&&n!==void 0?{by:`llm`,model:n,...r}:yF}var SF=C([vF,bF.transform(xF)]),CF=S({value:vF,setBy:M.optional(),updatedAt:N.optional()}),wF=[`none`,`decision`,`llm`];E(wF);var TF=w(`by`,[S({by:D(`none`)}),S({by:D(`decision`),model:hE.optional(),action:uF.optional()}),S({by:D(`llm`),model:hE,action:uF.optional()})]),EF={by:`none`},DF={fn:`fnsSearchDecision`,context:`contextSearchDecision`},OF=S({value:TF,setBy:M.optional(),updatedAt:N.optional()}),kF=S({fn:OF,context:OF}),AF=S({item:lN,value:TF});w(`key`,[S({key:D(`suggestDecision`),value:SF,setBy:M,updatedAt:N}),S({key:D(`autoClassifier`),value:TN,setBy:M,updatedAt:N}),S({key:D(DF.fn),value:TF,setBy:M,updatedAt:N}),S({key:D(DF.context),value:TF,setBy:M,updatedAt:N}),S({key:D(fP),value:pP,setBy:M,updatedAt:N}),S({key:D(`imageEmbedding`),value:_P,setBy:M,updatedAt:N}),S({key:D(BP),value:zP,setBy:M,updatedAt:N}),S({key:D(mb),value:hb,setBy:M,updatedAt:N}),S({key:D(UP),value:HP,setBy:M,updatedAt:N}),S({key:D(GP),value:WP,setBy:M,updatedAt:N}),S({key:D(_b),value:b(),setBy:M,updatedAt:N})]);var jF=E([`all`,`replies`,`none`]),MF=S({actor:M,role:E([`owner`,`member`,`agent`]),notify:jF,joinedAt:N}),NF=E([`idle`,`running`,`paused`]),PF=S({hash:v(),injected:x(I),at:al}),FF=S({id:j,title:v(),owner:M,...Tk.shape,selection:cx.optional(),participants:x(MF),forkOf:j.optional(),fork:Ok.optional(),tools:x(I),context:x(I),suggested:x(I).optional(),announcedSystems:pk.optional(),citationsTold:Ck.optional(),fixed:PF.optional(),status:NF,transcript:x(OT),createdAt:N,updatedAt:N,archived:b()}),IF=FF.pick({id:!0,title:!0,owner:!0,agent:!0,status:!0,createdAt:!0,updatedAt:!0,archived:!0}),LF=E([`local-time`,`suggested-context`,`suggested-fns`]),RF=S({type:D(`text`),text:v()}),zF=S({type:D(`mention`),provider:I,label:v(),target:O,text:v()}),BF=S({type:D(`command`),context:I,args:T(v(),v())}),VF=S({type:D(`file`),ref:Dx,name:v(),uri:Cx.optional(),text:v().optional(),truncated:b().optional()}),HF=S({type:D(`input-answer`),run:A,title:v(),value:O,text:v()}),UF=`input-answer`,WF=S({type:D(`loaded-for-you`),by:E([`decision`,`llm`,`recall`]),toolset:Rb.optional(),fns:x(S({fn:I,label:v(),why:v().optional(),broughtBy:I.optional()})),context:x(S({context:I,title:v().optional(),why:v().optional(),text:v(),fns:x(I).optional()}))}),GF=w(`type`,[RF,S({type:D(`reasoning`),text:v()}),zF,BF,S({type:D(`invocation`),run:A,fn:I}),S({type:D(`call`),run:A,fn:I}),VF,HF,S({type:D(`extra`),extra:LF,blocks:x(zj)}),S({type:D(`hook`),hook:I,blocks:x(zj)}),S({type:D(`attachment`),attachment:I,data:O,title:v()}),S({type:D(`link`),link:zx}),S({type:D(`systems-changed`),on:x(mk),off:x(mk)}),S({type:D(`kept-effects`),variants:x(Mk)}),WF]),KF=new Set([`extra`,`hook`,`input-answer`,`systems-changed`,`loaded-for-you`]);function qF(e){return KF.has(e.type)}var JF=w(`type`,[RF,zF.omit({text:!0}),BF,VF,HF]),YF=S({id:ol,session:j,turn:al,author:M,role:E([`user`,`assistant`,`note`]),parts:x(GF),runs:x(A),status:E([`streaming`,`done`,`failed`]),replyTo:ol.optional(),replyAll:b(),answerers:x(M),suggestions:hF.optional(),compared:D(!0).optional(),cacheMiss:S({call:Tl,at:N}).optional(),citations:x(Sk).optional(),createdAt:N}),XF=E([`pause`,`resume`,`cancel`]),ZF=S({run:A,fn:I,status:Gw,pause:b(),resume:b(),cancel:b()}),QF=S({pause:b(),cancel:b(),uncancellable:x(A),undoLastTurn:b(),continueLastTurn:b().optional(),runs:x(ZF).optional()}),$F=S({session:j,user:M,focused:b(),typing:b(),lastActiveAt:N}),eI=S({voiceInput:b(),voiceOutput:b(),dictation:S({engine:E(_E),language:v().optional()}).optional(),uploads:b(),meaning:b(),mentions:x(S({provider:I,title:v(),of:I.optional()})),commands:x(S({name:v(),context:I,args:x(gj),description:v(),unavailable:v().optional()})),agents:x(S({fn:I,description:v()})),display:T(v(),kw),invocations:x(S({fn:I,description:v(),args:Z})),methods:x(S({type:I,method:v(),fn:I,description:v(),args:Z})),clients:x(S({system:F,url:v(),hash:v()})),systems:x(S({name:F,status:nM,enabled:b()})),models:x(VM)}),tI=YF.pick({id:!0,session:!0,author:!0,role:!0,replyTo:!0,replyAll:!0,createdAt:!0}).extend({text:v()}),nI=nM.extract([`connected`,`disconnected`,`removed`]),rI=w(`type`,[S({type:D(`message`),message:tI}),S({type:D(`run`),run:A,fn:I,update:Qw,notified:b().optional()}),S({type:D(`resources`),changes:x(Lx)}),S({type:D(`system`),system:F,status:nI}),S({type:D(`fns`),added:x(I),removed:x(I),changed:x(I).default([])})]),iI=S({protocol:D(1),name:F,version:v(),instance:L.default(Ul),instances:uM.optional(),boot:v(),publicKey:v(),manifestHash:v(),contractHash:v().optional(),pairingToken:v().optional(),autoPair:eM.optional()}),aI=w(`kind`,[S({kind:D(`challenge`),nonce:v()}),S({kind:D(`pairing`),pairing:ul,code:v().optional(),url:v(),expiresAt:N})]),oI=S({signature:v()}),sI=S({maxFrame:y().int().min(1024),maxChunk:y().int().min(1024),heartbeat:kl}),cI=S({value:O,version:y().int().min(1)}),lI=S({instance:L,config:cI.optional(),start:S({first:b(),upgradedFrom:v().optional()}),token:v(),sendManifest:b(),limits:sI,autoPair:$j.optional()});S({system:F,instance:L,boot:v()});var uI=wC(`linkSession`,{provides:vC()}),dI=EM({name:`linkTel`}),fI=S({state:O,calls:T(v(),eT),reason:E([`resumed`,`restart`])}),pI=S({run:Dw,fn:v(),kind:jl,payload:O.optional(),args:O,budget:rT,handlers:x(v()),resume:fI.optional(),deadline:N,configVersion:y().int().min(0),connection:mD.optional(),approved:VO.optional()}),mI=C([S({run:A}),S({delivery:sl})]),hI=S({session:j,actor:M,user:ww,time:Tw}),gI=S({level:E([`debug`,`info`,`warn`,`error`]),key:v(),fields:Qc}),_I=S({run:A,action:E([`cancel`,`pause`])}),vI=S({accepted:b(),reason:v().optional()}),yI=E([`restart`,`upgrade`,`shutdown`,`removed`]),bI=S({title:v().min(1).max(120),body:v().max(2e3)}),xI=X(dI,uI).group({manifest:{body:Oj,response:Aj,ws:`mf`},patch:{body:kj,response:Aj,ws:`mp`},call:{body:S({parent:A,fn:I,args:O,key:v(),budget:S({cost:P.optional(),time:kl.optional()}).optional(),handlers:x(v()),background:b(),on:L.optional()}),response:eT,ws:`call`},handle:{body:S({run:A,handler:v(),args:O}),response:nT,ws:`ha`},control:{body:_I,response:vI,ws:`cl`},progress:{body:S({run:A,progress:Iw}),ws:`pg`},allow:{body:S({run:A,operations:jw.partial()}),ws:`al`},undoWith:{body:S({run:A,undo:O}),ws:`uw`},attach:{body:S({run:A,item:C([S({attachment:I,data:O,title:v()}),S({link:zx})])}),ws:`at`},types:{body:S({names:x(I).min(1),run:A.optional()}),response:_M,ws:`ty`},fnShape:{body:S({name:I}),response:S({fn:jj.optional()}),ws:`fsh`},resourcesChanged:{body:S({changes:x(Lx)}),ws:`rc`},llm:{body:RT,streamOut:zT,ws:`llm`},model:{body:dE,response:fE,ws:`mdl`},resource:{body:S({uri:Cx,want:x(jx),run:A.optional(),sections:x(wx).min(1).optional()}),response:Nx,ws:`rs`},resourceSections:{body:S({uri:Cx,run:A.optional()}),response:x(Ix),ws:`rsc`},content:{body:S({ref:Dx,offset:y().int().min(0),length:y().int().min(1),run:A.optional()}),response:S({chunk:v()}),ws:`ct`},upload:{body:S({upload:v(),chunk:v(),last:b(),mime:v()}),response:S({ref:Dx.optional()}),ws:`up`},setting:{body:S({run:A,setting:I}),response:S({value:O.optional()}),ws:`st`},stateGet:{body:S({owner:mI}),response:S({values:Qc,version:y().int()}),ws:`sg`},stateSet:{body:S({owner:mI,patch:Qc,clear:x(v()),version:y().int().optional()}),response:C([S({version:y().int()}),S({conflict:D(!0)})]),ws:`ss`},log:{body:gI,ws:`lg`},connectionUpdate:{body:vD,ws:`cu`},instanceConnect:{body:oD,ws:`ic`},shareFn:{body:VE,ws:`sh`},usableFns:{body:HE,response:S({fns:x(k)}),ws:`uf`},propose:{body:BO,response:WO,ws:`po`},decide:{body:VT,response:HT,ws:`de`},fleet:{body:S({}),response:x(FM),ws:`fl`},searchFns:{body:uN.extend({run:A.optional()}),response:yN,ws:`sf`},fnExamples:{body:aN,response:oN,ws:`fx`},examples:{body:iN,response:S({added:y().int().min(0),removed:y().int().min(0)}),ws:`xp`},models:{body:S({}),response:x(HM),ws:`mo`},grantPairing:{body:HO,response:UO,ws:`gp`},notifyAdmins:{body:bI,ws:`na`},notify:{body:S({run:A,notice:uP}),ws:`nf`},kindFns:{body:oP,response:sP,ws:`kf`},startRun:{body:cP,response:lP,ws:`sru`},notifyOwner:{body:S({fn:I,notice:uP}),ws:`nfo`},reportRefusal:{body:qN,ws:`rx`},mentionResources:{body:rP,response:iP,ws:`mr`},records:{body:DA,response:OA,ws:`rq`},record:{body:AA,response:S({record:TA.optional()}),ws:`rg`},recordTable:{body:kA,response:yO,ws:`rtb`},saveRecord:{body:jA,response:TA,ws:`rsv`},removeRecord:{body:NA,response:S({removed:b()}),ws:`rrm`}});Y({endpoints:{...X(dI).group({hello:{body:iI,response:aI,ws:`hi`},prove:{body:oI,response:lI,ws:`pr`},pairingInfo:{body:IM,ws:`pi`}}),...xI}}),Y({endpoints:{paired:pC({body:S({pairing:ul}),ws:`pd`}),run:pC({body:pI,response:$w,ws:`run`}),control:pC({body:_I,response:vI,ws:`ctl`}),undo:pC({body:S({run:Dw,fn:v(),kind:jl,fnPayload:O.optional(),payload:O}),response:tT,ws:`un`}),handler:pC({body:S({call:cl,run:A,key:v(),handler:v(),args:O}),response:nT,ws:`hd`}),child:pC({body:S({parent:A,key:v(),run:A,update:Qw.optional()}),ws:`ch`}),check:pC({body:S({kind:v(),payload:O}),response:S({problems:x(v()),description:Mj.optional()}),ws:`ck`}),context:pC({body:hI.partial({session:!0}).extend({name:v(),args:T(v(),v())}),response:S({text:v()}),ws:`cx`}),roots:pC({response:x(Ox),ws:`ro`}),list:pC({body:S({uri:Cx,cursor:v().optional()}),response:Rl(kx),ws:`ls`}),stat:pC({body:S({uri:Cx}),response:S({stat:kx.optional()}),ws:`sa`}),read:pC({body:S({uri:Cx,want:x(jx)}),response:Nx,ws:`rd`}),sections:pC({body:S({sectioner:v(),uri:Cx,version:v()}),response:x(Ix),ws:`sc`}),watch:pC({body:S({uris:x(Cx),on:b()}),ws:`wa`}),content:pC({body:S({ref:Dx,offset:y().int().min(0),length:y().int().min(1)}),response:S({chunk:v()}),ws:`ct`}),hook:pC({body:S({hook:v(),message:Fj}),response:x(zj),ws:`hk`}),mentions:pC({body:hI.extend({provider:v(),query:v(),request:nP}),response:x(Bj),ws:`mn`}),mentionHover:pC({body:hI.extend({provider:v(),target:O}),response:S({hover:Vj.optional()}),ws:`mh`}),mentionText:pC({body:hI.extend({provider:v(),target:O}),response:S({text:v()}),ws:`mt`}),event:pC({body:rI,ws:`ev`}),action:pC({body:hI.extend({delivery:sl,action:v(),input:O,run:A.optional()}),response:S({result:O}),ws:`ac`}),form:pC({body:S({delivery:sl,run:A,value:O}),ws:`fm`}),restart:pC({body:S({reason:v()}),ws:`rt`}),stop:pC({body:S({reason:yI,timeout:kl}),ws:`sp`}),configure:pC({body:cI.extend({previous:O.optional()}),ws:`cf`}),export:pC({body:S({timeout:kl}),response:S({data:v()}),ws:`ex`}),validate:pC({body:zD,response:BD,ws:`vl`}),preview:pC({body:IO,response:eP,ws:`pv`}),estimate:pC({body:CN,response:wN,ws:`es`}),providerChat:pC({body:wD,streamOut:TD,ws:`pc`}),providerEmbed:pC({body:ND,response:PD,ws:`pe`}),providerDecide:pC({body:kD,response:AD,ws:`pdc`}),providerModels:pC({body:DD,response:OD,ws:`pml`}),connectStart:pC({body:hD,response:S({url:fb}),ws:`cs`}),connectFinish:pC({body:gD,response:_D,ws:`cn`}),disconnect:pC({body:mD.pick({id:!0,owner:!0,credentials:!0}),ws:`dc`}),flags:pC({body:IO,response:kO,ws:`fg`}),claims:pC({body:UA,response:WA,ws:`pcl`}),checkArgs:pC({body:LO,response:RO,ws:`cka`})}});var SI=S({session:j,parts:x(JF).min(1),variants:Dk,client:Ow}),CI=kk.extend({status:Vk,spent:P,tokens:y().int().min(0),startedAt:N,endedAt:N.optional(),time:kl,messages:x(YF),approvals:x(PP)}),wI=Nk.omit({variants:!0}).extend({turn:al,session:j,message:ol,status:Vk,variants:x(CI)}),TI=S({turn:al,variant:wk,adopt:b().optional()}),EI=v().regex(Al).max(64).brand(),DI=S({uri:v(),system:F.optional(),instance:L.optional()}),OI=S({systems:x(F).optional(),fns:x(kP).optional(),types:x(Gl).optional(),context:x(Gl).optional(),resources:x(DI).optional()}),kI=S({include:OI,exclude:OI}),AI=E([`each`,`static`]),jI=S({id:El,slug:EI,name:v().min(1),instructions:v(),rules:kI,toolMode:AI,user:M,actor:M,secretDigest:v(),grantees:x(F),origins:x(v()),enabled:b(),createdBy:M,createdAt:N,updatedAt:N}),MI=jI.pick({slug:!0,name:!0,instructions:!0,rules:!0,toolMode:!0,user:!0,grantees:!0,origins:!0,enabled:!0});S({mcp:El,label:v().min(1),exp:y().int()});var NI=S({mcp:El,label:v().min(1),ttl:y().int().min(1e3).optional()}),PI=S({fns:x(I),types:x(I),closure:x(I),context:x(I),resources:x(DI),reach:x(I),warnings:x(v())}),FI=S({mcp:El,session:v(),label:v(),client:S({name:v(),version:v()}).optional(),since:N,lastCallAt:N.optional(),calls:y().int().min(0)}),II=jI.omit({secretDigest:!0}).extend({url:v(),sessions:y().int().min(0),callsToday:y().int().min(0)}),LI=E([`added`,`changed`,`removed`]),RI=S({id:v().min(1),system:F,section:PN,name:v().min(1),number:y().int().min(1),change:LI,decl:O,hash:v().min(1),declaredBy:mM.optional(),instance:L.optional(),savedBy:M.optional(),savedAt:N}),zI=zl.extend({system:F,section:PN,name:v().min(1)}),BI=Rl(RI);Ix.extend({uri:Cx,version:v(),hash:v()});var VI=(...e)=>e.join(`\0`),HI=`bearerAuth`,UI={security:{[HI]:{type:`http`,scheme:`bearer`,bearerFormat:`JWT`}}};function WI(e){let t=e?.name??HI,n=e?.doc??UI;return wC(t,{provides:vC(),requires:e?.requires??[],doc:n})}var GI=v().regex(/^[a-z]+:.+$/),KI=S({fnKind:jl.optional(),mode:ij.optional(),effects:x(cj).optional(),reads:x(I).optional(),writes:x(I).optional(),visibility:Il.optional(),on:b(),stage:tO.optional(),pending:b().optional(),examples:y().int().min(0).optional()}),qI=S({id:GI,kind:Yk,name:v().min(1),about:v(),system:F.optional(),external:b(),collapsed:y().int().min(0).optional(),facts:KI}),JI=S({from:GI,to:GI,kind:Zk,label:v().min(1),weight:y().min(0).max(1).optional()}),YI=S({node:GI,kind:Yk,count:y().int().min(1)}),XI=sA.pick({text:!0,filters:!0}).extend({systems:x(F).min(1).optional(),external:b().optional(),focus:S({node:GI,hops:y().int().min(1).max(4).optional()}).optional(),collapse:x(F).min(1).optional(),limit:y().int().min(1).max(1e3).optional()}),ZI=S({nodes:x(qI),edges:x(JI),more:x(YI),total:S({nodes:y().int().min(0),edges:y().int().min(0)})}),QI=`hub/visuals`,$I=S({columns:x(S({name:v().min(1),kind:rO,role:iO,numeric:b(),temporal:b(),day:b(),categorical:b(),key:b(),opaque:b(),distinct:y().int().min(0),nulls:y().min(0).max(1),nonNegative:b(),min:C([y(),v()]).optional(),max:C([y(),v()]).optional(),bound:S({min:y(),max:y()}).optional(),members:x(v()).optional()})),rows:y().int().min(0),whole:b()}),eL=new Set([`integer`,`number`]),tL=new Set([`date`,`datetime`]),nL=new Set([`text`,`boolean`]),rL=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function iL(e){return eL.has(e)?`measure`:tL.has(e)||nL.has(e)?`group`:`attribute`}function aL(e,t,n){return e===void 0||typeof e==typeof t&&(n===`min`?t<e:t>e)?t:e}function oL(e,t){return{columns:e.columns.map((n,r)=>{let i=new Set,a=0,o=0,s=0,c=!0,l,u;for(let t of e.rows){let e=t[r];e==null?a+=1:(s+=1,i.add(typeof e==`object`?JSON.stringify(e):String(e)),typeof e==`string`&&rL.test(e)&&(o+=1),(typeof e==`number`||typeof e==`string`)&&(l=aL(l,e,`min`),u=aL(u,e,`max`)),(typeof e!=`number`||e<0)&&(c=!1))}let d=n.kind,f=n.key===!0,p=d===`uuid`||s>0&&o===s||n.ref!==void 0||d===`binary`;return{name:n.name,kind:d,role:n.role??iL(d),numeric:eL.has(d),temporal:tL.has(d),day:d===`date`,categorical:nL.has(d),key:f,opaque:p,distinct:i.size,nulls:e.rows.length===0?0:a/e.rows.length,nonNegative:c&&s>0,...l===void 0?{}:{min:l},...u===void 0?{}:{max:u},...t?.(n)??{}}}),rows:e.rows.length,whole:e.offset===0&&!e.truncated}}var sL=T(k,x(v().min(1)).min(1));S({visual:k,coverage:y().int().min(0),priority:y(),bind:sL,styles:x(k).min(1),because:x(v())});var cL={floor:0,structural:10,encoded:20,"time-encoded":30},lL={"temporal-key":15,"low-cardinality":10,"enum-key":8,"high-null":-10,"many-categories":-10},uL=.5;function dL(e){return e.columns.filter(e=>!e.opaque)}function fL(e,t){return e.accepts.includes(t.kind)&&(e.role===void 0||e.role===t.role)}function pL(e,t,n){return!e.required&&e.role===`group`&&n>1&&t.distinct>=n}function mL(e,t,n){let r={},i=new Set;for(let a of e.channels){let e=t.filter(e=>!i.has(e.name)&&fL(a,e)&&!pL(a,e,n)).map(e=>e.name),o=a.many?e:e.slice(0,1);if(o.length<(a.many?a.min??1:1)){if(a.required)return`No column fits ${a.label} (${a.accepts.join(`, `)}).`;continue}let[s,...c]=o;if(s!==void 0){r[a.name]=[s,...c];for(let e of o)i.add(e)}}return r}function hL(e,t,n){return(e[t]??[]).flatMap(e=>n.columns.filter(t=>t.name===e))}function gL(e,t,n,r,i){switch(e.rule){case`distinct`:return hL(t,e.channel,n).some(t=>t.distinct>e.max)?`${e.channel} has more than ${String(e.max)} values.`:void 0;case`non-negative`:return hL(t,e.channel,n).every(e=>e.nonNegative)?void 0:`${e.channel} has values below 0.`;case`bounded`:return hL(t,e.channel,n).every(e=>e.bound!==void 0)||t.max!==void 0?void 0:`${e.channel} has no known range.`;case`distinct-columns`:{let n=e.channels.flatMap(e=>t[e]??[]);return new Set(n).size===n.length?void 0:`${e.channels.join(` and `)} need different columns.`}case`links`:{if(r===void 0||i===void 0)return;let n=e=>i.findIndex(n=>n.name===t[e]?.[0]),a=n(e.from),o=n(e.to);if(a<0||o<0)return`${e.to} must name values of ${e.from}.`;let s=new Set(r.map(e=>JSON.stringify(e[a]??null)));return r.every(e=>e[o]===null||s.has(JSON.stringify(e[o]??null)))?void 0:`${e.to} names values that are not ${e.from} values.`}}}function _L(e,t,n){let r=Object.values(t).flat().flatMap(e=>n.columns.filter(t=>t.name===e)),i=r.filter(e=>e.role===`group`),a={"temporal-key":i.some(e=>e.temporal),"low-cardinality":i.length>0&&i.every(e=>e.distinct<=8),"enum-key":i.some(e=>e.members!==void 0),"high-null":r.some(e=>e.nulls>uL),"many-categories":i.some(e=>e.distinct>5)},o=e.priority.terms.filter(e=>a[e]);return{priority:cL[e.priority.band]+o.reduce((e,t)=>e+lL[t],0),because:o.map(e=>`${e} (${String(lL[e])})`)}}function vL(e,t,n){return e.styles.filter(e=>(e.whole!==!0||n)&&(e.needs??[]).every(e=>t[e]!==void 0)).map(e=>e.name)}function yL(e,t,n,r){let i=[];for(let r of e.channels){let e=t[r.name]??[];if(e.length===0)r.required&&i.push(`${r.label} is not bound.`);else{!r.many&&e.length>1&&i.push(`${r.label} takes one column.`),r.many&&e.length<(r.min??1)&&i.push(`${r.label} needs at least ${String(r.min??1)} columns.`);for(let t of e){let e=n.columns.find(e=>e.name===t);e===void 0?i.push(`${r.label}: there is no column ${t}.`):(e.opaque&&i.push(`${r.label}: ${t} holds nothing a person reads.`),r.accepts.includes(e.kind)||i.push(`${r.label}: ${t} is ${e.kind}, not ${r.accepts.join(` or `)}.`))}}}n.rows<e.rows.min&&i.push(`Needs at least ${String(e.rows.min)} rows.`),e.rows.max!==void 0&&n.rows>e.rows.max&&e.size===void 0&&i.push(`Draws at most ${String(e.rows.max)} rows.`),e.whole&&!n.whole&&i.push(`Only draws a whole result, and this is one page of it.`);for(let a of e.rules){let e=gL(a,t,n,r?.rows,r?.columns);e!==void 0&&i.push(e)}return i}function bL(e,t,n){let r=dL(t);return e.flatMap((e,i)=>{let a=mL(e.shape,r.length>0?r:t.columns,t.rows);if(typeof a==`string`||yL(e.shape,a,t,n).length>0)return[];let[o,...s]=vL(e.shape,a,t.whole);if(o===void 0)return[];let{priority:c,because:l}=_L(e.shape,a,t),u=new Set(Object.values(a).flat().filter(e=>r.some(t=>t.name===e))).size;return[{rank:{visual:e.name,coverage:u,priority:c,bind:a,styles:[o,...s],because:[`covers ${String(u)}`,...l]},index:i}]}).sort((e,t)=>t.rank.coverage-e.rank.coverage||t.rank.priority-e.rank.priority||e.index-t.index).map(e=>e.rank)}var xL=[`integer`,`number`],SL=[`date`,`datetime`],CL=[`text`,`boolean`],wL=[`text`,`boolean`,`date`,`datetime`];function TL(e,t,n,r={}){return{name:e,label:t,accepts:[...n],required:r.required??!0,many:r.many??!1,...r.min===void 0?{}:{min:r.min},...r.role===void 0?{}:{role:r.role}}}var EL=[`table`,`value`,`part`,`category`,`time`,`distribution`,`crosstab`,`calendar`,`timeline`,`network`,`hierarchy`,`gauge`,`finance`];E(EL);var DL={table:{label:`Table`,icon:`table`,description:`Every readable column and row, sortable and paged; cards on a phone.`,shape:fO.parse({channels:[TL(`columns`,`Columns`,nO,{required:!1,many:!0})],rows:{min:0},whole:!1,size:`window`,pageSize:10,styles:[{name:`table`,label:`Table`},{name:`compact`,label:`Compact`},{name:`cards`,label:`Cards`}],priority:{band:`floor`,terms:[]}})},value:{label:`Value`,icon:`hash`,description:`One to four rows of numbers as cards, each titled by a text column or named by its column.`,shape:fO.parse({channels:[TL(`value`,`Values`,xL,{many:!0,role:`measure`}),TL(`title`,`Title`,[`text`],{required:!1})],rows:{min:1,max:4},whole:!0,styles:[{name:`cards`,label:`Cards`},{name:`single`,label:`Single`}],priority:{band:`encoded`,terms:[]}})},part:{label:`Part of a whole`,icon:`chart`,description:`Slices of a whole: one per category, sized by a measure.`,shape:fO.parse({channels:[TL(`itemName`,`Slice`,wL,{role:`group`}),TL(`value`,`Size`,xL,{role:`measure`})],rows:{min:1,max:100},whole:!0,size:`partition`,rules:[{rule:`non-negative`,channel:`value`}],styles:[{name:`pie`,label:`Pie`},{name:`doughnut`,label:`Doughnut`},{name:`rose`,label:`Rose`},{name:`half`,label:`Half doughnut`},{name:`funnel`,label:`Funnel`}],priority:{band:`encoded`,terms:[`low-cardinality`,`enum-key`,`many-categories`]}})},category:{label:`Bars`,icon:`chart`,description:`Measures per category, with an optional second key as series.`,shape:fO.parse({channels:[TL(`x`,`Category`,wL,{role:`group`}),TL(`y`,`Values`,xL,{many:!0,role:`measure`}),TL(`series`,`Series`,CL,{required:!1,role:`group`})],rows:{min:1,max:50},whole:!1,size:`top-n`,styles:[{name:`bar`,label:`Bars`},{name:`stacked`,label:`Stacked`},{name:`percent`,label:`100%`,whole:!0},{name:`horizontal`,label:`Horizontal`},{name:`line`,label:`Line`},{name:`area`,label:`Area`},{name:`radar`,label:`Radar`},{name:`polar`,label:`Polar bars`},{name:`pictorial`,label:`Pictorial`}],priority:{band:`encoded`,terms:[`low-cardinality`,`enum-key`,`high-null`]}})},time:{label:`Over time`,icon:`chart`,description:`Measures along a date axis, zoomable; zooming can set the from/to args.`,shape:fO.parse({channels:[TL(`x`,`Date`,SL,{role:`group`}),TL(`y`,`Values`,xL,{many:!0,role:`measure`}),TL(`series`,`Series`,CL,{required:!1,role:`group`})],rows:{min:2},whole:!1,size:`window`,claims:[{claim:`range`,channel:`x`}],styles:[{name:`line`,label:`Line`},{name:`smooth`,label:`Smooth`},{name:`area`,label:`Area`},{name:`stacked`,label:`Stacked area`},{name:`step`,label:`Step`},{name:`bar`,label:`Bars`},{name:`river`,label:`Stream`,needs:[`series`]}],priority:{band:`time-encoded`,terms:[`temporal-key`,`high-null`]}})},distribution:{label:`Distribution`,icon:`chart`,description:`How numbers spread: points, bubbles, bins, boxes or parallel axes.`,shape:fO.parse({channels:[TL(`x`,`X`,xL),TL(`y`,`Y`,xL,{required:!1}),TL(`size`,`Size`,xL,{required:!1}),TL(`group`,`Group`,CL,{required:!1}),TL(`dims`,`More axes`,xL,{required:!1,many:!0,min:1})],rows:{min:2,max:5e3},whole:!1,styles:[{name:`scatter`,label:`Points`,needs:[`y`]},{name:`bubble`,label:`Bubbles`,needs:[`y`,`size`]},{name:`pulse`,label:`Rippling points`,needs:[`y`]},{name:`histogram`,label:`Histogram`,whole:!0},{name:`boxplot`,label:`Box plot`,whole:!0},{name:`parallel`,label:`Parallel axes`,needs:[`y`,`dims`]}],priority:{band:`structural`,terms:[`high-null`]}})},crosstab:{label:`Cross-tab`,icon:`grid`,description:`A measure for each pair of two keys: a heatmap, value cells or small charts.`,shape:fO.parse({channels:[TL(`x`,`Columns`,wL,{role:`group`}),TL(`y`,`Rows`,wL,{role:`group`}),TL(`value`,`Value`,xL,{role:`measure`})],rows:{min:2},whole:!1,size:`top-n`,rules:[{rule:`distinct-columns`,channels:[`x`,`y`]},{rule:`distinct`,channel:`x`,max:50},{rule:`distinct`,channel:`y`,max:50}],styles:[{name:`heatmap`,label:`Heatmap`},{name:`cells`,label:`Value cells`},{name:`multiples`,label:`Small charts`}],priority:{band:`encoded`,terms:[`low-cardinality`]}})},calendar:{label:`Calendar`,icon:`calendar`,description:`Days on a calendar, shaded by a measure; the month shown can set the from/to args.`,shape:fO.parse({channels:[TL(`time`,`Date`,SL,{role:`group`}),TL(`value`,`Intensity`,xL,{required:!1,role:`measure`}),TL(`label`,`Label`,CL,{required:!1})],rows:{min:1},whole:!1,claims:[{claim:`range`,channel:`time`}],styles:[{name:`month`,label:`Month`},{name:`year`,label:`Year`}],priority:{band:`structural`,terms:[`temporal-key`]}})},timeline:{label:`Timeline`,icon:`calendar`,description:`Bars from a start to an end date, one row each: a gantt chart.`,shape:fO.parse({channels:[TL(`start`,`Start`,SL),TL(`end`,`End`,SL),TL(`label`,`Label`,CL),TL(`series`,`Lane`,CL,{required:!1})],rows:{min:1,max:500},whole:!1,size:`window`,rules:[{rule:`distinct-columns`,channels:[`start`,`end`]}],claims:[{claim:`range`,channel:`start`}],styles:[{name:`gantt`,label:`Gantt`},{name:`timeline`,label:`Timeline`}],priority:{band:`time-encoded`,terms:[]}})},network:{label:`Network`,icon:`graph`,description:`Links between things: each row is an edge from a source to a target.`,shape:fO.parse({channels:[TL(`source`,`From`,CL),TL(`target`,`To`,CL),TL(`value`,`Weight`,xL,{required:!1,role:`measure`})],rows:{min:1,max:2e3},whole:!0,rules:[{rule:`distinct-columns`,channels:[`source`,`target`]}],styles:[{name:`force`,label:`Graph`},{name:`circular`,label:`Circle`},{name:`sankey`,label:`Flow`},{name:`chord`,label:`Chord`}],priority:{band:`structural`,terms:[]}})},hierarchy:{label:`Hierarchy`,icon:`tree`,description:`A tree from a name and its parent column, sized by a measure.`,shape:fO.parse({channels:[TL(`name`,`Name`,CL),TL(`parent`,`Parent`,CL),TL(`value`,`Size`,xL,{required:!1,role:`measure`})],rows:{min:2,max:5e3},whole:!0,rules:[{rule:`distinct-columns`,channels:[`name`,`parent`]},{rule:`links`,from:`name`,to:`parent`}],styles:[{name:`tree`,label:`Tree`},{name:`radial`,label:`Radial tree`},{name:`treemap`,label:`Treemap`},{name:`sunburst`,label:`Sunburst`}],priority:{band:`structural`,terms:[]}})},gauge:{label:`Gauge`,icon:`gauge`,description:`One value against its known range.`,shape:fO.parse({channels:[TL(`value`,`Value`,xL,{role:`measure`}),TL(`max`,`Maximum`,xL,{required:!1})],rows:{min:1,max:1},whole:!0,rules:[{rule:`bounded`,channel:`value`}],styles:[{name:`gauge`,label:`Gauge`},{name:`progress`,label:`Progress ring`}],priority:{band:`encoded`,terms:[]}})},finance:{label:`Candlestick`,icon:`chart`,description:`Open, high, low and close per period, with optional volume.`,shape:fO.parse({channels:[TL(`x`,`Period`,wL,{role:`group`}),TL(`open`,`Open`,xL),TL(`close`,`Close`,xL),TL(`low`,`Low`,xL),TL(`high`,`High`,xL),TL(`volume`,`Volume`,xL,{required:!1})],rows:{min:2},whole:!1,size:`window`,claims:[{claim:`range`,channel:`x`}],styles:[{name:`candlestick`,label:`Candles`},{name:`volume`,label:`Candles and volume`,needs:[`volume`]}],priority:{band:`time-encoded`,terms:[`temporal-key`]}})}};EL.map(e=>({name:e,shape:DL[e].shape}));var OL=`widgets`,kL=`widgets/widget`,AL=[`today`,`today-1d`,`today+1d`,`today-7d`,`today-30d`,`today+7d`,`startOf(week)`,`endOf(week)`,`startOf(month)`,`endOf(month)`,`startOf(month,today-1mo)`,`startOf(quarter)`,`startOf(year)`,`now`,`now-1h`,`now-24h`],jL=E(AL),ML={today:{label:`Today`,yields:`day`},"today-1d":{label:`Yesterday`,yields:`day`},"today+1d":{label:`Tomorrow`,yields:`day`},"today-7d":{label:`7 days ago`,yields:`day`},"today-30d":{label:`30 days ago`,yields:`day`},"today+7d":{label:`In 7 days`,yields:`day`},"startOf(week)":{label:`Start of this week`,yields:`day`},"endOf(week)":{label:`End of this week`,yields:`day`},"startOf(month)":{label:`Start of this month`,yields:`day`},"endOf(month)":{label:`End of this month`,yields:`day`},"startOf(month,today-1mo)":{label:`Start of last month`,yields:`day`},"startOf(quarter)":{label:`Start of this quarter`,yields:`day`},"startOf(year)":{label:`Start of this year`,yields:`day`},now:{label:`Now`,yields:`instant`},"now-1h":{label:`An hour ago`,yields:`instant`},"now-24h":{label:`24 hours ago`,yields:`instant`}},NL=C([S({literal:O}),S({relative:jL})]),PL=S({label:v().min(1),value:NL.optional()}),FL=w(`show`,[S({show:D(`control`),label:v().min(1).optional(),choices:x(PL).min(1).optional(),custom:b().optional(),default:NL.optional()}),S({show:D(`pinned`),value:NL}),S({show:D(`hidden`)})]),IL=S({label:v().min(1),sets:T(k,NL)}),LL=S({from:k,to:k}),RL=S({offset:k,limit:k}),zL=S({visual:k,style:k,label:v().min(1).optional(),bind:sL}),BL=E([`open`,`refresh`,`status`]),VL=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:BL.optional()}),HL=S({fn:I,label:v().min(1),bind:T(k,v().min(1))}),UL=S({title:v().min(1),source:I,visuals:x(zL).min(1),args:T(k,FL),presets:x(IL),range:LL.optional(),paging:RL.optional(),actions:x(VL).optional(),drill:HL.optional(),live:D(!0).optional()}),WL=S({arg:k,label:v().min(1),argType:Z,optional:b(),defaulted:b().optional(),choices:x(PL).min(1).optional(),custom:b(),relative:b(),value:NL.optional()}),GL=S({offset:k,limit:k,window:y().int().min(1),more:b()}),KL=S({fn:I,label:v().min(1),mode:ij,confirm:b(),bind:T(k,v().min(1)),form:Z.optional(),then:BL}),qL=S({title:v().min(1),table:yO,facts:$I,source:S({fn:I,run:A,args:T(v(),O)}),visuals:x(zL).min(1),problems:x(v()),controls:x(WL),presets:x(IL),range:LL.optional(),paging:GL.optional(),actions:x(KL),drill:HL.optional(),readOnly:b(),live:S({every:y().int().min(1)}).optional(),summary:v().min(1)}),JL=S({types:x(I).max(20),narrow:x(VL).optional()}).refine(e=>e.types.length>0||(e.narrow?.length??0)>0,{message:`name a row type or an action to offer`}),YL=S({fn:I,args:T(v(),O)}),XL=YL.extend({on:L.optional()});S({source:cb,request:v().min(1),args:T(v(),O).optional(),fns:x(cb).max(10).optional(),widget:cb.optional(),show:b()});var ZL=S({name:k,description:v().min(1),spec:UL,preview:qL,replaces:cb.optional(),show:b()});S({name:k,description:v().min(1),spec:UL,replace:I.optional()});var QL=S({fn:I,args:v(),offset:k,limit:k,format:D(`csv`)});S({summary:v(),columns:x(v()),rows:x(x(O)),more:y().int().min(0),partial:v().optional()});function $L(e,t){return e!==`read`||t===!0}function eR(e,t){return t?`open`:e===`read`?`status`:`refresh`}function tR(e){return qC(e.split(/[/.]/).pop()??e)||e}var Q=EM(),$=WI(),nR=wC(`adminOnly`,{requires:[$]}),rR=S({access:v(),refresh:v(),expiresIn:kl,user:EP}),iR=mP.pick({name:!0,version:!0}).extend({needsAdmin:b(),sso:x(KP)}),aR=S({kind:E([`fn`,`context`]),name:I,description:v(),score:Ij,why:v().optional()}),oR=nk(v().min(1)),sR=S({approvals:x(PP),handlers:x(Bk)}),cR=PM.omit({publicKey:!0}),lR=S({fns:y().int().min(0),context:y().int().min(0),types:y().int().min(0),parts:y().int().min(0),instances:y().int().min(0),pending:y().int().min(0),refusals:y().int().min(0)}),uR=dM.omit({keyFingerprint:!0,publicKey:!0,config:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0,instances:!0}).extend(PM.pick({keyFingerprint:!0,config:!0,installed:!0,host:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0}).shape).extend({counts:lR,instanceMode:uM,needsConfig:b(),configType:O.optional(),configSecrets:KO.optional(),instances:x(cR)}),dR=w(`type`,[S({type:D(`message`),message:YF}),S({type:D(`token`),message:ol,text:v()}),S({type:D(`reasoning`),message:ol,text:v()}),S({type:D(`cite`),message:ol,cite:bk}),S({type:D(`controls`),controls:QF}),S({type:D(`run`),run:A,fn:I,update:Qw}),S({type:D(`state`),system:F,fields:x(Lk)}),S({type:D(`delivery`),delivery:zk}),S({type:D(`handler`),call:Bk}),S({type:D(`approval`),approval:PP}),S({type:D(`budget`),run:A,budget:lk,reason:v()}),S({type:D(`presence`),presence:$F}),S({type:D(`session`),session:IF}),S({type:D(`compare`),turn:al})]),fR=w(`type`,[S({type:D(`notification`),notification:tN}),S({type:D(`approval`),approval:PP}),S({type:D(`system`),system:F,status:nM}),S({type:D(`pairing`),pairing:fM}),S({type:D(`capabilities`)}),S({type:D(`session`),session:IF}),S({type:D(`session-deleted`),session:j}),S({type:D(`fn`),fn:I,system:F,stats:pM}),S({type:D(`resource`),uri:Cx,forms:x(Fx)}),S({type:D(`context`),name:I}),S({type:D(`identity`),identity:mP})]),pR=EC(Y({endpoints:X(Q).group({setup:{method:`GET`,response:iR,ws:`setup`},createAdmin:{body:S({email:Ns(),name:v().min(1),password:v().min(8),setup:v().trim().min(1)}),response:rR,ws:`createAdmin`},signIn:{body:S({email:Ns(),password:v()}),response:rR,errors:{401:S({reason:v()})},ws:`signIn`},refresh:{body:S({refresh:v()}),response:rR,ws:`refresh`},redeemSso:{body:S({code:v().min(1)}),cookies:S({[aF]:v().optional()}),response:rR,ws:`redeemSso`,httpOnly:!0}})}),Y({endpoints:X(Q,$).group({signOut:{ws:`signOut`},me:{method:`GET`,response:EP,ws:`me`},account:{method:`GET`,response:eF,ws:`account`}})})),mR=zl.extend({query:sA.optional()}),hR=zl.extend({session:j}),gR=zl.extend({unread:b().optional(),query:sA.optional()}),_R=FF.pick({title:!0,systems:!0,agent:!0,archived:!0}).partial().extend({priority:Fl.optional(),notify:jF.optional(),model:FF.shape.model.unwrap().nullable().optional(),mode:FF.shape.mode.unwrap().nullable().optional(),contextor:FF.shape.contextor.unwrap().nullable().optional(),fnMode:FF.shape.fnMode.unwrap().nullable().optional(),instructions:FF.shape.instructions.unwrap().nullable().optional(),citations:FF.shape.citations}),vR=Y({endpoints:X(Q,$).group({capabilities:{body:S({session:j.optional()}),response:eI,ws:`capabilities`},types:{body:S({names:x(I).min(1)}),response:_M,ws:`types`},sessions:{body:mR,response:Rl(IF),ws:`sessions`},session:{body:S({session:j}),response:FF,ws:`session`},createSession:{body:FF.pick({agent:!0,systems:!0,title:!0}).partial(),response:FF,ws:`createSession`},updateSession:{body:_R.extend({session:j}),response:FF,ws:`updateSession`},deleteSession:{body:S({session:j}),response:S({deleted:b()}),ws:`deleteSession`},limits:{body:S({session:j}),response:dk,ws:`limits`},messages:{body:hR,response:Rl(YF),ws:`messages`},send:{body:S({session:j,parts:x(JF).min(1),replyTo:ol.optional(),replyAll:b().optional(),client:Ow}),response:S({turn:al,message:YF}),ws:`send`},compare:{body:SI,response:S({turn:al,message:YF}),ws:`compare`},compareView:{body:S({turn:al}),response:wI,ws:`compareView`},chooseVariant:{body:TI,response:wI,ws:`chooseVariant`},invoke:{body:S({session:j,fn:I,args:O,on:L.optional(),client:Ow}),response:S({turn:al,run:A}),ws:`invoke`},control:{body:S({session:j,action:XF,runs:x(A).min(1).optional()}),response:QF,ws:`control`},controls:{body:S({session:j}),response:QF,ws:`controls`},presence:{body:$F.omit({user:!0,lastActiveAt:!0}),ws:`presence`}})}),yR=Y({endpoints:X(Q,$).group({background:{body:S({run:A}),response:S({accepted:b()}),ws:`background`},undoTurn:{body:S({turn:al}),response:qk,ws:`undoTurn`},continueTurn:{body:S({turn:al}),response:S({turn:al,run:A}),ws:`continueTurn`},tree:{body:S({turn:al}),response:Kk,ws:`tree`},run:{body:S({run:A}),response:Fk,ws:`run`},llmCall:{body:S({id:ll}),response:Gk,ws:`llmCall`},waiting:{body:S({session:j}),response:sR,ws:`waiting`},approve:{body:S({approval:pl,approve:b(),remember:NP,reason:v().optional(),answer:O.optional()}),response:PP,ws:`approve`},answer:{body:S({call:cl,value:O}),ws:`answer`},act:{body:S({session:j,system:F,action:v(),input:O,run:A.optional(),client:Ow}),response:S({delivery:sl}),ws:`act`},submit:{body:S({run:A,value:O}),response:S({delivery:sl}),ws:`submit`},state:{body:S({run:A}),response:S({system:F,fields:x(Lk)}),ws:`state`}})}),bR=Y({endpoints:X(Q,$).group({suggest:{body:S({session:j,text:v(),limit:y().int().min(1).max(20).optional()}),response:x(aR),ws:`suggest`},mentions:{body:S({session:j,provider:I,query:v()}),response:x(Bj),ws:`mentions`},mentionHover:{body:S({session:j,provider:I,target:O}),response:S({hover:Vj.optional()}),ws:`mentionHover`},resource:{body:S({uri:Cx,want:x(jx)}),response:Nx,ws:`resource`}})}),xR=Y({endpoints:X(Q,$).group({notifications:{body:gR,response:Rl(tN),ws:`notifications`},readNotifications:{body:S({ids:x(tN.shape.id)}),ws:`readNotifications`},pushKey:{method:`GET`,response:S({publicKey:v()}),ws:`pushKey`},subscribePush:{body:nN.pick({endpoint:!0,keys:!0,device:!0}),response:nN.pick({id:!0}),ws:`subscribePush`}})}),SR=Y({endpoints:X(Q,$).group({upload:{body:S({name:v(),mime:v(),size:y().int().min(0)}),response:S({url:v(),upload:v()}),ws:`upload`},uploaded:{body:S({upload:v()}),response:Dx,ws:`uploaded`},transcribe:{body:S({audio:Dx}),response:S({text:v()}),ws:`transcribe`}})}),CR=S({section:E([`fns`,`context`]),name:I,on:b()}),wR=S({system:F,section:PN.exclude([`fns`,`context`]),name:v().min(1),on:b()}),TR=Y({endpoints:X(Q,$,nR).group({systems:{body:S({query:sA.optional()}),response:x(uR),ws:`systems`},system:{body:S({system:F}),response:uR,ws:`system`},pairings:{body:S({status:fM.shape.status.optional()}),response:x(fM),ws:`pairings`},approvePairing:{body:S({pairing:ul,approve:b(),instance:L.optional(),config:O.optional(),autoPair:Qj.optional()}),response:S({system:F.optional()}),ws:`approvePairing`},createPairingToken:{body:S({name:F.optional(),expiresIn:kl,autoPair:Qj.optional()}),response:S({token:v(),expiresAt:N}),ws:`createPairingToken`},configureSystem:{body:S({system:F,config:O,instance:L.optional()}),response:C([S({version:y().int()}),S({problems:x(v())})]),ws:`configureSystem`},enableSystem:{body:S({system:F,functions:b().optional(),renderers:b().optional(),context:b().optional()}),response:S({enabled:sM}),ws:`enableSystem`},switchItem:{body:CR,response:S({on:b()}),ws:`switchItem`},switchPart:{body:wR,response:S({on:b()}),ws:`switchPart`},removeSystem:{body:S({system:F}),response:S({fnsUnavailable:y().int()}),ws:`removeSystem`},installSystem:{body:S({source:rM,config:O.optional(),autoStart:b().optional()}),response:S({name:F}),ws:`installSystem`},startSystem:{body:S({system:F,instance:L.optional()}),response:S({ok:b()}),ws:`startSystem`},stopSystem:{body:S({system:F,instance:L.optional()}),response:S({ok:b()}),ws:`stopSystem`},restartSystem:{body:S({system:F,instance:L.optional(),reason:v().min(1).max(200)}),response:S({ok:b()}),ws:`restartSystem`},upgradeSystem:{body:S({system:F,version:v().optional()}),response:S({from:v(),to:v()}),ws:`upgradeSystem`},reimport:{body:S({system:F}),response:Aj,ws:`reimport`}})}),ER=Y({endpoints:X(Q,$,nR).group({configureProvider:{body:oR,response:S({models:y().int()}),ws:`configureProvider`},providers:{body:S({}),response:x(S({id:Sl,provider:ik,models:y().int()})),ws:`providers`},setModelCategory:{body:ak.partial({id:!0}),response:ak.pick({id:!0}),ws:`setModelCategory`},setBudget:{body:lk.omit({setBy:!0}).partial({id:!0}),response:lk.pick({id:!0}),ws:`setBudget`},setPriority:{body:uk.omit({setBy:!0}).partial({id:!0}),response:uk.pick({id:!0}),ws:`setPriority`},setPolicy:{body:MP.omit({createdBy:!0,createdAt:!0}).partial({id:!0}),response:MP.pick({id:!0}),ws:`setPolicy`},setActorSetting:{body:S({setting:I,actor:M,value:O}),response:S({ok:b()}),ws:`setActorSetting`},addUser:{body:S({email:Ns(),name:v(),role:CP,groups:x(M).optional()}),response:S({id:M}),ws:`addUser`},addGroup:{body:S({name:v(),about:v(),members:x(M).optional()}),response:S({id:M}),ws:`addGroup`},updateUser:{body:nF,response:S({id:M}),ws:`updateUser`},setMembership:{body:rF,response:S({ok:b()}),ws:`setMembership`},setSignInPolicy:{body:zP,response:zP,ws:`setSignInPolicy`},setSignInLimits:{body:HP,response:HP,ws:`setSignInLimits`},setProxyTrust:{body:WP,response:WP,ws:`setProxyTrust`}})}),DR=Y({endpoints:X(Q,$,nR).group({systemFns:{body:S({system:F}),response:x(hM),ws:`systemFns`},systemParts:{body:wM,response:TM,ws:`systemParts`},systemLogs:{body:S({system:F,limit:y().int().min(1).max(2e3).optional()}),response:x(RM),ws:`systemLogs`},models:{body:S({provider:Sl.optional()}),response:x(VM),ws:`models`},modelCategories:{body:S({}),response:x(ak),ws:`modelCategories`},budgets:{body:S({}),response:x(UM),ws:`budgets`},priorityRules:{body:S({}),response:x(uk),ws:`priorityRules`},resolveLimits:{body:S({user:M,session:j.optional()}),response:dk,ws:`resolveLimits`},policies:{body:S({}),response:x(MP),ws:`policies`},actors:{body:S({kind:Ll.optional()}),response:x(TP),ws:`actors`},actorSettings:{body:S({}),response:S({declared:x(WM),values:x(DP)}),ws:`actorSettings`},runs:{body:zl.extend({query:sA.optional()}),response:Rl(Fk),ws:`runs`},llmCalls:{body:zl.extend({query:sA.optional()}),response:Rl(GM),ws:`llmCalls`},resources:{body:zl.extend({query:sA.optional()}),response:Rl(qM),ws:`resources`},removeRule:{body:KM,response:S({ok:b()}),ws:`removeRule`},indexStatus:{body:S({}),response:zM,ws:`indexStatus`}}),events:{systemLog:{params:S({system:F}),data:RM,guard:[$,nR],ws:`on.systemLog`}}}),OR=wC(`ownEvents`,{requires:[$]}),kR=wC(`sessionWatch`,{requires:[$]}),AR=S({user:M}),jR=Y({endpoints:{},events:{session:{params:S({session:j}),data:dR,guard:[$,kR],ws:`on.session`},user:{params:AR,data:fR,guard:[$,OR],ws:`on.user`}}}),MR=Rl(qM).extend({facets:x(gT)}),NR=S({record:qM,forms:x(aT),offers:x(oT)}),PR=Y({endpoints:X(Q,$).group({browseResources:{body:_T.extend({query:sA.optional()}),response:MR,ws:`browseResources`},resourceForms:{body:S({uri:Cx}),response:NR,ws:`resourceForms`},readResource:{body:ST,response:CT,ws:`readResource`},convertResource:{body:S({uri:Cx,kind:Fx}),response:aT,ws:`convertResource`},downloadResource:{body:S({uri:Cx,form:Fx.optional()}),response:S({url:v(),mime:v(),size:y().int().min(0)}),ws:`downloadResource`},importResource:{body:wT,response:qM,ws:`importResource`},renameResource:{body:S({uri:Cx,name:v().min(1)}),response:qM,ws:`renameResource`},deleteResource:{body:S({uri:Cx}),response:S({deleted:b(),referencedBy:y().int().min(0)}),ws:`deleteResource`},contextFromResource:{body:uS,response:dS,ws:`contextFromResource`}})}),FR=zl.extend({query:sA.optional()}),IR=S({record:yM,links:x(aS),backlinks:x(aS),text:v().optional()}),LR=Y({endpoints:X(Q,$).group({contexts:{body:FR,response:Rl(gN),ws:`contexts`},contextItem:{body:S({name:I}),response:IR,ws:`contextItem`},remember:{body:sS,response:S({name:I}),ws:`remember`},updateMemory:{body:lS,response:S({name:I}),ws:`updateMemory`},forget:{body:S({name:I}),response:S({ok:b()}),ws:`forget`},linkContext:{body:S({from:I,to:tS,relation:eS,weight:y().min(0).max(1)}),response:aS,ws:`linkContext`},unlinkContext:{body:aS.pick({from:!0,toKey:!0,relation:!0}),response:S({ok:b()}),ws:`unlinkContext`}})}),RR=EC(Y({endpoints:X(Q,$).group({modelLimits:{body:S({model:v().optional()}),response:x(ex),ws:`modelLimits`},previewSelection:{body:S({session:j,text:v()}),response:ax,ws:`previewSelection`}})}),Y({endpoints:X(Q,$,nR).group({setModelLimits:{body:S({model:v().min(1),limits:Xb}),response:ex,ws:`setModelLimits`},previewPrompt:{body:ox,response:sx,ws:`previewPrompt`}})})),zR=Y({endpoints:X(Q,$,nR).group({modelRoles:{body:S({}),response:x(SE),ws:`modelRoles`},setModelRole:{body:bE,response:SE,ws:`setModelRole`},clearModelRole:{body:S({role:pE}),response:SE,ws:`clearModelRole`}})}),BR=zl.extend({run:A.optional(),query:sA.optional()}),VR=Y({endpoints:X(Q,$,nR).group({modelCalls:{body:BR,response:Rl(uE),ws:`modelCalls`},modelCall:{body:S({id:Tl}),response:uE,ws:`modelCall`},fnMetrics:{body:ME,response:x(jE),ws:`fnMetrics`},fnMetricsDays:{body:S({fn:I,days:y().int().min(1).max(365).optional()}),response:x(AE),ws:`fnMetricsDays`}})}),HR=Y({endpoints:X(Q,$,nR).group({mcps:{body:S({}),response:x(II),ws:`mcps`},mcp:{body:S({mcp:El}),response:II,ws:`mcp`},createMcp:{body:MI,response:S({mcp:II,secret:v()}),ws:`createMcp`},updateMcp:{body:MI.partial().extend({mcp:El}),response:II,ws:`updateMcp`},rotateMcpSecret:{body:S({mcp:El}),response:S({secret:v()}),ws:`rotateMcpSecret`},deleteMcp:{body:S({mcp:El}),response:S({ok:b()}),ws:`deleteMcp`},previewMcp:{body:S({rules:kI}),response:PI,ws:`previewMcp`},mcpSessions:{body:S({mcp:El}),response:x(FI),ws:`mcpSessions`}})}),UR=Y({endpoints:X(Q,$,nR).group({pairing:{body:S({pairing:ul}),response:fM,ws:`pairing`},instances:{body:S({system:F}),response:x(cR),ws:`instances`},installPackage:{body:S({zip:Dx,instance:L.optional(),config:O.optional(),data:Dx.optional(),autoStart:b().optional()}),response:Wl,ws:`installPackage`},removeInstance:{body:Wl,response:S({ok:b()}),ws:`removeInstance`},addInstance:{body:LM,response:Wl,ws:`addInstance`},exportSystemData:{body:Wl.extend({withSecrets:b().optional()}),response:Dx.extend({url:v()}),ws:`exportSystemData`}})}),WR=EC(Y({endpoints:X(Q,$).group({query:{body:xA,response:SA,ws:`query`},listValues:{body:bA,response:x(yA),ws:`listValues`}})}),Y({endpoints:X(Q,$,nR).group({fns:{body:sA,response:Rl(hM),ws:`fns`}})})),GR=Y({endpoints:X(Q,$,nR).group({suggestDecision:{body:S({}),response:CF,ws:`suggestDecision`},setSuggestDecision:{body:vF,response:CF,ws:`setSuggestDecision`},searchDecisions:{body:S({}),response:kF,ws:`searchDecisions`},setSearchDecision:{body:AF,response:kF,ws:`setSearchDecision`},previewSuggestions:{body:S({session:j,text:v().min(1)}),response:hF,ws:`previewSuggestions`}})}),KR=Y({endpoints:X(Q,$,nR).group({imageEmbedding:{body:S({}),response:xP,ws:`imageEmbedding`},setImageEmbedding:{body:_P,response:xP,ws:`setImageEmbedding`}})}),qR=EC(Y({endpoints:X(Q,$).group({outsideImages:{body:S({}),response:gb,ws:`outsideImages`}})}),Y({endpoints:X(Q,$,nR).group({setOutsideImages:{body:S({value:hb}),response:gb,ws:`setOutsideImages`}})})),JR=EC(Y({endpoints:X(Q,$).group({https:{body:S({}),response:bb,ws:`https`}})}),Y({endpoints:X(Q,$,nR).group({setHttps:{body:S({on:b()}),response:bb,ws:`setHttps`}})})),YR=Y({endpoints:X(Q,$,nR).group({autoPairs:{body:S({system:F.optional()}),response:x(tM),ws:`autoPairs`},revokeAutoPair:{body:S({id:Dl}),response:S({ok:b()}),ws:`revokeAutoPair`}})}),XR=Y({endpoints:X(Q,$).group({accessInfo:{body:S({}),response:zE,ws:`accessInfo`},access:{body:S({targets:x(IE).min(1).max(200)}),response:x(RE),ws:`access`},setAccess:{body:S({target:IE,sharing:FE.omit({owner:!0})}),response:RE,ws:`setAccess`}})}),ZR=Y({endpoints:X(Q,$).group({connectPages:{body:S({}),response:x(pD),ws:`connectPages`},connect:{body:S({system:F,instance:L.optional(),key:sD.optional(),form:O.optional()}),response:C([S({url:fb}),S({connection:fD})]),ws:`connect`,httpOnly:!0},updateConnection:{body:yD,response:fD,ws:`updateConnection`},disconnect:{body:S({connection:Ol}),response:S({ok:b()}),ws:`disconnect`}})}),QR=Y({endpoints:X(Q,$).group({pick:{body:UE,response:x(WE),ws:`pick`}})}),$R=Y({endpoints:X(Q,$).group({approvals:{body:S({runs:x(A).min(1).max(200)}),response:x(PP),ws:`approvals`}})}),ez=Y({endpoints:X(Q,$).group({contributions:{body:S({registry:I}),response:x(hO),ws:`contributions`},systemPages:{body:S({}),response:x(ek),ws:`systemPages`}})}),tz=EC(Y({endpoints:X(Q,$).group({searchFns:{body:uN,response:yN,ws:`searchFns`},fnExamples:{body:aN,response:oN,ws:`fnExamples`},fnFacts:{body:S({fn:I,args:O.optional()}),response:SN,ws:`fnFacts`},fnsOfModelNames:{body:S({names:x(v().min(1).max(64)).min(1).max(200)}),response:T(v(),I),ws:`fnsOfModelNames`},clientLogs:{body:DN,response:ON,ws:`clientLogs`}})}),Y({endpoints:X(Q,$,nR).group({autoClassifier:{body:S({}),response:EN,ws:`autoClassifier`},setAutoClassifier:{body:TN,response:EN,ws:`setAutoClassifier`}})})),nz=Y({endpoints:X(Q,$).group({exploreRoots:{body:S({system:F,instance:L.optional()}),response:x(Ox),ws:`exploreRoots`},exploreList:{body:S({uri:Cx,cursor:v().optional()}),response:Rl(kx),ws:`exploreList`},exploreRead:{body:S({uri:Cx,want:x(jx).min(1)}),response:Nx,ws:`exploreRead`}})}),rz=Y({endpoints:X(Q,$,nR).group({systemReview:{body:S({system:F}),response:XN,ws:`systemReview`},goLive:{body:ZN,response:S({stage:tO,hash:v()}),ws:`goLive`},approveReview:{body:ZN,response:S({hash:v()}),ws:`approveReview`},rejectReview:{body:S({system:F,hash:v().min(1)}),response:S({ok:b()}),ws:`rejectReview`},decideReview:{body:QN,response:$N,ws:`decideReview`},testCall:{body:tP,response:S({run:A}),ws:`testCall`},refusals:{body:JN,response:YN,ws:`refusals`}})}),iz=Y({endpoints:X(Q,$).group({graph:{body:XI,response:ZI,ws:`graph`}})}),az=S({agent:I.optional(),context:I.optional(),mode:Rb.optional(),fnMode:ux.optional()}),oz=Y({endpoints:X(Q,$,nR).group({injections:{body:az,response:kb,ws:`injections`},setInjection:{body:Ab,response:Ob,ws:`setInjection`}})}),sz=EC(Y({endpoints:X(Q).group({identity:{method:`GET`,response:mP,ws:`identity`}})}),Y({endpoints:X(Q,$,nR).group({setHubName:{body:hP,response:mP,ws:`setHubName`}})})),cz=Y({endpoints:X(Q,$,nR).group({people:{body:sA,response:Rl(eF),ws:`people`},groups:{body:sA,response:Rl(tF),ws:`groups`},groupMembers:{body:zl.extend({group:M}),response:Rl(EP).extend({group:tF}),ws:`groupMembers`},signInSettings:{body:S({}),response:qP,ws:`signInSettings`},checkSsoProvider:{body:S({provider:FP}),response:YP,ws:`checkSsoProvider`},testSsoSignIn:{body:S({provider:FP}),response:S({url:fb,test:v()}),ws:`testSsoSignIn`,httpOnly:!0},ssoTestResult:{body:S({test:v()}),response:QP,ws:`ssoTestResult`}})}),lz=Y({endpoints:X(Q,$).group({itemVersions:{body:zI,response:BI,ws:`itemVersions`}})}),uz=Y({endpoints:X(Q,$).group({dataSets:{body:LA,response:RA,ws:`dataSets`},records:{body:DA,response:OA,ws:`records`},record:{body:AA,response:S({record:TA.optional()}),ws:`record`},recordTable:{body:kA,response:yO,ws:`recordTable`},saveRecord:{body:jA,response:TA,ws:`saveRecord`},updateRecord:{body:MA,response:TA,ws:`updateRecord`},removeRecord:{body:NA,response:S({removed:b()}),ws:`removeRecord`},recordVersions:{body:PA,response:FA,ws:`recordVersions`}})}),dz=EC(pR,vR,yR,bR,xR,SR,TR,ER,DR,jR,PR,LR,RR,zR,VR,HR,UR,WR,GR,YR,KR,qR,JR,XR,ZR,QR,$R,ez,tz,nz,rz,iz,oz,sz,lz,uz,Y({endpoints:X(Q,$).group({rowActions:{body:JL,response:x(KL),ws:`rowActions`},readFn:{body:XL,response:O,ws:`readFn`}})}),Y({endpoints:X(Q,$).group({export:{method:`GET`,query:QL,streamOut:`text/csv`,download:`export.csv`}})}),cz),fz={load_fns:`fns_load`,drop_fns:`fns_drop`,fn_examples:`fns_examples`,fn_get:`fns_get`,save_fn:`fns_save`,fn_metrics:`fns_metrics`,load_context:`ctx_load`,context_get:`ctx_get`,context_crawl:`ctx_crawl`,context_from_resource:`ctx_from_resource`,context_link:`ctx_link`,context_unlink:`ctx_unlink`};new Map(Object.entries(fz).map(([e,t])=>[`hub/${e}`,`hub/${t}`])),new Map(Object.entries(fz));var pz=E([`added`,`modified`,`deleted`,`renamed`]),mz=E([`binary`,`large`,`sensitive`,`not-in-git`]),hz=S({path:v().min(1),root:v().min(1),status:pz,from:v().min(1).optional(),size:y().int().min(0).optional(),diff:v().optional(),added:y().int().min(0).optional(),removed:y().int().min(0).optional(),noDiff:mz.optional(),sensitive:wO.optional(),certain:b()}),gz=S({source:E([`git`,`watcher`]),cwd:v().min(1),files:x(hz),ignored:y().int().min(0),truncated:b()}),_z=S({arg:k,label:v().min(1).optional(),choices:x(O).min(1).optional(),custom:b().optional(),pinned:O.optional(),hidden:b().optional()}),vz=S({offset:k.optional(),limit:k.optional(),size:y().int().min(1).max(500)}),yz=S({visual:k,label:v().min(1).optional(),bind:T(k,x(v().min(1)).min(1))}),bz=E([`refresh`,`show`,`none`]),xz=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:bz});S({title:v().min(1),source:I,visuals:x(yz).min(1),controls:x(_z),paging:vz.optional(),actions:x(xz).optional()});var Sz=v().regex(/^[A-Za-z_][A-Za-z0-9_]*$/),Cz=w(`type`,[S({type:D(`stdio`),command:v().min(1),args:x(v()).default([]),env:T(Sz,v()).optional(),cwd:v().min(1).optional()}),S({type:D(`http`),url:Ls()}),S({type:D(`sse`),url:Ls()})]),wz=E([`always`,`writes`,`never`]),Tz=S({label:v().min(1),description:v().optional(),transport:Cz,auth:ZE.default({kind:`none`}),trusted:b().default(!1),approval:wz.default(`writes`),prompts:b().default(!0),resources:b().default(!0),maxTools:y().int().min(1).max(1e3).default(200),timeout:y().int().min(1e3).default(12e4)}),Ez=[`transport.env`,...tD],Dz=S({instance:L,state:E([`connecting`,`connected`,`needs-auth`,`unreachable`,`failed`]),server:S({name:v(),version:v(),protocol:v(),instructions:v().optional()}).optional(),tools:y().int().min(0),prompts:y().int().min(0),resources:y().int().min(0),degraded:x(v()),leftOut:y().int().min(0),problem:v().optional(),checkedAt:N}),Oz=S({title:v().optional(),readOnlyHint:b().optional(),destructiveHint:b().optional(),idempotentHint:b().optional(),openWorldHint:b().optional()});S({tool:v().min(1),description:v(),inputSchema:O,outputSchema:O.optional(),args:Z,returns:Z.optional(),annotations:Oz.optional(),degraded:v().optional()});function kz(e,t){let n=`${e}_${t.replace(/[^A-Za-z0-9_.-]/g,`_`)}`.replace(/-/g,`_`);return eb.parse(n.split(`.`).map(e=>e.replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||`x`).join(`.`))}function Az(e){return`mcp://${e}/`}S({args:Z,returns:Z,program:UC}),S({service:sD,args:Z,returns:Z,request:UC,responseType:Z.optional(),output:UC.optional()});var jz=E([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`,`HEAD`,`OPTIONS`]),Mz=sD,Nz=`api/Service`,Pz=S({name:Mz,label:v().min(1),description:v().optional(),baseUrl:Ls(),allowPrivate:b().default(!1),privateTo:M.optional(),auth:$E.default({kind:`none`}),headers:qE.optional(),openapi:Ls().optional(),timeout:y().int().min(1e3).default(6e4),maxBody:y().int().min(1024).default(2097152)});S({label:v().min(1),description:v().optional(),baseUrl:Ls(),auth:QE.default({kind:`none`}),headers:qE.optional(),openapi:Ls().optional(),timeout:y().int().min(1e3).default(6e4),maxBody:y().int().min(1024).default(2097152)}),[...eD],S({method:jz,url:v(),headers:x(S({key:v(),value:v()})),body:v().optional(),response:S({status:y().int(),headers:x(S({key:v(),value:v()})),body:O.optional(),ms:y().int().min(0)}).optional()});var Fz=tN.pick({id:!0,title:!0,body:!0,link:!0,reason:!0,also:!0,key:!0,tone:!0}),Iz=`open`,Lz=E([`link`,`also`]),Rz=`also`;function zz(e,t=`link`){return`/inbox?${Iz}=${encodeURIComponent(e.id)}${t===`also`?`&via=also`:``}`}function Bz(e){return e.key??e.id}function Vz(e){return e.also===void 0?{link:zz(e)}:{link:zz(e),also:zz(e,`also`)}}function Hz(e,t){let n=e=>typeof e==`string`&&e.startsWith(`/`)&&!e.startsWith(`//`);if(n(e))return e;if(typeof e==`object`&&e){let r=Reflect.get(e,`also`),i=Reflect.get(e,`link`);if(t===`also`&&n(r))return r;if(n(i))return i}return`/inbox`}export{UL as $,Bl as $a,vg as $i,OE as $n,lS as $r,xM as $t,HR as A,M as Aa,fv as Ai,gk as An,Zc as Ao,ew as Ar,dF as At,lz as B,Tl as Ba,cv as Bi,_O as Bn,zC as Br,pP as Bt,LR as C,Ef as Ca,My as Ci,hA as Cn,ws as Co,Sw as Cr,EF as Ct,iz as D,gf as Da,Wy as Di,Jk as Dn,ic as Do,fw as Dr,yF as Dt,nz as E,tf as Ea,Uy as Ei,vA as En,E as Eo,tw as Er,_F as Et,PR as F,O as Fa,uv as Fi,GO as Fn,T as Fo,XC as Fr,kP as Ft,YL as G,I as Ga,Mg as Gi,SD as Gn,dC as Gr,oN as Gt,QL as H,vl as Ha,iv as Hi,$D as Hn,MC as Hr,WN as Ht,yR as I,ll as Ia,Eg as Ii,qO as In,v as Io,ZC as Ir,vP as It,kL as J,j as Ja,Ev as Ji,rD as Jn,$x as Jr,mN as Jt,JL as K,Vl as Ka,vv as Ki,lD as Kn,uS as Kr,aN as Kt,ER as L,k as La,Dg as Li,mO as Ln,vc as Lo,UC as Lr,gP as Lt,zR as M,Il as Ma,rv as Mi,ik as Mn,y as Mo,YC as Mr,WP as Mt,UR as N,El as Na,wg as Ni,ZO as Nn,S as No,qC as Nr,HP as Nt,dz as O,R as Oa,Sg as Oi,Rk as On,x as Oo,sw as Or,vF as Ot,WR as P,L as Pa,Tg as Pi,QO as Pn,Ec as Po,JC as Pr,iF as Pt,qL as Q,$c as Qa,Vg as Qi,LE as Qn,sS as Qr,eN as Qt,GR as R,Ul as Ra,gg as Ri,hO as Rn,C as Ro,VC as Rr,_P as Rt,ZR as S,pf as Sa,Ny as Si,_A as Sn,Uc as So,xw as Sr,pF as St,uz as T,Of as Ta,Xy as Ti,tA as Tn,oc as To,ow as Tr,cF as Tt,ML as U,Pl as Ua,bv as Ui,QD as Un,_S as Ur,TN as Ut,BL as V,Gl as Va,gv as Vi,yO as Vn,AC as Vr,NN as Vt,AL as W,ul as Wa,Ng as Wi,GD as Wn,cC as Wr,fN as Wt,RL as X,N as Xa,zg as Xi,BE as Xn,nS as Xr,lN as Xt,KL as Y,F as Ya,W_ as Yi,nD as Yn,rS as Yr,yN as Yt,ZL as Z,al as Za,Bg as Zi,PE as Zn,tS as Zr,jN as Zt,rR as _,_f as _a,vb as _i,zA as _n,zc as _o,qw as _r,UF as _t,Hz as a,wv as aa,Ix as ai,Xj as an,Lc as ao,DT as ar,EL as at,YR as b,Df as ba,ob as bi,wA as bn,yc as bo,Yw as br,qF as bt,Nz as c,qg as ca,Gb as ci,rj as cn,xc as co,bT as cr,bL as ct,Tz as d,jy as da,Jb as di,Oj as dn,Fc as do,vT as dr,VI as dt,Hg as ea,Gx as ei,yM as en,Ml as eo,EE as er,tR as et,Dz as f,am as fa,jb as fi,Cj as fn,rc as fo,yT as fr,MI as ft,oR as g,sf as ga,Sb as gi,BA as gn,Tc as go,Ww as gr,DI as gt,gz as h,Tf as ha,Cb as hi,qA as hn,dc as ho,Lw as hr,NI as ht,Fz as i,_v as ia,Cx as ii,Wj as in,nc as io,YT as ir,QI as it,VR as j,Ll as ja,Cg as ji,yk as jn,D as jo,QC as jr,RP as jt,oz as k,Hl as ka,_g as ki,Ek as kn,b as ko,dw as kr,gF as kt,Pz as l,U as la,lx as li,fj as ln,Gc as lo,xT as lr,GI as lt,kz as m,df as ma,zb as mi,Pj as mn,$s as mo,Zw as mr,EI as mt,Lz as n,nv as na,Tx as ni,gM as nn,ac as no,mE as nr,eR as nt,Bz as o,Wg as oa,wx as oi,Uj as on,qc as oo,iT as or,yL as ot,Az as p,hh as pa,Xb as pi,Nj as pn,kc as po,mT as pr,OI as pt,OL as q,A as qa,Lg as qi,sD as qn,oS as qr,dN as qt,Iz as r,lv as ra,Fx as ri,bM as rn,uc as ro,bE as rr,DL as rt,Vz as s,Gg as sa,Sx as si,Zj as sn,jc as so,uT as sr,oL as st,Rz as t,Ug as ta,Ux as ti,rM as tn,Nl as to,pE as tr,$L as tt,Ez as u,Yg as ua,Lb as ui,nj as un,Sc as uo,hT as ur,XI as ut,XR as v,Xl as va,pb as vi,TA as vn,Nc as vo,Xw as vr,JF as vt,RR as w,mf as wa,Vy as wi,eA as wn,pc as wo,Cw as wr,wF as wt,vR as x,nf as xa,rb as xi,aA as xn,Es as xo,Hw as xr,lF as xt,DR as y,of as ya,tb as yi,CA as yn,Vc as yo,Jw as yr,IF as yt,TR as z,ol as za,pv as zi,gO as zn,sc as zo,Z as zr,dP as zt};
402
+ //# sourceMappingURL=push-payload-D5efGCzd.js.map