fnloom 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +123 -19
- package/package.json +15 -11
- package/packages/build/package.json +2 -2
- package/packages/build/src/tests.ts +2 -2
- package/packages/cli/package.json +1 -1
- package/packages/cli/src/cli.ts +4 -3
- package/packages/cli/src/command.ts +4 -2
- package/packages/cli/src/commands/install.ts +104 -8
- package/packages/cli/src/commands/manage.ts +7 -5
- package/packages/cli/src/commands/mcp.ts +6 -6
- package/packages/cli/src/commands/store.ts +172 -0
- package/packages/cli/src/hub.ts +45 -26
- package/packages/cli/src/index.ts +1 -1
- package/packages/cli/src/io.ts +3 -2
- package/packages/cli/src/local.ts +7 -7
- package/packages/cli/src/premade.ts +1 -1
- package/packages/cli/src/testing.ts +2 -1
- package/packages/core/package.json +4 -4
- package/packages/core/src/auto-pair.ts +1 -1
- package/packages/core/src/connections.ts +1 -14
- package/packages/core/src/context-files.ts +3 -1
- package/packages/core/src/context-graph.ts +5 -1
- package/packages/core/src/context-plan.ts +451 -0
- package/packages/core/src/context-questions.ts +305 -0
- package/packages/core/src/data.ts +1 -1
- package/packages/core/src/fn-facts.ts +32 -4
- package/packages/core/src/https.ts +2 -2
- package/packages/core/src/identity.ts +2 -2
- package/packages/core/src/image-embeddings.ts +1 -1
- package/packages/core/src/index.ts +9 -8
- package/packages/core/src/link.ts +71 -1
- package/packages/core/src/manifest.ts +22 -3
- package/packages/core/src/mention-search.ts +1 -1
- package/packages/core/src/model-calls.ts +11 -2
- package/packages/core/src/package.ts +11 -1
- package/packages/core/src/ports.ts +2 -2
- package/packages/core/src/query.ts +4 -3
- package/packages/core/src/records/chat.ts +1 -1
- package/packages/core/src/records/content.ts +10 -2
- package/packages/core/src/records/runs.ts +12 -0
- package/packages/core/src/records/spend.ts +4 -0
- package/packages/core/src/records/systems.ts +87 -5
- package/packages/core/src/registries.ts +9 -3
- package/packages/core/src/run.ts +5 -0
- package/packages/core/src/sso.ts +2 -2
- package/packages/core/src/stores.ts +473 -0
- package/packages/core/src/suggestions.ts +5 -2
- package/packages/core/src/system-pages.ts +46 -7
- package/packages/core/src/tables.ts +233 -0
- package/packages/core/src/visuals.ts +47 -139
- package/packages/core/src/web.ts +116 -11
- package/packages/core/src/widgets-v1.ts +78 -1
- package/packages/hub/package.json +15 -12
- package/packages/hub/src/access/hits.ts +1 -1
- package/packages/hub/src/api/admin-ops.ts +41 -9
- package/packages/hub/src/api/auth.ts +10 -6
- package/packages/hub/src/api/https.ts +6 -6
- package/packages/hub/src/api/identities.ts +1 -1
- package/packages/hub/src/api/person-ops.ts +6 -0
- package/packages/hub/src/api/reads.ts +1 -1
- package/packages/hub/src/api/secrets.ts +1 -1
- package/packages/hub/src/api/serve.ts +2 -2
- package/packages/hub/src/api/sso-route.ts +2 -2
- package/packages/hub/src/api/sso.ts +6 -6
- package/packages/hub/src/api/store-ops.ts +54 -0
- package/packages/hub/src/api/testing/rig.ts +3 -3
- package/packages/hub/src/api/tls.ts +4 -4
- package/packages/hub/src/api/web/auth.ts +1 -1
- package/packages/hub/src/api/web/build5.ts +2 -1
- package/packages/hub/src/api/web/context-plans.ts +25 -0
- package/packages/hub/src/api/web/context-review.ts +43 -0
- package/packages/hub/src/api/web/find.ts +1 -1
- package/packages/hub/src/api/web/index.ts +4 -0
- package/packages/hub/src/api/web/pages.ts +17 -3
- package/packages/hub/src/api/web/pickers.ts +4 -4
- package/packages/hub/src/api/web/review.ts +16 -0
- package/packages/hub/src/api/web/systems.ts +14 -2
- package/packages/hub/src/boot/admin-fns.ts +8 -0
- package/packages/hub/src/boot/admin-secrets.ts +10 -4
- package/packages/hub/src/boot/env.ts +82 -73
- package/packages/hub/src/boot/hub-fns.ts +4 -4
- package/packages/hub/src/boot/hub-groups.ts +2 -2
- package/packages/hub/src/boot/identity.ts +2 -2
- package/packages/hub/src/boot/index.ts +10 -1
- package/packages/hub/src/boot/info.ts +1 -1
- package/packages/hub/src/boot/keys.ts +6 -6
- package/packages/hub/src/boot/log.ts +4 -4
- package/packages/hub/src/boot/modules.ts +16 -7
- package/packages/hub/src/boot/person-fns.ts +5 -0
- package/packages/hub/src/boot/plan-fns.ts +39 -0
- package/packages/hub/src/boot/services.ts +9 -9
- package/packages/hub/src/boot/start.ts +25 -24
- package/packages/hub/src/catalog/catalog.ts +44 -14
- package/packages/hub/src/catalog/index.ts +6 -2
- package/packages/hub/src/chat/cache.ts +1 -1
- package/packages/hub/src/chat/chat.ts +1 -1
- package/packages/hub/src/chat/compare.ts +2 -2
- package/packages/hub/src/chat/deliveries.ts +1 -1
- package/packages/hub/src/chat/deps.ts +3 -3
- package/packages/hub/src/chat/enrich.ts +7 -7
- package/packages/hub/src/chat/env.ts +20 -20
- package/packages/hub/src/chat/mention-requests.ts +1 -1
- package/packages/hub/src/chat/mention-search.ts +1 -1
- package/packages/hub/src/chat/mentions.ts +3 -3
- package/packages/hub/src/chat/notifications.ts +2 -2
- package/packages/hub/src/chat/presence.ts +2 -2
- package/packages/hub/src/chat/sessions.ts +2 -2
- package/packages/hub/src/chat/suggestions.ts +8 -8
- package/packages/hub/src/chat/testing.ts +3 -3
- package/packages/hub/src/chat/turns.ts +6 -6
- package/packages/hub/src/chat/undo.ts +1 -1
- package/packages/hub/src/connections/create.ts +1 -1
- package/packages/hub/src/connections/env.ts +2 -2
- package/packages/hub/src/connections/service.ts +5 -9
- package/packages/hub/src/contextor/brought.ts +5 -3
- package/packages/hub/src/contextor/contextors.ts +9 -9
- package/packages/hub/src/contextor/crawl.ts +1 -1
- package/packages/hub/src/contextor/create.ts +5 -5
- package/packages/hub/src/contextor/dynamic.ts +5 -5
- package/packages/hub/src/contextor/env.ts +46 -46
- package/packages/hub/src/contextor/injected.ts +1 -1
- package/packages/hub/src/contextor/limits.ts +9 -9
- package/packages/hub/src/contextor/planner.ts +11 -11
- package/packages/hub/src/contextor/testing.ts +5 -5
- package/packages/hub/src/data/env.ts +3 -3
- package/packages/hub/src/data/service.ts +5 -5
- package/packages/hub/src/execution/agent.ts +8 -8
- package/packages/hub/src/execution/ai.ts +7 -7
- package/packages/hub/src/execution/create.ts +13 -6
- package/packages/hub/src/execution/env.ts +16 -14
- package/packages/hub/src/execution/errors.ts +12 -0
- package/packages/hub/src/execution/executors.ts +16 -4
- package/packages/hub/src/execution/gateway.ts +1 -1
- package/packages/hub/src/execution/index.ts +9 -1
- package/packages/hub/src/execution/ledger.ts +2 -2
- package/packages/hub/src/execution/limits.ts +2 -2
- package/packages/hub/src/execution/link-handlers.ts +16 -4
- package/packages/hub/src/execution/models.ts +2 -2
- package/packages/hub/src/execution/ports.ts +1 -1
- package/packages/hub/src/execution/providers.ts +55 -11
- package/packages/hub/src/execution/queues.ts +6 -6
- package/packages/hub/src/execution/runs.ts +216 -15
- package/packages/hub/src/execution/stream-guard.ts +2 -2
- package/packages/hub/src/execution/testing.ts +7 -6
- package/packages/hub/src/execution/wire.ts +3 -3
- package/packages/hub/src/fns/auto.ts +2 -2
- package/packages/hub/src/fns/client-logs.ts +2 -2
- package/packages/hub/src/fns/create.ts +2 -2
- package/packages/hub/src/fns/decided.ts +2 -2
- package/packages/hub/src/fns/env.ts +14 -14
- package/packages/hub/src/fns/examples.ts +3 -3
- package/packages/hub/src/fns/facts.ts +5 -5
- package/packages/hub/src/fns/search.ts +28 -9
- package/packages/hub/src/graph/graph.ts +3 -3
- package/packages/hub/src/index/context-sections.ts +1 -1
- package/packages/hub/src/index/embedders.ts +3 -3
- package/packages/hub/src/index/env.ts +12 -12
- package/packages/hub/src/index/index.ts +10 -3
- package/packages/hub/src/index/indexer.ts +71 -20
- package/packages/hub/src/index/search.ts +2 -1
- package/packages/hub/src/index/suggester.ts +2 -2
- package/packages/hub/src/index/testing.ts +2 -2
- package/packages/hub/src/link/build.ts +71 -34
- package/packages/hub/src/link/connections.ts +41 -3
- package/packages/hub/src/link/describer.ts +19 -2
- package/packages/hub/src/link/env.ts +21 -11
- package/packages/hub/src/link/grants.ts +10 -10
- package/packages/hub/src/link/handlers.ts +6 -0
- package/packages/hub/src/link/index.ts +16 -4
- package/packages/hub/src/link/lifecycle.ts +15 -8
- package/packages/hub/src/link/migrate-api.ts +55 -15
- package/packages/hub/src/link/packages.ts +17 -4
- package/packages/hub/src/link/pairing.ts +3 -3
- package/packages/hub/src/link/process.ts +11 -5
- package/packages/hub/src/link/rig.ts +15 -11
- package/packages/hub/src/link/status.ts +14 -0
- package/packages/hub/src/link/supervisor.ts +17 -1
- package/packages/hub/src/link/systems.ts +16 -5
- package/packages/hub/src/mcp/calls.ts +6 -6
- package/packages/hub/src/mcp/create.ts +5 -5
- package/packages/hub/src/mcp/env.ts +6 -6
- package/packages/hub/src/mcp/fns.ts +2 -2
- package/packages/hub/src/mcp/index.ts +2 -2
- package/packages/hub/src/mcp/sources.ts +3 -3
- package/packages/hub/src/mcp/tokens.ts +1 -1
- package/packages/hub/src/models/create.ts +1 -1
- package/packages/hub/src/models/decide.ts +2 -2
- package/packages/hub/src/models/index.ts +1 -1
- package/packages/hub/src/models/roles.ts +78 -11
- package/packages/hub/src/query/columns.ts +4 -1
- package/packages/hub/src/query/contexts.ts +10 -3
- package/packages/hub/src/query/env.ts +5 -5
- package/packages/hub/src/query/sources.ts +3 -3
- package/packages/hub/src/questions/apply.ts +163 -0
- package/packages/hub/src/questions/carry.ts +30 -0
- package/packages/hub/src/questions/duplicates.ts +181 -0
- package/packages/hub/src/questions/index.ts +112 -0
- package/packages/hub/src/questions/metadata.ts +142 -0
- package/packages/hub/src/questions/pending.ts +64 -0
- package/packages/hub/src/questions/plan-match.ts +79 -0
- package/packages/hub/src/questions/plan-prompts.ts +110 -0
- package/packages/hub/src/questions/planner.ts +382 -0
- package/packages/hub/src/questions/plans.ts +353 -0
- package/packages/hub/src/questions/review.ts +253 -0
- package/packages/hub/src/questions/setting.ts +50 -0
- package/packages/hub/src/questions/testing.ts +131 -0
- package/packages/hub/src/questions/worker.ts +182 -0
- package/packages/hub/src/resources/context.ts +61 -23
- package/packages/hub/src/resources/converters.ts +2 -2
- package/packages/hub/src/resources/create.ts +20 -8
- package/packages/hub/src/resources/env.ts +15 -11
- package/packages/hub/src/resources/fetch.ts +5 -5
- package/packages/hub/src/resources/fns.ts +6 -2
- package/packages/hub/src/resources/forms.ts +5 -5
- package/packages/hub/src/resources/index.ts +9 -3
- package/packages/hub/src/resources/library.ts +2 -2
- package/packages/hub/src/resources/raw.ts +1 -1
- package/packages/hub/src/resources/reader.ts +2 -2
- package/packages/hub/src/resources/sqlite-files.ts +1 -1
- package/packages/hub/src/resources/storage.ts +5 -5
- package/packages/hub/src/resources/testing.ts +22 -6
- package/packages/hub/src/store/codec.ts +23 -5
- package/packages/hub/src/store/context-status.ts +56 -0
- package/packages/hub/src/store/derived.ts +53 -0
- package/packages/hub/src/store/env.ts +4 -4
- package/packages/hub/src/store/hybrid.ts +37 -10
- package/packages/hub/src/store/lists.ts +2 -1
- package/packages/hub/src/store/migrate-fn-names.ts +5 -2
- package/packages/hub/src/store/rows.ts +8 -1
- package/packages/hub/src/store/schema.ts +2 -1
- package/packages/hub/src/store/sqlite.ts +5 -4
- package/packages/hub/src/stores/backups.ts +163 -0
- package/packages/hub/src/stores/drivers.ts +100 -0
- package/packages/hub/src/stores/guard.ts +116 -0
- package/packages/hub/src/stores/host.ts +459 -0
- package/packages/hub/src/stores/moves.ts +380 -0
- package/packages/hub/src/stores/plugin.ts +42 -0
- package/packages/hub/src/stores/service.ts +340 -0
- package/packages/hub/src/stores/testing.ts +149 -0
- package/packages/hub/src/tables/env.ts +3 -3
- package/packages/hub/src/tables/index.ts +5 -5
- package/packages/hub/src/tables/service.ts +7 -7
- package/packages/sdk/AUTHORING.md +3229 -1309
- package/packages/sdk/package.json +15 -8
- package/packages/sdk/src/agent.ts +1 -1
- package/packages/sdk/src/app-parts.ts +95 -0
- package/packages/sdk/src/authored.ts +26 -0
- package/packages/sdk/src/authoring.ts +13 -30
- package/packages/sdk/src/build.ts +3 -0
- package/packages/sdk/src/client-runtime.ts +24 -1
- package/packages/sdk/src/client-ui/AddServiceDialog.vue +43 -0
- package/packages/sdk/src/client-ui/InstanceNameField.vue +29 -0
- package/packages/sdk/src/client-ui/PairRowsEditor.vue +74 -0
- package/packages/sdk/src/client-ui/RemoteAuthFields.vue +95 -0
- package/packages/sdk/src/client-ui/ServiceRows.vue +57 -0
- package/packages/sdk/src/client-ui/draft.ts +10 -0
- package/packages/sdk/src/client-ui/host.ts +37 -0
- package/packages/sdk/src/client-ui/index.ts +19 -0
- package/packages/sdk/src/client-ui/loaded.ts +69 -0
- package/packages/sdk/src/client-ui/problems.ts +98 -0
- package/packages/sdk/src/client-ui/remote-config.ts +199 -0
- package/packages/sdk/src/client-ui/service-rows.ts +25 -0
- package/packages/sdk/src/client-ui/state.ts +14 -0
- package/packages/sdk/src/client-ui/testing.ts +147 -0
- package/packages/sdk/src/client-ui/vue-shim.d.ts +13 -0
- package/packages/sdk/src/client.ts +104 -11
- package/packages/sdk/src/ctx.ts +51 -17
- package/packages/sdk/src/declare.ts +36 -12
- package/packages/sdk/src/hub.ts +226 -14
- package/packages/sdk/src/impl.ts +3 -3
- package/packages/sdk/src/index.ts +19 -12
- package/packages/sdk/src/manifest.ts +5 -0
- package/packages/sdk/src/page-parts.ts +4 -0
- package/packages/sdk/src/program/env.ts +7 -7
- package/packages/sdk/src/program/runtime.ts +5 -5
- package/packages/sdk/src/program/tools.ts +3 -3
- package/packages/sdk/src/providers.ts +2 -2
- package/packages/sdk/src/remote-auth.ts +128 -7
- package/packages/sdk/src/server/asks.ts +12 -1
- package/packages/sdk/src/server/context-files.ts +1 -1
- package/packages/sdk/src/server/env.ts +47 -35
- package/packages/sdk/src/server/fake-hub-widgets.ts +7 -6
- package/packages/sdk/src/server/host.ts +106 -35
- package/packages/sdk/src/server/index.ts +23 -4
- package/packages/sdk/src/server/live.ts +4 -4
- package/packages/sdk/src/server/llm-wire.ts +4 -4
- package/packages/sdk/src/server/package.ts +11 -2
- package/packages/sdk/src/server/pairing.ts +1 -1
- package/packages/sdk/src/server/results.ts +4 -4
- package/packages/sdk/src/server/run.ts +6 -1
- package/packages/sdk/src/server/runtime.ts +78 -22
- package/packages/sdk/src/server/socket-guard.ts +1 -1
- package/packages/sdk/src/server/start-gate.ts +174 -0
- package/packages/sdk/src/server/store/checksum.ts +162 -0
- package/packages/sdk/src/server/store/engines.ts +400 -0
- package/packages/sdk/src/server/store/extend.ts +25 -0
- package/packages/sdk/src/server/store/keeper.ts +392 -0
- package/packages/sdk/src/server/store/link-driver.ts +142 -0
- package/packages/sdk/src/server/store/measure.ts +45 -0
- package/packages/sdk/src/server/store/migrations.ts +238 -0
- package/packages/sdk/src/server/store/move.ts +488 -0
- package/packages/sdk/src/server/store/portable.ts +288 -0
- package/packages/sdk/src/server/store/stable.ts +146 -0
- package/packages/sdk/src/server/store/tables.ts +28 -0
- package/packages/sdk/src/server/store/vectors.ts +185 -0
- package/packages/sdk/src/server/store/work-checks.ts +288 -0
- package/packages/sdk/src/server/store/work.ts +369 -0
- package/packages/sdk/src/server/supervise.ts +4 -4
- package/packages/sdk/src/server/table.ts +3 -1
- package/packages/sdk/src/server/testing.ts +116 -3
- package/packages/sdk/src/store.ts +91 -0
- package/packages/sdk/src/system.ts +58 -30
- package/packages/sdk/src/testing/env.ts +6 -6
- package/packages/sdk/src/testing/hub.ts +21 -6
- package/packages/sdk/src/testing/models.ts +3 -3
- package/packages/sdk/src/testing/openrouter.ts +3 -2
- package/packages/sdk/src/testing/preview.ts +7 -7
- package/packages/sdk/src/widgets.ts +21 -136
- package/packages/sdk/tsconfig.json +2 -2
- package/packages/web/dist/assets/{ActorSettingsView-BuMYRDqv.js → ActorSettingsView-CDszUbHz.js} +2 -2
- package/packages/web/dist/assets/AdminLayout-CFIz4GsQ.js +2 -0
- package/packages/web/dist/assets/{AdminLayout-1hbRPV3d.css → AdminLayout-ggcdQGlQ.css} +1 -1
- package/packages/web/dist/assets/{AppPage-DSzDKCFz.js → AppPage-BvoVTk6h.js} +2 -2
- package/packages/web/dist/assets/{AutoPairPicker-nV38ALjl.js → AutoPairPicker-CLjD-muP.js} +2 -2
- package/packages/web/dist/assets/{BrowserFrame-Bic7U7jN.js → BrowserFrame-BcN-A76X.js} +2 -2
- package/packages/web/dist/assets/ChatPage-DhTpAyM2.js +4 -0
- package/packages/web/dist/assets/{ChatPage-CbsRmktV.css → ChatPage-DjPv238m.css} +1 -1
- package/packages/web/dist/assets/{CodeViewer-xHS3Xah9.js → CodeViewer-K9jrTmFO.js} +2 -2
- package/packages/web/dist/assets/ConfigWithCustom-BvrvSVIp.js +3 -0
- package/packages/web/dist/assets/{ConfirmDialog-DjQUzNqk.js → ConfirmDialog-BDvLleYf.js} +2 -2
- package/packages/web/dist/assets/{ConnectPage-CfRDrXvJ.js → ConnectPage-Dg6IPNNh.js} +2 -2
- package/packages/web/dist/assets/ContextItemPage-Cv4G0k_o.css +1 -0
- package/packages/web/dist/assets/ContextItemPage-qisBQetR.js +2 -0
- package/packages/web/dist/assets/ContextPage-C8u0UnYl.css +1 -0
- package/packages/web/dist/assets/ContextPage-DXa6Yqk-.js +3 -0
- package/packages/web/dist/assets/ContextRow-Chx99Xac.css +1 -0
- package/packages/web/dist/assets/ContextRow-DDYnYRaL.js +2 -0
- package/packages/web/dist/assets/{DataPage-wSIoGcb5.js → DataPage-DOE_pKAY.js} +2 -2
- package/packages/web/dist/assets/DataTypePage-BnP_JELT.js +2 -0
- package/packages/web/dist/assets/{DataTypePage-Cr238Hx_.css → DataTypePage-CWrWvUPs.css} +1 -1
- package/packages/web/dist/assets/{DesignPage-DidMUX8m.js → DesignPage-B9MJbF10.js} +3 -3
- package/packages/web/dist/assets/{ExplorePage-MUyVydVB.js → ExplorePage-cRDQZRea.js} +2 -2
- package/packages/web/dist/assets/{FnPill-BshAvm2I.js → FnPill-CbLZCXYM.js} +2 -2
- package/packages/web/dist/assets/{FnView-B8MGAOoB.js → FnView-CG_wBKTP.js} +2 -2
- package/packages/web/dist/assets/{FnsView-CeqIoaBT.js → FnsView-BybyK12w.js} +2 -2
- package/packages/web/dist/assets/{GinExprView-DYVUwZrd.js → GinExprView-BYCKSD_n.js} +2 -2
- package/packages/web/dist/assets/{GinForm-D3mwMRTQ.js → GinForm-CXjYVf2_.js} +2 -2
- package/packages/web/dist/assets/{GinTypeView-C0YifSmE.js → GinTypeView-Bmbmx9e_.js} +2 -2
- package/packages/web/dist/assets/{GinValueView-HfEPq9le.js → GinValueView-CWUzS7ti.js} +2 -2
- package/packages/web/dist/assets/{GraphPage-ySnuA4Hp.js → GraphPage-D6OhckfJ.js} +2 -2
- package/packages/web/dist/assets/GraphPanel-BTitgA-K.js +2 -0
- package/packages/web/dist/assets/{HubPicker-C_vA752L.js → HubPicker-DVly8dLD.js} +2 -2
- package/packages/web/dist/assets/{InboxApprovals-DcPCCmZ5.js → InboxApprovals-BF84edZU.js} +2 -2
- package/packages/web/dist/assets/{InboxPage-C2DT2nuF.js → InboxPage-DohZ9EDP.js} +2 -2
- package/packages/web/dist/assets/InjectedList-e6qr1kdU.js +2 -0
- package/packages/web/dist/assets/InstallDialog-JJCKYs2s.js +2 -0
- package/packages/web/dist/assets/{InstallDialog-yWLZK_zN.css → InstallDialog-K-j0sdHm.css} +1 -1
- package/packages/web/dist/assets/InstanceTypes-BqUzx87o.js +2 -0
- package/packages/web/dist/assets/InstanceTypes-CwVSAULg.css +1 -0
- package/packages/web/dist/assets/InstanceView-C73pev7A.js +2 -0
- package/packages/web/dist/assets/InstanceView-_9uE70tS.css +1 -0
- package/packages/web/dist/assets/{ItemHistory-CUGa8b6s.js → ItemHistory-dbGgOZsw.js} +2 -2
- package/packages/web/dist/assets/LimitsView-Ddp5WakY.js +2 -0
- package/packages/web/dist/assets/ListSearch-CYNNAuMB.js +2 -0
- package/packages/web/dist/assets/{LlmCallDetails-2yQftCqd.js → LlmCallDetails-C9H5Hc2J.js} +2 -2
- package/packages/web/dist/assets/{LlmCallsView-DOHX3r0K.js → LlmCallsView-CBqyZ8Cj.js} +2 -2
- package/packages/web/dist/assets/{LoadState-DeXfLvYv.js → LoadState-B2YhZlyC.js} +2 -2
- package/packages/web/dist/assets/McpDialog-DhlLklIq.js +2 -0
- package/packages/web/dist/assets/{McpView-CC2oNOMa.js → McpView-D_ZmNO56.js} +2 -2
- package/packages/web/dist/assets/{McpsView-CwJvyyxV.js → McpsView-9_gwBuzw.js} +2 -2
- package/packages/web/dist/assets/{MemoryDialog-Dbvh5uLq.js → MemoryDialog-pTHIxKEX.js} +2 -2
- package/packages/web/dist/assets/{ModelCallsView-RvnW3EBP.js → ModelCallsView-FHv2XWRX.js} +2 -2
- package/packages/web/dist/assets/{ModelPicker-DcjwQFHC.js → ModelPicker-EqOuvVnE.js} +2 -2
- package/packages/web/dist/assets/ModelsView-D9UaL4PX.js +2 -0
- package/packages/web/dist/assets/{NotFoundPage-CeSwzTV-.js → NotFoundPage-BsuJysan.js} +2 -2
- package/packages/web/dist/assets/PairPage-B_ZXsbL4.js +2 -0
- package/packages/web/dist/assets/PairPage-D_aPS1Ot.css +1 -0
- package/packages/web/dist/assets/{PanelHost-BkrFAnPa.js → PanelHost-Dx-vNNl5.js} +2 -2
- package/packages/web/dist/assets/PeopleView-D6dmEgMs.js +2 -0
- package/packages/web/dist/assets/{PeopleView-CJ8yArTh.css → PeopleView-DBxdbT1C.css} +1 -1
- package/packages/web/dist/assets/PoliciesView-Bn4rm-ao.js +2 -0
- package/packages/web/dist/assets/{RefusalList-DQoyUoPG.js → RefusalList-aosRD1ie.js} +2 -2
- package/packages/web/dist/assets/RendererHost-Ym_SMkhp.css +1 -0
- package/packages/web/dist/assets/RendererHost-rjnpSgyQ.js +2 -0
- package/packages/web/dist/assets/{ResourceViewer-Po24y4pj.js → ResourceViewer-C4tRColf.js} +2 -2
- package/packages/web/dist/assets/ResourcesPage-7mCLBORZ.js +2 -0
- package/packages/web/dist/assets/ResultGrid-CL2WSYQH.css +1 -0
- package/packages/web/dist/assets/ResultGrid-GIMoQUAr.js +2 -0
- package/packages/web/dist/assets/{ReviewSummaryStrip-k3HevESg.js → ReviewSummaryStrip-Bvjn3Iq8.js} +2 -2
- package/packages/web/dist/assets/ReviewView-DIqsUedT.js +3 -0
- package/packages/web/dist/assets/{RuleRow-CoXDA-SH.js → RuleRow-zRg-e8Vj.js} +2 -2
- package/packages/web/dist/assets/RunCard-C7wOGaw8.js +2 -0
- package/packages/web/dist/assets/RunCard-CSDiz-Nt.css +1 -0
- package/packages/web/dist/assets/{RunDetails-CGhQQ6OI.js → RunDetails-W4GbE6AE.js} +2 -2
- package/packages/web/dist/assets/{RunDot-Ch_45985.js → RunDot-C46uzzNM.js} +2 -2
- package/packages/web/dist/assets/{RunPage-C_t20pB7.js → RunPage-DPLtZpeB.js} +2 -2
- package/packages/web/dist/assets/{RunProgress-VrZUHUEC.js → RunProgress-Cr_6TBaF.js} +2 -2
- package/packages/web/dist/assets/RunsView-tU350TPK.js +2 -0
- package/packages/web/dist/assets/{SettingsPage-CykfuYj1.js → SettingsPage-B8QmmMN3.js} +2 -2
- package/packages/web/dist/assets/{SettingsPage-t03BqXw8.css → SettingsPage-BTl3Ie4F.css} +1 -1
- package/packages/web/dist/assets/SignInPage-CXxLf7Rp.css +1 -0
- package/packages/web/dist/assets/{SignInPage-DrXZ1sG2.js → SignInPage-DTwdqlnB.js} +2 -2
- package/packages/web/dist/assets/{StatusBadge-Dpb9uG5e.js → StatusBadge-D7wKMAcD.js} +2 -2
- package/packages/web/dist/assets/StorePlacementStep-C04nRU-u.js +2 -0
- package/packages/web/dist/assets/StorePlacementStep-D_G4e3ue.css +1 -0
- package/packages/web/dist/assets/{SystemConfig-72qKRkUk.js → SystemConfig-CE3keXWq.js} +2 -2
- package/packages/web/dist/assets/SystemPageHost-CEhz4li8.js +2 -0
- package/packages/web/dist/assets/SystemPageHost-DX7LrFoN.css +1 -0
- package/packages/web/dist/assets/SystemView-CBFzEGfm.js +2 -0
- package/packages/web/dist/assets/{SystemView-C8ScHUe2.css → SystemView-_9q6eDfV.css} +1 -1
- package/packages/web/dist/assets/SystemsView-0G8JntMV.js +2 -0
- package/packages/web/dist/assets/{SystemsView-B6HEL9VS.css → SystemsView-CWKnupLW.css} +1 -1
- package/packages/web/dist/assets/TableView-BK0uwLHl.js +3 -0
- package/packages/web/dist/assets/TableView-B_4MViVb.css +1 -0
- package/packages/web/dist/assets/{TableViewer-BQ7bYLOP.js → TableViewer-nbMInGJJ.js} +2 -2
- package/packages/web/dist/assets/{ThemePicker-C2nJ21Vd.js → ThemePicker-fZpVSYqG.js} +2 -2
- package/packages/web/dist/assets/{TurnTree-CORdfTHj.js → TurnTree-Co-iBqhT.js} +2 -2
- package/packages/web/dist/assets/{UserMessage-BtECa8ka.css → UserMessage-B63G9sxC.css} +1 -1
- package/packages/web/dist/assets/{UserMessage-qyc8dG5D.js → UserMessage-CDjUxKY0.js} +6 -6
- package/packages/web/dist/assets/{ValueVisual-aXEUaQ5Y.js → ValueVisual-EJnCKgSy.js} +2 -2
- package/packages/web/dist/assets/actor-names-OdvpVZeb.js +4 -0
- package/packages/web/dist/assets/{fn-modal-DqcxUhOQ.js → fn-modal-DtE65mFt.js} +2 -2
- package/packages/web/dist/assets/{fn-notices-BYaH6IoA.js → fn-notices-CCZ-DFbi.js} +2 -2
- package/packages/web/dist/assets/{formats-DI__ADVG.js → formats-CyHV2siv.js} +2 -2
- package/packages/web/dist/assets/index-BY7M8QUk.css +1 -0
- package/packages/web/dist/assets/index-OZS2EluT.js +4 -0
- package/packages/web/dist/assets/{labels-BhJpmLWA.js → labels-CT7_K0Pt.js} +2 -2
- package/packages/web/dist/assets/{layout-DQKldU13.js → layout-B6fBDg80.js} +2 -2
- package/packages/web/dist/assets/loaded-LaPjk6mK.js +2 -0
- package/packages/web/dist/assets/{metrics-Cio5ykX6.js → metrics-9n8bKI7u.js} +2 -2
- package/packages/web/dist/assets/problems--AW4igVY.js +2 -0
- package/packages/web/dist/assets/{push-payload-D5efGCzd.js → push-payload-B3EcrsVz.js} +64 -64
- package/packages/web/dist/assets/record-edits-B-FWAbxR.js +2 -0
- package/packages/web/dist/assets/{review-CGUGvRV9.js → review-uLESCEz1.js} +3 -3
- package/packages/web/dist/assets/routes-B7Zmt8wh.js +4 -0
- package/packages/web/dist/assets/runs-CUb2PTFg.js +2 -0
- package/packages/web/dist/assets/{shared-DTpYDMc_.js → shared-Bxhw_9et.js} +2 -2
- package/packages/web/dist/assets/{sources-Bm-TrxhL.js → sources-YgkjgFLe.js} +2 -2
- package/packages/web/dist/assets/src-DY1fSFJS.js +43 -0
- package/packages/web/dist/assets/state-ChQDWWj-.js +2 -0
- package/packages/web/dist/assets/{systems-DIp94AET.js → systems-CjwjRySu.js} +2 -2
- package/packages/web/dist/assets/table-host-B_D9dmCz.js +2 -0
- package/packages/web/dist/assets/tables-CaxIuHdw.js +2 -0
- package/packages/web/dist/assets/ui-DWjytmDS.js +17 -0
- package/packages/web/dist/assets/{ui-C7ZH_6oC.css → ui-DycHjPTZ.css} +1 -1
- package/packages/web/dist/assets/{url-BIg5IhGs.js → url-DbGOI14W.js} +2 -2
- package/packages/web/dist/index.html +52 -50
- package/packages/web/dist/sw.js +1 -1
- package/packages/web/package.json +2 -4
- package/premade/claude.zip +0 -0
- package/premade/database.zip +0 -0
- package/premade/web.zip +0 -0
- package/scripts/dev-env.ts +9 -9
- package/scripts/run-stack.ts +17 -16
- package/scripts/stack.ts +76 -19
- package/scripts/start.ts +27 -18
- package/systems/api/client/ApiServiceForm.vue +55 -0
- package/systems/api/client/ServiceList.vue +90 -0
- package/systems/api/client/ServicePage.vue +142 -0
- package/systems/api/client/ServicesPage.vue +32 -0
- package/systems/api/client/index.ts +15 -0
- package/systems/api/client/logic.ts +140 -0
- package/systems/api/client/state.ts +92 -0
- package/systems/api/package.json +9 -6
- package/systems/api/server/authoring.ts +2 -1
- package/systems/api/server/env.ts +1 -1
- package/systems/api/server/guard.ts +1 -1
- package/systems/api/server/http.ts +3 -2
- package/systems/api/server/impl.ts +3 -2
- package/systems/api/server/main.ts +11 -7
- package/systems/api/server/openapi.ts +1 -1
- package/systems/api/server/program.ts +2 -1
- package/systems/api/server/services.ts +2 -1
- package/systems/api/shared/http.ts +2 -1
- package/systems/api/shared/index.ts +15 -5
- package/{packages/core/src/programs.ts → systems/api/shared/services.ts} +7 -51
- package/systems/api/system.json +2 -1
- package/systems/api/tsconfig.json +2 -2
- package/systems/code/package.json +4 -3
- package/systems/code/server/authoring.ts +2 -1
- package/systems/code/server/impl.ts +2 -1
- package/systems/code/server/main.ts +5 -5
- package/systems/code/shared/index.ts +2 -3
- package/systems/code/shared/program.ts +23 -0
- package/systems/embedder/package.json +1 -1
- package/systems/embedder/server/env.ts +1 -1
- package/systems/embedder/server/main.ts +5 -5
- package/systems/embedder/shared/index.ts +1 -1
- package/systems/fs/client/fakes.ts +2 -0
- package/systems/fs/client/index.ts +4 -2
- package/systems/fs/client/machines/CoreHeatmap.vue +94 -0
- package/systems/fs/client/machines/MachineFiles.vue +121 -0
- package/systems/fs/client/machines/MachineMetrics.vue +330 -0
- package/systems/fs/client/machines/MachinesPage.vue +119 -0
- package/systems/fs/client/machines/TimeChart.vue +128 -0
- package/systems/fs/client/machines/fakes.ts +95 -0
- package/systems/fs/client/machines/files/ChangesPane.vue +90 -0
- package/systems/fs/client/machines/files/CodeView.vue +158 -0
- package/systems/fs/client/machines/files/CommentComposer.vue +86 -0
- package/systems/fs/client/machines/files/CommentThread.vue +115 -0
- package/systems/fs/client/machines/files/CommitPane.vue +80 -0
- package/systems/fs/client/machines/files/ComparePane.vue +81 -0
- package/systems/fs/client/machines/files/FileHistory.vue +89 -0
- package/systems/fs/client/machines/files/FilePane.vue +199 -0
- package/systems/fs/client/machines/files/FileTree.vue +26 -0
- package/systems/fs/client/machines/files/FolderPane.vue +154 -0
- package/systems/fs/client/machines/files/HistoryPane.vue +106 -0
- package/systems/fs/client/machines/files/ImageView.vue +160 -0
- package/systems/fs/client/machines/files/PatchView.vue +31 -0
- package/systems/fs/client/machines/files/QuickOpen.vue +67 -0
- package/systems/fs/client/machines/files/SearchPane.vue +87 -0
- package/systems/fs/client/machines/files/TreeNode.vue +72 -0
- package/systems/fs/client/machines/files/api.ts +127 -0
- package/systems/fs/client/machines/files/fake-kinds.ts +16 -0
- package/systems/fs/client/machines/files/fakes.ts +305 -0
- package/systems/fs/client/machines/files/ink.ts +117 -0
- package/systems/fs/client/machines/files/logic.ts +205 -0
- package/systems/fs/client/machines/files/state.ts +187 -0
- package/systems/fs/client/machines/files/viewers/CsvView.vue +29 -0
- package/systems/fs/client/machines/files/viewers/HexView.vue +27 -0
- package/systems/fs/client/machines/files/viewers/HtmlView.vue +17 -0
- package/systems/fs/client/machines/files/viewers/JsonNode.vue +45 -0
- package/systems/fs/client/machines/files/viewers/JsonView.vue +25 -0
- package/systems/fs/client/machines/metrics.ts +245 -0
- package/systems/fs/client/machines/palette.ts +98 -0
- package/systems/fs/client/preview/machines.ts +323 -0
- package/systems/fs/context/authoring/index.md +4 -0
- package/systems/fs/context/authoring/parts/actions.md +5 -1
- package/systems/fs/context/authoring/parts/actions.reference.md +6 -2
- package/systems/fs/context/authoring/parts/calling.md +5 -1
- package/systems/fs/context/authoring/parts/calling.reference.md +4 -0
- package/systems/fs/context/authoring/parts/client.md +31 -5
- package/systems/fs/context/authoring/parts/client.reference/client.md +8 -13
- package/systems/fs/context/authoring/parts/client.reference/pageinbox.md +524 -0
- package/systems/fs/context/authoring/parts/client.reference/{resultview.md → visuals.md} +135 -163
- package/systems/fs/context/authoring/parts/client.reference.md +11 -7
- package/systems/fs/context/authoring/parts/context/questions.md +49 -0
- package/systems/fs/context/authoring/parts/context.md +24 -2
- package/systems/fs/context/authoring/parts/context.reference.md +27 -3
- package/systems/fs/context/authoring/parts/contract.md +11 -1
- package/systems/fs/context/authoring/parts/contract.reference.md +26 -9
- package/systems/fs/context/authoring/parts/core-types/access-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/admin-ts.md +6 -2
- package/systems/fs/context/authoring/parts/core-types/api-index-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/approvals-ts.md +11 -7
- package/systems/fs/context/authoring/parts/core-types/auto-pair-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/checks-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/claims-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/config-secrets-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/connections-ts.md +15 -0
- package/systems/fs/context/authoring/parts/core-types/context-files-ts.md +9 -1
- package/systems/fs/context/authoring/parts/core-types/context-graph-ts.md +6 -2
- package/systems/fs/context/authoring/parts/core-types/context-questions-ts.md +26 -0
- package/systems/fs/context/authoring/parts/core-types/contextdecl.md +10 -2
- package/systems/fs/context/authoring/parts/core-types/data-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/decisions-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/fn-block-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/fn-facts-ts.md +11 -0
- package/systems/fs/context/authoring/parts/core-types/gin-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/grants-ts.md +5 -1
- package/systems/fs/context/authoring/parts/core-types/lifecycle-ts.md +44 -6
- package/systems/fs/context/authoring/parts/core-types/link-ts.md +7 -3
- package/systems/fs/context/authoring/parts/core-types/llm-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/manifest.md +41 -3
- package/systems/fs/context/authoring/parts/core-types/manifestpatch.md +34 -2
- package/systems/fs/context/authoring/parts/core-types/mention-search-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/model-calls-ts.md +5 -1
- package/systems/fs/context/authoring/parts/core-types/model-names-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/modes-ts.md +6 -2
- package/systems/fs/context/authoring/parts/core-types/owner-runs-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/package-ts.md +9 -0
- package/systems/fs/context/authoring/parts/core-types/primitives-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/query-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/records-actors-ts.md +7 -3
- package/systems/fs/context/authoring/parts/core-types/records-chat-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/records-content-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/records-runs-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/records-systems-ts.md +148 -0
- package/systems/fs/context/authoring/parts/core-types/registries-ts.md +101 -1
- package/systems/fs/context/authoring/parts/core-types/resources-ts.md +5 -1
- package/systems/fs/context/authoring/parts/core-types/run-ts.md +8 -1
- package/systems/fs/context/authoring/parts/core-types/sensitivity-ts.md +5 -1
- package/systems/fs/context/authoring/parts/core-types/stores-ts.md +199 -0
- package/systems/fs/context/authoring/parts/core-types/system-events-ts.md +8 -1
- package/systems/fs/context/authoring/parts/core-types/system-pages-ts.md +7 -1
- package/systems/fs/context/authoring/parts/core-types/system-providers-ts.md +5 -1
- package/systems/fs/context/authoring/parts/core-types/tables-ts.md +91 -0
- package/systems/fs/context/authoring/parts/core-types/validation-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/visuals-ts.md +4 -0
- package/systems/fs/context/authoring/parts/core-types/web-ts.md +4 -1
- package/systems/fs/context/authoring/parts/core-types.md +15 -8
- package/systems/fs/context/authoring/parts/ctx/update-result.md +33 -0
- package/systems/fs/context/authoring/parts/ctx.md +11 -1
- package/systems/fs/context/authoring/parts/ctx.reference/{hubai.md → adminnotices.md} +45 -4
- package/systems/fs/context/authoring/parts/ctx.reference/fnctx.md +21 -23
- package/systems/fs/context/authoring/parts/ctx.reference.md +8 -4
- package/systems/fs/context/authoring/parts/data.md +11 -6
- package/systems/fs/context/authoring/parts/data.reference.md +4 -0
- package/systems/fs/context/authoring/parts/examples/client-findview-vue.md +4 -0
- package/systems/fs/context/authoring/parts/examples/client-index-ts.md +4 -0
- package/systems/fs/context/authoring/parts/examples/client-notecard-vue.md +4 -0
- package/systems/fs/context/authoring/parts/examples/client-noteinput-vue.md +4 -0
- package/systems/fs/context/authoring/parts/examples/client-notespage-vue.md +4 -0
- package/systems/fs/context/authoring/parts/examples/client-reviewform-vue.md +4 -0
- package/systems/fs/context/authoring/parts/examples/client-wordcount-vue.md +4 -0
- package/systems/fs/context/authoring/parts/examples/package-json.md +4 -0
- package/systems/fs/context/authoring/parts/examples/server-env-ts.md +4 -0
- package/systems/fs/context/authoring/parts/examples/server-impl-ts.md +4 -0
- package/systems/fs/context/authoring/parts/examples/server-index-ts.md +4 -0
- package/systems/fs/context/authoring/parts/examples/server-main-ts.md +8 -4
- package/systems/fs/context/authoring/parts/examples/server-notes-test-ts.md +4 -0
- package/systems/fs/context/authoring/parts/examples/shared-index-ts.md +10 -0
- package/systems/fs/context/authoring/parts/examples/system-json.md +4 -0
- package/systems/fs/context/authoring/parts/examples/{systems-fs-shared-index-ts-lines-1-189.md → systems-fs-shared-index-ts-lines-1-178.md} +23 -30
- package/systems/fs/context/authoring/parts/examples/{systems-fs-shared-index-ts-lines-190-370.md → systems-fs-shared-index-ts-lines-179-382.md} +33 -6
- package/systems/fs/context/authoring/parts/examples/systems-fs-shared-index-ts-lines-383-567.md +210 -0
- package/systems/fs/context/authoring/parts/examples/systems-fs-shared-index-ts-lines-568-660.md +117 -0
- package/systems/fs/context/authoring/parts/examples/tsconfig-json.md +5 -1
- package/systems/fs/context/authoring/parts/examples.md +18 -11
- package/systems/fs/context/authoring/parts/fns.md +6 -2
- package/systems/fs/context/authoring/parts/fns.reference/fillclaims.md +5 -1
- package/systems/fs/context/authoring/parts/fns.reference/fn.md +6 -2
- package/systems/fs/context/authoring/parts/fns.reference.md +4 -0
- package/systems/fs/context/authoring/parts/folder.md +10 -6
- package/systems/fs/context/authoring/parts/gin.md +4 -0
- package/systems/fs/context/authoring/parts/gin.reference.md +4 -0
- package/systems/fs/context/authoring/parts/handlers-progress.md +5 -1
- package/systems/fs/context/authoring/parts/handlers-progress.reference.md +4 -0
- package/systems/fs/context/authoring/parts/hooks.md +5 -1
- package/systems/fs/context/authoring/parts/hooks.reference.md +5 -1
- package/systems/fs/context/authoring/parts/hub/context-questions.md +40 -0
- package/systems/fs/context/authoring/parts/hub/{hub-run-background.md → hub-ctx-from-resource.md} +52 -57
- package/systems/fs/context/authoring/parts/hub/hub-fns-load.md +35 -42
- package/systems/fs/context/authoring/parts/hub/hub-install-package.md +327 -0
- package/systems/fs/context/authoring/parts/hub/kinds-of-hub.md +8 -0
- package/systems/fs/context/authoring/parts/hub.md +14 -8
- package/systems/fs/context/authoring/parts/hub.reference.md +11 -2
- package/systems/fs/context/authoring/parts/internals/manifestof.md +6 -2
- package/systems/fs/context/authoring/parts/internals/permissionargs.md +8 -4
- package/systems/fs/context/authoring/parts/internals/usagefromwire.md +47 -2
- package/systems/fs/context/authoring/parts/internals.md +6 -2
- package/systems/fs/context/authoring/parts/kinds-agents.md +6 -2
- package/systems/fs/context/authoring/parts/kinds-agents.reference/authoringsession.md +10 -4
- package/systems/fs/context/authoring/parts/kinds-agents.reference/kind.md +11 -7
- package/systems/fs/context/authoring/parts/kinds-agents.reference.md +4 -0
- package/systems/fs/context/authoring/parts/lifecycle.md +8 -3
- package/systems/fs/context/authoring/parts/lifecycle.reference.md +6 -2
- package/systems/fs/context/authoring/parts/mentions.md +5 -1
- package/systems/fs/context/authoring/parts/mentions.reference.md +6 -2
- package/systems/fs/context/authoring/parts/mistakes.md +7 -2
- package/systems/fs/context/authoring/parts/named-types.md +4 -0
- package/systems/fs/context/authoring/parts/named-types.reference.md +6 -2
- package/systems/fs/context/authoring/parts/outcomes.md +7 -3
- package/systems/fs/context/authoring/parts/outcomes.reference.md +6 -2
- package/systems/fs/context/authoring/parts/owner-runs.md +5 -1
- package/systems/fs/context/authoring/parts/owner-runs.reference.md +36 -11
- package/systems/fs/context/authoring/parts/packaging.md +14 -7
- package/systems/fs/context/authoring/parts/packaging.reference.md +7 -2
- package/systems/fs/context/authoring/parts/providers.md +5 -1
- package/systems/fs/context/authoring/parts/providers.reference.md +5 -1
- package/systems/fs/context/authoring/parts/remote.md +9 -5
- package/systems/fs/context/authoring/parts/remote.reference.md +204 -16
- package/systems/fs/context/authoring/parts/resources.md +5 -1
- package/systems/fs/context/authoring/parts/resources.reference.md +4 -0
- package/systems/fs/context/authoring/parts/server.md +12 -8
- package/systems/fs/context/authoring/parts/server.reference.md +55 -34
- package/systems/fs/context/authoring/parts/settings-attachments.md +5 -1
- package/systems/fs/context/authoring/parts/settings-attachments.reference.md +4 -0
- package/systems/fs/context/authoring/parts/start.md +5 -1
- package/systems/fs/context/authoring/parts/state-forms.md +5 -1
- package/systems/fs/context/authoring/parts/state-forms.reference.md +4 -0
- package/systems/fs/context/authoring/parts/store/ctx-store.md +49 -0
- package/systems/fs/context/authoring/parts/store/declare.md +32 -0
- package/systems/fs/context/authoring/parts/store/engines.md +25 -0
- package/systems/fs/context/authoring/parts/store/migrations.md +53 -0
- package/systems/fs/context/authoring/parts/store/moves.md +38 -0
- package/systems/fs/context/authoring/parts/store/placement.md +25 -0
- package/systems/fs/context/authoring/parts/store/serve.md +30 -0
- package/systems/fs/context/authoring/parts/store/store-tables.md +24 -0
- package/systems/fs/context/authoring/parts/store/vectors.md +32 -0
- package/systems/fs/context/authoring/parts/store/when-to-use.md +27 -0
- package/systems/fs/context/authoring/parts/store/work.md +37 -0
- package/systems/fs/context/authoring/parts/store.md +65 -0
- package/systems/fs/context/authoring/parts/store.reference.md +459 -0
- package/systems/fs/context/authoring/parts/testing.md +14 -1
- package/systems/fs/context/authoring/parts/testing.reference/{memoryjournal.md → equal.md} +57 -50
- package/systems/fs/context/authoring/parts/testing.reference/fakehub.md +27 -46
- package/systems/fs/context/authoring/parts/testing.reference/{toolcall.md → kindprops.md} +128 -9
- package/systems/fs/context/authoring/parts/testing.reference/storeconnection.md +93 -0
- package/systems/fs/context/authoring/parts/testing.reference.md +16 -9
- package/systems/fs/context/authoring/parts/widgets.md +36 -22
- package/systems/fs/context/authoring/parts/widgets.reference.md +506 -8
- package/systems/fs/context/authoring/topics/begin.md +4 -0
- package/systems/fs/context/authoring/topics/client.md +4 -0
- package/systems/fs/context/authoring/topics/declare.md +4 -0
- package/systems/fs/context/authoring/topics/examples.md +4 -0
- package/systems/fs/context/authoring/topics/fns.md +4 -0
- package/systems/fs/context/authoring/topics/server.md +4 -0
- package/systems/fs/context/authoring/topics/types.md +8 -1
- package/systems/fs/context/comments/answer.md +21 -0
- package/systems/fs/context/comments/find.md +23 -0
- package/systems/fs/context/comments/read.md +26 -0
- package/systems/fs/context/comments.md +23 -0
- package/systems/fs/context/files-page.md +30 -0
- package/systems/fs/context/guide/attachments.md +16 -0
- package/systems/fs/context/guide/change.md +23 -0
- package/systems/fs/context/guide/commands.md +19 -0
- package/systems/fs/context/guide/documents.md +21 -0
- package/systems/fs/context/guide/find.md +25 -0
- package/systems/fs/context/guide/paths.md +24 -0
- package/systems/fs/context/guide/read.md +21 -0
- package/systems/fs/context/machine/history.md +25 -0
- package/systems/fs/context/machine/now.md +25 -0
- package/systems/fs/context/machine/processes.md +20 -0
- package/systems/fs/context/machine/recording.md +19 -0
- package/systems/fs/context/machine.md +24 -0
- package/systems/fs/package.json +5 -3
- package/systems/fs/server/files-page/browse.ts +391 -0
- package/systems/fs/server/files-page/comments.ts +439 -0
- package/systems/fs/server/files-page/fns.ts +158 -0
- package/systems/fs/server/files-page/git-view.ts +391 -0
- package/systems/fs/server/files-page/kinds.ts +56 -0
- package/systems/fs/server/hosting.ts +10 -10
- package/systems/fs/server/impl.ts +66 -7
- package/systems/fs/server/main.ts +28 -12
- package/systems/fs/server/metrics/collector.ts +424 -0
- package/systems/fs/server/metrics/index.ts +181 -0
- package/systems/fs/server/metrics/os.ts +144 -0
- package/systems/fs/server/metrics/parsers.ts +268 -0
- package/systems/fs/server/metrics/rrd.ts +363 -0
- package/systems/fs/server/metrics/testing.ts +80 -0
- package/systems/fs/server/shell.ts +1 -1
- package/systems/fs/server/snapshots.ts +216 -33
- package/systems/fs/server/testing.ts +15 -9
- package/systems/fs/shared/files-page.ts +506 -0
- package/systems/fs/shared/index.ts +138 -11
- package/systems/fs/shared/metrics.ts +179 -0
- package/systems/fs/system.json +10 -1
- package/systems/google-calendar/package.json +1 -1
- package/systems/google-calendar/server/main.ts +4 -4
- package/systems/input/package.json +3 -3
- package/systems/input/server/main.ts +6 -6
- package/systems/mcp/client/McpServerForm.vue +99 -0
- package/systems/mcp/client/ServerList.vue +78 -0
- package/systems/mcp/client/ServerPage.vue +194 -0
- package/systems/mcp/client/ServersPage.vue +32 -0
- package/systems/mcp/client/index.ts +15 -0
- package/systems/mcp/client/logic.ts +224 -0
- package/systems/mcp/client/state.ts +128 -0
- package/systems/mcp/package.json +9 -6
- package/systems/mcp/server/dial.ts +1 -1
- package/systems/mcp/server/impl.ts +2 -1
- package/systems/mcp/server/instance.ts +3 -5
- package/systems/mcp/server/main.ts +10 -6
- package/systems/mcp/server/mirror.ts +2 -3
- package/systems/mcp/server/oauth.ts +3 -2
- package/systems/mcp/server/server-link.ts +2 -1
- package/systems/mcp/shared/index.ts +15 -2
- package/{packages/core/src/mcp-servers.ts → systems/mcp/shared/servers.ts} +6 -5
- package/systems/mcp/system.json +2 -1
- package/systems/mcp/tsconfig.json +2 -2
- package/systems/ollama/package.json +3 -3
- package/systems/ollama/server/main.ts +5 -5
- package/systems/schedule/package.json +3 -4
- package/systems/schedule/server/env.ts +1 -1
- package/systems/schedule/server/fns.ts +5 -4
- package/systems/schedule/server/impl.ts +2 -2
- package/systems/schedule/server/import.ts +189 -0
- package/systems/schedule/server/index.ts +2 -0
- package/systems/schedule/server/main.ts +9 -7
- package/systems/schedule/server/placements.ts +41 -0
- package/systems/schedule/server/store.ts +159 -79
- package/systems/schedule/server/timer.ts +142 -107
- package/systems/schedule/shared/index.ts +2 -1
- package/systems/schedule/system.json +5 -1
- package/systems/schedule/tsconfig.json +1 -1
- package/systems/template/README.md +2 -2
- package/systems/template/package.json +1 -1
- package/systems/template/server/main.ts +4 -4
- package/systems/widgets/client/ChipRow.vue +22 -0
- package/systems/widgets/client/ProposalCard.vue +6 -5
- package/systems/widgets/client/SavedWidget.vue +11 -8
- package/systems/widgets/client/WidgetChips.vue +137 -0
- package/systems/widgets/client/WidgetView.vue +32 -0
- package/systems/widgets/client/charts/ChartVisual.vue +157 -0
- package/systems/widgets/client/charts/chart-data.ts +230 -0
- package/systems/widgets/client/charts/echarts-setup.ts +69 -0
- package/systems/widgets/client/charts/export.ts +36 -0
- package/systems/widgets/client/charts/families/calendar.ts +105 -0
- package/systems/widgets/client/charts/families/category.ts +186 -0
- package/systems/widgets/client/charts/families/crosstab.ts +113 -0
- package/systems/widgets/client/charts/families/distribution.ts +160 -0
- package/systems/widgets/client/charts/families/finance.ts +96 -0
- package/systems/widgets/client/charts/families/gauge.ts +75 -0
- package/systems/widgets/client/charts/families/hierarchy.ts +166 -0
- package/systems/widgets/client/charts/families/index.ts +21 -0
- package/systems/widgets/client/charts/families/network.ts +140 -0
- package/systems/widgets/client/charts/families/part.ts +61 -0
- package/systems/widgets/client/charts/families/profile.ts +30 -0
- package/systems/widgets/client/charts/families/progress.ts +76 -0
- package/systems/widgets/client/charts/families/range.ts +107 -0
- package/systems/widgets/client/charts/families/time.ts +177 -0
- package/systems/widgets/client/charts/families/timeline.ts +114 -0
- package/systems/widgets/client/charts/families/wide.ts +41 -0
- package/systems/widgets/client/charts/index.ts +37 -0
- package/systems/widgets/client/charts/maths.ts +139 -0
- package/systems/widgets/client/charts/size.ts +39 -0
- package/systems/widgets/client/chips.ts +150 -0
- package/systems/widgets/client/index.ts +18 -5
- package/systems/widgets/client/proposal.ts +2 -1
- package/systems/widgets/package.json +7 -4
- package/systems/widgets/server/authoring.ts +13 -7
- package/systems/widgets/server/env.ts +1 -1
- package/systems/widgets/server/impl.ts +10 -6
- package/systems/widgets/server/main.ts +6 -6
- package/systems/widgets/server/run.ts +16 -9
- package/systems/widgets/server/upgrade.ts +34 -0
- package/systems/widgets/shared/args.ts +137 -0
- package/systems/widgets/shared/charts.ts +243 -0
- package/systems/widgets/shared/index.ts +12 -3
- package/{packages/sdk/src → systems/widgets/shared}/relative-dates.ts +2 -1
- package/systems/widgets/shared/spec.ts +208 -0
- package/{packages/sdk/src → systems/widgets/shared}/widget-check.ts +7 -9
- package/{packages/sdk/src → systems/widgets/shared}/widget-schema.ts +4 -4
- package/packages/core/src/remote-auth.ts +0 -111
- package/packages/core/src/widgets.ts +0 -427
- package/packages/web/dist/assets/AdminLayout-sLjVTrmV.js +0 -2
- package/packages/web/dist/assets/ApiServiceForm-BrMTU-7u.js +0 -2
- package/packages/web/dist/assets/ApiServiceForm-BxprSaAq.css +0 -1
- package/packages/web/dist/assets/ApiServiceView-BMF2zD6Q.js +0 -2
- package/packages/web/dist/assets/ApiServiceView-BVmdRCjR.css +0 -1
- package/packages/web/dist/assets/ApiServicesView-BTLV6c8n.css +0 -1
- package/packages/web/dist/assets/ApiServicesView-bjLAWO_j.js +0 -2
- package/packages/web/dist/assets/ChartVisual-BnFG9aFi.css +0 -1
- package/packages/web/dist/assets/ChartVisual-DWw7WsfN.js +0 -11
- package/packages/web/dist/assets/ChatPage-7Yebk7rl.js +0 -4
- package/packages/web/dist/assets/ConfigWithCustom-DreTUdf0.js +0 -3
- package/packages/web/dist/assets/ContextItemPage-B6rJG3OT.js +0 -2
- package/packages/web/dist/assets/ContextItemPage-BRsWxOmu.css +0 -1
- package/packages/web/dist/assets/ContextPage-CloIZ_2y.js +0 -2
- package/packages/web/dist/assets/ContextPage-rYKxjiVI.css +0 -1
- package/packages/web/dist/assets/ContextRow-Byz_7HG-.css +0 -1
- package/packages/web/dist/assets/ContextRow-Dvv8CTFk.js +0 -2
- package/packages/web/dist/assets/DataTypePage-Ba_zBV4b.js +0 -4
- package/packages/web/dist/assets/FnList-BCnb4kOB.css +0 -1
- package/packages/web/dist/assets/FnList-CjQRwYaT.js +0 -2
- package/packages/web/dist/assets/GraphPanel-Cy5-KGo1.js +0 -2
- package/packages/web/dist/assets/InjectedList-CJsEFEbz.js +0 -2
- package/packages/web/dist/assets/InstallDialog-C9GDoUI2.js +0 -2
- package/packages/web/dist/assets/InstanceTypes-D8Jcxn70.js +0 -2
- package/packages/web/dist/assets/InstanceTypes-DAowwLB7.css +0 -1
- package/packages/web/dist/assets/InstanceView-CuBD3JPU.css +0 -1
- package/packages/web/dist/assets/InstanceView-p7tMaylE.js +0 -2
- package/packages/web/dist/assets/LimitsView-DsZG6u5P.js +0 -2
- package/packages/web/dist/assets/ListSearch-BK4p7Nxa.js +0 -2
- package/packages/web/dist/assets/McpDialog-CA_0WKWF.js +0 -2
- package/packages/web/dist/assets/McpServerForm-CAG8Wp2N.js +0 -2
- package/packages/web/dist/assets/McpServerForm-DsHaf5Um.css +0 -1
- package/packages/web/dist/assets/McpServerView-7I76EznB.css +0 -1
- package/packages/web/dist/assets/McpServerView-CD8qw6W_.js +0 -2
- package/packages/web/dist/assets/McpServersView-DNycG35u.js +0 -2
- package/packages/web/dist/assets/ModelsView-C_iN19xt.js +0 -2
- package/packages/web/dist/assets/PairPage-Bs2KuRjC.css +0 -1
- package/packages/web/dist/assets/PairPage-TEXPpsqi.js +0 -2
- package/packages/web/dist/assets/PeopleView-D1QGPYp7.js +0 -2
- package/packages/web/dist/assets/PoliciesView-BU1fudNF.js +0 -2
- package/packages/web/dist/assets/RemoteAuthFields-Dm44vz2t.css +0 -1
- package/packages/web/dist/assets/RemoteAuthFields-nxGWfmhf.js +0 -2
- package/packages/web/dist/assets/ResourcesPage-YluNBqIv.js +0 -2
- package/packages/web/dist/assets/ResultGrid-CuUQyTjW.css +0 -1
- package/packages/web/dist/assets/ResultGrid-uoq4yUYj.js +0 -2
- package/packages/web/dist/assets/ReviewView-79Z5rU1v.js +0 -3
- package/packages/web/dist/assets/RunCard-CBSGdwdQ.js +0 -2
- package/packages/web/dist/assets/RunCard-CfyRaDLS.css +0 -1
- package/packages/web/dist/assets/RunsView-Dz9Xsvu5.js +0 -2
- package/packages/web/dist/assets/ServiceRows-6BU4-MeL.css +0 -1
- package/packages/web/dist/assets/ServiceRows-DNzDiutg.js +0 -2
- package/packages/web/dist/assets/SignInPage-Djx-M-0U.css +0 -1
- package/packages/web/dist/assets/SystemPageHost-BeZ-6N0-.css +0 -1
- package/packages/web/dist/assets/SystemPageHost-DLNg2FYK.js +0 -2
- package/packages/web/dist/assets/SystemView-Es5wtkYU.js +0 -2
- package/packages/web/dist/assets/SystemsView-CeuSFhlF.js +0 -2
- package/packages/web/dist/assets/WidgetView-BZyDyYRI.js +0 -3
- package/packages/web/dist/assets/WidgetView-DQUDeFkB.css +0 -1
- package/packages/web/dist/assets/export-BwFkEtcm.js +0 -15
- package/packages/web/dist/assets/index-Bv42jNvr.js +0 -4
- package/packages/web/dist/assets/index-CSisx5mi.css +0 -1
- package/packages/web/dist/assets/problems-BZY0Dwif.js +0 -2
- package/packages/web/dist/assets/record-edits-CveFEsal.js +0 -2
- package/packages/web/dist/assets/remote-config-BkaarDf3.js +0 -2
- package/packages/web/dist/assets/routes-qP_j74V5.js +0 -4
- package/packages/web/dist/assets/runs-k76usGfd.js +0 -2
- package/packages/web/dist/assets/size-BwnshyOe.js +0 -2
- package/packages/web/dist/assets/src-DLK1P7oz.js +0 -43
- package/packages/web/dist/assets/state-CjE-qA2w.js +0 -2
- package/packages/web/dist/assets/ui-W12UYhVu.js +0 -17
- package/packages/web/dist/assets/widget-host-BCf6Tlt5.js +0 -2
- package/packages/web/dist/assets/widgets-CrbkovMT.js +0 -2
- package/systems/fs/context/authoring/parts/client.reference/fnpillprops.md +0 -141
- package/systems/fs/context/authoring/parts/core-types/remote-auth-ts.md +0 -60
- package/systems/fs/context/authoring/parts/core-types/widgets-ts.md +0 -299
- package/systems/fs/context/authoring/parts/examples/systems-fs-shared-index-ts-lines-371-533.md +0 -183
- package/systems/fs/context/authoring/parts/hub/hub-auto-pair-revoke.md +0 -189
- package/systems/fs/context/authoring/parts/widgets.reference/hub-visuals.md +0 -623
- package/systems/fs/context/authoring/parts/widgets.reference/sourcecompatible.md +0 -150
|
@@ -52,72 +52,72 @@ function e(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object
|
|
|
52
52
|
|
|
53
53
|
`)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},s,c=ae,l=!rt.jitless,u=l&&oe.value,d=t.catchall,f;e._zod.parse=(i,a)=>{f??=r.value;let p=i.value;return c(p)?l&&u&&a?.async===!1&&a.jitless!==!0?(s||=o(t.shape),i=s(i,a),d?zr([],p,i,a,f,e,a?.abortEarly===!0):i):n(i,a):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function Hr(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Ee(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Me(e,r,it())))}),t)}var Ur=_(`$ZodUnion`,(e,t)=>{Fn.init(e,t),qe(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),qe(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),qe(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),qe(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>o(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Hr(t,r,e,i)):Hr(o,r,e,i)}});function Wr(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}var Gr=_(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Ur.init(e,t);let n=e._zod.parse;qe(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||u(t,e,new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=d(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=i(()=>Wr(t));e._zod.parse=(i,a)=>{let o=i.value;if(!ae(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),Kr=_(`$ZodIntersection`,(e,t)=>{Fn.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Jr(e,t,n)):Jr(e,i,a)}});function qr(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(se(e)&&se(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=qr(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=qr(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Jr(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=qr(t.value,n.value);if(!c.valid){if(Ee(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Yr=_(`$ZodTuple`,(e,t)=>{Fn.init(e,t);let n=t.items,r=rt.memoizer;r?.attach(e),e._zod.parse=(i,a)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:`tuple`,code:`invalid_type`}),i;i.value=r?r.alloc(e,i,[],a):[];let s=[],c=Xr(n,`optin`),l=Xr(n,`optout`);if(!t.rest){if(o.length<c)return i.issues.push({code:`too_small`,minimum:c,inclusive:!0,input:o,inst:e,origin:`array`}),i;o.length>n.length&&i.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:o,inst:e,origin:`array`})}let u=Array(n.length),d=t.rest?a?.abortEarly:void 0,f=!1;for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:o[e],issues:[]},a);t instanceof Promise?s.push(t.then(t=>{u[e]=t})):(u[e]=t,d&&!f&&t.issues.length&&(f=Ee(t)))}if(t.rest&&!f){let e=n.length-1,r=o.slice(n.length),c=i.issues.length;for(let n of r){if(d&&i.issues.length!==c){if(Ee(i,c))break;c=i.issues.length}e++;let r=t.rest._zod.run({value:n,issues:[]},a);r instanceof Promise?s.push(r.then(t=>Zr(t,i,e))):Zr(r,i,e)}}return s.length?Promise.all(s).then(()=>Qr(u,i,n,o,l)):Qr(u,i,n,o,l)}});function Xr(e,t){for(let n=e.length-1;n>=0;n--)if(!(t===`optin`?e[n]._zod.optin!==void 0:e[n]._zod.optout===`optional`))return n+1;return 0}function Zr(e,t,n){e.issues.length&&t.issues.push(...Oe(n,e.issues)),t.value[n]=e.value}function Qr(e,t,n,r,i){for(let a=0;a<n.length;a++){let o=e[a],s=a<r.length;if(!s&&a>=i&&n[a]._zod.optin===`optional`){t.value.length=a;break}if(o.issues.length){if(!s&&a>=i){t.value.length=a;break}t.issues.push(...Oe(a,o.issues))}t.value[a]=o.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var $r=_(`$ZodRecord`,(e,t)=>{Fn.init(e,t);let n=rt.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!se(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Me(e,i,it())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...Oe(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...Oe(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&un.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>Me(e,i,it())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...Oe(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...Oe(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),ei=_(`$ZodEnum`,(t,n)=>{Fn.init(t,n);let r=e(n.entries),i=new Set(r);t._zod.values=i,qe(t,`pattern`,t=>{let n=e(t.def.entries).filter(e=>le.has(typeof e));return RegExp(n.length?`^(${n.map(e=>de(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),t._zod.parse=(e,n)=>{let a=e.value;return i.has(a)||e.issues.push({code:`invalid_value`,values:r,input:a,inst:t}),e}}),ti=_(`$ZodLiteral`,(e,t)=>{Fn.init(e,t);let n=new Set(t.values);e._zod.values=n,qe(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?de(e):e?de(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),ni=_(`$ZodTransform`,(e,t)=>{Fn.init(e,t),e._zod.optin=`optional`,rt.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nt(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new tt;return n.value=i,n}});function ri(e,t){return e.value=t.issues.length?void 0:t.value,e}var ii=_(`$ZodOptional`,(e,t)=>{Fn.init(e,t),qe(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,qe(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),qe(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${o(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>ri(e,t)):ri(e,r)}return t.innerType._zod.run(e,n)}}),ai=_(`$ZodExactOptional`,(e,t)=>{ii.init(e,t),qe(e,`values`,e=>e.def.innerType._zod.values),qe(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),oi=_(`$ZodNullable`,(e,t)=>{Fn.init(e,t),qe(e,`optin`,e=>e.def.innerType._zod.optin),qe(e,`optout`,e=>e.def.innerType._zod.optout),qe(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${o(t.source)}|null)$`):void 0}),qe(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),si=_(`$ZodDefault`,(e,t)=>{Fn.init(e,t),e._zod.optin=`defaulted`,qe(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>ci(e,t)):ci(r,t)}});function ci(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var li=_(`$ZodPrefault`,(e,t)=>{Fn.init(e,t),e._zod.optin=`defaulted`,qe(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),ui=_(`$ZodNonOptional`,(e,t)=>{Fn.init(e,t),qe(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>di(t,e)):di(i,e)}});function di(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function fi(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>Me(e,r,it()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var pi=_(`$ZodCatch`,(e,t)=>{Fn.init(e,t),qe(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),qe(e,`optout`,e=>e.def.innerType._zod.optout),qe(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>fi(e,r,t,n)):fi(e,r,t,n)}}),mi=_(`$ZodPipe`,(e,t)=>{Fn.init(e,t),qe(e,`values`,e=>e.def.in._zod.values),qe(e,`optin`,e=>e.def.in._zod.optin),qe(e,`optout`,e=>e.def.out._zod.optout),qe(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>hi(e,t.in,n)):hi(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>hi(e,t.out,n)):hi(r,t.out,n)}});function hi(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var gi=_(`$ZodReadonly`,(e,t)=>{Fn.init(e,t),qe(e,`propValues`,e=>e.def.innerType._zod.propValues),qe(e,`values`,e=>e.def.innerType._zod.values),qe(e,`optin`,e=>e.def.innerType?._zod?.optin),qe(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(_i):_i(r)}});function _i(e){return e.memo||(e.value=Object.freeze(e.value)),e}function vi(e){let t=e._zod.def,n=t.pattern,r=!!t.format?.includes(`int`),i,a;for(let e of t.checks??[]){let t=e._zod.def;t.pattern&&(n=t.pattern),r||=!!t.format?.includes(`int`);let o=t.minimum??t.length,s=t.maximum??t.length;o!==void 0&&(i===void 0||o>i)&&(i=o),s!==void 0&&(a===void 0||s<a)&&(a=s)}if(n)return n.source;if(i!==void 0&&a!==void 0&&i>a)return`(?!)`;if(i!==void 0||a!==void 0)return cn({minimum:i,maximum:a}).source;let o=e._zod.pattern;return(r&&o===un?ln:o)?.source}function yi(e){let t=e._zod.def,n=e._zod.pattern?.source,r=t.innerType??e._zod.innerType;if(r){let e=r._zod.pattern?.source,t=yi(r);return n&&e&&t&&t!==e?n.replace(o(e),()=>o(t)):n}if(t.options){let e=t.options.map(yi);if(e.every(Boolean))return`^(${e.map(e=>o(e)).join(`|`)})$`}return vi(e)}var bi=_(`$ZodTemplateLiteral`,(e,t)=>{Fn.init(e,t);let n=[];for(let e of t.parts)if(typeof e==`object`&&e){let t=yi(e);if(!t)throw Error(`Invalid template literal part, no pattern found: ${[...e._zod.traits].shift()}`);n.push(o(t))}else if(e===null||ue.has(typeof e))n.push(de(`${e}`));else throw Error(`Invalid template literal part: ${e}`);e._zod.pattern=RegExp(`^${n.join(``)}$`),e._zod.parse=(n,r)=>typeof n.value==`string`?(e._zod.pattern.lastIndex=0,e._zod.pattern.test(n.value)||n.issues.push({input:n.value,inst:e,code:`invalid_format`,format:t.format??`template_literal`,pattern:e._zod.pattern.source}),n):(n.issues.push({input:n.value,inst:e,expected:`string`,code:`invalid_type`}),n)}),xi=_(`$ZodLazy`,(e,t)=>{Fn.init(e,t),l(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),qe(e,`pattern`,e=>e.innerType?._zod?.pattern),qe(e,`propValues`,e=>e.innerType?._zod?.propValues),qe(e,`optin`,e=>e.innerType?._zod?.optin??void 0),qe(e,`optout`,e=>e.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Si=_(`$ZodCustom`,(e,t)=>{hn.init(e,t),Fn.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Ci(t,n,r,e));Ci(i,n,r,e)}});function Ci(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Le(e))}}var wi=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},Ti=`~memo`,Ei=[];function Di(e){return typeof e==`object`&&!!e}function Oi(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var ki=new WeakMap,Ai=0,ji=1,Mi=2;function Ni(e,t,n){let r=ki.get(e);if(r!==void 0)return r?Mi:Ai;if(t.has(e))return Mi;t.add(e);let i=Ai,a=e=>{if(i!==Mi&&e?._zod){let r=Ni(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=Ai;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?ji:o.value?._zod?Ni(o.value,t,n):Ai;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=d(c);s(e?o(e,!0):ji),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?Ni(r,t,!1):ji);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),Pi(e,i)}function Pi(e,t){return t!==ji&&ki.set(e,t===Mi),t}function Fi(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var Ii,Li=[],Ri={alloc(e,t,n){let r=Ii;if(!r)return n;Ii=void 0;let i={value:n,issues:null};return r.set(t.value,i),Li.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&Bi(n,e.value))throw new wi;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=Ni(e,new Set,!1);if(i===Ai)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===Mi||r?n=!0:r=!0}let l=s.value;if(!Di(l))return t(s,c);let u=c[Ti];u||(u={buckets:new WeakMap,backEdges:void 0},c[Ti]=u);let d;i===c?d=a:(d=Fi(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...Oi(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;Ii=d;let p=Li.length,m=t(s,c);Ii=void 0;let h=Li.length>p?Li.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?Oi(e.issues):Ei),e)):(h&&(h.issues=m.issues.length?Oi(m.issues):Ei),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function zi(){return Ri}function Bi(e,t){let n=e[Ti]?.backEdges;return n!==void 0&&Di(t)&&n.has(t)}var Vi=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function n(t){return e[t]??null}let r={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},i={nan:`NaN`};function a(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):i[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${a(e.expected)}, received ${a(Ie(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${pe(e.values[0])}`:`Invalid option: expected one of ${t(e.values,`|`)}`;case`too_big`:{let t=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=n(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${t}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${t}${e.maximum.toString()}`}case`too_small`:{let t=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=n(e.origin);return r?`Too small: expected ${e.origin} to have ${t}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${t}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${r[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${t(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Hi(){return{localeError:Vi()}}var Ui,Wi=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Gi(){return new Wi}(Ui=globalThis).__zod_globalRegistry??(Ui.__zod_globalRegistry=Gi());var Ki=globalThis.__zod_globalRegistry;function qi(e){return e.checks&&=[...e.checks],e}function Ji(e,t){return new e(qi({type:`string`,...g(t)}))}function Yi(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...g(t)})}function Xi(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...g(t)})}function Zi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...g(t)})}function Qi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...g(t)})}function $i(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...g(t)})}function ea(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...g(t)})}function ta(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...g(t)})}function na(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...g(t)})}function ra(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...g(t)})}function ia(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...g(t)})}function aa(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...g(t)})}function oa(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...g(t)})}function sa(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...g(t)})}function ca(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...g(t)})}function la(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...g(t)})}function ua(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...g(t)})}function da(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...g(t)})}function fa(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...g(t)})}function pa(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...g(t)})}function ma(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...g(t)})}function ha(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...g(t)})}function ga(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...g(t)})}function _a(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...g(t)})}function va(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...g(t)})}function ya(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...g(t)})}function ba(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...g(t)})}function xa(e,t){return new e(qi({type:`number`,checks:[],...g(t)}))}function Sa(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...g(t)})}function Ca(e,t){return new e({type:`boolean`,...g(t)})}function wa(e,t){return new e({type:`null`,...g(t)})}function Ta(e){return new e({type:`unknown`})}function Ea(e,t){return new e({type:`never`,...g(t)})}function Da(e,t){return new vn({check:`less_than`,...g(t),value:e,inclusive:!1})}function Oa(e,t){return new vn({check:`less_than`,...g(t),value:e,inclusive:!0})}function ka(e,t){return new yn({check:`greater_than`,...g(t),value:e,inclusive:!1})}function Aa(e,t){return new yn({check:`greater_than`,...g(t),value:e,inclusive:!0})}function ja(e,t){return new bn({check:`multiple_of`,...g(t),value:e})}function Ma(e,t){return new Sn({check:`max_length`,...g(t),maximum:e})}function Na(e,t){return new Cn({check:`min_length`,...g(t),minimum:e})}function Pa(e,t){return new wn({check:`length_equals`,...g(t),length:e})}function Fa(e,t){return new En({check:`string_format`,format:`regex`,...g(t),pattern:e})}function Ia(e){return new Dn({check:`string_format`,format:`lowercase`,...g(e)})}function La(e){return new On({check:`string_format`,format:`uppercase`,...g(e)})}function Ra(e,t){return new kn({check:`string_format`,format:`includes`,...g(t),includes:e})}function za(e,t){return new An({check:`string_format`,format:`starts_with`,...g(t),prefix:e})}function Ba(e,t){return new jn({check:`string_format`,format:`ends_with`,...g(t),suffix:e})}function Va(e){return new Mn({check:`overwrite`,tx:e})}function Ha(e){return Va(t=>t.normalize(e))}function Ua(){return Va(e=>e.trim())}function Wa(){return Va(e=>e.toLowerCase())}function Ga(){return Va(e=>e.toUpperCase())}function Ka(){return Va(e=>re(e))}function qa(e,t,n){return new e({type:`array`,element:t,...g(n)})}function Ja(e,t,n){let r=g(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function Ya(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...g(n)})}function Xa(e,t){let n=Za(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Le(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Le(r))}},e(t.value,t)),t);return n}function Za(e,t){let n=new hn({check:`custom`,...g(t)});return n._zod.check=e,n}function Qa(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&u(e,t,n[t]);return e}function $a(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Ki,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function eo(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function to(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,to(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Qa(o.schema,c),t.io===`input`&&fo(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function no(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ro(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${no(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+no(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
54
54
|
|
|
55
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function io(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;io(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ao=new Set([`type`,`properties`,`required`,`additionalProperties`]),oo=[`oneOf`,`anyOf`];function so(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function co(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ao.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??so(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}u(n,r,e.length===1?e[0]:co(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=so(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function lo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ao)if(t in e)return;let n=t.filter(e=>oo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=co(t);else{let e=n[0],i=oo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>co([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Qa(e,r))}function uo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Qa(i,s),Qa(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())io(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])lo(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Qa(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,u(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:mo(t,`input`,e.processors),output:mo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function fo(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return fo(r.element,n);if(r.type===`set`)return fo(r.valueType,n);if(r.type===`lazy`)return fo(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return fo(r.innerType,n);if(r.type===`intersection`)return fo(r.left,n)||fo(r.right,n);if(r.type===`record`||r.type===`map`)return fo(r.keyType,n)||fo(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:fo(r.in,n)||fo(r.out,n);if(r.type===`object`){for(let e in r.shape)if(fo(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(fo(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(fo(e,n))return!0;return!!(r.rest&&fo(r.rest,n))}return!1}var po=(e,t={})=>n=>{let r=$a({...n,processors:t});return to(e,r),ro(r,e),uo(r,e)},mo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=$a({...i??{},target:a,io:t,processors:n});return to(e,o),ro(o,e),uo(o,e)},ho=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},go=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},_o=(e,t)=>{ho(e,`minimum`,t),go(e,`maximum`,t)},vo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},yo=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},bo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},xo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},So=(e,t)=>ho(e,`minimum`,t.minimum),Co=(e,t)=>go(e,`maximum`,t.maximum),wo=e=>(t,n)=>{xo(t,n.format);let[r,i]=e[n.format];ho(t,`minimum`,r),go(t,`maximum`,i)},To={greater_than:(e,t)=>ho(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>go(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>vo(e,t.value),number_format:wo(he),bigint_format:wo(ge),min_length:So,max_length:Co,length_equals:(e,t)=>_o(e,t.length),min_size:So,max_size:Co,size_equals:(e,t)=>_o(e,t.size),string_format:(e,t)=>{xo(e,t.format),t.pattern&&yo(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>bo(e,t.mime)};function Eo(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)To[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&ho(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&ho(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&go(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&go(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&vo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&bo(t,i.mime);for(let e of i.patterns??[])yo(t,e);return t}var Do={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Oo=new Map([[_r,Xt],[yr,Zt]]),ko=e=>Oo.get(e)??e,Ao=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=Eo(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Do[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(ko);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},jo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Eo(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):eo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Mo=(e,t,n,r)=>{n.type=`boolean`},No=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Po=(e,t,n,r)=>{n.not={}},Fo=(t,n,r,i)=>{let a=t._zod.def,o=e(a.entries);o.length===0?r.not={}:(o.every(e=>typeof e==`number`)&&(r.type=`number`),o.every(e=>typeof e==`string`)&&(r.type=`string`),r.enum=o)},Io=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(eo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(eo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Lo=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Ro=(e,t,n,r)=>{eo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},zo=(e,t,n,r)=>{eo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Bo=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=Eo(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=to(a.element,t,{...r,path:[...r.path,`items`]})};function Vo(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Vo(t.out):t.type===`catch`?Vo(t.innerType):e._zod.optin}var Ho=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&eo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)u(i.properties,e,to(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Vo(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=to(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Uo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>to(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Wo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=to(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},Go=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>to(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?to(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?Vo(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=Eo(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function Ko(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Ko(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Ko(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?un:ln).source)),p}var qo=new WeakMap;function Jo(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of qo.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Ko(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var Yo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=Eo(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=to(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)u(i.patternProperties,ko(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=to(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=qo.get(t);n||(n=[],qo.set(t,n),t.deferred.push(()=>Jo(t))),n.push(e)}i.additionalProperties=to(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Vo(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Xo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Zo=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Qo=Symbol();function $o(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(eo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Qo):JSON.parse(o)}var es=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n.default=o)},ts=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n._prefault=o)},ns=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{eo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},rs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;to(o,t,r);let s=t.seen.get(e);s.ref=o},is=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},as=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},os=(e,t,n,r)=>{let i=e._zod.innerType;to(i,t,r);let a=t.seen.get(e);a.ref=i},ss=new WeakSet([Object.prototype,Error.prototype]);function cs(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var ls=_(`ZodError`,(e,t)=>{ut.init(e,t),e.name=`ZodError`;let r=Object.getPrototypeOf(e);ss.has(r)||(ss.add(r),cs(r,`format`,e=>t=>pt(e,t)),cs(r,`flatten`,e=>t=>ft(e,t)),cs(r,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,n,2)}),cs(r,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,n,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),us=ht(ls),ds=gt(ls),fs=_t(ls),ps=yt(ls),ms=Tt(ls),hs=Et(ls),gs=Dt(ls),_s=Ot(ls),vs=kt(ls),ys=At(ls),bs=jt(ls),xs=Mt(ls);function Ss(){rt.localeError||it(Hi())}function Cs(){rt.memoizer||it({memoizer:zi()})}var ws=_(`ZodType`,(e,t)=>(Ss(),Fn.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(te(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return fe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Yc(e,t))},superRefine(e,t){return this.check(Xc(e,t))},overwrite(e){return this.check(Va(e))},optional(){return Ec(this)},exactOptional(){return Oc(this)},nullable(){return Ac(this)},nullish(){return Ec(Ac(this))},nonoptional(e){return Ic(this,e)},array(){return x(this)},or(e){return C([this,e])},and(e){return gc(this,e)},transform(e){return Bc(this,wc(e))},default(e){return Mc(this,e)},prefault(e){return Pc(this,e)},catch(e){return Rc(this,e)},pipe(e){return Bc(this,e)},readonly(){return Hc(this)},describe(e){let t=this.clone();return Ki.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ki.get(this);let t=this.clone();return Ki.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Be(this,`~standard`,{...Rn(this),jsonSchema:{input:mo(this,`input`),output:mo(this,`output`)}})},set"~standard"(e){ze(this,`~standard`,e)},parse:function e(t,n){return us(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await ds(this,t,n,{callee:e})},safeParse(e,t){return fs(this,e,t)},async safeParseAsync(e,t){return ps(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){ze(this,`spa`,e)},validate(e,t){return St(this,e,t)},validateAsync(e,t){return wt(this,e,t)},encode:function e(t,n){return ms(this,t,n,{callee:e})},decode:function e(t,n){return hs(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await gs(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await _s(this,t,n,{callee:e})},safeEncode(e,t){return vs(this,e,t)},safeDecode(e,t){return ys(this,e,t)},async safeEncodeAsync(e,t){return bs(this,e,t)},async safeDecodeAsync(e,t){return xs(this,e,t)},toJSONSchema(e){return po(this,{})(e)},get description(){return Ki.get(this)?.description},get _def(){return this._zod.def}}),Ts=_(`_ZodString`,(e,t)=>{zn.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r)},Ve({format:e=>Eo(e).format??null,minLength:e=>Eo(e).minimum??null,maxLength:e=>Eo(e).maximum??null},{regex(...e){return this.check(Fa(...e))},includes(...e){return this.check(Ra(...e))},startsWith(...e){return this.check(za(...e))},endsWith(...e){return this.check(Ba(...e))},min(...e){return this.check(Na(...e))},max(...e){return this.check(Ma(...e))},length(...e){return this.check(Pa(...e))},nonempty(...e){return this.check(Na(1,...e))},lowercase(e){return this.check(Ia(e))},uppercase(e){return this.check(La(e))},trim(){return this.check(Ua())},normalize(...e){return this.check(Ha(...e))},toLowerCase(){return this.check(Wa())},toUpperCase(){return this.check(Ga())},slugify(){return this.check(Ka())}})),Es=_(`ZodString`,(e,t)=>{zn.init(e,t),Ts.init(e,t)},{email(e){return this.check(Yi(Ms,e))},url(e){return this.check(ta(Is,e))},jwt(e){return this.check(ga(Qs,e))},emoji(e){return this.check(na(Rs,e))},guid(e){return this.check(Xi(Ps,e))},uuid(e){return this.check(Zi(Fs,e))},uuidv4(e){return this.check(Qi(Fs,e))},uuidv6(e){return this.check($i(Fs,e))},uuidv7(e){return this.check(ea(Fs,e))},nanoid(e){return this.check(ra(zs,e))},cuid(e){return this.check(ia(Bs,e))},cuid2(e){return this.check(aa(Vs,e))},ulid(e){return this.check(oa(Hs,e))},base64(e){return this.check(pa(Ys,e))},base64url(e){return this.check(ma(Xs,e))},xid(e){return this.check(sa(Us,e))},ksuid(e){return this.check(ca(Ws,e))},ipv4(e){return this.check(la(Gs,e))},ipv6(e){return this.check(ua(Ks,e))},cidrv4(e){return this.check(da(qs,e))},cidrv6(e){return this.check(fa(Js,e))},e164(e){return this.check(ha(Zs,e))},datetime(e){return this.check(_a(Os,e))},date(e){return this.check(va(ks,e))},time(e){return this.check(ya(As,e))},duration(e){return this.check(ba(js,e))}});function v(e){return Ji(Es,e)}var Ds=_(`ZodStringFormat`,(e,t)=>{Bn.init(e,t),Ts.init(e,t)}),Os=_(`ZodISODateTime`,(e,t)=>{ar.init(e,t),Ds.init(e,t)}),ks=_(`ZodISODate`,(e,t)=>{or.init(e,t),Ds.init(e,t)}),As=_(`ZodISOTime`,(e,t)=>{sr.init(e,t),Ds.init(e,t)}),js=_(`ZodISODuration`,(e,t)=>{cr.init(e,t),Ds.init(e,t)}),Ms=_(`ZodEmail`,(e,t)=>{Un.init(e,t),Ds.init(e,t)});function Ns(e){return Yi(Ms,e)}var Ps=_(`ZodGUID`,(e,t)=>{Vn.init(e,t),Ds.init(e,t)}),Fs=_(`ZodUUID`,(e,t)=>{Hn.init(e,t),Ds.init(e,t)}),Is=_(`ZodURL`,(e,t)=>{Zn.init(e,t),Ds.init(e,t)});function Ls(e){return ta(Is,e)}var Rs=_(`ZodEmoji`,(e,t)=>{Qn.init(e,t),Ds.init(e,t)}),zs=_(`ZodNanoID`,(e,t)=>{$n.init(e,t),Ds.init(e,t)}),Bs=_(`ZodCUID`,(e,t)=>{er.init(e,t),Ds.init(e,t)}),Vs=_(`ZodCUID2`,(e,t)=>{tr.init(e,t),Ds.init(e,t)}),Hs=_(`ZodULID`,(e,t)=>{nr.init(e,t),Ds.init(e,t)}),Us=_(`ZodXID`,(e,t)=>{rr.init(e,t),Ds.init(e,t)}),Ws=_(`ZodKSUID`,(e,t)=>{ir.init(e,t),Ds.init(e,t)}),Gs=_(`ZodIPv4`,(e,t)=>{lr.init(e,t),Ds.init(e,t)}),Ks=_(`ZodIPv6`,(e,t)=>{fr.init(e,t),Ds.init(e,t)}),qs=_(`ZodCIDRv4`,(e,t)=>{pr.init(e,t),Ds.init(e,t)}),Js=_(`ZodCIDRv6`,(e,t)=>{hr.init(e,t),Ds.init(e,t)}),Ys=_(`ZodBase64`,(e,t)=>{vr.init(e,t),Ds.init(e,t)}),Xs=_(`ZodBase64URL`,(e,t)=>{xr.init(e,t),Ds.init(e,t)}),Zs=_(`ZodE164`,(e,t)=>{Sr.init(e,t),Ds.init(e,t)}),Qs=_(`ZodJWT`,(e,t)=>{wr.init(e,t),Ds.init(e,t)}),$s=_(`ZodNumber`,(e,t)=>{Tr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jo(e,t,n,r),e.isFinite=!0},Ve({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Eo(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Eo(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=Eo(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Eo(e).format??null},{gt(e,t){return this.check(ka(e,t))},gte(e,t){return this.check(Aa(e,t))},min(e,t){return this.check(Aa(e,t))},lt(e,t){return this.check(Da(e,t))},lte(e,t){return this.check(Oa(e,t))},max(e,t){return this.check(Oa(e,t))},int(e){return this.check(tc(e))},safe(e){return this.check(tc(e))},positive(e){return this.check(ka(0,e))},nonnegative(e){return this.check(Aa(0,e))},negative(e){return this.check(Da(0,e))},nonpositive(e){return this.check(Oa(0,e))},multipleOf(e,t){return this.check(ja(e,t))},step(e,t){return this.check(ja(e,t))},finite(){return this}}));function y(e){return xa($s,e)}var ec=_(`ZodNumberFormat`,(e,t)=>{Er.init(e,t),$s.init(e,t)});function tc(e){return Sa(ec,e)}var nc=_(`ZodBoolean`,(e,t)=>{Dr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mo(e,t,n,r)});function b(e){return Ca(nc,e)}var rc=_(`ZodNull`,(e,t)=>{Or.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>No(e,t,n,r)});function ic(e){return wa(rc,e)}var ac=_(`ZodAny`,(e,t)=>{kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0}),oc=_(`ZodUnknown`,(e,t)=>{Ar.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function sc(){return Ta(oc)}var cc=_(`ZodNever`,(e,t)=>{jr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Po(e,t,n,r)});function lc(e){return Ea(cc,e)}var uc=_(`ZodArray`,(e,t)=>{Cs(),Fr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Na(e,t))},nonempty(e){return this.check(Na(1,e))},max(e,t){return this.check(Ma(e,t))},length(e,t){return this.check(Pa(e,t))},unwrap(){return this.element}});function x(e,t){return qa(uc,e,t)}var dc=_(`ZodObject`,(e,t)=>{Cs(),Vr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ho(e,t,n,r),Je(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return E(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(te(this._zod.def,{catchall:e}))},passthrough(){return this.clone(te(this._zod.def,{catchall:sc()}))},loose(){return this.clone(te(this._zod.def,{catchall:sc()}))},strict(){return this.clone(te(this._zod.def,{catchall:lc()}))},strip(){return this.clone(te(this._zod.def,{catchall:void 0}))},extend(e){return be(this,e)},safeExtend(e){return Se(this,e)},merge(e){return Ce(this,e)},pick(e){return _e(this,e)},omit(e){return ye(this,e)},partial(...e){return we(Tc,this,e[0])},exactPartial(...e){return we(Dc,this,e[0],`exactPartial`)},required(...e){return Te(Fc,this,e[0])}});function S(e,t){return new dc({type:`object`,shape:e??{},...g(t)})}function fc(e,t){return new dc({type:`object`,shape:e,catchall:sc(),...g(t)})}var pc=_(`ZodUnion`,(e,t)=>{Ur.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uo(e,t,n,r),e.options=t.options});function C(e,t){return new pc({type:`union`,options:e,...g(t)})}var mc=_(`ZodDiscriminatedUnion`,(e,t)=>{pc.init(e,t),Gr.init(e,t)});function w(e,t,n){return new mc({type:`union`,options:t,discriminator:e,...g(n)})}var hc=_(`ZodIntersection`,(e,t)=>{Kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wo(e,t,n,r)});function gc(e,t){return new hc({type:`intersection`,left:e,right:t})}var _c=_(`ZodTuple`,(e,t)=>{Cs(),Yr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Go(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Tc({type:`optional`,innerType:e}))})}});function vc(e,t,n){let r=t instanceof Fn;return new _c({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}var yc=_(`ZodRecord`,(e,t)=>{Cs(),$r.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function T(e,t,n){return!t||!t._zod?new yc({type:`record`,keyType:v(),valueType:e,...g(t)}):new yc({type:`record`,keyType:e,valueType:t,...g(n)})}function bc(e,t,n){return new yc({type:`record`,keyType:e,valueType:t,...g(n),partial:!0})}var xc=_(`ZodEnum`,(e,t)=>{ei.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})}});function E(e,t){return new xc({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...g(t)})}var Sc=_(`ZodLiteral`,(e,t)=>{ti.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Io(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function D(e,t){return new Sc({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}var Cc=_(`ZodTransform`,(e,t)=>{Cs(),ni.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zo(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Le(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Le(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function wc(e){return new Cc({type:`transform`,transform:e})}var Tc=_(`ZodOptional`,(e,t)=>{ii.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ec(e){return new Tc({type:`optional`,innerType:e})}var Dc=_(`ZodExactOptional`,(e,t)=>{ai.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Oc(e){return new Dc({type:`optional`,innerType:e})}var kc=_(`ZodNullable`,(e,t)=>{oi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ac(e){return new kc({type:`nullable`,innerType:e})}var jc=_(`ZodDefault`,(e,t)=>{si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mc(e,t){return new jc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Nc=_(`ZodPrefault`,(e,t)=>{li.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pc(e,t){return new Nc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Fc=_(`ZodNonOptional`,(e,t)=>{ui.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e,t){return new Fc({type:`nonoptional`,innerType:e,...g(t)})}var Lc=_(`ZodCatch`,(e,t)=>{pi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Rc(e,t){return new Lc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Xe(t)})}var zc=_(`ZodPipe`,(e,t)=>{mi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),e.in=t.in,e.out=t.out});function Bc(e,t){return new zc({type:`pipe`,in:e,out:t})}var Vc=_(`ZodReadonly`,(e,t)=>{gi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e){return new Vc({type:`readonly`,innerType:e})}var Uc=_(`ZodTemplateLiteral`,(e,t)=>{bi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lo(e,t,n,r)});function Wc(e,t){return new Uc({type:`template_literal`,parts:e,...g(t)})}var Gc=_(`ZodLazy`,(e,t)=>{xi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Kc(e){return new Gc({type:`lazy`,getter:e})}var qc=_(`ZodCustom`,(e,t)=>{Si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ro(e,t,n,r)});function Jc(e,t){return Ja(qc,e??(()=>!0),t)}function Yc(e,t={}){return Ya(qc,e,t)}function Xc(e,t){return Xa(e,t)}function Zc(e){let t=Kc(()=>C([v(e),y(),b(),ic(),x(t),T(v(),t)]));return t}var O=Zc(),Qc=T(v(),O);function $c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var el={run:`run`,turn:`trn`,session:`ses`,actor:`act`,message:`msg`,delivery:`dlv`,handlerCall:`hcl`,llmInteraction:`llm`,pairing:`par`,pairingToken:`ptk`,policy:`pol`,approval:`apr`,budget:`bgt`,priorityRule:`pri`,reservation:`rsv`,ledger:`led`,notification:`ntf`,push:`psh`,secret:`sec`,modelCategory:`mct`,provider:`prv`,sectionRule:`srl`,authSession:`aus`,modelCall:`mdl`,mcp:`mcp`,autoPair:`apk`,connection:`cnx`,fnExample:`fex`,refusal:`rfs`,record:`rec`,mentionRequest:`mrq`},tl=e=>v().regex(RegExp(`^${el[e]}_.+$`),`expected a ${e} id starting with "${el[e]}_"`).brand().describe(`${e} id`),nl=e=>Object.hasOwn(el,e);function rl(){return Object.fromEntries(Object.keys(el).filter(nl).map(e=>[e,tl(e)]))}var k=v().regex(/^[A-Za-z_][A-Za-z0-9_.-]*$/),il=rl(),A=il.run,al=il.turn,j=il.session,M=il.actor,ol=il.message,sl=il.delivery,cl=il.handlerCall,ll=il.llmInteraction,ul=il.pairing,dl=il.pairingToken,fl=il.policy,pl=il.approval,ml=il.budget,hl=il.priorityRule,gl=il.reservation,_l=il.ledger,vl=il.notification,yl=il.push,bl=il.secret,xl=il.modelCategory,Sl=il.provider,Cl=il.sectionRule,wl=il.authSession,Tl=il.modelCall,El=il.mcp,Dl=il.autoPair,Ol=il.connection,kl=y().int().min(0),N=y().int(),P=y(),Al=/^[a-z][a-z0-9-]*$/,F=v().regex(Al).brand(),I=Wc([v().regex(Al),`/`,v().min(1)]),jl=C([D(`native`),I]);function Ml(e,t){return`${e}/${t}`}function Nl(e){let t=e.indexOf(`/`);return{system:e.slice(0,t),local:e.slice(t+1)}}var Pl=[`urgent`,`interactive`,`normal`,`background`],Fl=E(Pl),Il=E([`user`,`llm`,`both`,`none`]),Ll=E([`user`,`group`,`agent`,`system`,`mcp`]),Rl=e=>S({items:x(e),cursor:v().optional()}),zl=S({cursor:v().optional(),limit:y().int().min(1).max(200).optional()});function Bl(e){return e instanceof Error?e.message:String(e)}var Vl=`read`,Hl=`admin`,L=v().regex(Al).brand(),Ul=L.parse(`main`),Wl=S({system:F,instance:L}),Gl=v().regex(/^[a-z*][a-z0-9*-]*\/[A-Za-z0-9_.*-]+$/).brand(),Kl=Object.defineProperty,ql=(e,t)=>{for(var n in t)Kl(e,n,{get:t[n],enumerable:!0})},R={};ql(R,{array:()=>dp,boolean:()=>rp,codec:()=>Tp,conditional:()=>vp,declare:()=>Op,default:()=>xp,define:()=>Dp,dependent:()=>yp,discriminatedUnion:()=>hp,dispatch:()=>Ep,enum:()=>op,fromJSONSchema:()=>Qf,int:()=>np,intersection:()=>gp,json:()=>lp,literal:()=>ap,module:()=>kp,never:()=>sp,not:()=>_p,null:()=>ip,nullable:()=>Sp,number:()=>tp,object:()=>up,optional:()=>bp,record:()=>pp,ref:()=>Cp,refOf:()=>wp,string:()=>ep,tuple:()=>fp,union:()=>mp,unknown:()=>cp});var Jl=Object.freeze({length:!0,range:!0,items:`all`,pattern:`full`}),Yl=Object.freeze({length:!1,range:!1,items:`none`,pattern:`none`}),Xl=Object.freeze({id:`lenient`,family:`lenient`,strict:!1,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!0,conditionals:!0,patternProperties:!0,defs:!0,recursion:!0,any:`empty`,constraints:Jl,formats:`all`,examples:`keyword`,propertyOrdering:!1,rootObject:!1}),Zl=Object.freeze({...Xl,id:`people`,family:`people`,audience:`people`}),Ql=Object.freeze({...Xl,id:`openai`,family:`openai`,rootObject:!0,request:Object.freeze({maxTools:128})}),$l=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`ipv4`,`ipv6`,`uuid`]),eu=Object.freeze({id:`openai-strict`,family:`openai`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`anyOf`,nulls:`anyOf`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,refSiblings:!1,recursion:!0,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:$l,examples:`description`,propertyOrdering:!1,maxDepth:10,rootObject:!0,limits:Object.freeze({maxProperties:5e3,maxDepth:10,maxStringChars:12e4,maxEnumValues:1e3,largeEnumValues:250,maxLargeEnumChars:15e3}),request:Object.freeze({maxTools:128}),loose:Ql}),tu=Object.freeze({...eu,id:`openai-finetuned-strict`,constraints:Yl,formats:new Set}),nu=Object.freeze({...Xl,id:`anthropic`,family:`anthropic`,rootObject:!0}),ru=Object.freeze({id:`anthropic-strict`,family:`anthropic`,strict:!0,optional:`omit`,closedObjects:!0,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!1,range:!1,items:`min-0-1`,pattern:`basic`}),formats:new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]),examples:`description`,propertyOrdering:!1,rootObject:!0,request:Object.freeze({maxStrictTools:20,totals:Object.freeze({maxOptional:24,maxUnions:16})}),loose:nu,alwaysStrictOutput:!0}),iu=`Return ONLY a single raw JSON object that conforms to the schema above. Do NOT wrap it in markdown code fences, do NOT add any prose before or after it, and do NOT echo the schema itself: emit only the JSON instance.`,au=Object.freeze({...Xl,id:`google`,family:`google`,recursion:`guarded`,maxEnumValues:40,rootObject:!0,jsonInstruction:iu}),ou=Object.freeze({id:`google-strict`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:`guarded`,any:`empty`,constraints:Object.freeze({length:!1,range:!0,items:`all`,pattern:`none`}),formats:new Set([`date-time`,`date`,`time`]),examples:`description`,propertyOrdering:!1,maxEnumValues:40,rootObject:!0,loose:au,jsonInstruction:iu}),su=Object.freeze({id:`google-openapi`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`nullable`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:new Set([`date-time`,`date`,`time`,`duration`]),examples:`description`,propertyOrdering:!0,maxEnumValues:40,maxDepth:10,rootObject:!0,loose:au,jsonInstruction:iu}),cu=new Set([`date`,`time`,`date-time`,`email`,`uuid`,`ipv4`,`ipv6`,`uri`]),lu=Object.freeze({id:`xai-strict`,family:`xai`,strict:!0,optional:`omit`,closedObjects:!0,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`flat`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:cu,examples:`description`,propertyOrdering:!1,rootObject:!0}),uu=Object.freeze({...lu,id:`xai`,strict:!1}),du=Object.freeze({...Xl,id:`ollama`,family:`ollama`,rootObject:!0}),fu=Object.freeze({id:`minimal`,family:`minimal`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`tagged`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Yl,formats:new Set,examples:`description`,propertyOrdering:!1,maxDepth:6,maxEnumValues:8,rootObject:!0}),pu=new Map,mu=new Map;function hu(e){pu.set(e.id,e);let t=mu.get(e.family)??{};e.strict?t.strict??=e:t.loose??=e,mu.set(e.family,t)}for(let e of[Xl,Zl,Ql,eu,tu,nu,ru,au,ou,su,lu,uu,du,fu])hu(e);var gu=new WeakMap;function _u(e){let t=gu.get(e);return t||(t=Object.freeze({profile:e,records:e.records,optional:e.optional,recordWord:e.records===`pairs`?`a list of {key, value} entries`:`an object`}),gu.set(e,t)),t}Object.freeze({properties:0,depth:0,stringChars:0,enumValues:0,enums:Object.freeze([]),optional:0,unions:0});function vu(e){let t=0,n=0,r=0,i=0,a=0,o=[],s=e.$defs??{};for(let e of Object.keys(s))n+=e.length;let c=e=>{if(!e||typeof e!=`object`)return;if(Array.isArray(e)){for(let t of e)c(t);return}let s=e;if(s.properties&&typeof s.properties==`object`){let e=s.properties,r=new Set(Array.isArray(s.required)?s.required:[]);for(let[a,o]of Object.entries(e))t++,n+=a.length,r.has(a)||i++,c(o)}if(Array.isArray(s.enum)){let e=0;for(let t of s.enum)typeof t==`string`&&(e+=t.length);r+=s.enum.length,n+=e,o.push({values:s.enum.length,chars:e})}typeof s.const==`string`&&(n+=s.const.length);let l=s.anyOf??s.oneOf;(Array.isArray(l)&&l.length>1||Array.isArray(s.type)&&s.type.length>1)&&a++;for(let e of[`items`,`prefixItems`,`anyOf`,`oneOf`,`allOf`,`additionalProperties`,`not`,`if`,`then`,`else`])e in s&&c(s[e]);if(s.patternProperties&&typeof s.patternProperties==`object`)for(let e of Object.values(s.patternProperties))c(e)},{$defs:l,...u}=e;c(u);for(let e of Object.values(s))c(e);let d=e=>{if(typeof e.$ref==`string`)return/^#\/\$defs\/(.+)$/.exec(e.$ref)?.[1]?.replace(/~1/g,`/`).replace(/~0/g,`~`)},f=yu(s,d),p=new Set,m=new Map,h=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e;if(typeof t.$ref==`string`){let e=d(t);if(!e||p.has(e)||!s[e])return 0;let n=f.get(e),r=e;if(n){r+=`|`;for(let e of n)r+=p.has(e)?`1`:`0`}let i=m.get(r);if(i!==void 0)return i;p.add(e);let a=h(s[e]);return p.delete(e),m.set(r,a),a}let n=t.type===`object`||t.type===`array`||Array.isArray(t.type)&&(t.type.includes(`object`)||t.type.includes(`array`)),r=0,i=e=>{let t=h(e);t>r&&(r=t)};if(t.properties&&typeof t.properties==`object`)for(let e of Object.values(t.properties))i(e);for(let e of[`items`,`additionalProperties`,`not`])e in t&&i(t[e]);for(let e of[`prefixItems`,`anyOf`,`oneOf`,`allOf`])if(Array.isArray(t[e]))for(let n of t[e])i(n);return+!!n+r},ee=h(u);return{properties:t,depth:ee,stringChars:n,enumValues:r,enums:o,optional:i,unions:a}}function yu(e,t){let n=new Map,r=(n,i)=>{if(!n||typeof n!=`object`)return;if(Array.isArray(n)){for(let e of n)r(e,i);return}let a=t(n);a!==void 0&&e[a]&&i.add(a);for(let e of Object.values(n))r(e,i)};for(let t of Object.keys(e)){let i=new Set;r(e[t],i),n.set(t,[...i])}let i=new Map,a=new Map,o=new Set,s=[],c=new Map,l=0;for(let e of n.keys()){if(i.has(e))continue;let t=[[e,0]];for(;t.length;){let e=t[t.length-1],[r,u]=e;u===0&&(i.set(r,l),a.set(r,l),l++,s.push(r),o.add(r));let d=n.get(r);if(u<d.length){e[1]++;let n=d[u];i.has(n)?o.has(n)&&a.set(r,Math.min(a.get(r),i.get(n))):t.push([n,0]);continue}t.pop();let f=t[t.length-1];if(f&&a.set(f[0],Math.min(a.get(f[0]),a.get(r))),a.get(r)===i.get(r)){let e=[],t;do t=s.pop(),o.delete(t),e.push(t);while(t!==r);if(e.length>1||d.includes(r))for(let t of e)c.set(t,e)}}}return c}var bu=class extends Error{constructor(e){super(`@aeye/schema: ${e}`),this.name=`SchemaDefinitionError`}},xu=class extends Error{constructor(e,t=Vd(e)){super(t),this.issues=e,this.name=`SchemaParseError`}issues};function Su(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function Cu(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function wu(e,t,n=Cu(e.length)){let r=e.toLowerCase(),i=[];for(let a=0;a<t.length;a++){let o=t[a];if(Math.abs(o.length-e.length)>n)continue;let s=Su(r,o.toLowerCase());s<=n&&i.push({candidate:o,index:a,ci:s,exact:Su(e,o)})}return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function Tu(e,t,n){return wu(e,t,n)[0]}var Eu=Object.freeze({detail:`full`,maxErrors:5,maxChars:2e3,suggestions:!0,context:3,depth:6,header:!0});function Du(...e){let t;for(let n of e)n!==void 0&&(t={...t,...ku(typeof n==`string`?{detail:n}:n)});return t}function Ou(...e){let t=Du(...e)??{},n=t.detail??Eu.detail;return{...Eu,...t,detail:n,expected:t.expected??n===`full`}}function ku(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Au(e){let t=typeof e==`string`?e:e?.detail??Eu.detail;return t===`markers`||t===`full`}var ju=new WeakMap;function Mu(e,t){ju.set(e,t)}function Nu(e,t,n){for(let r=t;r<e.length;r++){let t=ju.get(e[r]);t&&!t.node&&(t.node=n)}}var Pu=/^[A-Za-z_$][\w$]*$/;function Fu(e){let t=``,n=``;for(let r of e)r===`(json)`?(t+=`${n||`(root)`} \u2192 JSON text \u2192 `,n=``):n+=typeof r==`number`?`[${r}]`:Pu.test(r)?n?`.${r}`:r:`[${JSON.stringify(r)}]`;return t&&!n?t.slice(0,-3):t+(n||(t?``:`(root)`))}var Iu=Symbol(`absent`);function Lu(e,t){let n=e;for(let e of t)if(e===`(json)`){if(typeof n!=`string`)continue;if(n=zu(n),n===Iu)return Iu}else{if(typeof n==`string`&&(n=zu(n)),typeof n!=`object`||!n||!Object.prototype.hasOwnProperty.call(n,e))return Iu;n=n[e]}return n}var Ru;function zu(e){let t=Ru?.get(e);if(t!==void 0)return t;let n;try{n=JSON.parse(e)}catch{n=Iu}return Ru?.set(e,n),n}function Bu(e,t=160){for(let n of[2,1,0]){let r=Hu(e,n,6);if(r.length<=t)return r}let n=Hu(e,0,3);return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Vu(e){return e.replace(/^#\/\$defs\//,``).replace(/~1/g,`/`).replace(/~0/g,`~`)}function Hu(e,t,n){if(typeof e.$ref==`string`)return Vu(e.$ref);if(`const`in e)return JSON.stringify(e.const);if(Array.isArray(e.enum))return Wu(e.enum.map(e=>JSON.stringify(e)),n,` | `);let r=e.anyOf??e.oneOf;if(Array.isArray(r))return Wu([...new Set(r.map(e=>Hu(e,t,n)))],n,` | `,`options`);if(Array.isArray(e.allOf))return e.allOf.map(e=>Uu(Hu(e,t,n))).join(` & `);if(Array.isArray(e.type))return e.type.map(r=>Hu({...e,type:r},t,n)).join(` | `);if(e.nullable===!0)return`${Uu(Hu({...e,nullable:!1},t,n))} | null`;switch(e.type){case`string`:if(typeof e.description==`string`&&/JSON text/.test(e.description)){let t=/TypeScript type: ([^\n(]+?)(?: \(its named types|\.\s*$)/.exec(e.description);return t?`string (JSON text of ${t[1].trim()})`:`string (JSON text)`}return typeof e.format==`string`?`string (${e.format})`:`string`;case`integer`:return`integer`;case`number`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:return Array.isArray(e.prefixItems)?`[${e.prefixItems.map(e=>Hu(e,t-1,n)).join(`, `)}]`:`${Uu(e.items&&typeof e.items==`object`?Hu(e.items,t-1,n):`any`)}[]`;case`object`:{let r=e.properties??{},i=Object.keys(r),a=e.additionalProperties&&typeof e.additionalProperties==`object`?e.additionalProperties:void 0;if(!i.length&&!a)return e.additionalProperties===!1?`{}`:`object`;if(t<=0)return`{…}`;let o=new Set(e.required??[]),s=i.slice(0,n).map(e=>`${Pu.test(e)?e:JSON.stringify(e)}${o.has(e)?``:`?`}: ${Hu(r[e],t-1,n)}`);return i.length>n&&s.push(`\u2026 ${i.length-n} more`),a&&s.push(`[key: string]: ${Hu(a,t-1,n)}`),`{ ${s.join(`; `)} }`}default:return`any JSON value`}}function Uu(e){return/ \| | & /.test(e)&&!/^[{[(]/.test(e)?`(${e})`:e}function Wu(e,t,n,r=`more`){return e.length<=t?e.join(n):`${e.slice(0,t).join(n)}${n}\u2026 (${e.length} ${r===`more`?`values`:r})`}function Gu(e,t){let n=t?.node;if(n&&t&&t.kind!==`enum`&&t.kind!==`literal`&&t.kind!==`tag`&&t.kind!==`tool`&&t.kind!==`rule`&&t.kind!==`unknown-key`&&t.kind!==`not-allowed`)try{if(n.jsonText&&n.schema){let e=n.typeText();return`string (JSON text of ${e.length>120?`${e.slice(0,119)}\u2026`:e})`}let e=Bu(n.json());return t.kind===`type`&&/^(string|number|integer|boolean|null)$/.test(e)?void 0:e}catch{return}}function Ku(e){let t=e.message;for(let n of e.path)t+=`\0${typeof n==`number`?`#`:n}`;return t}function qu(e){let t=[],n=new Map;for(let r of e){let e=Ku(r),i=n.get(e);if(i){i.paths.push(r.path);continue}let a={issue:r,info:ju.get(r),paths:[r.path]};n.set(e,a),t.push(a)}return t}function Ju(e,t){let n=e.issue.message,r=e.info?.kind;if(t.terse&&e.info?.candidates&&(r===`enum`||r===`tag`||r===`tool`)){let t=e.info.candidates().length;n=n.replace(/ one of: .*$/s,` one of ${t} value${t===1?``:`s`}.`)}if(t.suggestions&&e.info?.candidates){let t=Yu(e.issue,e.info);t&&(n=n.replace(/\.$/,``)+t)}if(e.paths.length>1){if(t.terse)n+=` (the same at ${e.paths.length-1} more place${e.paths.length===2?``:`s`})`;else{let t=e.paths.slice(1,3).map(Fu),r=e.paths.length-1-t.length;n+=` (the same at ${t.join(`, `)}${r>0?` and ${r} more place${r===1?``:`s`}`:``})`}}return n.length>400?`${n.slice(0,399)}\u2026`:n}function Yu(e,t){let n=t.candidates();if(!n.length)return``;if(t.kind===`required`){let t=e.path[e.path.length-1];if(typeof t!=`string`)return``;let r=Tu(t,n);return r?` \u2014 you wrote \`${r}\`; did you mean \`${t}\`?`:``}let r=t.kind===`unknown-key`?e.path[e.path.length-1]:t.received;if(typeof r!=`string`)return``;let i=wu(r,n)[0];return i!==void 0&&i!==r?` \u2014 did you mean \`${i}\`?`:``}function Xu(e,t,n,r=`your answer`){if(!e.length)return``;let i=Qu(n)?n:Ou(n),a=qu(i.suggestions?Zu(e):e),o=Ru;Ru=new Map;try{for(let e of $u(i)){let n=td(a,t,e,r);if(n.length<=i.maxChars)return n}let e=td(a,t,{...i,detail:`summary`,maxErrors:1,terse:!0},r);return e.length<=i.maxChars?e:`${e.slice(0,Math.max(0,i.maxChars-1))}\u2026`}finally{Ru=o}}function Zu(e){let t,n=0;for(let r of e){let e=ju.get(r);if(e?.kind!==`required`||!e.candidates||++n>50)continue;let i=r.path[r.path.length-1],a=typeof i==`string`?Tu(i,e.candidates()):void 0;a!==void 0&&(t??=new Set).add(nd([...r.path.slice(0,-1),a]))}return t?e.filter(e=>!(ju.get(e)?.kind===`unknown-key`&&t.has(nd(e.path)))):e}function Qu(e){return typeof e==`object`&&!!e&&`detail`in e&&`maxChars`in e&&`expected`in e&&`context`in e&&`depth`in e&&`header`in e&&`suggestions`in e&&`maxErrors`in e}function*$u(e){for(let t of ed(e))yield t,yield{...t,terse:!0}}function*ed(e){let t=e;if(yield t,t.detail===`markers`||t.detail===`full`){for(t.expected&&(yield t={...t,expected:!1}),t.context>0&&(yield t={...t,context:0}),t.depth>2&&(yield t={...t,depth:2});t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};yield t={...t,detail:`list`,maxErrors:e.maxErrors}}for(;t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};t.detail!==`summary`&&(yield{...t,detail:`summary`})}function td(e,t,n,r){let i=e.slice(0,Math.max(1,n.maxErrors)),a=e.reduce((e,t)=>e+t.paths.length,0),o=e.length-i.length,s=e.slice(i.length).reduce((e,t)=>e+t.paths.length,0),c=`${a} problem${a===1?``:`s`}`;if(n.detail===`summary`){let e=i[0],t=a-e.paths.length;return`${n.header?`${a===1?`A problem`:c} in ${r}: `:``}at ${Fu(e.issue.path)}: ${Ju(e,n)}${t>0?` (and ${t} more problem${t===1?``:`s`})`:``}`}let l=[];if(n.header&&l.push(`${c} in ${r}:`),n.detail===`list`)for(let e of i){let t=n.expected?Gu(e.issue,e.info):void 0;l.push(`- at ${Fu(e.issue.path)}: ${Ju(e,n)}${t?` (expected: ${t})`:``}`)}else n.header&&l.push(``),l.push(...od(i,t,n));return s>0&&l.push(`\u2026 and ${s} more problem${s===1?``:`s`}${o>1?` (${o} kinds)`:``} not shown.`),l.join(`
|
|
56
|
-
`)}var
|
|
55
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function io(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;io(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var ao=new Set([`type`,`properties`,`required`,`additionalProperties`]),oo=[`oneOf`,`anyOf`];function so(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function co(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ao.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??so(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}u(n,r,e.length===1?e[0]:co(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=so(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function lo(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ao)if(t in e)return;let n=t.filter(e=>oo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=co(t);else{let e=n[0],i=oo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>co([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Qa(e,r))}function uo(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Qa(i,s),Qa(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())io(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])lo(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Qa(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,u(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:mo(t,`input`,e.processors),output:mo(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function fo(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return fo(r.element,n);if(r.type===`set`)return fo(r.valueType,n);if(r.type===`lazy`)return fo(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return fo(r.innerType,n);if(r.type===`intersection`)return fo(r.left,n)||fo(r.right,n);if(r.type===`record`||r.type===`map`)return fo(r.keyType,n)||fo(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:fo(r.in,n)||fo(r.out,n);if(r.type===`object`){for(let e in r.shape)if(fo(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(fo(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(fo(e,n))return!0;return!!(r.rest&&fo(r.rest,n))}return!1}var po=(e,t={})=>n=>{let r=$a({...n,processors:t});return to(e,r),ro(r,e),uo(r,e)},mo=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=$a({...i??{},target:a,io:t,processors:n});return to(e,o),ro(o,e),uo(o,e)},ho=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},go=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},_o=(e,t)=>{ho(e,`minimum`,t),go(e,`maximum`,t)},vo=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},yo=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},bo=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},xo=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},So=(e,t)=>ho(e,`minimum`,t.minimum),Co=(e,t)=>go(e,`maximum`,t.maximum),wo=e=>(t,n)=>{xo(t,n.format);let[r,i]=e[n.format];ho(t,`minimum`,r),go(t,`maximum`,i)},To={greater_than:(e,t)=>ho(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>go(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>vo(e,t.value),number_format:wo(he),bigint_format:wo(ge),min_length:So,max_length:Co,length_equals:(e,t)=>_o(e,t.length),min_size:So,max_size:Co,size_equals:(e,t)=>_o(e,t.size),string_format:(e,t)=>{xo(e,t.format),t.pattern&&yo(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>bo(e,t.mime)};function Eo(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)To[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&ho(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&ho(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&go(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&go(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&vo(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&bo(t,i.mime);for(let e of i.patterns??[])yo(t,e);return t}var Do={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Oo=new Map([[_r,Xt],[yr,Zt]]),ko=e=>Oo.get(e)??e,Ao=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=Eo(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Do[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(ko);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},jo=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Eo(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):eo(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Mo=(e,t,n,r)=>{n.type=`boolean`},No=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Po=(e,t,n,r)=>{n.not={}},Fo=(t,n,r,i)=>{let a=t._zod.def,o=e(a.entries);o.length===0?r.not={}:(o.every(e=>typeof e==`number`)&&(r.type=`number`),o.every(e=>typeof e==`string`)&&(r.type=`string`),r.enum=o)},Io=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(eo(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(eo(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Lo=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Ro=(e,t,n,r)=>{eo(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},zo=(e,t,n,r)=>{eo(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},Bo=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=Eo(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=to(a.element,t,{...r,path:[...r.path,`items`]})};function Vo(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Vo(t.out):t.type===`catch`?Vo(t.innerType):e._zod.optin}var Ho=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&eo(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)u(i.properties,e,to(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Vo(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=to(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Uo=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>to(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Wo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=to(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},Go=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>to(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?to(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?Vo(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=Eo(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function Ko(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Ko(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Ko(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?un:ln).source)),p}var qo=new WeakMap;function Jo(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of qo.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Ko(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var Yo=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=Eo(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=to(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)u(i.patternProperties,ko(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=to(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=qo.get(t);n||(n=[],qo.set(t,n),t.deferred.push(()=>Jo(t))),n.push(e)}i.additionalProperties=to(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Vo(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Xo=(e,t,n,r)=>{let i=e._zod.def,a=to(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Zo=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Qo=Symbol();function $o(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(eo(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Qo):JSON.parse(o)}var es=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n.default=o)},ts=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=$o(i.defaultValue,e,t,n,r);o!==Qo&&(n._prefault=o)},ns=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{eo(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},rs=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;to(o,t,r);let s=t.seen.get(e);s.ref=o},is=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},as=(e,t,n,r)=>{let i=e._zod.def;to(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},os=(e,t,n,r)=>{let i=e._zod.innerType;to(i,t,r);let a=t.seen.get(e);a.ref=i},ss=new WeakSet([Object.prototype,Error.prototype]);function cs(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var ls=_(`ZodError`,(e,t)=>{ut.init(e,t),e.name=`ZodError`;let r=Object.getPrototypeOf(e);ss.has(r)||(ss.add(r),cs(r,`format`,e=>t=>pt(e,t)),cs(r,`flatten`,e=>t=>ft(e,t)),cs(r,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,n,2)}),cs(r,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,n,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),us=ht(ls),ds=gt(ls),fs=_t(ls),ps=yt(ls),ms=Tt(ls),hs=Et(ls),gs=Dt(ls),_s=Ot(ls),vs=kt(ls),ys=At(ls),bs=jt(ls),xs=Mt(ls);function Ss(){rt.localeError||it(Hi())}function Cs(){rt.memoizer||it({memoizer:zi()})}var ws=_(`ZodType`,(e,t)=>(Ss(),Fn.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(te(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return fe(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Yc(e,t))},superRefine(e,t){return this.check(Xc(e,t))},overwrite(e){return this.check(Va(e))},optional(){return Ec(this)},exactOptional(){return Oc(this)},nullable(){return Ac(this)},nullish(){return Ec(Ac(this))},nonoptional(e){return Ic(this,e)},array(){return x(this)},or(e){return C([this,e])},and(e){return gc(this,e)},transform(e){return Bc(this,wc(e))},default(e){return Mc(this,e)},prefault(e){return Pc(this,e)},catch(e){return Rc(this,e)},pipe(e){return Bc(this,e)},readonly(){return Hc(this)},describe(e){let t=this.clone();return Ki.add(t,{description:e}),t},meta(...e){if(e.length===0)return Ki.get(this);let t=this.clone();return Ki.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Be(this,`~standard`,{...Rn(this),jsonSchema:{input:mo(this,`input`),output:mo(this,`output`)}})},set"~standard"(e){ze(this,`~standard`,e)},parse:function e(t,n){return us(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await ds(this,t,n,{callee:e})},safeParse(e,t){return fs(this,e,t)},async safeParseAsync(e,t){return ps(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){ze(this,`spa`,e)},validate(e,t){return St(this,e,t)},validateAsync(e,t){return wt(this,e,t)},encode:function e(t,n){return ms(this,t,n,{callee:e})},decode:function e(t,n){return hs(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await gs(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await _s(this,t,n,{callee:e})},safeEncode(e,t){return vs(this,e,t)},safeDecode(e,t){return ys(this,e,t)},async safeEncodeAsync(e,t){return bs(this,e,t)},async safeDecodeAsync(e,t){return xs(this,e,t)},toJSONSchema(e){return po(this,{})(e)},get description(){return Ki.get(this)?.description},get _def(){return this._zod.def}}),Ts=_(`_ZodString`,(e,t)=>{zn.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ao(e,t,n,r)},Ve({format:e=>Eo(e).format??null,minLength:e=>Eo(e).minimum??null,maxLength:e=>Eo(e).maximum??null},{regex(...e){return this.check(Fa(...e))},includes(...e){return this.check(Ra(...e))},startsWith(...e){return this.check(za(...e))},endsWith(...e){return this.check(Ba(...e))},min(...e){return this.check(Na(...e))},max(...e){return this.check(Ma(...e))},length(...e){return this.check(Pa(...e))},nonempty(...e){return this.check(Na(1,...e))},lowercase(e){return this.check(Ia(e))},uppercase(e){return this.check(La(e))},trim(){return this.check(Ua())},normalize(...e){return this.check(Ha(...e))},toLowerCase(){return this.check(Wa())},toUpperCase(){return this.check(Ga())},slugify(){return this.check(Ka())}})),Es=_(`ZodString`,(e,t)=>{zn.init(e,t),Ts.init(e,t)},{email(e){return this.check(Yi(Ms,e))},url(e){return this.check(ta(Is,e))},jwt(e){return this.check(ga(Qs,e))},emoji(e){return this.check(na(Rs,e))},guid(e){return this.check(Xi(Ps,e))},uuid(e){return this.check(Zi(Fs,e))},uuidv4(e){return this.check(Qi(Fs,e))},uuidv6(e){return this.check($i(Fs,e))},uuidv7(e){return this.check(ea(Fs,e))},nanoid(e){return this.check(ra(zs,e))},cuid(e){return this.check(ia(Bs,e))},cuid2(e){return this.check(aa(Vs,e))},ulid(e){return this.check(oa(Hs,e))},base64(e){return this.check(pa(Ys,e))},base64url(e){return this.check(ma(Xs,e))},xid(e){return this.check(sa(Us,e))},ksuid(e){return this.check(ca(Ws,e))},ipv4(e){return this.check(la(Gs,e))},ipv6(e){return this.check(ua(Ks,e))},cidrv4(e){return this.check(da(qs,e))},cidrv6(e){return this.check(fa(Js,e))},e164(e){return this.check(ha(Zs,e))},datetime(e){return this.check(_a(Os,e))},date(e){return this.check(va(ks,e))},time(e){return this.check(ya(As,e))},duration(e){return this.check(ba(js,e))}});function v(e){return Ji(Es,e)}var Ds=_(`ZodStringFormat`,(e,t)=>{Bn.init(e,t),Ts.init(e,t)}),Os=_(`ZodISODateTime`,(e,t)=>{ar.init(e,t),Ds.init(e,t)}),ks=_(`ZodISODate`,(e,t)=>{or.init(e,t),Ds.init(e,t)}),As=_(`ZodISOTime`,(e,t)=>{sr.init(e,t),Ds.init(e,t)}),js=_(`ZodISODuration`,(e,t)=>{cr.init(e,t),Ds.init(e,t)}),Ms=_(`ZodEmail`,(e,t)=>{Un.init(e,t),Ds.init(e,t)});function Ns(e){return Yi(Ms,e)}var Ps=_(`ZodGUID`,(e,t)=>{Vn.init(e,t),Ds.init(e,t)}),Fs=_(`ZodUUID`,(e,t)=>{Hn.init(e,t),Ds.init(e,t)}),Is=_(`ZodURL`,(e,t)=>{Zn.init(e,t),Ds.init(e,t)});function Ls(e){return ta(Is,e)}var Rs=_(`ZodEmoji`,(e,t)=>{Qn.init(e,t),Ds.init(e,t)}),zs=_(`ZodNanoID`,(e,t)=>{$n.init(e,t),Ds.init(e,t)}),Bs=_(`ZodCUID`,(e,t)=>{er.init(e,t),Ds.init(e,t)}),Vs=_(`ZodCUID2`,(e,t)=>{tr.init(e,t),Ds.init(e,t)}),Hs=_(`ZodULID`,(e,t)=>{nr.init(e,t),Ds.init(e,t)}),Us=_(`ZodXID`,(e,t)=>{rr.init(e,t),Ds.init(e,t)}),Ws=_(`ZodKSUID`,(e,t)=>{ir.init(e,t),Ds.init(e,t)}),Gs=_(`ZodIPv4`,(e,t)=>{lr.init(e,t),Ds.init(e,t)}),Ks=_(`ZodIPv6`,(e,t)=>{fr.init(e,t),Ds.init(e,t)}),qs=_(`ZodCIDRv4`,(e,t)=>{pr.init(e,t),Ds.init(e,t)}),Js=_(`ZodCIDRv6`,(e,t)=>{hr.init(e,t),Ds.init(e,t)}),Ys=_(`ZodBase64`,(e,t)=>{vr.init(e,t),Ds.init(e,t)}),Xs=_(`ZodBase64URL`,(e,t)=>{xr.init(e,t),Ds.init(e,t)}),Zs=_(`ZodE164`,(e,t)=>{Sr.init(e,t),Ds.init(e,t)}),Qs=_(`ZodJWT`,(e,t)=>{wr.init(e,t),Ds.init(e,t)}),$s=_(`ZodNumber`,(e,t)=>{Tr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jo(e,t,n,r),e.isFinite=!0},Ve({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Eo(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Eo(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=Eo(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Eo(e).format??null},{gt(e,t){return this.check(ka(e,t))},gte(e,t){return this.check(Aa(e,t))},min(e,t){return this.check(Aa(e,t))},lt(e,t){return this.check(Da(e,t))},lte(e,t){return this.check(Oa(e,t))},max(e,t){return this.check(Oa(e,t))},int(e){return this.check(tc(e))},safe(e){return this.check(tc(e))},positive(e){return this.check(ka(0,e))},nonnegative(e){return this.check(Aa(0,e))},negative(e){return this.check(Da(0,e))},nonpositive(e){return this.check(Oa(0,e))},multipleOf(e,t){return this.check(ja(e,t))},step(e,t){return this.check(ja(e,t))},finite(){return this}}));function y(e){return xa($s,e)}var ec=_(`ZodNumberFormat`,(e,t)=>{Er.init(e,t),$s.init(e,t)});function tc(e){return Sa(ec,e)}var nc=_(`ZodBoolean`,(e,t)=>{Dr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mo(e,t,n,r)});function b(e){return Ca(nc,e)}var rc=_(`ZodNull`,(e,t)=>{Or.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>No(e,t,n,r)});function ic(e){return wa(rc,e)}var ac=_(`ZodAny`,(e,t)=>{kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0}),oc=_(`ZodUnknown`,(e,t)=>{Ar.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function sc(){return Ta(oc)}var cc=_(`ZodNever`,(e,t)=>{jr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Po(e,t,n,r)});function lc(e){return Ea(cc,e)}var uc=_(`ZodArray`,(e,t)=>{Cs(),Fr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bo(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Na(e,t))},nonempty(e){return this.check(Na(1,e))},max(e,t){return this.check(Ma(e,t))},length(e,t){return this.check(Pa(e,t))},unwrap(){return this.element}});function x(e,t){return qa(uc,e,t)}var dc=_(`ZodObject`,(e,t)=>{Cs(),Vr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ho(e,t,n,r),Je(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return E(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(te(this._zod.def,{catchall:e}))},passthrough(){return this.clone(te(this._zod.def,{catchall:sc()}))},loose(){return this.clone(te(this._zod.def,{catchall:sc()}))},strict(){return this.clone(te(this._zod.def,{catchall:lc()}))},strip(){return this.clone(te(this._zod.def,{catchall:void 0}))},extend(e){return be(this,e)},safeExtend(e){return Se(this,e)},merge(e){return Ce(this,e)},pick(e){return _e(this,e)},omit(e){return ye(this,e)},partial(...e){return we(Tc,this,e[0])},exactPartial(...e){return we(Dc,this,e[0],`exactPartial`)},required(...e){return Te(Fc,this,e[0])}});function S(e,t){return new dc({type:`object`,shape:e??{},...g(t)})}function fc(e,t){return new dc({type:`object`,shape:e,catchall:sc(),...g(t)})}var pc=_(`ZodUnion`,(e,t)=>{Ur.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uo(e,t,n,r),e.options=t.options});function C(e,t){return new pc({type:`union`,options:e,...g(t)})}var mc=_(`ZodDiscriminatedUnion`,(e,t)=>{pc.init(e,t),Gr.init(e,t)});function w(e,t,n){return new mc({type:`union`,options:t,discriminator:e,...g(n)})}var hc=_(`ZodIntersection`,(e,t)=>{Kr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wo(e,t,n,r)});function gc(e,t){return new hc({type:`intersection`,left:e,right:t})}var _c=_(`ZodTuple`,(e,t)=>{Cs(),Yr.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Go(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Tc({type:`optional`,innerType:e}))})}});function vc(e,t,n){let r=t instanceof Fn;return new _c({type:`tuple`,items:e,rest:r?t:null,...g(r?n:t)})}var yc=_(`ZodRecord`,(e,t)=>{Cs(),$r.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yo(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function T(e,t,n){return!t||!t._zod?new yc({type:`record`,keyType:v(),valueType:e,...g(t)}):new yc({type:`record`,keyType:e,valueType:t,...g(n)})}function bc(e,t,n){return new yc({type:`record`,keyType:e,valueType:t,...g(n),partial:!0})}var xc=_(`ZodEnum`,(e,t)=>{ei.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fo(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new xc({...t,checks:[],...g(r),entries:i})}});function E(e,t){return new xc({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...g(t)})}var Sc=_(`ZodLiteral`,(e,t)=>{ti.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Io(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function D(e,t){return new Sc({type:`literal`,values:Array.isArray(e)?e:[e],...g(t)})}var Cc=_(`ZodTransform`,(e,t)=>{Cs(),ni.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zo(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new nt(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Le(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Le(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function wc(e){return new Cc({type:`transform`,transform:e})}var Tc=_(`ZodOptional`,(e,t)=>{ii.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ec(e){return new Tc({type:`optional`,innerType:e})}var Dc=_(`ZodExactOptional`,(e,t)=>{ai.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>as(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Oc(e){return new Dc({type:`optional`,innerType:e})}var kc=_(`ZodNullable`,(e,t)=>{oi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ac(e){return new kc({type:`nullable`,innerType:e})}var jc=_(`ZodDefault`,(e,t)=>{si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>es(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mc(e,t){return new jc({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Nc=_(`ZodPrefault`,(e,t)=>{li.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ts(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pc(e,t){return new Nc({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Fc=_(`ZodNonOptional`,(e,t)=>{ui.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ic(e,t){return new Fc({type:`nonoptional`,innerType:e,...g(t)})}var Lc=_(`ZodCatch`,(e,t)=>{pi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ns(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Rc(e,t){return new Lc({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Xe(t)})}var zc=_(`ZodPipe`,(e,t)=>{mi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rs(e,t,n,r),e.in=t.in,e.out=t.out});function Bc(e,t){return new zc({type:`pipe`,in:e,out:t})}var Vc=_(`ZodReadonly`,(e,t)=>{gi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>is(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Hc(e){return new Vc({type:`readonly`,innerType:e})}var Uc=_(`ZodTemplateLiteral`,(e,t)=>{bi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lo(e,t,n,r)});function Wc(e,t){return new Uc({type:`template_literal`,parts:e,...g(t)})}var Gc=_(`ZodLazy`,(e,t)=>{xi.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>os(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function Kc(e){return new Gc({type:`lazy`,getter:e})}var qc=_(`ZodCustom`,(e,t)=>{Si.init(e,t),ws.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ro(e,t,n,r)});function Jc(e,t){return Ja(qc,e??(()=>!0),t)}function Yc(e,t={}){return Ya(qc,e,t)}function Xc(e,t){return Xa(e,t)}function Zc(e){let t=Kc(()=>C([v(e),y(),b(),ic(),x(t),T(v(),t)]));return t}function Qc(e){return _a(Os,e)}function $c(e){return va(ks,e)}var O=Zc(),el=T(v(),O);function tl(e){return e===void 0?null:O.parse(JSON.parse(JSON.stringify(e)))}function nl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var rl={run:`run`,turn:`trn`,session:`ses`,actor:`act`,message:`msg`,delivery:`dlv`,handlerCall:`hcl`,llmInteraction:`llm`,pairing:`par`,pairingToken:`ptk`,policy:`pol`,approval:`apr`,budget:`bgt`,priorityRule:`pri`,reservation:`rsv`,ledger:`led`,notification:`ntf`,push:`psh`,secret:`sec`,modelCategory:`mct`,provider:`prv`,sectionRule:`srl`,authSession:`aus`,modelCall:`mdl`,mcp:`mcp`,autoPair:`apk`,connection:`cnx`,fnExample:`fex`,refusal:`rfs`,record:`rec`,mentionRequest:`mrq`},il=e=>v().regex(RegExp(`^${rl[e]}_.+$`),`expected a ${e} id starting with "${rl[e]}_"`).brand().describe(`${e} id`),al=e=>Object.hasOwn(rl,e);function ol(){return Object.fromEntries(Object.keys(rl).filter(al).map(e=>[e,il(e)]))}var k=v().regex(/^[A-Za-z_][A-Za-z0-9_.-]*$/),sl=ol(),A=sl.run,cl=sl.turn,j=sl.session,M=sl.actor,ll=sl.message,ul=sl.delivery,dl=sl.handlerCall,fl=sl.llmInteraction,pl=sl.pairing,ml=sl.pairingToken,hl=sl.policy,gl=sl.approval,_l=sl.budget,vl=sl.priorityRule,yl=sl.reservation,bl=sl.ledger,xl=sl.notification,Sl=sl.push,Cl=sl.secret,wl=sl.modelCategory,Tl=sl.provider,El=sl.sectionRule,Dl=sl.authSession,Ol=sl.modelCall,kl=sl.mcp,Al=sl.autoPair,jl=sl.connection,Ml=y().int().min(0),N=y().int(),P=y(),Nl=/^[a-z][a-z0-9-]*$/,F=v().regex(Nl).brand(),I=Wc([v().regex(Nl),`/`,v().min(1)]),Pl=C([D(`native`),I]);function Fl(e,t){return`${e}/${t}`}function Il(e){let t=e.indexOf(`/`);return{system:e.slice(0,t),local:e.slice(t+1)}}var Ll=[`urgent`,`interactive`,`normal`,`background`],Rl=E(Ll),zl=E([`user`,`llm`,`both`,`none`]),Bl=E([`user`,`group`,`agent`,`system`,`mcp`]),Vl=e=>S({items:x(e),cursor:v().optional()}),Hl=S({cursor:v().optional(),limit:y().int().min(1).max(200).optional()});function Ul(e){return e instanceof Error?e.message:String(e)}var Wl=`read`,Gl=`admin`,L=v().regex(Nl).brand(),Kl=L.parse(`main`),ql=S({system:F,instance:L}),Jl=v().regex(/^[a-z*][a-z0-9*-]*\/[A-Za-z0-9_.*-]+$/).brand(),Yl=Object.defineProperty,Xl=(e,t)=>{for(var n in t)Yl(e,n,{get:t[n],enumerable:!0})},R={};Xl(R,{array:()=>gp,boolean:()=>cp,codec:()=>Ap,conditional:()=>Cp,declare:()=>Np,default:()=>Ep,define:()=>Mp,dependent:()=>wp,discriminatedUnion:()=>bp,dispatch:()=>jp,enum:()=>dp,fromJSONSchema:()=>rp,int:()=>sp,intersection:()=>xp,json:()=>mp,literal:()=>up,module:()=>Pp,never:()=>fp,not:()=>Sp,null:()=>lp,nullable:()=>Dp,number:()=>op,object:()=>hp,optional:()=>Tp,record:()=>vp,ref:()=>Op,refOf:()=>kp,string:()=>ap,tuple:()=>_p,union:()=>yp,unknown:()=>pp});var Zl=Object.freeze({length:!0,range:!0,items:`all`,pattern:`full`}),Ql=Object.freeze({length:!1,range:!1,items:`none`,pattern:`none`}),$l=Object.freeze({id:`lenient`,family:`lenient`,strict:!1,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!0,conditionals:!0,patternProperties:!0,defs:!0,recursion:!0,any:`empty`,constraints:Zl,formats:`all`,examples:`keyword`,propertyOrdering:!1,rootObject:!1}),eu=Object.freeze({...$l,id:`people`,family:`people`,audience:`people`}),tu=Object.freeze({...$l,id:`openai`,family:`openai`,rootObject:!0,request:Object.freeze({maxTools:128})}),nu=new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`ipv4`,`ipv6`,`uuid`]),ru=Object.freeze({id:`openai-strict`,family:`openai`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`anyOf`,nulls:`anyOf`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,refSiblings:!1,recursion:!0,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:nu,examples:`description`,propertyOrdering:!1,maxDepth:10,rootObject:!0,limits:Object.freeze({maxProperties:5e3,maxDepth:10,maxStringChars:12e4,maxEnumValues:1e3,largeEnumValues:250,maxLargeEnumChars:15e3}),request:Object.freeze({maxTools:128}),loose:tu}),iu=Object.freeze({...ru,id:`openai-finetuned-strict`,constraints:Ql,formats:new Set}),au=Object.freeze({...$l,id:`anthropic`,family:`anthropic`,rootObject:!0}),ou={id:`anthropic-strict`,family:`anthropic`,strict:!0,optional:`omit`,closedObjects:!0,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!1,range:!1,items:`min-0-1`,pattern:`basic`}),formats:new Set([`date-time`,`time`,`date`,`duration`,`email`,`hostname`,`uri`,`ipv4`,`ipv6`,`uuid`]),examples:`description`,propertyOrdering:!1,rootObject:!0,limits:Object.freeze({maxObjectProperties:34}),request:Object.freeze({maxStrictTools:20,totals:Object.freeze({maxOptional:24,maxUnions:16,maxProperties:54})}),loose:au,alwaysStrictOutput:!0},su=Object.freeze({...ou,id:`anthropic-strict-output`,limits:Object.freeze({maxObjectOptional:12})}),cu=Object.freeze({...ou,output:su}),lu=`Return ONLY a single raw JSON object that conforms to the schema above. Do NOT wrap it in markdown code fences, do NOT add any prose before or after it, and do NOT echo the schema itself: emit only the JSON instance.`,uu=Object.freeze({...$l,id:`google`,family:`google`,recursion:`guarded`,maxEnumValues:40,rootObject:!0,jsonInstruction:lu}),du=Object.freeze({id:`google-strict`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:`guarded`,any:`empty`,constraints:Object.freeze({length:!1,range:!0,items:`all`,pattern:`none`}),formats:new Set([`date-time`,`date`,`time`]),examples:`description`,propertyOrdering:!1,maxEnumValues:40,rootObject:!0,loose:uu,jsonInstruction:lu}),fu=Object.freeze({id:`google-openapi`,family:`google`,strict:!0,optional:`omit`,closedObjects:!1,records:`pairs`,tuples:`array`,unions:`anyOf`,nulls:`nullable`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:new Set([`date-time`,`date`,`time`,`duration`]),examples:`description`,propertyOrdering:!0,maxEnumValues:40,maxDepth:10,rootObject:!0,loose:uu,jsonInstruction:lu}),pu=new Set([`date`,`time`,`date-time`,`email`,`uuid`,`ipv4`,`ipv6`,`uri`]),mu=Object.freeze({id:`xai-strict`,family:`xai`,strict:!0,optional:`omit`,closedObjects:!0,records:`open`,tuples:`prefixItems`,unions:`anyOf`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!0,recursion:!1,any:`flat`,constraints:Object.freeze({length:!0,range:!0,items:`all`,pattern:`basic`}),formats:pu,examples:`description`,propertyOrdering:!1,rootObject:!0}),hu=Object.freeze({...mu,id:`xai`,strict:!1}),gu=Object.freeze({...$l,id:`ollama`,family:`ollama`,rootObject:!0}),_u=Object.freeze({id:`minimal`,family:`minimal`,strict:!0,optional:`null`,closedObjects:!0,records:`pairs`,tuples:`object`,unions:`tagged`,nulls:`type-array`,allOf:!1,conditionals:!1,patternProperties:!1,defs:!1,recursion:!1,any:`json-text`,constraints:Ql,formats:new Set,examples:`description`,propertyOrdering:!1,maxDepth:6,maxEnumValues:8,rootObject:!0}),vu=new Map,yu=new Map;function bu(e){vu.set(e.id,e);let t=yu.get(e.family)??{};e.strict?t.strict??=e:t.loose??=e,yu.set(e.family,t)}for(let e of[$l,eu,tu,ru,iu,au,cu,su,uu,du,fu,mu,hu,gu,_u])bu(e);var xu=new WeakMap;function Su(e){let t=xu.get(e);return t||(t=Object.freeze({profile:e,records:e.records,optional:e.optional,recordWord:e.records===`pairs`?`a list of {key, value} entries`:`an object`}),xu.set(e,t)),t}Object.freeze({properties:0,depth:0,stringChars:0,enumValues:0,enums:Object.freeze([]),optional:0,unions:0,objectProperties:0,objectOptional:0});function Cu(e){let t=0,n=0,r=0,i=0,a=0,o=0,s=0,c=[],l=e.$defs??{};for(let e of Object.keys(l))n+=e.length;let u=e=>{if(!e||typeof e!=`object`)return;if(Array.isArray(e)){for(let t of e)u(t);return}let l=e;if(l.properties&&typeof l.properties==`object`){let e=l.properties,r=new Set(Array.isArray(l.required)?l.required:[]),a=Object.keys(e);o=Math.max(o,a.length),s=Math.max(s,a.filter(e=>!r.has(e)).length);for(let[a,o]of Object.entries(e))t++,n+=a.length,r.has(a)||i++,u(o)}if(Array.isArray(l.enum)){let e=0;for(let t of l.enum)typeof t==`string`&&(e+=t.length);r+=l.enum.length,n+=e,c.push({values:l.enum.length,chars:e})}typeof l.const==`string`&&(n+=l.const.length);let d=l.anyOf??l.oneOf;(Array.isArray(d)&&d.length>1||Array.isArray(l.type)&&l.type.length>1)&&a++;for(let e of[`items`,`prefixItems`,`anyOf`,`oneOf`,`allOf`,`additionalProperties`,`not`,`if`,`then`,`else`])e in l&&u(l[e]);if(l.patternProperties&&typeof l.patternProperties==`object`)for(let e of Object.values(l.patternProperties))u(e)},{$defs:d,...f}=e;u(f);for(let e of Object.values(l))u(e);let p=e=>{if(typeof e.$ref==`string`)return/^#\/\$defs\/(.+)$/.exec(e.$ref)?.[1]?.replace(/~1/g,`/`).replace(/~0/g,`~`)},m=wu(l,p),h=new Set,ee=new Map,te=e=>{if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e;if(typeof t.$ref==`string`){let e=p(t);if(!e||h.has(e)||!l[e])return 0;let n=m.get(e),r=e;if(n){r+=`|`;for(let e of n)r+=h.has(e)?`1`:`0`}let i=ee.get(r);if(i!==void 0)return i;h.add(e);let a=te(l[e]);return h.delete(e),ee.set(r,a),a}let n=t.type===`object`||t.type===`array`||Array.isArray(t.type)&&(t.type.includes(`object`)||t.type.includes(`array`)),r=0,i=e=>{let t=te(e);t>r&&(r=t)};if(t.properties&&typeof t.properties==`object`)for(let e of Object.values(t.properties))i(e);for(let e of[`items`,`additionalProperties`,`not`])e in t&&i(t[e]);for(let e of[`prefixItems`,`anyOf`,`oneOf`,`allOf`])if(Array.isArray(t[e]))for(let n of t[e])i(n);return+!!n+r},ne=te(f);return{properties:t,depth:ne,stringChars:n,enumValues:r,enums:c,optional:i,unions:a,objectProperties:o,objectOptional:s}}function wu(e,t){let n=new Map,r=(n,i)=>{if(!n||typeof n!=`object`)return;if(Array.isArray(n)){for(let e of n)r(e,i);return}let a=t(n);a!==void 0&&e[a]&&i.add(a);for(let e of Object.values(n))r(e,i)};for(let t of Object.keys(e)){let i=new Set;r(e[t],i),n.set(t,[...i])}let i=new Map,a=new Map,o=new Set,s=[],c=new Map,l=0;for(let e of n.keys()){if(i.has(e))continue;let t=[[e,0]];for(;t.length;){let e=t[t.length-1],[r,u]=e;u===0&&(i.set(r,l),a.set(r,l),l++,s.push(r),o.add(r));let d=n.get(r);if(u<d.length){e[1]++;let n=d[u];i.has(n)?o.has(n)&&a.set(r,Math.min(a.get(r),i.get(n))):t.push([n,0]);continue}t.pop();let f=t[t.length-1];if(f&&a.set(f[0],Math.min(a.get(f[0]),a.get(r))),a.get(r)===i.get(r)){let e=[],t;do t=s.pop(),o.delete(t),e.push(t);while(t!==r);if(e.length>1||d.includes(r))for(let t of e)c.set(t,e)}}}return c}var Tu=class extends Error{constructor(e){super(`@aeye/schema: ${e}`),this.name=`SchemaDefinitionError`}},Eu=class extends Error{constructor(e,t=Kd(e)){super(t),this.issues=e,this.name=`SchemaParseError`}issues};function Du(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function Ou(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function ku(e,t,n=Ou(e.length)){let r=e.toLowerCase(),i=[];for(let a=0;a<t.length;a++){let o=t[a];if(Math.abs(o.length-e.length)>n)continue;let s=Du(r,o.toLowerCase());s<=n&&i.push({candidate:o,index:a,ci:s,exact:Du(e,o)})}return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function Au(e,t,n){return ku(e,t,n)[0]}var ju=Object.freeze({detail:`full`,maxErrors:5,maxChars:2e3,suggestions:!0,context:3,depth:6,header:!0});function Mu(...e){let t;for(let n of e)n!==void 0&&(t={...t,...Pu(typeof n==`string`?{detail:n}:n)});return t}function Nu(...e){let t=Mu(...e)??{},n=t.detail??ju.detail;return{...ju,...t,detail:n,expected:t.expected??n===`full`}}function Pu(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Fu(e){let t=typeof e==`string`?e:e?.detail??ju.detail;return t===`markers`||t===`full`}var Iu=new WeakMap;function Lu(e,t){Iu.set(e,t)}function Ru(e,t,n){for(let r=t;r<e.length;r++){let t=Iu.get(e[r]);t&&!t.node&&(t.node=n)}}var zu=/^[A-Za-z_$][\w$]*$/;function Bu(e){let t=``,n=``;for(let r of e)r===`(json)`?(t+=`${n||`(root)`} \u2192 JSON text \u2192 `,n=``):n+=typeof r==`number`?`[${r}]`:zu.test(r)?n?`.${r}`:r:`[${JSON.stringify(r)}]`;return t&&!n?t.slice(0,-3):t+(n||(t?``:`(root)`))}var Vu=Symbol(`absent`);function Hu(e,t){let n=e;for(let e of t)if(e===`(json)`){if(typeof n!=`string`)continue;if(n=Wu(n),n===Vu)return Vu}else{if(typeof n==`string`&&(n=Wu(n)),typeof n!=`object`||!n||!Object.prototype.hasOwnProperty.call(n,e))return Vu;n=n[e]}return n}var Uu;function Wu(e){let t=Uu?.get(e);if(t!==void 0)return t;let n;try{n=JSON.parse(e)}catch{n=Vu}return Uu?.set(e,n),n}function Gu(e,t=160){for(let n of[2,1,0]){let r=qu(e,n,6);if(r.length<=t)return r}let n=qu(e,0,3);return n.length<=t?n:`${n.slice(0,t-1)}\u2026`}function Ku(e){return e.replace(/^#\/\$defs\//,``).replace(/~1/g,`/`).replace(/~0/g,`~`)}function qu(e,t,n){if(typeof e.$ref==`string`)return Ku(e.$ref);if(`const`in e)return JSON.stringify(e.const);if(Array.isArray(e.enum))return Yu(e.enum.map(e=>JSON.stringify(e)),n,` | `);let r=e.anyOf??e.oneOf;if(Array.isArray(r))return Yu([...new Set(r.map(e=>qu(e,t,n)))],n,` | `,`options`);if(Array.isArray(e.allOf))return e.allOf.map(e=>Ju(qu(e,t,n))).join(` & `);if(Array.isArray(e.type))return e.type.map(r=>qu({...e,type:r},t,n)).join(` | `);if(e.nullable===!0)return`${Ju(qu({...e,nullable:!1},t,n))} | null`;switch(e.type){case`string`:if(typeof e.description==`string`&&/JSON text/.test(e.description)){let t=/TypeScript type: ([^\n(]+?)(?: \(its named types|\.\s*$)/.exec(e.description);return t?`string (JSON text of ${t[1].trim()})`:`string (JSON text)`}return typeof e.format==`string`?`string (${e.format})`:`string`;case`integer`:return`integer`;case`number`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:return Array.isArray(e.prefixItems)?`[${e.prefixItems.map(e=>qu(e,t-1,n)).join(`, `)}]`:`${Ju(e.items&&typeof e.items==`object`?qu(e.items,t-1,n):`any`)}[]`;case`object`:{let r=e.properties??{},i=Object.keys(r),a=e.additionalProperties&&typeof e.additionalProperties==`object`?e.additionalProperties:void 0;if(!i.length&&!a)return e.additionalProperties===!1?`{}`:`object`;if(t<=0)return`{…}`;let o=new Set(e.required??[]),s=i.slice(0,n).map(e=>`${zu.test(e)?e:JSON.stringify(e)}${o.has(e)?``:`?`}: ${qu(r[e],t-1,n)}`);return i.length>n&&s.push(`\u2026 ${i.length-n} more`),a&&s.push(`[key: string]: ${qu(a,t-1,n)}`),`{ ${s.join(`; `)} }`}default:return`any JSON value`}}function Ju(e){return/ \| | & /.test(e)&&!/^[{[(]/.test(e)?`(${e})`:e}function Yu(e,t,n,r=`more`){return e.length<=t?e.join(n):`${e.slice(0,t).join(n)}${n}\u2026 (${e.length} ${r===`more`?`values`:r})`}function Xu(e,t){let n=t?.node;if(n&&t&&t.kind!==`enum`&&t.kind!==`literal`&&t.kind!==`tag`&&t.kind!==`tool`&&t.kind!==`rule`&&t.kind!==`unknown-key`&&t.kind!==`not-allowed`)try{if(n.jsonText&&n.schema){let e=n.typeText();return`string (JSON text of ${e.length>120?`${e.slice(0,119)}\u2026`:e})`}let e=Gu(n.json());return t.kind===`type`&&/^(string|number|integer|boolean|null)$/.test(e)?void 0:e}catch{return}}function Zu(e){let t=e.message;for(let n of e.path)t+=`\0${typeof n==`number`?`#`:n}`;return t}function Qu(e){let t=[],n=new Map;for(let r of e){let e=Zu(r),i=n.get(e);if(i){i.paths.push(r.path);continue}let a={issue:r,info:Iu.get(r),paths:[r.path]};n.set(e,a),t.push(a)}return t}function $u(e,t){let n=e.issue.message,r=e.info?.kind;if(t.terse&&e.info?.candidates&&(r===`enum`||r===`tag`||r===`tool`)){let t=e.info.candidates().length;n=n.replace(/ one of: .*$/s,` one of ${t} value${t===1?``:`s`}.`)}if(t.suggestions&&e.info?.candidates){let t=ed(e.issue,e.info);t&&(n=n.replace(/\.$/,``)+t)}if(e.paths.length>1){if(t.terse)n+=` (the same at ${e.paths.length-1} more place${e.paths.length===2?``:`s`})`;else{let t=e.paths.slice(1,3).map(Bu),r=e.paths.length-1-t.length;n+=` (the same at ${t.join(`, `)}${r>0?` and ${r} more place${r===1?``:`s`}`:``})`}}return n.length>400?`${n.slice(0,399)}\u2026`:n}function ed(e,t){let n=t.candidates();if(!n.length)return``;if(t.kind===`required`){let t=e.path[e.path.length-1];if(typeof t!=`string`)return``;let r=Au(t,n);return r?` \u2014 you wrote \`${r}\`; did you mean \`${t}\`?`:``}let r=t.kind===`unknown-key`?e.path[e.path.length-1]:t.received;if(typeof r!=`string`)return``;let i=ku(r,n)[0];return i!==void 0&&i!==r?` \u2014 did you mean \`${i}\`?`:``}function td(e,t,n,r=`your answer`){if(!e.length)return``;let i=rd(n)?n:Nu(n),a=Qu(i.suggestions?nd(e):e),o=Uu;Uu=new Map;try{for(let e of id(i)){let n=od(a,t,e,r);if(n.length<=i.maxChars)return n}let e=od(a,t,{...i,detail:`summary`,maxErrors:1,terse:!0},r);return e.length<=i.maxChars?e:`${e.slice(0,Math.max(0,i.maxChars-1))}\u2026`}finally{Uu=o}}function nd(e){let t,n=0;for(let r of e){let e=Iu.get(r);if(e?.kind!==`required`||!e.candidates||++n>50)continue;let i=r.path[r.path.length-1],a=typeof i==`string`?Au(i,e.candidates()):void 0;a!==void 0&&(t??=new Set).add(sd([...r.path.slice(0,-1),a]))}return t?e.filter(e=>!(Iu.get(e)?.kind===`unknown-key`&&t.has(sd(e.path)))):e}function rd(e){return typeof e==`object`&&!!e&&`detail`in e&&`maxChars`in e&&`expected`in e&&`context`in e&&`depth`in e&&`header`in e&&`suggestions`in e&&`maxErrors`in e}function*id(e){for(let t of ad(e))yield t,yield{...t,terse:!0}}function*ad(e){let t=e;if(yield t,t.detail===`markers`||t.detail===`full`){for(t.expected&&(yield t={...t,expected:!1}),t.context>0&&(yield t={...t,context:0}),t.depth>2&&(yield t={...t,depth:2});t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};yield t={...t,detail:`list`,maxErrors:e.maxErrors}}for(;t.maxErrors>1;)yield t={...t,maxErrors:Math.max(1,Math.floor(t.maxErrors/2))};t.detail!==`summary`&&(yield{...t,detail:`summary`})}function od(e,t,n,r){let i=e.slice(0,Math.max(1,n.maxErrors)),a=e.reduce((e,t)=>e+t.paths.length,0),o=e.length-i.length,s=e.slice(i.length).reduce((e,t)=>e+t.paths.length,0),c=`${a} problem${a===1?``:`s`}`;if(n.detail===`summary`){let e=i[0],t=a-e.paths.length;return`${n.header?`${a===1?`A problem`:c} in ${r}: `:``}at ${Bu(e.issue.path)}: ${$u(e,n)}${t>0?` (and ${t} more problem${t===1?``:`s`})`:``}`}let l=[];if(n.header&&l.push(`${c} in ${r}:`),n.detail===`list`)for(let e of i){let t=n.expected?Xu(e.issue,e.info):void 0;l.push(`- at ${Bu(e.issue.path)}: ${$u(e,n)}${t?` (expected: ${t})`:``}`)}else n.header&&l.push(``),l.push(...dd(i,t,n));return s>0&&l.push(`\u2026 and ${s} more problem${s===1?``:`s`}${o>1?` (${o} kinds)`:``} not shown.`),l.join(`
|
|
56
|
+
`)}var sd=e=>{let t=``;for(let n of e)t+=`${typeof n==`number`?`#`:`$`}${n}\0`;return t};function cd(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n];if(r!==i)return typeof r==`number`&&typeof i==`number`?r-i:String(r)<String(i)?-1:1}return e.length-t.length}function ld(e,t){let n=[];for(let r=0;r<Math.min(e.length,t.length)&&e[r]===t[r];r++)n.push(e[r]);return n}var ud=e=>e.filter(e=>e!==`(json)`).length;function dd(e,t,n){let r=[],i=[];for(let n of e){let e=n.issue.path,a=n.info?.kind;t===void 0?i.push(n):Hu(t,e)===Vu?e.length&&fd(Hu(t,e.slice(0,-1)))?r.push({p:n,at:e.slice(0,-1),where:`missing`}):i.push(n):r.push({p:n,at:e,where:a===`unknown-key`||a===`not-allowed`?`key`:`value`})}r.sort((e,t)=>cd(e.p.issue.path,t.p.issue.path));let a=[],o=e=>{let t=[];for(let r of e){if(ud(e)-ud(t)<=n.depth)break;t.push(r)}return t};for(let e of r){let t=a[a.length-1];if(t){let r=ld(t.anchor,e.at);if([...t.members,e].every(e=>ud(e.at)-ud(r)<=n.depth+1)){t.anchor=r,t.members.push(e);continue}}a.push({anchor:o(e.at),members:[e]})}let s=[];for(let e of a){let r=e.anchor;for(;r.length&&Hu(t,r)===Vu;)r=r.slice(0,-1);let i=new Map,a=new Map;for(let t of e.members){let e=sd(t.at),n=i.get(e);n?n.push({p:t.p,where:t.where}):i.set(e,[{p:t.p,where:t.where}]);for(let e=r.length;e<t.at.length;e++){let n=sd(t.at.slice(0,e)),r=a.get(n);r?r.add(t.at[e]):a.set(n,new Set([t.at[e]]))}}s.length&&s.push(``),r.length&&s.push(`at ${Bu(r)}:`),new md(i,a,n,s,r.length).node(Hu(t,r),r,``,``,``)}for(let e of i)s.push(`- at ${Bu(e.issue.path)}: ${$u(e,n)}`);return s}var fd=e=>typeof e==`object`&&!!e;function pd(e){if(!e.length)return`…`;let t=e[0],n=Bu(e);return t===`(json)`?`\u2026 \u2192 ${n.replace(/^\(root\) → /,``)}`:typeof t==`number`||!zu.test(t)?`\u2026${n}`:`\u2026.${n}`}var md=class{constructor(e,t,n,r,i=0){this.marks=e,this.below=t,this.f=n,this.out=r,this.from=i}marks;below;f;out;from;node(e,t,n,r,i){let a=sd(t),o=this.below.has(a);if(typeof e==`string`&&o){let a=Wu(e);if(a!==Vu){let e=[...t,`(json)`],o=sd(e);return this.marks.has(o)||this.below.has(o)?this.node(a,e,n,`${r}/* JSON text */ `,i):this.node(a,t,n,r,i)}}let s=this.marks.get(a)??[];if(!(fd(e)&&(o||s.some(e=>e.where===`missing`)))){let t=hd(e,60);this.out.push(n+r+t+i);for(let e of s)e.where===`key`?this.mark(e.p,n.length,r.length+t.length):this.mark(e.p,n.length+r.length,t.length);return}let c=Array.isArray(e);this.out.push(`${n}${r}${c?`[`:`{`}`);for(let e of s)this.mark(e.p,n.length+r.length,1);let l=`${n} `;c?this.items(e,t,l):this.keys(e,t,l),this.out.push(`${n}${c?`]`:`}`}${i}`)}keys(e,t,n){let r=Object.keys(e),i=this.below.get(sd(t)),a=r.filter(e=>i?.has(e)),o=r.filter(e=>!a.includes(e)),s=new Set(o.filter(t=>hd(e[t],40).length<=40&&!fd(e[t])).slice(0,this.f.context));for(let e of o)s.size<this.f.context&&!s.has(e)&&s.add(e);let c=r.filter(e=>a.includes(e)||s.has(e)),l=r.length-c.length;c.forEach((r,i)=>{let a=i===c.length-1&&!l;this.node(e[r],[...t,r],n,`${JSON.stringify(r)}: `,a?``:`,`)}),l&&this.out.push(`${n}\u2026 ${l} more key${l===1?``:`s`}`)}items(e,t,n){let r=new Set;for(let n of this.below.get(sd(t))??[])typeof n==`number`&&n<e.length&&r.add(n);let i=e.length-r.size<=this.f.context&&e.every((e,t)=>r.has(t)||hd(e,40).length<=40),a=0,o=!1,s=()=>{a&&(this.out.push(`${n}\u2026 ${a} item${a===1?``:`s`}`),a=0,o=!0)};for(let c=0;c<e.length;c++){if(!i&&!r.has(c)){a++;continue}s();let l=c===e.length-1,u=o||!i&&c>0?`/* ${c} */ `:``;this.node(e[c],[...t,c],n,u,l?``:`,`)}s()}mark(e,t,n){let r=Math.max(1,Math.min(n,40)),i=`${this.from?pd(e.issue.path.slice(this.from)):Bu(e.issue.path)}: ${$u(e,this.f)}`;this.out.push(`${` `.repeat(t)}${`^`.repeat(r)} ${i}`);let a=this.f.expected?Xu(e.issue,e.info):void 0;a&&this.out.push(`${` `.repeat(t+r+1)}expected: ${a}`)}};function hd(e,t){if(typeof e==`string`){let n=JSON.stringify(e);return n.length<=t?n:`${n.slice(0,t-2)}\u2026"`}if(!fd(e))return e===void 0?`undefined`:JSON.stringify(e);let n=gd(e,t);if(n!==void 0)return n;if(Array.isArray(e))return`[\u2026 ${e.length} item${e.length===1?``:`s`}]`;let r=Object.keys(e).length;return`{\u2026 ${r} key${r===1?``:`s`}}`}function gd(e,t){let n=``,r=e=>{if(n.length>t)return!1;if(Array.isArray(e)){n+=`[`;for(let t=0;t<e.length;t++)if(t&&(n+=`,`),!r(e[t]))return!1;return n+=`]`,n.length<=t}if(fd(e)){n+=`{`;let i=!0;for(let t of Object.keys(e)){let a=e[t];if(a!==void 0&&(i||(n+=`,`),i=!1,n+=`${JSON.stringify(t)}:`,!r(a)))return!1}return n+=`}`,n.length<=t}return n+=e===void 0?`null`:JSON.stringify(e),n.length<=t};return r(e)?n:void 0}var _d=class{constructor(e){this.issues=e}issues};function vd(){return{objects:0,arrays:0,edits:0,parsed:0,repaired:0}}function yd(e){let t=``;for(let n of e)t+=typeof n==`number`?`[${n}]`:/^[A-Za-z_$][\w$]*$/.test(n)?t?`.${n}`:n:`[${JSON.stringify(n)}]`;return t||`(root)`}var bd=Object.freeze({path:[],codePath:[],message:``}),xd=vd(),Sd=Symbol(`absent`),Cd=Symbol(`order`),wd,Td=class e{constructor(e,t,n,r=!0,i=!1){this.inPlace=e,this.dry=t,this.stats=n,this.repair=r,this.countOnly=i}inPlace;dry;stats;repair;countOnly;errors=[];undo;undoN=0;wire=[];code=[];wd=0;cd=0;fail(e,t=`other`,n,r,i){if(this.countOnly){this.errors.push(bd);return}let a={path:this.wire.slice(0,this.wd),codePath:this.code.slice(0,this.cd),message:e};this.errors.push(a),Lu(a,{kind:t,node:i,received:n,candidates:r})}failAt(e,t,n=`rule`){if(!e.length)return this.fail(t,n);if(this.countOnly){this.errors.push(bd);return}let r={path:[...this.wire.slice(0,this.wd),...e],codePath:[...this.code.slice(0,this.cd),...e],message:t};this.errors.push(r),Lu(r,{kind:n})}enter(e,t=e){this.wire[this.wd++]=e,t!==null&&(this.code[this.cd++]=t)}leave(e=!0){this.wd--,e&&this.cd--}dryRun(t=!1){if(!t)return new e(!1,!0,xd,this.repair,!0);let n=new e(!1,!0,xd,this.repair);for(let e=0;e<this.wd;e++)n.wire[n.wd++]=this.wire[e];for(let e=0;e<this.cd;e++)n.code[n.cd++]=this.code[e];return n}saving(e,t,n=!1){let r=this.undo;if(!r)return;n&&this.ordered!==e&&(this.ordered=e,r[this.undoN++]=e,r[this.undoN++]=Cd,r[this.undoN++]=Object.keys(e));let i=Object.prototype.hasOwnProperty.call(e,t);r[this.undoN++]=e,r[this.undoN++]=t,r[this.undoN++]=i?e[t]:Sd}ordered;restore(){let e=this.undo;if(e)for(let t=this.undoN-3;t>=0;t-=3){let n=e[t],r=e[t+1],i=e[t+2];if(r===Cd)for(let e of i){let t=n[e];delete n[e],n[e]=t}else i===Sd?delete n[r]:n[r]=i}}keepUndo(){this.undo=wd??[],wd=void 0,this.undoN=0}releaseUndo(){let e=this.undo;if(e){for(let t=0;t<this.undoN;t++)e[t]=void 0;this.undo=void 0,this.undoN=0,e.length<=65536&&(wd=e)}}},Ed=class{constructor(e,t){this.impl=e,this.compiler=t}impl;compiler;needs=!1;schema;outer;jsonText=!1;_json;get own(){return!!this.impl?.own}get deps(){return this.impl?.deps??[]}json(){return this._json||=this.compiler.decorate(this,this.impl.emit()),this._json}run(e,t){let n=t.errors,r=n.length,i=this.impl.run(e,t);return n.length===r&&(this.schema?.checks.length&&this.check(i,t,this.schema),this.outer?.checks.length&&n.length===r&&this.check(i,t,this.outer),n.length===r)||t.countOnly||Ru(n,r,this),i}check(e,t,n){if(n)for(let r of n.checks){let n=r.fn(e);if(n!==!0){if(Array.isArray(n))for(let e of n)typeof e==`string`?t.fail(e,`rule`):t.failAt(e.path,e.message,`rule`);else t.fail(typeof n==`string`?n:r.message??`Failed a check.`,`rule`)}}}typeText(){return this.schema?this.schema.print(new Dd(this.compiler.env)):`any JSON value`}encode(e,t=vd()){return this.needs?this.impl.encode(e,t):e}child(e){return this.impl?.child?.(e)}},Dd=class{constructor(e){this.env=e}env;names=new Set;print(e){return e.print(this)}ref(e){return this.names.add(e),e}used(){return[...this.names]}definitions(e){for(let t of e)this.names.add(t);let t=[],n=new Set;for(let e=!0;e;){e=!1;for(let r of[...this.names]){if(n.has(r))continue;n.add(r),e=!0;let i=this.env.get(r);i&&t.push(`type ${r} = ${i.print(this)}`)}}return t.join(`
|
|
57
57
|
`)}full(e){let t=this.print(e),n=[],r=new Set;for(let e=!0;e;){e=!1;for(let t of[...this.names]){if(r.has(t))continue;r.add(t),e=!0;let i=this.env.get(t);i&&n.push(`type ${t} = ${i.print(this)}`)}}return n.length?`${t}
|
|
58
58
|
where
|
|
59
59
|
${n.join(`
|
|
60
|
-
`)}`:t}},
|
|
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
|
|
62
|
-
${
|
|
63
|
-
${new
|
|
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??=
|
|
65
|
-
`)}var Hd=class e{constructor(e={}){this.defs=e}defs;define(t){for(let e of Object.keys(t))if(e in this.defs)throw new bu(`"${e}" is already defined.`);return new e({...this.defs,...t})}declare(){return this}dynamic(e,t={}){return new Ud(this.defs,e,t)}result(e){return new Gd(this.defs,Wd(e))}},Ud=class{constructor(e,t,n){this.defs=e,this.fn=t,this.opts=n}defs;fn;opts;result(e){return new Gd(this.defs,Wd(e),{fn:this.fn,opts:this.opts})}};function Wd(e){return typeof e==`string`?new Of(e):e}var Gd=class e{constructor(e,t,n){this.defs=e,this.root=t,this.dyn=n}defs;root;dyn;cache=new Map;staticBound;bind=(...e)=>{let t=this.dyn;if(!t)return this.staticBound??=new Kd(new Map(Object.entries(this.defs)),this.root);let n=t.opts.key?.(...e);if(n!==void 0){let e=this.cache.get(n);if(e)return this.cache.delete(n),this.cache.set(n,e),e}let r=t.fn(...e),i=new Map(Object.entries(this.defs));for(let[e,t]of Object.entries(r)){if(i.has(e))throw new bu(`the dynamic step redefined "${e}".`);i.set(e,t)}let a=new Kd(i,this.root);if(n!==void 0){this.cache.set(n,a);let e=t.opts.cacheSize??4;for(;this.cache.size>e;)this.cache.delete(this.cache.keys().next().value)}return a};adapt(t){let n=this.dyn;if(!n)return this;let r=n.opts.key;return new e(this.defs,this.root,{fn:(...e)=>n.fn(...t(...e)),opts:{...n.opts,...r?{key:(...e)=>r(...t(...e))}:{}}})}render(e,...t){return this.bind(...t).render(e)}},Kd=class{constructor(e,t){this.env=e,this.root=t;let n=[],r=t=>{for(let r of t.refNames())!e.has(r)&&!n.includes(r)&&n.push(r)};r(t);for(let t of e.values())r(t);if(n.length)throw new bu(`unresolved ref(s) ${n.join(`, `)}.`)}env;root;rendered=new Map;render(e){let t=this.rendered.get(e.id);if(!t){let n=()=>this.render(Xl),r=new Fd(e,this.env,n),i;try{i=r.compile(this.root)}catch(t){if(!(t instanceof Pd))throw t;r=new Fd(e,this.env,n,!0),i=r.compile(this.root)}r.finish(),t=new zd(r,i),this.rendered.set(e.id,t)}return t}},qd=new WeakMap;function Jd(e){let t=qd.get(e);return t||qd.set(e,t=new Gd({},e)),t}var Yd=Object.freeze({}),Xd=Object.freeze([]),Zd=class{meta=Yd;checks=Xd;_refNames;refNames(){if(!this._refNames){let e=new Set;this instanceof Of&&e.add(this.name);for(let t of this.children())for(let n of t.refNames())e.add(n);if(this.meta.forModels)for(let t of this.meta.forModels.refNames())e.add(t);this._refNames=e}return this._refNames}with(e){let t=Object.create(Object.getPrototypeOf(this));return Object.assign(t,this,e,{_refNames:void 0}),t}describe(e){return this.with({meta:{...this.meta,description:e}})}title(e){return this.with({meta:{...this.meta,title:e}})}example(...e){return this.with({meta:{...this.meta,examples:[...this.meta.examples??[],...e]}})}refine(e,t,n){let r={fn:e,...t===void 0?{}:{message:t},visible:n?.visible??t!==void 0};return this.with({checks:[...this.checks,r]})}brand(){return this}forPeople(){return this.with({meta:{...this.meta,audience:`people`}})}forModels(e){return this.with({meta:{...this.meta,forModels:e}})}optional(){return new Ef(this)}nullable(){return new Df(this)}default(e){return new Tf(this,e)}bind(){return Jd(this).bind()}render(e){return Jd(this).bind().render(e)}ruleHint(){let e=this.checks.filter(e=>e.visible&&e.message).map(e=>e.message);return e.length?`Rules: ${e.join(` `)}`:void 0}hintOf(e){let t=[...e],n=this.ruleHint();return n&&t.push(n),t.length?t.join(` `):void 0}},Qd={"date-time":/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,date:/^\d{4}-\d{2}-\d{2}$/,time:/^\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,duration:/^-?P(?=\d|T\d)(\d+(\.\d+)?Y)?(\d+(\.\d+)?M)?(\d+(\.\d+)?W)?(\d+(\.\d+)?D)?(T(?=\d)(\d+(\.\d+)?H)?(\d+(\.\d+)?M)?(\d+(\.\d+)?S)?)?$/,email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,uuid:/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,uri:/^[a-zA-Z][a-zA-Z\d+.-]*:\S*$/,hostname:/^(?=.{1,253}$)[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,ipv4:/^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:{test:e=>e.includes(`:`)&&/^[0-9a-fA-F:.]+$/.test(e)&&$d(`[${e}]`)}};function $d(e){try{return new URL(`http://${e}/`),!0}catch{return!1}}function ef(e){if(/\(\?<?[=!]|\\[bB]|\\[pP]\{|\\[1-9]|\\k</.test(e))return!1;for(let t of e.matchAll(/\{(\d+)(?:,(\d*))?\}/g))if(Number(t[1])>100||Number(t[2]||0)>100)return!1;return!0}var tf=class extends Zd{constructor(e={}){super(),this.options=e}options;kind=`string`;children(){return[]}min(e){return this.opts({minLength:e})}max(e){return this.opts({maxLength:e})}pattern(e,t){let n=typeof e==`string`?t:t??(e.flags||void 0);return this.opts({pattern:typeof e==`string`?e:e.source,...n?{flags:n}:{}})}format(e){return this.opts({format:e})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`string`}compile(e){let t=this.options,n=e.profile,r=t.pattern===void 0?void 0:new RegExp(t.pattern,t.flags?.replace(/[gy]/g,``)),i=`/${t.pattern}/${t.flags??``}`,a=t.format===void 0?void 0:Qd[t.format],o=[];return e.node({hint:()=>this.hintOf(o),emit:()=>{let e={type:`string`};Kf(e,o,`minLength`,t.minLength,n.constraints.length,`At least ${t.minLength} characters.`),Kf(e,o,`maxLength`,t.maxLength,n.constraints.length,`At most ${t.maxLength} characters.`);let r=!t.flags&&(n.constraints.pattern===`full`||n.constraints.pattern===`basic`&&t.pattern!==void 0&&ef(t.pattern));return Kf(e,o,`pattern`,t.pattern,r,`Must match ${i}.`),Kf(e,o,`format`,t.format,n.formats===`all`||t.format!==void 0&&n.formats.has(t.format),`Format: ${t.format}.`),e},run:(e,n)=>typeof e==`string`?(t.minLength!==void 0&&e.length<t.minLength&&n.fail(`Must be at least ${t.minLength} characters.`,`rule`),t.maxLength!==void 0&&e.length>t.maxLength&&n.fail(`Must be at most ${t.maxLength} characters.`,`rule`),r&&!r.test(e)&&n.fail(`Must match ${i}.`,`rule`),a&&!a.test(e)&&n.fail(`Must be a valid ${t.format}.`,`rule`),e):Pf(n,e,`Expected a string, got ${jf(e)}.`),encode:e=>e})}},nf=class extends Zd{constructor(e={}){super(),this.options=e}options;kind=`number`;children(){return[]}min(e){return this.opts({minimum:e})}max(e){return this.opts({maximum:e})}gt(e){return this.opts({exclusiveMinimum:e})}lt(e){return this.opts({exclusiveMaximum:e})}positive(){return this.gt(0)}negative(){return this.lt(0)}nonnegative(){return this.min(0)}int(){return this.opts({int:!0})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`number`}compile(e){let t=this.options,n=e.profile.constraints.range,r=[];return e.node({hint:()=>this.hintOf(r),emit:()=>{let e={type:t.int?`integer`:`number`};return Kf(e,r,`minimum`,t.minimum,n,`At least ${t.minimum}.`),Kf(e,r,`maximum`,t.maximum,n,`At most ${t.maximum}.`),Kf(e,r,`exclusiveMinimum`,t.exclusiveMinimum,n,`Greater than ${t.exclusiveMinimum}.`),Kf(e,r,`exclusiveMaximum`,t.exclusiveMaximum,n,`Less than ${t.exclusiveMaximum}.`),e},run:(e,n)=>typeof e!=`number`||!Number.isFinite(e)?Pf(n,e,`Expected a number, got ${jf(e)}.`):(t.int&&!Number.isInteger(e)&&n.fail(`Expected a whole number.`,`type`),t.minimum!==void 0&&e<t.minimum&&n.fail(`Must be at least ${t.minimum}.`,`rule`),t.exclusiveMinimum!==void 0&&e<=t.exclusiveMinimum&&n.fail(`Must be greater than ${t.exclusiveMinimum}.`,`rule`),t.exclusiveMaximum!==void 0&&e>=t.exclusiveMaximum&&n.fail(`Must be less than ${t.exclusiveMaximum}.`,`rule`),t.maximum!==void 0&&e>t.maximum&&n.fail(`Must be at most ${t.maximum}.`,`rule`),e),encode:e=>e})}},rf=class extends Zd{kind=`boolean`;children(){return[]}print(){return`boolean`}compile(e){return e.node({hint:()=>this.ruleHint(),emit:()=>({type:`boolean`}),run:(e,t)=>typeof e==`boolean`?e:Pf(t,e,`Expected true or false, got ${jf(e)}.`),encode:e=>e})}},af=class extends Zd{kind=`null`;children(){return[]}print(){return`null`}compile(e){return e.node({emit:()=>({type:`null`}),run:(e,t)=>e===null?e:Pf(t,e,`Expected null, got ${jf(e)}.`),encode:e=>e})}},of=class extends Zd{constructor(e){super(),this.value=e}value;kind=`literal`;children(){return[]}print(){return JSON.stringify(this.value)}compile(e){let t=this.value;return e.node({hint:()=>this.ruleHint(),emit:()=>t===null?{type:`null`}:{type:Nf(t),enum:[t]},run:(e,n)=>e===t?e:Pf(n,e,`Expected ${JSON.stringify(t)}.`,`literal`,typeof t==`string`?()=>[t]:void 0),encode:e=>e})}},sf=class extends Zd{constructor(e){super(),this.values=e}values;kind=`enum`;children(){return[]}print(){return this.values.length?this.values.map(e=>JSON.stringify(e)).join(` | `):`never`}compile(e){let t=this.values;if(!t.length)return wf(e,()=>this.ruleHint());let n=new Set(t),r=e.profile.maxEnumValues,i=r!==void 0&&t.length>r;return e.node({hint:()=>this.hintOf(i?[`One of: ${t.join(`, `)}.`]:[]),emit:()=>i?{type:`string`}:{type:`string`,enum:[...t]},run:(e,r)=>typeof e!=`string`||!n.has(e)?Pf(r,e,`Expected one of: ${Ff(t)}.`,`enum`,()=>t):e,encode:e=>e})}},cf=class extends Zd{kind=`any`;children(){return[]}print(){return`any JSON value`}compile(e){let t=e.profile.any;return t===`empty`||t===`flat`?e.node({hint:()=>this.ruleHint(),emit:()=>t===`empty`?{}:{anyOf:uf.map(e=>({...e}))},run:(e,t)=>e===void 0?Pf(t,e,`Required.`,`required`):e,encode:e=>e}):lf(e.node({own:!0,hint:()=>this.hintOf([`Write the value as JSON text.`]),emit:()=>({type:`string`}),run:(e,t)=>{let n=Rd(e,t);return n===Ld?e:n},encode:e=>JSON.stringify(e)}))}};function lf(e){return e.jsonText=!0,e}var uf=Object.freeze([{type:`string`},{type:`number`},{type:`boolean`},{type:`null`},{type:`array`},{type:`object`,additionalProperties:!0}]),df=class extends Zd{constructor(e,t={}){super(),this.element=e,this.options=t}element;options;kind=`array`;children(){return[this.element]}min(e){return this.with({options:{...this.options,minItems:e}})}max(e){return this.with({options:{...this.options,maxItems:e}})}print(e){let t=e.print(this.element);return/[|&]/.test(t)?`(${t})[]`:`${t}[]`}compile(e){let t=Cf(this.element,e.env)?{...this.options,maxItems:0}:this.options,n=(t.minItems??0)>0?e.compile(this.element):e.guarded(this.element),r=e.profile.constraints.items,i=[];return e.node({deps:[n],hint:()=>this.hintOf(i),emit:()=>{let e={type:`array`,items:n.json()};return Kf(e,i,`minItems`,t.minItems,r===`all`||r===`min-0-1`&&(t.minItems??0)<=1,`At least ${t.minItems} items.`),Kf(e,i,`maxItems`,t.maxItems,r===`all`,`At most ${t.maxItems} items.`),e},run:(e,r)=>{let i=qf(e,r,`array`);if(!Array.isArray(i))return Pf(r,i,`Expected a list, got ${jf(i)}.`);t.minItems!==void 0&&i.length<t.minItems&&r.fail(`Must have at least ${t.minItems} items.`,`rule`),t.maxItems!==void 0&&i.length>t.maxItems&&r.fail(`Must have at most ${t.maxItems} items.`,`rule`);let a=i;for(let e=0;e<i.length;e++){r.enter(e);let t=n.run(i[e],r);r.leave(),t!==i[e]&&!r.dry&&(a=Zf(a,i,e,t,r))}return a},encode:(e,t)=>Jf(e,e=>n.encode(e,t),t),child:()=>n})}},ff=class extends Zd{constructor(e){super(),this.items=e}items;kind=`tuple`;children(){return this.items}print(e){return`[${this.items.map(t=>e.print(t)).join(`, `)}]`}compile(e){let t=this.items.map(t=>e.compile(t)),n=e.profile.tuples,r=t.length,i=(e,n,i)=>{let a=e;for(let o=0;o<r;o++){n.enter(i(o),o);let r=t[o].run(e[o],n);n.leave(),r!==e[o]&&!n.dry&&(a=Zf(a,e,o,r,n))}return a};return e.node({own:n===`object`,deps:t,hint:()=>this.hintOf(n===`object`?[`Positions are written as keys "0".."${r-1}".`]:n===`array`?[`Exactly ${r} items, in order: ${this.items.map(t=>t.print(new Sd(e.env))).join(`, `)}.`]:[]),emit:()=>{if(n===`object`){let n={};return t.forEach((e,t)=>n[String(t)]=e.json()),e.object(n,Object.keys(n))}return n===`prefixItems`?{type:`array`,prefixItems:t.map(e=>e.json()),minItems:r,maxItems:r}:{type:`array`,items:{anyOf:t.map(e=>e.json())}}},run:(e,t)=>{if(n===`object`){let n=qf(e,t,`object`);if(!Af(n))return Pf(t,n,`Expected an object with keys "0".."`+(r-1)+`".`);let a=Array(r);for(let e=0;e<r;e++)a[e]=n[String(e)];t.dry||t.stats.arrays++;let o=i(a,t,e=>String(e));return t.dry?n:o}let a=qf(e,t,`array`);return Array.isArray(a)?(a.length!==r&&t.fail(`Expected exactly ${r} items.`,`rule`),i(a,t,e=>e)):Pf(t,a,`Expected a list of ${r} items.`)},encode:(e,r)=>{let i=e;if(n!==`object`)return Jf(i,(e,n)=>t[n].encode(e,r),r);let a={};return r.objects++,i.forEach((e,n)=>a[String(n)]=t[n].encode(e,r)),a},child:e=>t[Number(e)]})}},pf=class e extends Zd{constructor(e,t=!1,n={}){super(),this.shape=e,this.closed=t,this.extras=n}shape;closed;extras;kind=`object`;children(){let e=Object.values(this.shape);this.extras.rest&&e.push(this.extras.rest);for(let t of this.extras.patterns??[])e.push(t.schema);return e}strict(){return this.with({closed:!0})}extend(t){return new e({...this.shape,...t},this.closed,this.extras)}rest(t){return new e(this.shape,this.closed,{...this.extras,rest:t})}patterns(t){let n=Object.entries(t).map(([e,t])=>({pattern:e,schema:t}));return new e(this.shape,this.closed,{...this.extras,patterns:[...this.extras.patterns??[],...n]})}dependent(t,n,r,i){let a=new bf(n,r,i??new cf);return new e({...this.shape,[t]:a},this.closed,this.extras)}print(e){let t=Object.entries(this.shape).map(([t,n])=>{let r=n instanceof Ef||n instanceof Tf;return`${/^[A-Za-z_$][\w$]*$/.test(t)?t:JSON.stringify(t)}${r?`?`:``}: ${e.print(r?n.inner:n)}`}),n=this.extraValue();return n&&t.push(`[key: string]: ${e.print(n)}`),`{ ${t.join(`; `)} }`}_extraValue;extraValue(){if(this._extraValue===void 0){let e=[...(this.extras.patterns??[]).map(e=>e.schema),...this.extras.rest?[this.extras.rest]:[]];this._extraValue=e.length===0?null:e.length===1?e[0]:new gf(e)}return this._extraValue??void 0}compile(e){let t=e.profile,n=t.optional===`null`,r=t.audience!==`people`,i=[],a=new Set;for(let[t,n]of Object.entries(this.shape)){let o=r?n.meta.forModels:void 0,s=o?o.meta.description===void 0&&n.meta.description!==void 0?o.describe(n.meta.description):o:n;if(r&&n.meta.audience===`people`){a.add(t);continue}let c=s instanceof Tf?s:void 0,l=s instanceof Ef||!!c,u=s instanceof Ef?s.inner:c?c.inner:s;if(l&&Cf(u,e.env)){a.add(t);continue}let d=l?e.guarded(u,s):e.compile(u);i.push({key:t,optional:l,node:d,nullable:u instanceof Df,...u instanceof bf?{dep:u}:{},...c?{dflt:c}:{}})}let o=i.filter(e=>!e.dep),s=i.filter(e=>e.dep),c=new Set(Object.keys(this.shape)),l=this.extraValue(),u=(this.extras.patterns??[]).map(t=>({re:new RegExp(t.pattern),pattern:t.pattern,node:e.guarded(t.schema)})),d=this.extras.rest?e.guarded(this.extras.rest):void 0,f=l?t.records===`pairs`?`pairs`:t.patternProperties?`keywords`:`open`:`none`,p=f===`pairs`?c.has(`extra`)?`_extra`:`extra`:``,m=l&&f!==`keywords`?e.guarded(l):void 0,h=e=>u.find(t=>t.re.test(e))?.node??d;return e.node({own:n&&i.some(e=>e.optional&&!e.nullable)||a.size>0||f===`pairs`||i.some(e=>e.dflt),deps:[...i.map(e=>e.node),...u.map(e=>e.node),...d?[d]:[],...m?[m]:[]],hint:()=>this.hintOf(f===`pairs`?[`Other keys go in "${p}" as a list of {key, value} entries.`]:f===`open`&&u.length?[`Other keys: ${u.map(t=>`keys matching /${t.pattern}/ hold ${t.node.schema?.print(new Sd(e.env))??`a value`}`).join(`; `)}${d?`; any other key holds the rest`:``}.`]:[]),emit:()=>{let r={},a=[];for(let t of i){let i=t.node.json();t.dep&&(i={...i,description:[i.description,`Its type is given by "${t.dep.on}".`].filter(Boolean).join(`
|
|
60
|
+
`)}`:t}},Od=new Set([`object`,`array`,`record`,`tuple`]),kd=new WeakMap;function Ad(e){let t=kd.get(e);return t===void 0&&(t=e.kind===`dependent`||e.children().some(Ad),kd.set(e,t)),t}var jd=new WeakMap;function Md(e){let t=jd.get(e);return t===void 0&&(t=+!!Od.has(e.kind)+Math.max(0,...e.children().map(Md)),jd.set(e,t)),t}var Nd=new WeakMap,Pd=new WeakMap;function Fd(e){let t=Pd.get(e);return t||Pd.set(e,t=new Bd(e,Id,Rd,!1,!0)),t}var Id=new Map,Ld;function Rd(){if(!Ld){let e=Fd($l);Ld=new Wd(e,e.node({emit:()=>({}),run:e=>e,encode:e=>e}))}return Ld}var zd=class extends Error{},Bd=class{constructor(e,t,n,r=!1,i=!1){this.profile=e,this.env=t,this.lenient=n,this.inlineOnce=r,this.shared=i,this.view=Su(e)}profile;env;lenient;inlineOnce;shared;nodes=[];defs=new Map;glossary=new Set;inlined=new Set;recursive=new Map;view;stack=[];depth=0;guard=0;isRecursive(e){let t=this.recursive.get(e);if(t===void 0){let n=new Set,r=[...this.env.get(e)?.refNames()??[]];for(t=!1;r.length;){let i=r.pop();if(i===e){t=!0;break}n.has(i)||(n.add(i),r.push(...this.env.get(i)?.refNames()??[]))}this.recursive.set(e,t)}return t}node(e){return new Ed(e,this)}compile(e,t){if(this.profile.audience!==`people`&&e.meta.forModels){let{forModels:t,...n}=e.meta,r=t;e=r.meta.description===void 0&&n.description!==void 0?r.describe(n.description):r}let n=Od.has(e.kind);if(n&&this.profile.maxDepth!==void 0&&this.depth>=this.profile.maxDepth)return this.escape(e,`Nested too deep for this model to describe directly.`);let r=!t&&e.refNames().size===0&&!Ad(e)&&(this.profile.maxDepth===void 0||this.depth+Md(e)<this.profile.maxDepth);if(r){let t=Nd.get(e)?.get(this.profile.id);if(t)return t;if(!this.shared){let t=Fd(this.profile),n=t.compile(e);return t.finish(),n}}n&&this.depth++;let i=e.compile(this);if(n&&this.depth--,i.schema=e,i.outer=t,this.nodes.push(i),r){let t=Nd.get(e);t||Nd.set(e,t=new Map),t.set(this.profile.id,i)}return i}guarded(e,t){this.guard++;try{return this.compile(e,t)}finally{this.guard--}}ref(e){let t=this.env.get(e);if(!t)throw new Tu(`ref "${e}" is not defined (the chain's types should have prevented this).`);let n=this.profile,r=this.stack.find(t=>t.name===e);if(r)return n.defs&&(n.recursion===!0||n.recursion===`guarded`&&this.guard>r.guard)?this.defRef(e,this.defs.get(e)):this.escape(t,`"${e}" contains itself, which this model cannot describe directly.`,e);if(n.defs){let n=this.defs.get(e);if(n)return this.defRef(e,n);let r=new Vd(this);return this.defs.set(e,r),this.stack.push({name:e,guard:this.guard}),r.target=this.compile(t),this.stack.pop(),this.nodes.push(r),this.defRef(e,r)}if(this.inlineOnce&&this.isRecursive(e)){if(this.inlined.has(e))return this.escape(t,`"${e}" is written out once elsewhere in this schema.`,e);this.inlined.add(e)}else if(!this.inlineOnce&&this.nodes.length>4e3)throw new zd;this.stack.push({name:e,guard:this.guard});let i=this.compile(t);return this.stack.pop(),i}defRef(e,t){let n=this.node({deps:[t],emit:()=>({$ref:`#/$defs/${e.replace(/~/g,`~0`).replace(/\//g,`~1`)}`}),run:(e,n)=>t.run(e,n),encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)});return this.nodes.push(n),n.refName=e,n}escape(e,t,n){let r=new Dd(this.env),i=n??r.print(e);for(let e of n?[n]:r.used())this.glossary.add(e);let a=n||r.used().length?` (its named types are defined in the description of the whole schema)`:``,o,s=()=>o??=this.lenient().nodeFor(e),c=this.node({own:!0,emit:()=>({type:`string`,description:`${t} Write it as JSON text of this TypeScript type: ${i}${a}.`}),run:(e,t)=>{let n=Ud(e,t);if(n===Hd)return e;t.enter(`(json)`,null);let r=s().run(n,t);return t.leave(!1),r},encode:e=>JSON.stringify(e)});return c.jsonText=!0,this.nodes.push(c),c}late(e){let t=this.compile(e);return this.finish(),t}finish(){for(let e=!0;e;){e=!1;for(let t of this.nodes)t.needs||(t.own||t.deps.some(e=>e.needs))&&(t.needs=!0,e=!0)}this.shared&&(this.nodes.length=0)}text(e){return e===void 0?void 0:typeof e==`function`?e(this.view):e}nullable(e){let t=this.profile.nulls;if(e.nullable===!0||Array.isArray(e.type)&&e.type.includes(`null`)||e.type===`null`)return e;if(t===`nullable`)return{...e,nullable:!0};if(t===`type-array`&&typeof e.type==`string`&&!(`$ref`in e)&&!(`anyOf`in e)){let t={...e,type:[e.type,`null`]};return Array.isArray(e.enum)&&(t.enum=[...e.enum,null]),t}if(Array.isArray(e.anyOf)&&!(`$ref`in e))return e.anyOf.some(e=>e.type===`null`)?e:{...e,anyOf:[...e.anyOf,{type:`null`}]};let{description:n,...r}=e;return n===void 0?{anyOf:[r,{type:`null`}]}:{anyOf:[r,{type:`null`}],description:n}}object(e,t,n=this.profile.closedObjects){let r={type:`object`,properties:e,required:[...t]};return n&&(r.additionalProperties=!1),this.profile.propertyOrdering&&(r.propertyOrdering=Object.keys(e)),r}decorate(e,t){let n=[],r=[e.schema?.meta,e.outer?.meta],i,a=[];for(let t of r){if(!t)continue;let r=this.text(t.description);if(r&&n.push(r),t.title&&(i=t.title),t.examples)for(let n of t.examples)this.checkExample(e,n),a.push(e.encode(n))}let o=e.impl?.hint?.(this.view);o&&n.push(o);let s=typeof t.description==`string`?t.description:void 0;s&&n.push(s);let c={...t};if(i&&(c.title=i),a.length&&(this.profile.examples===`keyword`?c.examples=a:this.profile.examples===`description`&&n.push(`Example${a.length>1?`s`:``}: ${a.map(e=>JSON.stringify(e)).join(` ; `)}`)),n.length&&(c.description=n.join(`
|
|
61
|
+
`)),this.profile.refSiblings===!1&&typeof c.$ref==`string`&&(c.description!==void 0||c.title!==void 0||c.examples!==void 0)){let{$ref:e,...t}=c;return{anyOf:[{$ref:e}],...t}}return c}checkExample(e,t){let n=e.schema;if(!n)return;let r=new Td(!1,!0,vd(),!1);if(this.lenient().nodeFor(n).run(t,r),r.errors.length)throw new Tu(`example ${JSON.stringify(t)} does not fit its schema:
|
|
62
|
+
${Kd(r.errors)}`)}},Vd=class extends Ed{target;constructor(e){super(void 0,e)}get own(){return!1}get deps(){return this.target?[this.target]:[]}json(){return this.target.json()}run(e,t){return this.target.run(e,t)}encode(e,t=vd()){return this.target.encode(e,t)}child(e){return this.target.child(e)}},Hd=Symbol(`failed`);function Ud(e,t){if(typeof e!=`string`)return t.repair&&e!==void 0?(t.dry||t.stats.repaired++,e):(t.fail(`Expected a string of JSON text.`,`type`),Hd);try{let n=JSON.parse(e);return t.dry||t.stats.parsed++,n}catch(e){return t.fail(`Not valid JSON text: ${e.message}`,`json`),Hd}}var Wd=class{constructor(e,t){this.compiler=e,this.root=t}compiler;root;_json;_body;_wrapped;_measure;_encoder;get profile(){return this.compiler.profile}body(){if(!this._body){let e=this.root.refName;this._body=e?this.compiler.defs.get(e).json():this.root.json()}return this._body}get wrapped(){if(this._wrapped===void 0){let e=this.body();this._wrapped=this.profile.rootObject&&!(e.type===`object`&&!(`anyOf`in e))}return this._wrapped}get jsonSchema(){if(this._json)return this._json;let e=this.body();if(this.wrapped&&(e=this.compiler.object({input:e},[`input`],this.profile.closedObjects||this.profile.strict)),this.compiler.glossary.size){let t=`Named types used by the fields written as JSON text:
|
|
63
|
+
${new Dd(this.compiler.env).definitions(this.compiler.glossary)}`;e={...e,description:typeof e.description==`string`?`${e.description}
|
|
64
|
+
${t}`:t}}let t={};for(let[e,n]of this.compiler.defs)t[e]=n.json();return this._json=this.compiler.defs.size?{...e,$defs:t}:e,this._json}get measure(){return this._measure??=Cu(this.jsonSchema)}parse(e,t){return this.decode(e,t,void 0)}decode(e,t,n){let r=vd(),i=t?.inPlace??!0,a=new Td(i,!1,r,t?.repair??!0),o=i&&!n&&Fu(t?.errorFormat);o&&a.keepUndo();let s;if(this.wrapped?typeof e!=`object`||!e||Array.isArray(e)||!(`input`in e)?a.fail(`Expected an object with an "input" field.`,`type`):(a.enter(`input`,null),s=this.root.run(e.input,a),a.leave(!1)):s=this.root.run(e,a),a.errors.length){a.restore(),a.releaseUndo();let i=n?n():e;return{ok:!1,issues:a.errors,message:td(a.errors,i,Nu(t?.errorFormat),t?.label),stats:r}}return o&&a.releaseUndo(),{ok:!0,value:s,stats:r}}parseText(e,t){let n;try{n=JSON.parse(e)}catch(e){let n=[{path:[],codePath:[],message:`Not valid JSON: ${e.message}`}];return Lu(n[0],{kind:`json`}),{ok:!1,issues:n,message:td(n,void 0,Nu(t?.errorFormat),t?.label),stats:vd()}}return this.decode(n,t,()=>JSON.parse(e))}parseOrThrow(e,t){let n=this.parse(e,t);if(!n.ok)throw new Eu(n.issues,n.message);return n.value}encode(e,t=vd()){let n=this.root.encode(e,t);return this.wrapped?(t.objects++,{input:n}):n}encodeAt(e,t,n=vd()){let r=Gd(t);if(!r.length)return this.encode(e,n);let i=this.root;for(let e of r)if(i=i?.child(e),!i)throw new Tu(`no schema at path ${yd(r)}.`);return i.encode(e,n)}encodeText(e,t={}){let n=t.path===void 0?this.encode(e):this.encodeAt(e,t.path),r=t.pretty===!0?2:typeof t.pretty==`number`?t.pretty:void 0;return JSON.stringify(n,null,r)}get encoder(){if(!this._encoder){let e=((e,t)=>this.encodeText(e,t));e.wire=(e,t)=>t===void 0?this.encode(e):this.encodeAt(e,t),this._encoder=Object.freeze(e)}return this._encoder}nodeFor(e){let t=this.lateNodes.get(e);return t||this.lateNodes.set(e,t=this.compiler.late(e)),t}lateNodes=new WeakMap;typescript(){let e=this.root.schema;return new Dd(this.compiler.env).full(e)}};function Gd(e){return e===void 0||e===``?[]:typeof e==`string`?e.split(`.`).map(e=>/^\d+$/.test(e)?Number(e):e):[...e]}function Kd(e){return e.map(e=>`- at ${yd(e.path)}: ${e.message}`).join(`
|
|
65
|
+
`)}var qd=class e{constructor(e={}){this.defs=e}defs;define(t){for(let e of Object.keys(t))if(e in this.defs)throw new Tu(`"${e}" is already defined.`);return new e({...this.defs,...t})}declare(){return this}dynamic(e,t={}){return new Jd(this.defs,e,t)}result(e){return new Xd(this.defs,Yd(e))}},Jd=class{constructor(e,t,n){this.defs=e,this.fn=t,this.opts=n}defs;fn;opts;result(e){return new Xd(this.defs,Yd(e),{fn:this.fn,opts:this.opts})}};function Yd(e){return typeof e==`string`?new Nf(e):e}var Xd=class e{constructor(e,t,n){this.defs=e,this.root=t,this.dyn=n}defs;root;dyn;cache=new Map;staticBound;bind=(...e)=>{let t=this.dyn;if(!t)return this.staticBound??=new Zd(new Map(Object.entries(this.defs)),this.root);let n=t.opts.key?.(...e);if(n!==void 0){let e=this.cache.get(n);if(e)return this.cache.delete(n),this.cache.set(n,e),e}let r=t.fn(...e),i=new Map(Object.entries(this.defs));for(let[e,t]of Object.entries(r)){if(i.has(e))throw new Tu(`the dynamic step redefined "${e}".`);i.set(e,t)}let a=new Zd(i,this.root);if(n!==void 0){this.cache.set(n,a);let e=t.opts.cacheSize??4;for(;this.cache.size>e;)this.cache.delete(this.cache.keys().next().value)}return a};adapt(t){let n=this.dyn;if(!n)return this;let r=n.opts.key;return new e(this.defs,this.root,{fn:(...e)=>n.fn(...t(...e)),opts:{...n.opts,...r?{key:(...e)=>r(...t(...e))}:{}}})}render(e,...t){return this.bind(...t).render(e)}},Zd=class{constructor(e,t){this.env=e,this.root=t;let n=[],r=t=>{for(let r of t.refNames())!e.has(r)&&!n.includes(r)&&n.push(r)};r(t);for(let t of e.values())r(t);if(n.length)throw new Tu(`unresolved ref(s) ${n.join(`, `)}.`)}env;root;rendered=new Map;render(e){let t=this.rendered.get(e.id);if(!t){let n=()=>this.render($l),r=new Bd(e,this.env,n),i;try{i=r.compile(this.root)}catch(t){if(!(t instanceof zd))throw t;r=new Bd(e,this.env,n,!0),i=r.compile(this.root)}r.finish(),t=new Wd(r,i),this.rendered.set(e.id,t)}return t}},Qd=new WeakMap;function $d(e){let t=Qd.get(e);return t||Qd.set(e,t=new Xd({},e)),t}var ef=Object.freeze({}),tf=Object.freeze([]),nf=class{meta=ef;checks=tf;_refNames;refNames(){if(!this._refNames){let e=new Set;this instanceof Nf&&e.add(this.name);for(let t of this.children())for(let n of t.refNames())e.add(n);if(this.meta.forModels)for(let t of this.meta.forModels.refNames())e.add(t);this._refNames=e}return this._refNames}with(e){let t=Object.create(Object.getPrototypeOf(this));return Object.assign(t,this,e,{_refNames:void 0}),t}describe(e){return this.with({meta:{...this.meta,description:e}})}title(e){return this.with({meta:{...this.meta,title:e}})}example(...e){return this.with({meta:{...this.meta,examples:[...this.meta.examples??[],...e]}})}refine(e,t,n){let r={fn:e,...t===void 0?{}:{message:t},visible:n?.visible??t!==void 0};return this.with({checks:[...this.checks,r]})}brand(){return this}forPeople(){return this.with({meta:{...this.meta,audience:`people`}})}forModels(e){return this.with({meta:{...this.meta,forModels:e}})}optional(){return new jf(this)}nullable(){return new Mf(this)}default(e){return new Af(this,e)}bind(){return $d(this).bind()}render(e){return $d(this).bind().render(e)}ruleHint(){let e=this.checks.filter(e=>e.visible&&e.message).map(e=>e.message);return e.length?`Rules: ${e.join(` `)}`:void 0}hintOf(e){let t=[...e],n=this.ruleHint();return n&&t.push(n),t.length?t.join(` `):void 0}},rf={"date-time":/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,date:/^\d{4}-\d{2}-\d{2}$/,time:/^\d{2}:\d{2}(:\d{2}(\.\d+)?)?([Zz]|[+-]\d{2}:?\d{2})?$/,duration:/^-?P(?=\d|T\d)(\d+(\.\d+)?Y)?(\d+(\.\d+)?M)?(\d+(\.\d+)?W)?(\d+(\.\d+)?D)?(T(?=\d)(\d+(\.\d+)?H)?(\d+(\.\d+)?M)?(\d+(\.\d+)?S)?)?$/,email:/^[^\s@]+@[^\s@]+\.[^\s@]+$/,uuid:/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,uri:/^[a-zA-Z][a-zA-Z\d+.-]*:\S*$/,hostname:/^(?=.{1,253}$)[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,ipv4:/^((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:{test:e=>e.includes(`:`)&&/^[0-9a-fA-F:.]+$/.test(e)&&af(`[${e}]`)}};function af(e){try{return new URL(`http://${e}/`),!0}catch{return!1}}function of(e){if(/\(\?<?[=!]|\\[bB]|\\[pP]\{|\\[1-9]|\\k</.test(e))return!1;for(let t of e.matchAll(/\{(\d+)(?:,(\d*))?\}/g))if(Number(t[1])>100||Number(t[2]||0)>100)return!1;return!0}var sf=class extends nf{constructor(e={}){super(),this.options=e}options;kind=`string`;children(){return[]}min(e){return this.opts({minLength:e})}max(e){return this.opts({maxLength:e})}pattern(e,t){let n=typeof e==`string`?t:t??(e.flags||void 0);return this.opts({pattern:typeof e==`string`?e:e.source,...n?{flags:n}:{}})}format(e){return this.opts({format:e})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`string`}compile(e){let t=this.options,n=e.profile,r=t.pattern===void 0?void 0:new RegExp(t.pattern,t.flags?.replace(/[gy]/g,``)),i=`/${t.pattern}/${t.flags??``}`,a=t.format===void 0?void 0:rf[t.format],o=[];return e.node({hint:()=>this.hintOf(o),emit:()=>{let e={type:`string`};Zf(e,o,`minLength`,t.minLength,n.constraints.length,`At least ${t.minLength} characters.`),Zf(e,o,`maxLength`,t.maxLength,n.constraints.length,`At most ${t.maxLength} characters.`);let r=!t.flags&&(n.constraints.pattern===`full`||n.constraints.pattern===`basic`&&t.pattern!==void 0&&of(t.pattern));return Zf(e,o,`pattern`,t.pattern,r,`Must match ${i}.`),Zf(e,o,`format`,t.format,n.formats===`all`||t.format!==void 0&&n.formats.has(t.format),`Format: ${t.format}.`),e},run:(e,n)=>typeof e==`string`?(t.minLength!==void 0&&e.length<t.minLength&&n.fail(`Must be at least ${t.minLength} characters.`,`rule`),t.maxLength!==void 0&&e.length>t.maxLength&&n.fail(`Must be at most ${t.maxLength} characters.`,`rule`),r&&!r.test(e)&&n.fail(`Must match ${i}.`,`rule`),a&&!a.test(e)&&n.fail(`Must be a valid ${t.format}.`,`rule`),e):zf(n,e,`Expected a string, got ${If(e)}.`),encode:e=>e})}},cf=class extends nf{constructor(e={}){super(),this.options=e}options;kind=`number`;children(){return[]}min(e){return this.opts({minimum:e})}max(e){return this.opts({maximum:e})}gt(e){return this.opts({exclusiveMinimum:e})}lt(e){return this.opts({exclusiveMaximum:e})}positive(){return this.gt(0)}negative(){return this.lt(0)}nonnegative(){return this.min(0)}int(){return this.opts({int:!0})}opts(e){return this.with({options:{...this.options,...e}})}print(){return`number`}compile(e){let t=this.options,n=e.profile.constraints.range,r=[];return e.node({hint:()=>this.hintOf(r),emit:()=>{let e={type:t.int?`integer`:`number`};return Zf(e,r,`minimum`,t.minimum,n,`At least ${t.minimum}.`),Zf(e,r,`maximum`,t.maximum,n,`At most ${t.maximum}.`),Zf(e,r,`exclusiveMinimum`,t.exclusiveMinimum,n,`Greater than ${t.exclusiveMinimum}.`),Zf(e,r,`exclusiveMaximum`,t.exclusiveMaximum,n,`Less than ${t.exclusiveMaximum}.`),e},run:(e,n)=>typeof e!=`number`||!Number.isFinite(e)?zf(n,e,`Expected a number, got ${If(e)}.`):(t.int&&!Number.isInteger(e)&&n.fail(`Expected a whole number.`,`type`),t.minimum!==void 0&&e<t.minimum&&n.fail(`Must be at least ${t.minimum}.`,`rule`),t.exclusiveMinimum!==void 0&&e<=t.exclusiveMinimum&&n.fail(`Must be greater than ${t.exclusiveMinimum}.`,`rule`),t.exclusiveMaximum!==void 0&&e>=t.exclusiveMaximum&&n.fail(`Must be less than ${t.exclusiveMaximum}.`,`rule`),t.maximum!==void 0&&e>t.maximum&&n.fail(`Must be at most ${t.maximum}.`,`rule`),e),encode:e=>e})}},lf=class extends nf{kind=`boolean`;children(){return[]}print(){return`boolean`}compile(e){return e.node({hint:()=>this.ruleHint(),emit:()=>({type:`boolean`}),run:(e,t)=>typeof e==`boolean`?e:zf(t,e,`Expected true or false, got ${If(e)}.`),encode:e=>e})}},uf=class extends nf{kind=`null`;children(){return[]}print(){return`null`}compile(e){return e.node({emit:()=>({type:`null`}),run:(e,t)=>e===null?e:zf(t,e,`Expected null, got ${If(e)}.`),encode:e=>e})}},df=class extends nf{constructor(e){super(),this.value=e}value;kind=`literal`;children(){return[]}print(){return JSON.stringify(this.value)}compile(e){let t=this.value;return e.node({hint:()=>this.ruleHint(),emit:()=>t===null?{type:`null`}:{type:Rf(t),enum:[t]},run:(e,n)=>e===t?e:zf(n,e,`Expected ${JSON.stringify(t)}.`,`literal`,typeof t==`string`?()=>[t]:void 0),encode:e=>e})}},ff=class extends nf{constructor(e){super(),this.values=e}values;kind=`enum`;children(){return[]}print(){return this.values.length?this.values.map(e=>JSON.stringify(e)).join(` | `):`never`}compile(e){let t=this.values;if(!t.length)return kf(e,()=>this.ruleHint());let n=new Set(t),r=e.profile.maxEnumValues,i=r!==void 0&&t.length>r;return e.node({hint:()=>this.hintOf(i?[`One of: ${t.join(`, `)}.`]:[]),emit:()=>i?{type:`string`}:{type:`string`,enum:[...t]},run:(e,r)=>typeof e!=`string`||!n.has(e)?zf(r,e,`Expected one of: ${Bf(t)}.`,`enum`,()=>t):e,encode:e=>e})}},pf=class extends nf{kind=`any`;children(){return[]}print(){return`any JSON value`}compile(e){let t=e.profile.any;return t===`empty`||t===`flat`?e.node({hint:()=>this.ruleHint(),emit:()=>t===`empty`?{}:{anyOf:hf.map(e=>({...e}))},run:(e,t)=>e===void 0?zf(t,e,`Required.`,`required`):e,encode:e=>e}):mf(e.node({own:!0,hint:()=>this.hintOf([`Write the value as JSON text.`]),emit:()=>({type:`string`}),run:(e,t)=>{let n=Ud(e,t);return n===Hd?e:n},encode:e=>JSON.stringify(e)}))}};function mf(e){return e.jsonText=!0,e}var hf=Object.freeze([{type:`string`},{type:`number`},{type:`boolean`},{type:`null`},{type:`array`},{type:`object`,additionalProperties:!0}]),gf=class extends nf{constructor(e,t={}){super(),this.element=e,this.options=t}element;options;kind=`array`;children(){return[this.element]}min(e){return this.with({options:{...this.options,minItems:e}})}max(e){return this.with({options:{...this.options,maxItems:e}})}print(e){let t=e.print(this.element);return/[|&]/.test(t)?`(${t})[]`:`${t}[]`}compile(e){let t=Of(this.element,e.env)?{...this.options,maxItems:0}:this.options,n=(t.minItems??0)>0?e.compile(this.element):e.guarded(this.element),r=e.profile.constraints.items,i=[];return e.node({deps:[n],hint:()=>this.hintOf(i),emit:()=>{let e={type:`array`,items:n.json()};return Zf(e,i,`minItems`,t.minItems,r===`all`||r===`min-0-1`&&(t.minItems??0)<=1,`At least ${t.minItems} items.`),Zf(e,i,`maxItems`,t.maxItems,r===`all`,`At most ${t.maxItems} items.`),e},run:(e,r)=>{let i=Qf(e,r,`array`);if(!Array.isArray(i))return zf(r,i,`Expected a list, got ${If(i)}.`);t.minItems!==void 0&&i.length<t.minItems&&r.fail(`Must have at least ${t.minItems} items.`,`rule`),t.maxItems!==void 0&&i.length>t.maxItems&&r.fail(`Must have at most ${t.maxItems} items.`,`rule`);let a=i;for(let e=0;e<i.length;e++){r.enter(e);let t=n.run(i[e],r);r.leave(),t!==i[e]&&!r.dry&&(a=np(a,i,e,t,r))}return a},encode:(e,t)=>$f(e,e=>n.encode(e,t),t),child:()=>n})}},_f=class extends nf{constructor(e){super(),this.items=e}items;kind=`tuple`;children(){return this.items}print(e){return`[${this.items.map(t=>e.print(t)).join(`, `)}]`}compile(e){let t=this.items.map(t=>e.compile(t)),n=e.profile.tuples,r=t.length,i=(e,n,i)=>{let a=e;for(let o=0;o<r;o++){n.enter(i(o),o);let r=t[o].run(e[o],n);n.leave(),r!==e[o]&&!n.dry&&(a=np(a,e,o,r,n))}return a};return e.node({own:n===`object`,deps:t,hint:()=>this.hintOf(n===`object`?[`Positions are written as keys "0".."${r-1}".`]:n===`array`?[`Exactly ${r} items, in order: ${this.items.map(t=>t.print(new Dd(e.env))).join(`, `)}.`]:[]),emit:()=>{if(n===`object`){let n={};return t.forEach((e,t)=>n[String(t)]=e.json()),e.object(n,Object.keys(n))}return n===`prefixItems`?{type:`array`,prefixItems:t.map(e=>e.json()),minItems:r,maxItems:r}:{type:`array`,items:{anyOf:t.map(e=>e.json())}}},run:(e,t)=>{if(n===`object`){let n=Qf(e,t,`object`);if(!Ff(n))return zf(t,n,`Expected an object with keys "0".."`+(r-1)+`".`);let a=Array(r);for(let e=0;e<r;e++)a[e]=n[String(e)];t.dry||t.stats.arrays++;let o=i(a,t,e=>String(e));return t.dry?n:o}let a=Qf(e,t,`array`);return Array.isArray(a)?(a.length!==r&&t.fail(`Expected exactly ${r} items.`,`rule`),i(a,t,e=>e)):zf(t,a,`Expected a list of ${r} items.`)},encode:(e,r)=>{let i=e;if(n!==`object`)return $f(i,(e,n)=>t[n].encode(e,r),r);let a={};return r.objects++,i.forEach((e,n)=>a[String(n)]=t[n].encode(e,r)),a},child:e=>t[Number(e)]})}},vf=class e extends nf{constructor(e,t=!1,n={}){super(),this.shape=e,this.closed=t,this.extras=n}shape;closed;extras;kind=`object`;children(){let e=Object.values(this.shape);this.extras.rest&&e.push(this.extras.rest);for(let t of this.extras.patterns??[])e.push(t.schema);return e}strict(){return this.with({closed:!0})}extend(t){return new e({...this.shape,...t},this.closed,this.extras)}rest(t){return new e(this.shape,this.closed,{...this.extras,rest:t})}patterns(t){let n=Object.entries(t).map(([e,t])=>({pattern:e,schema:t}));return new e(this.shape,this.closed,{...this.extras,patterns:[...this.extras.patterns??[],...n]})}dependent(t,n,r,i){let a=new Tf(n,r,i??new pf);return new e({...this.shape,[t]:a},this.closed,this.extras)}print(e){let t=Object.entries(this.shape).map(([t,n])=>{let r=n instanceof jf||n instanceof Af;return`${/^[A-Za-z_$][\w$]*$/.test(t)?t:JSON.stringify(t)}${r?`?`:``}: ${e.print(r?n.inner:n)}`}),n=this.extraValue();return n&&t.push(`[key: string]: ${e.print(n)}`),`{ ${t.join(`; `)} }`}_extraValue;extraValue(){if(this._extraValue===void 0){let e=[...(this.extras.patterns??[]).map(e=>e.schema),...this.extras.rest?[this.extras.rest]:[]];this._extraValue=e.length===0?null:e.length===1?e[0]:new xf(e)}return this._extraValue??void 0}compile(e){let t=e.profile,n=t.optional===`null`,r=t.audience!==`people`,i=[],a=new Set;for(let[t,n]of Object.entries(this.shape)){let o=r?n.meta.forModels:void 0,s=o?o.meta.description===void 0&&n.meta.description!==void 0?o.describe(n.meta.description):o:n;if(r&&n.meta.audience===`people`){a.add(t);continue}let c=s instanceof Af?s:void 0,l=s instanceof jf||!!c,u=s instanceof jf?s.inner:c?c.inner:s;if(l&&Of(u,e.env)){a.add(t);continue}let d=l?e.guarded(u,s):e.compile(u);i.push({key:t,optional:l,node:d,nullable:u instanceof Mf,...u instanceof Tf?{dep:u}:{},...c?{dflt:c}:{}})}let o=i.filter(e=>!e.dep),s=i.filter(e=>e.dep),c=new Set(Object.keys(this.shape)),l=this.extraValue(),u=(this.extras.patterns??[]).map(t=>({re:new RegExp(t.pattern),pattern:t.pattern,node:e.guarded(t.schema)})),d=this.extras.rest?e.guarded(this.extras.rest):void 0,f=l?t.records===`pairs`?`pairs`:t.patternProperties?`keywords`:`open`:`none`,p=f===`pairs`?c.has(`extra`)?`_extra`:`extra`:``,m=l&&f!==`keywords`?e.guarded(l):void 0,h=e=>u.find(t=>t.re.test(e))?.node??d;return e.node({own:n&&i.some(e=>e.optional&&!e.nullable)||a.size>0||f===`pairs`||i.some(e=>e.dflt),deps:[...i.map(e=>e.node),...u.map(e=>e.node),...d?[d]:[],...m?[m]:[]],hint:()=>this.hintOf(f===`pairs`?[`Other keys go in "${p}" as a list of {key, value} entries.`]:f===`open`&&u.length?[`Other keys: ${u.map(t=>`keys matching /${t.pattern}/ hold ${t.node.schema?.print(new Dd(e.env))??`a value`}`).join(`; `)}${d?`; any other key holds the rest`:``}.`]:[]),emit:()=>{let r={},a=[];for(let t of i){let i=t.node.json();t.dep&&(i={...i,description:[i.description,`Its type is given by "${t.dep.on}".`].filter(Boolean).join(`
|
|
66
66
|
`)}),t.dflt&&(i={...i,description:[i.description,`Default when left out: ${JSON.stringify(t.node.encode(t.dflt.value))}.`].filter(Boolean).join(`
|
|
67
67
|
`)}),t.optional&&n&&(i=e.nullable(i),i.description=[i.description,`Write null to leave it out.`].filter(Boolean).join(`
|
|
68
|
-
`)),r[t.key]=i,(!t.optional||n)&&a.push(t.key)}f===`pairs`&&(r[p]={type:`array`,items:e.object({key:{type:`string`},value:m.json()},[`key`,`value`],!0)},n&&a.push(p));let o=e.object(r,a,this.closed||t.closedObjects);return f===`keywords`?(u.length&&(o.patternProperties=Object.fromEntries(u.map(e=>[e.pattern,e.node.json()]))),d&&(o.additionalProperties=d.json())):f===`open`&&(o.additionalProperties=m.json()),o},run:(t,r)=>{let i=qf(t,r,`object`);if(!Af(i))return Pf(r,i,`Expected an object, got ${jf(i)}.`);let u=i,d=u;for(let e=0;e<o.length;e++){let t=o[e],i=Object.prototype.hasOwnProperty.call(u,t.key)?u[t.key]:void 0;if(i===void 0){t.dflt?r.dry||(d=Yf(d,u,t.key,t.dflt.fresh(r.stats),r)):t.optional||(r.enter(t.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),t.node),r.leave());continue}if(i===null&&t.optional&&n&&!t.nullable){r.dry||(d=t.dflt?Yf(d,u,t.key,t.dflt.fresh(r.stats),r):Xf(d,u,t.key,r));continue}r.enter(t.key);let a=t.node.run(i,r);r.leave(),a!==i&&!r.dry&&(d=Yf(d,u,t.key,a,r))}for(let t=0;t<s.length;t++){let i=s[t],a=u[i.key];if(a===void 0||a===null&&i.optional&&n){a===null&&!r.dry?d=Xf(d,u,i.key,r):i.optional||(r.enter(i.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),i.node),r.leave());continue}r.enter(i.key);let o=r.errors.length,l=i.node.run(a,r);if(r.errors.length===o){let t=i.dep.schemaFor(d[i.dep.on]);t&&(l=e.lenient().nodeFor(t).run(l,r))}r.leave(),l!==a&&!r.dry&&(d=Yf(d,u,i.key,l,r))}if(a.size)for(let e of a)Object.prototype.hasOwnProperty.call(u,e)&&(r.enter(e),r.fail(`Not allowed.`,`not-allowed`),r.leave());if(f===`pairs`){let e=u[p];if(e!=null){r.enter(p,null);let t=qf(e,r,`array`);if(!Array.isArray(t))Pf(r,t,`Expected a list of {key, value} entries.`);else{r.dry||(d=Xf(d,u,p,r));for(let e=0;e<t.length;e++){let n=t[e];if(r.enter(e,null),!Af(n)||typeof n.key!=`string`){r.fail(`Expected a {key, value} entry with a string key.`,`type`),r.leave(!1);continue}let i=n.key;if(c.has(i)||Object.prototype.hasOwnProperty.call(d,i)){r.enter(`key`,null),r.fail(`Duplicate key "${i}".`,`rule`),r.leave(!1),r.leave(!1);continue}let a=h(i);r.enter(`value`,i);let o=a?a.run(n.value,r):this.closed?Pf(r,n.value,`Key "${i}" is not allowed.`,`not-allowed`):n.value;r.leave(),r.dry||(d=Yf(d,u,i,o,r)),r.leave(!1)}}r.leave(!1)}else p&&e===null&&!r.dry&&(d=Xf(d,u,p,r))}else if(l||this.closed){let e=Object.keys(u);for(let t=0;t<e.length;t++){let n=e[t];if(c.has(n))continue;let i=l?h(n):void 0;if(i){r.enter(n);let e=i.run(u[n],r);r.leave(),e!==u[n]&&!r.dry&&(d=Yf(d,u,n,e,r))}else this.closed&&(r.enter(n),r.fail(`Unknown field "${n}".`,`unknown-key`,n,()=>[...c].filter(e=>!Object.prototype.hasOwnProperty.call(u,e))),r.leave())}}return d},encode:(e,t)=>{let r=e,o={};t.objects++;let s=[];for(let e of Object.keys(r)){if(a.has(e)||c.has(e))continue;let n=h(e),i=n?n.encode(r[e],t):r[e];f===`pairs`?s.push({key:e,value:i}):o[e]=i}for(let e of i){let i=r[e.key];i===void 0?e.optional&&n&&(o[e.key]=null):o[e.key]=e.node.encode(i,t)}return f===`pairs`&&(s.length||n)&&(t.arrays++,t.objects+=s.length,o[p]=s),o},child:e=>i.find(t=>t.key===e)?.node??(typeof e==`string`?h(e):void 0)})}},mf=class extends Zd{constructor(e,t){super(),this.value=e,this.key=t}value;key;kind=`record`;children(){return this.key?[this.key,this.value]:[this.value]}print(e){return`{ [key: ${this.key?e.print(this.key):`string`}]: ${e.print(this.value)} }`}compile(e){let t=e.guarded(this.value),n=e.compile(this.key??hf),r=e.profile.records===`pairs`;return e.node({own:r,deps:[t,n],hint:e=>this.hintOf(r?[`A map written as ${e.recordWord}; each key at most once.`]:[]),emit:()=>{if(r)return{type:`array`,items:e.object({key:n.json(),value:t.json()},[`key`,`value`],!0)};let i={type:`object`,additionalProperties:t.json()};return this.key&&!e.profile.closedObjects&&!(this.key instanceof tf&&!Object.keys(this.key.options).length)&&(i.propertyNames=n.json()),i},run:(i,a)=>{if(r){let r=qf(i,a,`array`);if(!Array.isArray(r)){let t=a.repair?qf(i,a,`object`):i;if(a.repair&&!a.dry&&Af(t)){t===i&&a.stats.repaired++;let r=t,o=e.lenient().nodeFor(this.value),s=r;for(let e of Object.keys(r)){a.enter(e),n.run(e,a);let t=o.run(r[e],a);a.leave(),t!==r[e]&&!a.dry&&(s=Yf(s,r,e,t,a))}return s}return Pf(a,r,`Expected a list of {key, value} entries, got ${jf(r)}.`)}let o={};a.dry||a.stats.objects++;for(let e=0;e<r.length;e++){let i=r[e];if(a.enter(e,null),!Af(i)){Pf(a,i,`Expected a {key, value} entry.`),a.leave(!1);continue}let s=i.key;a.enter(`key`,null),s===void 0?a.fail(`Required.`,`required`,void 0,()=>Object.keys(i).filter(e=>e!==`key`&&e!==`value`),n):n.run(s,a),a.leave(!1),typeof s==`string`&&(Object.prototype.hasOwnProperty.call(o,s)&&(a.enter(`key`,null),a.fail(`Duplicate key "${s}".`,`rule`),a.leave(!1)),a.enter(`value`,s),o[s]=t.run(i.value,a),a.leave()),a.leave(!1)}return a.dry?r:o}let o=qf(i,a,`object`);if(!Af(o))return Pf(a,o,`Expected an object, got ${jf(o)}.`);let s=o,c=s;for(let e of Object.keys(s)){this.key&&(a.enter(e),n.run(e,a),a.leave()),a.enter(e);let r=t.run(s[e],a);a.leave(),r!==s[e]&&!a.dry&&(c=Yf(c,s,e,r,a))}return c},encode:(e,n)=>{let i=e;if(r){let e=Object.keys(i);return n.arrays++,n.objects+=e.length,e.map(e=>({key:e,value:t.encode(i[e],n)}))}let a=i;for(let e of Object.keys(i)){let r=t.encode(i[e],n);r!==i[e]&&(a===i&&(a={...i},n.objects++),a[e]=r)}return a},child:()=>t})}},hf=new tf,gf=class extends Zd{constructor(e,t){super(),this.options=e,this.tag=t}options;tag;kind=`union`;children(){return this.options}print(e){return this.options.map(t=>e.print(t)).join(` | `)}tagIndex(e,t){let n=this.tag??Vf(this.options,e);if(!n)return;let r=new Map,i=[];return this.options.forEach((a,o)=>{let s=t.has(o)?void 0:Lf(a,n,e);if(s)for(let e of s)r.has(e)||r.set(e,o);else i.push(o)}),{tag:n,byTag:r,fallback:i}}label(e,t){let n=this.tag?Wf(this.options[e],t).shape?.[this.tag]:void 0;return n instanceof of&&typeof n.value==`string`?n.value:`option${e+1}`}compile(e){if(this.options.some(t=>Cf(t,e.env))){let t=this.options.filter(t=>!Cf(t,e.env));return t.length?this.with({options:t}).compile(e):wf(e,()=>this.ruleHint())}let t=e.profile.unions===`tagged`,n=new Set,r=this.options.map(t=>e.compile(t));if(r.length>1&&r.every(e=>e.jsonText))return e.escape(this,`Nested too deep for this model to describe directly.`);let i=t=>Wf(t,e.env)?.kind,a=this.options.some(t=>i(t)===`array`||i(t)===`tuple`&&e.profile.tuples!==`object`),o=r.map((r,o,s)=>t||s.length<2?r:r.jsonText?(n.add(o),Uf(e,r)):a&&e.profile.records===`pairs`&&i(this.options[o])===`record`?(n.add(o),Uf(e,r,`entries`)):r),s=this.tagIndex(e.env,n),c=s?.byTag,l=s?.tag,u=this.options.map((t,n)=>this.label(n,e.env)),d=t=>Wf(this.options[t],e.env)instanceof af,f=(t,n)=>{if(c&&Af(t)){let r=c.get(t[l]);if(r!==void 0){let i=new Set(zf(this.options[r],e.env));if(e.profile.closedObjects&&i.size&&s.fallback.length&&Object.keys(t).some(e=>!i.has(e)))for(let e of s.fallback){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return r}}let r=!Af(t)||t[l]===void 0;for(let e of s&&!r?s.fallback:o.keys()){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return-1},p=()=>new Sd(e.env);return e.node({own:t,deps:o,hint:()=>this.hintOf(t?[`Fill exactly one of these fields and set the others to null.`]:[]),emit:()=>{if(t){let t={};return o.forEach((n,r)=>t[u[r]]=e.nullable(d(r)?{type:`boolean`,enum:[!0],description:`true for null`}:n.json())),e.object(t,u)}return{anyOf:o.map(e=>e.json())}},run:(n,r)=>{if(t){if(!Af(n))return Pf(r,n,`Expected an object with one of: ${u.join(`, `)}.`);let e=u.filter(e=>n[e]!=null);if(e.length!==1)return Pf(r,n,`Fill exactly one of: ${u.join(`, `)} (got ${e.length}).`,`union`);let t=u.indexOf(e[0]);if(d(t))return n[e[0]]===!0?null:Pf(r,n,`Set ${e[0]} to true for null.`,`literal`);r.enter(e[0],null);let i=o[t].run(n[e[0]],r);return r.leave(!1),i}let i=f(n,r);if(i<0){if(c&&!s.fallback.length&&Af(n)&&n[l]!==void 0){r.enter(l);let e=n[l];return r.fail(`Expected ${l} to be one of: ${Ff([...c.keys()].map(e=>JSON.stringify(e)))}.`,`tag`,e,()=>[...c.keys()].filter(e=>typeof e==`string`)),r.leave(),n}let t=Hf(this.options,n,e.env);return t>=0?o[t].run(n,r):Pf(r,n,`Did not match any of: ${If(this.options.map(e=>e.print(p())).join(` | `),300)}.`,`union`,typeof n==`string`?()=>Rf(this.options,e.env):void 0)}return o[i].run(n,r)},encode:(n,r)=>{let i=this.optionOf(n,e,c,l);if(i<0)return n;let a=d(i)&&t?!0:o[i].encode(n,r);return t?(r.objects++,Object.fromEntries(u.map((e,t)=>[e,t===i?a:null]))):a},child:t=>{let n=o.map(e=>e.child(t)).filter(e=>!!e);if(n.length<=1)return n[0];let r=t=>n.find(n=>!n.schema||Gf(e,n.schema,t))??n[0],i=e.node({deps:n,emit:()=>({anyOf:n.map(e=>e.json())}),run:(e,t)=>r(e).run(e,t),encode:(e,t)=>r(e).encode(e,t),child:e=>n[0].child(e)});return i.needs=n.some(e=>e.needs),i}})}optionOf(e,t,n,r){if(n&&Af(e)){let t=n.get(e[r]);if(t!==void 0)return t}let i=t.lenient();return this.options.findIndex(t=>{let n=new bd(!1,!0,pd(),!1,!0);return i.nodeFor(t).run(e,n),n.errors.length===0})}},_f=class extends Zd{constructor(e){super(),this.members=e}members;kind=`intersection`;children(){return this.members}print(e){return this.members.map(t=>e.print(t)).join(` & `)}mergedByEnv=new WeakMap;merged(e){let t=this.mergedByEnv.get(e);if(t===void 0){let n=this.members.map(t=>Wf(t,e));if(n.every(e=>e instanceof pf)){let e=n,r={};for(let t of e)Object.assign(r,t.shape);let i=e.map(e=>e.extras.rest).filter(Boolean).at(-1),a=e.flatMap(e=>e.extras.patterns??[]);t=new pf(r,e.some(e=>e.closed),{...i?{rest:i}:{},...a.length?{patterns:a}:{}}).with({checks:[...e.flatMap(e=>e.checks),...this.checks],meta:this.meta})}else t=null;this.mergedByEnv.set(e,t)}return t??void 0}compile(e){let t=this.merged(e.env);if(t){let n=e.compile(t);return e.node({deps:[n],emit:()=>n.json(),run:(e,t)=>n.run(e,t),encode:(e,t)=>n.encode(e,t),child:e=>n.child(e)})}let n=this.members.map(t=>e.compile(t)),r=this.members.slice(1),i=()=>e.profile.allOf&&n.every(e=>!e.needs);return e.node({deps:n,hint:()=>this.hintOf(i()?[]:[`Must also be: ${r.map(t=>t.print(new Sd(e.env))).join(` & `)}.`]),emit:()=>i()?{allOf:n.map(e=>e.json())}:n[0].json(),run:(t,i)=>{let a=i.errors.length,o=n[0].run(t,i);if(i.errors.length!==a)return o;let s=e.lenient();for(let e of r){let t=i.dryRun(!0);s.nodeFor(e).run(o,t);for(let e of t.errors)i.errors.push(e)}return o},encode:(e,t)=>n[0].encode(e,t),child:e=>n[0].child(e)})}},vf=class extends Zd{constructor(e,t){super(),this.excluded=e,this.base=t}excluded;base;kind=`not`;children(){return[this.base,this.excluded]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=()=>e.profile.conditionals?[]:[`Must not be: ${this.excluded.print(new Sd(e.env))}.`];return e.node({deps:[t],hint:()=>this.hintOf(n()),emit:()=>e.profile.conditionals?{...t.json(),not:e.lenient().nodeFor(this.excluded).json()}:t.json(),run:(n,r)=>{let i=r.errors.length,a=t.run(n,r);return r.errors.length===i&&Gf(e,this.excluded,a)&&r.fail(`Must not be: ${this.excluded.print(new Sd(e.env))}.`,`rule`),a},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},yf=class extends Zd{constructor(e,t,n,r){super(),this.base=e,this.when=t,this.then=n,this.otherwise=r}base;when;then;otherwise;kind=`conditional`;children(){return[this.base,this.when,...this.then?[this.then]:[],...this.otherwise?[this.otherwise]:[]]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=t=>t.print(new Sd(e.env)),r=[this.then?`If it is ${n(this.when)}, it must also be ${n(this.then)}.`:``,this.otherwise?`${this.then?`Otherwise`:`If it is not ${n(this.when)}`}, it must be ${n(this.otherwise)}.`:``].filter(Boolean).join(` `);return e.node({deps:[t],hint:()=>this.hintOf(e.profile.conditionals?[]:[r]),emit:()=>{if(!e.profile.conditionals)return t.json();let n=e.lenient();return{...t.json(),if:n.nodeFor(this.when).json(),...this.then?{then:n.nodeFor(this.then).json()}:{},...this.otherwise?{else:n.nodeFor(this.otherwise).json()}:{}}},run:(n,i)=>{let a=i.errors.length,o=t.run(n,i);if(i.errors.length!==a)return o;let s=Gf(e,this.when,o)?this.then:this.otherwise;return s&&!Gf(e,s,o)&&i.fail(r,`rule`),o},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},bf=class extends Zd{constructor(e,t,n=new cf){super(),this.on=e,this.schemaFor=t,this.base=n}on;schemaFor;base;kind=`dependent`;children(){return[this.base]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>t.run(e,n),encode:(e,n)=>t.encode(e,n)})}},xf=class extends Zd{constructor(e,t=`tool`,n=`args`){super(),this.cases=e,this.tagKey=t,this.argsKey=n}cases;tagKey;argsKey;kind=`dispatch`;children(){return this.cases.map(e=>e.schema)}print(e){return this.cases.map(t=>`{ ${this.tagKey}: ${JSON.stringify(t.name)}; ${this.argsKey}: ${e.print(t.schema)} }`).join(` | `)}compile(e){let t=this.cases.map(e=>e.name),n=new Map(t.map((e,t)=>[e,t])),r=this.cases.map(t=>e.compile(t.schema)),i=e.compile(new sf(t)),a=e.profile.unions===`tagged`,{tagKey:o,argsKey:s}=this,c=this.cases.map(e=>`- ${e.name}${e.description?`: ${e.description}`:``}`).join(`
|
|
68
|
+
`)),r[t.key]=i,(!t.optional||n)&&a.push(t.key)}f===`pairs`&&(r[p]={type:`array`,items:e.object({key:{type:`string`},value:m.json()},[`key`,`value`],!0)},n&&a.push(p));let o=e.object(r,a,this.closed||t.closedObjects);return f===`keywords`?(u.length&&(o.patternProperties=Object.fromEntries(u.map(e=>[e.pattern,e.node.json()]))),d&&(o.additionalProperties=d.json())):f===`open`&&(o.additionalProperties=m.json()),o},run:(t,r)=>{let i=Qf(t,r,`object`);if(!Ff(i))return zf(r,i,`Expected an object, got ${If(i)}.`);let u=i,d=u;for(let e=0;e<o.length;e++){let t=o[e],i=Object.prototype.hasOwnProperty.call(u,t.key)?u[t.key]:void 0;if(i===void 0){t.dflt?r.dry||(d=ep(d,u,t.key,t.dflt.fresh(r.stats),r)):t.optional||(r.enter(t.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),t.node),r.leave());continue}if(i===null&&t.optional&&n&&!t.nullable){r.dry||(d=t.dflt?ep(d,u,t.key,t.dflt.fresh(r.stats),r):tp(d,u,t.key,r));continue}r.enter(t.key);let a=t.node.run(i,r);r.leave(),a!==i&&!r.dry&&(d=ep(d,u,t.key,a,r))}for(let t=0;t<s.length;t++){let i=s[t],a=u[i.key];if(a===void 0||a===null&&i.optional&&n){a===null&&!r.dry?d=tp(d,u,i.key,r):i.optional||(r.enter(i.key),r.fail(`Required.`,`required`,void 0,()=>Object.keys(u).filter(e=>!c.has(e)),i.node),r.leave());continue}r.enter(i.key);let o=r.errors.length,l=i.node.run(a,r);if(r.errors.length===o){let t=i.dep.schemaFor(d[i.dep.on]);t&&(l=e.lenient().nodeFor(t).run(l,r))}r.leave(),l!==a&&!r.dry&&(d=ep(d,u,i.key,l,r))}if(a.size)for(let e of a)Object.prototype.hasOwnProperty.call(u,e)&&(r.enter(e),r.fail(`Not allowed.`,`not-allowed`),r.leave());if(f===`pairs`){let e=u[p];if(e!=null){r.enter(p,null);let t=Qf(e,r,`array`);if(!Array.isArray(t))zf(r,t,`Expected a list of {key, value} entries.`);else{r.dry||(d=tp(d,u,p,r));for(let e=0;e<t.length;e++){let n=t[e];if(r.enter(e,null),!Ff(n)||typeof n.key!=`string`){r.fail(`Expected a {key, value} entry with a string key.`,`type`),r.leave(!1);continue}let i=n.key;if(c.has(i)||Object.prototype.hasOwnProperty.call(d,i)){r.enter(`key`,null),r.fail(`Duplicate key "${i}".`,`rule`),r.leave(!1),r.leave(!1);continue}let a=h(i);r.enter(`value`,i);let o=a?a.run(n.value,r):this.closed?zf(r,n.value,`Key "${i}" is not allowed.`,`not-allowed`):n.value;r.leave(),r.dry||(d=ep(d,u,i,o,r)),r.leave(!1)}}r.leave(!1)}else p&&e===null&&!r.dry&&(d=tp(d,u,p,r))}else if(l||this.closed){let e=Object.keys(u);for(let t=0;t<e.length;t++){let n=e[t];if(c.has(n))continue;let i=l?h(n):void 0;if(i){r.enter(n);let e=i.run(u[n],r);r.leave(),e!==u[n]&&!r.dry&&(d=ep(d,u,n,e,r))}else this.closed&&(r.enter(n),r.fail(`Unknown field "${n}".`,`unknown-key`,n,()=>[...c].filter(e=>!Object.prototype.hasOwnProperty.call(u,e))),r.leave())}}return d},encode:(e,t)=>{let r=e,o={};t.objects++;let s=[];for(let e of Object.keys(r)){if(a.has(e)||c.has(e))continue;let n=h(e),i=n?n.encode(r[e],t):r[e];f===`pairs`?s.push({key:e,value:i}):o[e]=i}for(let e of i){let i=r[e.key];i===void 0?e.optional&&n&&(o[e.key]=null):o[e.key]=e.node.encode(i,t)}return f===`pairs`&&(s.length||n)&&(t.arrays++,t.objects+=s.length,o[p]=s),o},child:e=>i.find(t=>t.key===e)?.node??(typeof e==`string`?h(e):void 0)})}},yf=class extends nf{constructor(e,t){super(),this.value=e,this.key=t}value;key;kind=`record`;children(){return this.key?[this.key,this.value]:[this.value]}print(e){return`{ [key: ${this.key?e.print(this.key):`string`}]: ${e.print(this.value)} }`}compile(e){let t=e.guarded(this.value),n=e.compile(this.key??bf),r=e.profile.records===`pairs`;return e.node({own:r,deps:[t,n],hint:e=>this.hintOf(r?[`A map written as ${e.recordWord}; each key at most once.`]:[]),emit:()=>{if(r)return{type:`array`,items:e.object({key:n.json(),value:t.json()},[`key`,`value`],e.profile.closedObjects)};let i={type:`object`,additionalProperties:t.json()};return this.key&&!e.profile.closedObjects&&!(this.key instanceof sf&&!Object.keys(this.key.options).length)&&(i.propertyNames=n.json()),i},run:(i,a)=>{if(r){let r=Qf(i,a,`array`);if(!Array.isArray(r)){let t=a.repair?Qf(i,a,`object`):i;if(a.repair&&!a.dry&&Ff(t)){t===i&&a.stats.repaired++;let r=t,o=e.lenient().nodeFor(this.value),s=r;for(let e of Object.keys(r)){a.enter(e),n.run(e,a);let t=o.run(r[e],a);a.leave(),t!==r[e]&&!a.dry&&(s=ep(s,r,e,t,a))}return s}return zf(a,r,`Expected a list of {key, value} entries, got ${If(r)}.`)}let o={};a.dry||a.stats.objects++;for(let e=0;e<r.length;e++){let i=r[e];if(a.enter(e,null),!Ff(i)){zf(a,i,`Expected a {key, value} entry.`),a.leave(!1);continue}let s=i.key;a.enter(`key`,null),s===void 0?a.fail(`Required.`,`required`,void 0,()=>Object.keys(i).filter(e=>e!==`key`&&e!==`value`),n):n.run(s,a),a.leave(!1),typeof s==`string`&&(Object.prototype.hasOwnProperty.call(o,s)&&(a.enter(`key`,null),a.fail(`Duplicate key "${s}".`,`rule`),a.leave(!1)),a.enter(`value`,s),o[s]=t.run(i.value,a),a.leave()),a.leave(!1)}return a.dry?r:o}let o=Qf(i,a,`object`);if(!Ff(o))return zf(a,o,`Expected an object, got ${If(o)}.`);let s=o,c=s;for(let e of Object.keys(s)){this.key&&(a.enter(e),n.run(e,a),a.leave()),a.enter(e);let r=t.run(s[e],a);a.leave(),r!==s[e]&&!a.dry&&(c=ep(c,s,e,r,a))}return c},encode:(e,n)=>{let i=e;if(r){let e=Object.keys(i);return n.arrays++,n.objects+=e.length,e.map(e=>({key:e,value:t.encode(i[e],n)}))}let a=i;for(let e of Object.keys(i)){let r=t.encode(i[e],n);r!==i[e]&&(a===i&&(a={...i},n.objects++),a[e]=r)}return a},child:()=>t})}},bf=new sf,xf=class extends nf{constructor(e,t){super(),this.options=e,this.tag=t}options;tag;kind=`union`;children(){return this.options}print(e){return this.options.map(t=>e.print(t)).join(` | `)}tagIndex(e,t){let n=this.tag??Kf(this.options,e);if(!n)return;let r=new Map,i=[];return this.options.forEach((a,o)=>{let s=t.has(o)?void 0:Hf(a,n,e);if(s)for(let e of s)r.has(e)||r.set(e,o);else i.push(o)}),{tag:n,byTag:r,fallback:i}}label(e,t){let n=this.tag?Yf(this.options[e],t).shape?.[this.tag]:void 0;return n instanceof df&&typeof n.value==`string`?n.value:`option${e+1}`}compile(e){if(this.options.some(t=>Of(t,e.env))){let t=this.options.filter(t=>!Of(t,e.env));return t.length?this.with({options:t}).compile(e):kf(e,()=>this.ruleHint())}let t=e.profile.unions===`tagged`,n=new Set,r=this.options.map(t=>e.compile(t));if(r.length>1&&r.every(e=>e.jsonText))return e.escape(this,`Nested too deep for this model to describe directly.`);let i=t=>Yf(t,e.env)?.kind,a=this.options.some(t=>i(t)===`array`||i(t)===`tuple`&&e.profile.tuples!==`object`),o=r.map((r,o,s)=>t||s.length<2?r:r.jsonText?(n.add(o),Jf(e,r)):a&&e.profile.records===`pairs`&&i(this.options[o])===`record`?(n.add(o),Jf(e,r,`entries`)):r),s=this.tagIndex(e.env,n),c=s?.byTag,l=s?.tag,u=this.options.map((t,n)=>this.label(n,e.env)),d=t=>Yf(this.options[t],e.env)instanceof uf,f=(t,n)=>{if(c&&Ff(t)){let r=c.get(t[l]);if(r!==void 0){let i=new Set(Wf(this.options[r],e.env));if(e.profile.closedObjects&&i.size&&s.fallback.length&&Object.keys(t).some(e=>!i.has(e)))for(let e of s.fallback){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return r}}let r=!Ff(t)||t[l]===void 0;for(let e of s&&!r?s.fallback:o.keys()){let r=n.dryRun();if(o[e].run(t,r),!r.errors.length)return e}return-1},p=()=>new Dd(e.env);return e.node({own:t,deps:o,hint:()=>this.hintOf(t?[`Fill exactly one of these fields and set the others to null.`]:[]),emit:()=>{if(t){let t={};return o.forEach((n,r)=>t[u[r]]=e.nullable(d(r)?{type:`boolean`,enum:[!0],description:`true for null`}:n.json())),e.object(t,u)}return{anyOf:o.map(e=>e.json())}},run:(n,r)=>{if(t){if(!Ff(n))return zf(r,n,`Expected an object with one of: ${u.join(`, `)}.`);let e=u.filter(e=>n[e]!=null);if(e.length!==1)return zf(r,n,`Fill exactly one of: ${u.join(`, `)} (got ${e.length}).`,`union`);let t=u.indexOf(e[0]);if(d(t))return n[e[0]]===!0?null:zf(r,n,`Set ${e[0]} to true for null.`,`literal`);r.enter(e[0],null);let i=o[t].run(n[e[0]],r);return r.leave(!1),i}let i=f(n,r);if(i<0){if(c&&!s.fallback.length&&Ff(n)&&n[l]!==void 0){r.enter(l);let e=n[l];return r.fail(`Expected ${l} to be one of: ${Bf([...c.keys()].map(e=>JSON.stringify(e)))}.`,`tag`,e,()=>[...c.keys()].filter(e=>typeof e==`string`)),r.leave(),n}let t=qf(this.options,n,e.env);return t>=0?o[t].run(n,r):zf(r,n,`Did not match any of: ${Vf(this.options.map(e=>e.print(p())).join(` | `),300)}.`,`union`,typeof n==`string`?()=>Uf(this.options,e.env):void 0)}return o[i].run(n,r)},encode:(n,r)=>{let i=this.optionOf(n,e,c,l);if(i<0)return n;let a=d(i)&&t?!0:o[i].encode(n,r);return t?(r.objects++,Object.fromEntries(u.map((e,t)=>[e,t===i?a:null]))):a},child:t=>{let n=o.map(e=>e.child(t)).filter(e=>!!e);if(n.length<=1)return n[0];let r=t=>n.find(n=>!n.schema||Xf(e,n.schema,t))??n[0],i=e.node({deps:n,emit:()=>({anyOf:n.map(e=>e.json())}),run:(e,t)=>r(e).run(e,t),encode:(e,t)=>r(e).encode(e,t),child:e=>n[0].child(e)});return i.needs=n.some(e=>e.needs),i}})}optionOf(e,t,n,r){if(n&&Ff(e)){let t=n.get(e[r]);if(t!==void 0)return t}let i=t.lenient();return this.options.findIndex(t=>{let n=new Td(!1,!0,vd(),!1,!0);return i.nodeFor(t).run(e,n),n.errors.length===0})}},Sf=class extends nf{constructor(e){super(),this.members=e}members;kind=`intersection`;children(){return this.members}print(e){return this.members.map(t=>e.print(t)).join(` & `)}mergedByEnv=new WeakMap;merged(e){let t=this.mergedByEnv.get(e);if(t===void 0){let n=this.members.map(t=>Yf(t,e));if(n.every(e=>e instanceof vf)){let e=n,r={};for(let t of e)Object.assign(r,t.shape);let i=e.map(e=>e.extras.rest).filter(Boolean).at(-1),a=e.flatMap(e=>e.extras.patterns??[]);t=new vf(r,e.some(e=>e.closed),{...i?{rest:i}:{},...a.length?{patterns:a}:{}}).with({checks:[...e.flatMap(e=>e.checks),...this.checks],meta:this.meta})}else t=null;this.mergedByEnv.set(e,t)}return t??void 0}compile(e){let t=this.merged(e.env);if(t){let n=e.compile(t);return e.node({deps:[n],emit:()=>n.json(),run:(e,t)=>n.run(e,t),encode:(e,t)=>n.encode(e,t),child:e=>n.child(e)})}let n=this.members.map(t=>e.compile(t)),r=this.members.slice(1),i=()=>e.profile.allOf&&n.every(e=>!e.needs);return e.node({deps:n,hint:()=>this.hintOf(i()?[]:[`Must also be: ${r.map(t=>t.print(new Dd(e.env))).join(` & `)}.`]),emit:()=>i()?{allOf:n.map(e=>e.json())}:n[0].json(),run:(t,i)=>{let a=i.errors.length,o=n[0].run(t,i);if(i.errors.length!==a)return o;let s=e.lenient();for(let e of r){let t=i.dryRun(!0);s.nodeFor(e).run(o,t);for(let e of t.errors)i.errors.push(e)}return o},encode:(e,t)=>n[0].encode(e,t),child:e=>n[0].child(e)})}},Cf=class extends nf{constructor(e,t){super(),this.excluded=e,this.base=t}excluded;base;kind=`not`;children(){return[this.base,this.excluded]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=()=>e.profile.conditionals?[]:[`Must not be: ${this.excluded.print(new Dd(e.env))}.`];return e.node({deps:[t],hint:()=>this.hintOf(n()),emit:()=>e.profile.conditionals?{...t.json(),not:e.lenient().nodeFor(this.excluded).json()}:t.json(),run:(n,r)=>{let i=r.errors.length,a=t.run(n,r);return r.errors.length===i&&Xf(e,this.excluded,a)&&r.fail(`Must not be: ${this.excluded.print(new Dd(e.env))}.`,`rule`),a},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},wf=class extends nf{constructor(e,t,n,r){super(),this.base=e,this.when=t,this.then=n,this.otherwise=r}base;when;then;otherwise;kind=`conditional`;children(){return[this.base,this.when,...this.then?[this.then]:[],...this.otherwise?[this.otherwise]:[]]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base),n=t=>t.print(new Dd(e.env)),r=[this.then?`If it is ${n(this.when)}, it must also be ${n(this.then)}.`:``,this.otherwise?`${this.then?`Otherwise`:`If it is not ${n(this.when)}`}, it must be ${n(this.otherwise)}.`:``].filter(Boolean).join(` `);return e.node({deps:[t],hint:()=>this.hintOf(e.profile.conditionals?[]:[r]),emit:()=>{if(!e.profile.conditionals)return t.json();let n=e.lenient();return{...t.json(),if:n.nodeFor(this.when).json(),...this.then?{then:n.nodeFor(this.then).json()}:{},...this.otherwise?{else:n.nodeFor(this.otherwise).json()}:{}}},run:(n,i)=>{let a=i.errors.length,o=t.run(n,i);if(i.errors.length!==a)return o;let s=Xf(e,this.when,o)?this.then:this.otherwise;return s&&!Xf(e,s,o)&&i.fail(r,`rule`),o},encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},Tf=class extends nf{constructor(e,t,n=new pf){super(),this.on=e,this.schemaFor=t,this.base=n}on;schemaFor;base;kind=`dependent`;children(){return[this.base]}print(e){return e.print(this.base)}compile(e){let t=e.compile(this.base);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>t.run(e,n),encode:(e,n)=>t.encode(e,n)})}},Ef=class extends nf{constructor(e,t=`tool`,n=`args`){super(),this.cases=e,this.tagKey=t,this.argsKey=n}cases;tagKey;argsKey;kind=`dispatch`;children(){return this.cases.map(e=>e.schema)}print(e){return this.cases.map(t=>`{ ${this.tagKey}: ${JSON.stringify(t.name)}; ${this.argsKey}: ${e.print(t.schema)} }`).join(` | `)}compile(e){let t=this.cases.map(e=>e.name),n=new Map(t.map((e,t)=>[e,t])),r=this.cases.map(t=>e.compile(t.schema)),i=e.compile(new ff(t)),a=e.profile.unions===`tagged`,{tagKey:o,argsKey:s}=this,c=this.cases.map(e=>`- ${e.name}${e.description?`: ${e.description}`:``}`).join(`
|
|
69
69
|
`);return e.node({own:!0,deps:[i,...r],hint:()=>this.hintOf([`Set "${o}" to the tool to run and "${s}" to its arguments.`]),emit:()=>{let n={...i.json(),description:[i.json().description,`The tool to run:
|
|
70
70
|
${c}`].filter(Boolean).join(`
|
|
71
|
-
`)},l;if(a){let n={};t.forEach((t,i)=>n[t]=e.nullable(r[i].json())),l={...e.object(n,t),description:`Fill only the field named by "${o}"; set the others to null.`}}else l=r.length===1?r[0].json():{anyOf:r.map(e=>e.json())};return e.object({[o]:n,[s]:l},[o,s])},run:(e,i)=>{let c=qf(e,i,`object`);if(!Af(c))return Pf(i,c,`Expected an object with "${o}" and "${s}".`);let l=c,u=l[o],d=typeof u==`string`?n.get(u):void 0;if(d===void 0)return i.enter(o),i.fail(`Expected one of: ${Ff(t)}.`,`tool`,u,()=>t),i.leave(),c;let f=l[s];if(a){let e=qf(f,i,`object`);f=Af(e)?e[u]:void 0,i.enter(s),i.enter(u,null)}else i.enter(s);let p=f===void 0?Pf(i,f,`Required.`,`required`,r[d]):r[d].run(f,i);return a&&i.leave(!1),i.leave(),p!==l[s]&&!i.dry?Yf(l,l,s,p,i):l},encode:(e,i)=>{let c=e,l=c[o],u=n.get(l);if(u===void 0)return e;let d=r[u].encode(c[s],i);return i.objects++,a?(i.objects++,{[o]:l,[s]:Object.fromEntries(t.map(e=>[e,e===l?d:null]))}):{[o]:l,[s]:d}}})}},Sf=class extends Zd{kind=`never`;children(){return[]}print(){return`never`}compile(e){return wf(e,()=>this.ruleHint())}};function Cf(e,t){let n=Wf(e,t);return n?n.kind===`never`?!0:n instanceof sf?n.values.length===0:n instanceof gf&&n.options.every(e=>Cf(e,t)):!1}function wf(e,t){return e.node({hint:()=>[`No value is allowed here.`,t()].filter(Boolean).join(` `),emit:()=>e.profile.conditionals?{not:{}}:{type:`null`},run:(e,t)=>Pf(t,e,`No value is allowed here.`,`not-allowed`),encode:e=>e})}var Tf=class extends Zd{constructor(e,t){super(),this.inner=e,this.value=t}inner;value;kind=`default`;children(){return[this.inner]}print(e){return e.print(this.inner)}fresh(e){let t=this.value;return typeof t!=`object`||!t?t:(e&&(Array.isArray(t)?e.arrays++:e.objects++),structuredClone(t))}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`,r=this.inner instanceof Df;return e.node({own:!0,deps:[t],hint:()=>this.hintOf([`Default when left out: ${JSON.stringify(t.encode(this.value))}.`]),emit:()=>n&&!r?e.nullable(t.json()):t.json(),run:(e,i)=>e===void 0||e===null&&n&&!r?this.fresh(i.dry?void 0:i.stats):t.run(e,i),encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},Ef=class extends Zd{constructor(e){super(),this.inner=e}inner;kind=`optional`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | undefined`}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`;return e.node({own:n,deps:[t],emit:()=>n?e.nullable(t.json()):t.json(),run:(e,r)=>e===void 0?e:e===null&&n&&!(this.inner instanceof Df)?void 0:t.run(e,r),encode:(e,r)=>e===void 0?n?null:void 0:t.encode(e,r),child:e=>t.child(e)})}},Df=class extends Zd{constructor(e){super(),this.inner=e}inner;kind=`nullable`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | null`}compile(e){let t=e.guarded(this.inner);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>e.nullable(t.json()),run:(e,n)=>e===null?e:t.run(e,n),encode:(e,n)=>e===null?null:t.encode(e,n),child:e=>t.child(e)})}},Of=class extends Zd{constructor(e){super(),this.name=e}name;kind=`ref`;children(){return[]}print(e){return e.ref(this.name)}compile(e){return e.ref(this.name)}},kf=class extends Zd{constructor(e,t){super(),this.wire=e,this.codec=t}wire;codec;kind=`codec`;children(){return[this.wire]}print(e){return e.print(this.wire)}compile(e){let t=e.compile(this.wire);return e.node({own:!0,deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>{let r=n.errors.length,i=t.run(e,n);if(n.errors.length!==r)return e;let a=this.codec.decode(i);if(a instanceof Error)return Pf(n,e,a.message,`other`);if(a instanceof fd){if(!a.issues.length)return Pf(n,e,`Rejected.`,`rule`);for(let e of a.issues)n.failAt(e.path,e.message,`rule`);return e}return a},encode:(e,n)=>t.encode(this.codec.encode(e),n)})}};function Af(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jf(e){return typeof e==`string`?Mf(e)??`string`:e===null?`null`:Array.isArray(e)?`a list`:typeof e==`object`?`an object`:typeof e}function Mf(e){let t=e.trimStart()[0];if(t===`{`||t===`[`)try{JSON.parse(e);return}catch(e){return`a string of JSON text that doesn't parse (${e.message}); send the value itself, not as a string`}}function Nf(e){return typeof e==`string`?`string`:typeof e==`number`?`number`:typeof e==`boolean`?`boolean`:`null`}function Pf(e,t,n,r=`type`,i){return typeof i==`function`?e.fail(n,r,t,i):e.fail(n,r,t,void 0,i),t}function Ff(e,t=30){return e.length<=t?e.join(`, `):`${e.slice(0,t).join(`, `)}, \u2026 (${e.length-t} more)`}function If(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Lf(e,t,n,r=0){let i=Wf(e,n);if(i instanceof pf){let e=Wf(i.shape[t],n);return e instanceof of?[e.value]:e instanceof sf?[...e.values]:void 0}if(i instanceof gf&&r<8){let e=[];for(let a of i.options){let i=Lf(a,t,n,r+1);if(!i)return;e.push(...i)}return e}}function Rf(e,t,n=0){let r=[];for(let i of e){let e=Wf(i,t);e instanceof sf?r.push(...e.values):e instanceof of&&typeof e.value==`string`?r.push(e.value):e instanceof gf&&n<8&&r.push(...Rf(e.options,t,n+1))}return r}function zf(e,t,n=0){let r=Wf(e,t);return r instanceof pf?Object.keys(r.shape):r instanceof gf&&n<8?zf(r.options[0],t,n+1):[]}var Bf=new WeakMap;function Vf(e,t){let n=Bf.get(e);n||Bf.set(e,n=new WeakMap);let r=n.get(t);if(r===void 0){if(r=null,e.length>1)for(let n of zf(e[0],t)){let i=new Set,a=!0;for(let r of e){let e=Lf(r,n,t);if(!e||e.some(e=>i.has(e))){a=!1;break}for(let t of e)i.add(t)}if(a){r=n;break}}n.set(t,r)}return r??void 0}function Hf(e,t,n){if(!Af(t))return-1;let r=t,i=-1,a=0,o=!1;if(e.forEach((e,t)=>{let s=0;for(let t of zf(e,n)){let i=Lf(e,t,n);i&&t in r&&(s+=i.includes(r[t])?1:-1)}s>a?(i=t,a=s,o=!1):s===a&&s>0&&(o=!0)}),!o&&i>=0)return i;let s=Object.keys(r);return s.length?(i=-1,a=0,o=!1,e.forEach((e,t)=>{let r=new Set(zf(e,n));if(!r.size||s.some(e=>!r.has(e)))return;let c=s.length;c>a?(i=t,a=c,o=!1):c===a&&(o=!0)}),o?-1:i):-1}function Uf(e,t,n=`json`){let r=e.node({own:!0,deps:[t],emit:()=>e.object({[n]:t.json()},[n]),run:(e,r)=>{if(!Af(e)||!(n in e))return Pf(r,e,n===`json`?`Expected {"json": "<JSON text>"}.`:`Expected {"${n}": [...]}.`);r.enter(n,null);let i=t.run(e[n],r);return r.leave(!1),i},encode:(e,r)=>(r.objects++,{[n]:t.encode(e,r)})});return e.nodes.push(r),r}function Wf(e,t){for(let n=0;e instanceof Of&&n<16;n++)e=t.get(e.name);return e}function Gf(e,t,n){let r=new bd(!1,!0,pd(),!1,!0);return e.lenient().nodeFor(t).run(n,r),r.errors.length===0}function Kf(e,t,n,r,i,a){r!==void 0&&(i?e[n]=r:t.includes(a)||t.push(a))}function qf(e,t,n){if(!t.repair||typeof e!=`string`)return e;let r=e;for(let t=0;t<2&&typeof r==`string`;t++){let t=r.trim();if(!/^[[{"]/.test(t))return e;try{r=JSON.parse(t)}catch{return e}}return(n===`array`?Array.isArray(r):Af(r))?(t.dry||t.stats.repaired++,r):e}function Jf(e,t,n){let r=e;for(let i=0;i<e.length;i++){let a=t(e[i],i);a!==e[i]&&(r===e&&(r=e.slice(),n.arrays++),r[i]=a)}return r}function Yf(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e={...t},i.stats.objects++),e[n]=r,e)}function Xf(e,t,n,r){return r.inPlace?(r.saving(t,n,!0),delete t[n],r.stats.edits++,t):(e===t&&(e={...t},r.stats.objects++),delete e[n],e)}function Zf(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e=t.slice(),i.stats.arrays++),e[n]=r,e)}function Qf(e,t={unsupported:[]}){let n=typeof e==`object`?e:{},r={...n.definitions??{},...n.$defs??{}},i={},a=!1,o=e=>{if(e===`#`)return a=!0,`__root`;let n=/^#\/(?:\$defs|definitions)\/(.+)$/.exec(e);return n?n[1].replace(/~1/g,`/`).replace(/~0/g,`~`):(t.unsupported.push(`$ref ${e}`),`__any`)},s=e=>{if(e===!0||e===void 0)return new cf;if(e===!1)return new gf([new af]).refine(()=>!1,`No value is allowed here.`);let{allOf:n,not:r,if:i,then:a,else:o,...l}=e,u=Object.keys(l).every(e=>[`description`,`title`,`examples`,`$comment`,`default`].includes(e)),d=c(l);if(Array.isArray(n)&&n.length){let e=n.map(s),t=u?e:[d,...e];d=t.length===1?t[0]:new _f(t)}r!==void 0&&(d=new vf(s(r),d)),i!==void 0&&(d=new yf(d,s(i),a===void 0?void 0:s(a),o===void 0?void 0:s(o)));for(let n of[`dependentSchemas`,`dependentRequired`])n in e&&t.unsupported.push(n);return typeof e.description==`string`&&(d=d.describe(e.description)),typeof e.title==`string`&&(d=d.title(e.title)),Array.isArray(e.examples)&&(d=d.example(...e.examples)),d},c=e=>{if(typeof e.$ref==`string`)return new Of(o(e.$ref));if(`const`in e)return new of(e.const);if(Array.isArray(e.enum)){let t=e.enum,n=t.filter(e=>typeof e==`string`),r=t.includes(null),i=n.length===t.length-+!!r&&n.length?new sf(n):new gf(t.filter(e=>e!==null).map(e=>new of(e)));return r?new Df(i):i}let t=e.anyOf??e.oneOf;if(Array.isArray(t)){let e=t.map(s),n=e.filter(e=>!(e instanceof af)),r=n.length===1?n[0]:new gf(n);return n.length<e.length?new Df(r):r}if(Array.isArray(e.type)){let t=e.type,n=t.filter(e=>e!==`null`).map(t=>c({...e,type:t})),r=n.length===1?n[0]:n.length?new gf(n):new af;return t.includes(`null`)&&n.length?new Df(r):r}let n=e.type??$f(e);switch(n){case`string`:{let t=new tf;return typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),typeof e.pattern==`string`&&(t=t.pattern(e.pattern)),typeof e.format==`string`&&(t=t.format(e.format)),t}case`number`:case`integer`:{let t=new nf({int:e.type===`integer`});return typeof e.minimum==`number`&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&(t=t.max(e.maximum)),t}case`boolean`:return new rf;case`null`:return new af;case`array`:{if(Array.isArray(e.prefixItems)&&e.prefixItems.length)return new ff(e.prefixItems.map(s));let t=new df(s(e.items??!0));return typeof e.minItems==`number`&&(t=t.min(e.minItems)),typeof e.maxItems==`number`&&(t=t.max(e.maxItems)),t}default:{if(n===void 0&&!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new cf;if(!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new mf(new cf);let t=e.properties??{},r=new Set(e.required??[]),i=e.additionalProperties,a=e.patternProperties;if(!Object.keys(t).length&&!a&&i!==void 0&&i!==!1)return new mf(i===!0?new cf:s(i));let o={};for(let[e,n]of Object.entries(t))o[e]=r.has(e)?s(n):new Ef(s(n));for(let e of r)e in o||(o[e]=new cf);let c=new pf(o);return a&&(c=c.patterns(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,s(t)])))),i===!0?c=c.rest(new cf):i!==void 0&&typeof i==`object`&&(c=c.rest(s(i))),i===!1?c.strict():c}}};for(let[e,t]of Object.entries(r))i[e]=s(t);let{$defs:l,definitions:u,...d}=n,f=s(d);a&&(i.__root=f),(t.unsupported.includes(`$ref`)||Object.values(i).some(()=>!1))&&(i.__any=new cf);for(let e of[f,...Object.values(i)].flatMap(e=>[...e.refNames()]))e in i||(e.startsWith(`__`)||t.unsupported.push(`$ref to a missing definition "${e}" (any JSON instead)`),i[e]=new cf().describe(`Unknown reference ${e}.`));return new Gd(i,a?new Of(`__root`):f)}function $f(e){if([`minLength`,`maxLength`,`pattern`,`format`].some(t=>t in e))return`string`;if([`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`].some(t=>t in e))return`number`;if([`items`,`prefixItems`,`minItems`,`maxItems`].some(t=>t in e))return`array`;if([`properties`,`required`,`patternProperties`,`additionalProperties`].some(t=>t in e))return`object`}var ep=()=>new tf,tp=()=>new nf,np=()=>new nf({int:!0}),rp=()=>new rf,ip=()=>new af,ap=e=>new of(e);function op(e){return new sf([...e])}var sp=()=>new Sf,cp=()=>new cf,lp=()=>new cf,up=e=>new pf(e),dp=e=>new df(e),fp=e=>new ff(e);function pp(e,t){return t?new mf(t,e):new mf(e)}function mp(e){return new gf([...e])}function hp(e,t){return new gf([...t],e)}var gp=e=>new _f(e);function _p(e,t){return new vf(e,t??new cf)}function vp(e,t){return new yf(e,t.if,t.then,t.else)}function yp(e,t,n){return new bf(e,t,n)}var bp=e=>new Ef(e),xp=(e,t)=>new Tf(e,t),Sp=e=>new Df(e),Cp=e=>new Of(e),wp=e=>new Of(e),Tp=(e,t)=>new kf(e,t),Ep=(e,t={})=>new xf(e,t.tag??`tool`,t.args??`args`),Dp=e=>new Hd(e),Op=()=>new Hd,kp=()=>new Hd;function Ap(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function jp(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function Mp(e,t,n){let r=e.toLowerCase(),i=t.map((t,n)=>({candidate:t,index:n,ci:Ap(r,t.toLowerCase()),exact:Ap(e,t)})).filter(e=>e.ci<=n);return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function Np(e,t,n=jp(e.length)){return Mp(e,t,n)[0]}function Pp(e,t,n={}){let r=Math.max(1,n.max??1),i=Mp(e,t,jp(e.length)).slice(0,r);return i.length===0?``:` \u2014 did you mean ${Fp(i.map(e=>`\`${e}\``))}?`}function Fp(e){return e.length===2?`${e[0]} or ${e[1]}`:e.length>2?`${e.slice(0,-1).join(`, `)}, or ${e[e.length-1]}`:e.join(`, `)}function Ip(e,t,n=2){let r=e.length,i=t.length,a=[];for(let e=0;e<=i;e++)a[e]=e*n;for(let o=1;o<=r;o++){let r=a[0];a[0]=o*n;let s=e[o-1].toLowerCase();for(let e=1;e<=i;e++){let i=a[e],o=r+Ap(s,t[e-1].toLowerCase());a[e]=Math.min(a[e]+n,a[e-1]+n,o),r=i}}return a[i]}function Lp(e,t,n,r,i={}){if(r.length===0)return;let a=i.maxDepth??Math.min(6,r.length+1),o=r[r.length-1].toLowerCase(),s=jp(o.length),c=r.reduce((e,t)=>e+jp(t.length),0)+2,l=i.nodeBudget??2e3,u,d=new Set,f=(e,i)=>{if(!(l<=0)){for(let n of t(e)){if(l<=0)return;if(l--,Ap(n.toLowerCase(),o)>s)continue;let e=[...i,n],t=Ip(e,r);t>c||(!u||t<u.score||t===u.score&&e.length<u.path.length)&&(u={score:t,path:e})}if(!(i.length>=a||d.has(e))){d.add(e);for(let[t,r]of n(e)){if(l<=0)break;f(r,[...i,t])}d.delete(e)}}};return f(e,[]),u?.path}var Rp=[`name`,`docs`,`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`],zp=[`docs`,`type`,`get`,`default`,`set`],Bp=[`docs`,`key`,`value`,`get`,`set`,`loop`,`loopDynamic`],Vp=[`docs`,`types`,`args`,`returns`,`throws`,`get`,`set`],Hp=[`docs`,`args`,`run`];function Up(e,t,n,r){let i=e;for(let n of Jp(i))if(!Rp.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown key '${n}'`+Qp(n,i[n],Rp,t,`top`,r));let a=Yp(e.options)?e.options:void 0;if(t?.optionKeys&&a){for(let n of Jp(a))if(!t.optionKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown options key '${n}'`+Qp(n,a[n],t.optionKeys,t,`options`,r))}let o=Yp(e.generic)?e.generic:void 0;if(n&&t?.genericKeys&&o){for(let n of Jp(o))if(!t.genericKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown generic parameter '${n}'`+Qp(n,o[n],t.genericKeys,t,`generic`,r))}}function Wp(e,t,n,r,i){if(Yp(t))for(let a of Jp(t)){if(n.includes(a))continue;let o=r?.[a],s=typeof o==`function`?o(t[a],i):o,c=Np(a,n);throw Error(`gin.parse: ${e} has unknown key '${a}'`+(s?` \u2014 ${s}`:c?` \u2014 did you mean \`${c}\`?`:` \u2014 valid keys: ${n.join(`, `)}`))}}var Gp={generic:`a fn declares its type parameters on the TYPE, not the call: {"name":"fn","generic":{"T":{"name":"any"}},"call":{"args":…,"returns":…}}`},Kp=[{by:`prop`,keys:[`prop`],example:`{"prop":"name"}`},{by:`args`,keys:[`args`,`generic`,`catch`],example:`{"args":{…}}`},{by:`key`,keys:[`key`],example:`{"key":<expr>}`}];function qp(e){if(!Yp(e))return;let t=Kp.filter(t=>e[t.by]!==void 0);if(t.length===0){let t=Jp(e),n=Kp.map(e=>e.by),r=t.map(e=>Np(e,n)).find(e=>e!==void 0);throw Error(`gin.parse: path step selects no form (keys: ${t.join(`, `)||`none`})`+(r?` \u2014 did you mean \`${r}\`?`:``)+` \u2014 a step is one of ${Kp.map(e=>e.example).join(`, `)}`)}if(t.length>1){let n=t.map(e=>`'${e.by}'`).join(` and `),r=t.map(t=>t.by===`prop`?JSON.stringify({prop:e.prop}):t.example).join(`, `);throw Error(`gin.parse: path step names ${t.length} forms (${n}) \u2014 each is its own step: [${r}]`)}Wp(`path step`,e,t[0].keys)}function Jp(e){return Object.keys(e).filter(t=>e[t]!==void 0)}function Yp(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xp(e){return Array.isArray(e)?e.length>0&&Xp(e[0]):Yp(e)&&typeof e.name==`string`}function Zp(e){return Yp(e)&&`type`in e}function Qp(e,t,n,r,i,a){let o=[],s=Np(e,n);if(s)return` \u2014 did you mean \`${s}\`?`;let c=r?.genericKeys??[],l=i===`options`?em(t,r,a):void 0;return l?o.push(l):r&&i!==`generic`&&c.length>0&&Xp(t)?o.push(`that value is a TypeDef, and '${r.NAME}' takes its type argument${c.length>1?`s`:``} in \`generic\` (${c.join(`, `)})`):i===`top`&&Zp(t)&&(r?.consumes??[]).includes(`props`)&&o.push("that value is a PropDef — declare it under `props`"),o.push(rm(n,r,i)),` \u2014 ${o.join(`; `)}`}var $p=12;function em(e,t,n){if(!(!t||t.NAME===`enum`||(t.genericKeys?.length??0)>0))return nm(e,n,"an `enum` in gin, not an option")}var tm={values:(e,t)=>t?nm(e,t,`the prop's TYPE in gin, not a key beside it`,e=>`{"type":${e}}`):"a closed set of constants is the prop's TYPE in gin, not a key beside it: declare `type` as an `enum`"};function nm(e,t,n,r=e=>e){let i=!Array.isArray(e)&&Yp(e),a=Array.isArray(e)?e:i?Object.values(e):void 0;if(!a||a.length===0)return;let o=typeof a[0];if(!a.every(e=>typeof e===o)||o!==`number`&&o!==`boolean`&&o!==`string`)return;let s=`a closed set of constants is ${n}`;if(a.length>$p)return s;let c=i?e:Object.fromEntries(a.map(e=>[String(e),e])),l=o===`number`?t.enum(c,t.num()):o===`boolean`?t.enum(c,t.bool()):o===`string`?t.enum(c,t.text()):void 0;if(l)return`${s}: ${r(JSON.stringify(l.toJSON()))}`}function rm(e,t,n){let r=t?`'${t.NAME}'`:`this type`;return n===`top`?`valid keys: ${e.join(`, `)}`:n===`options`?e.length===0?`${r} takes no options`:`valid options for ${r}: ${e.join(`, `)}`:e.length===0?`${r} is not generic`:`valid generic parameters for ${r}: ${e.join(`, `)}`}var im=/^(?:\w[\w-]*\/)*\w+$/;function am(e){return typeof e==`string`&&im.test(e)}var om={any:`Type_any`,void:`Type_void`,null:`Type_null`,bool:`Type_bool`,num:`Type_num`,text:`Type_text`,list:`Type_list`,map:`Type_map`,tuple:`Type_tuple`,obj:`Type_object`,optional:`Type_optional`,nullable:`Type_nullable`,not:`Type_not`,or:`Type_or`,and:`Type_and`,enum:`Type_enum`,literal:`Type_literal`,fn:`Type_function`,interface:`Type_interface`,typ:`Type_typ`,date:`Type_date`,timestamp:`Type_timestamp`,duration:`Type_duration`,color:`Type_color`},sm=()=>R.string().pattern(im.source).describe(`A type name: an identifier, optionally namespaced as ns/Name.`);function cm(e,t){let n=om[t],r=e.typeClass(t);return r!==void 0&&n!==void 0&&e.namedTypeList().every(e=>e.name!==t)?R.ref(n):r===void 0?R.object({name:R.literal(t)}):r.toA?.()??R.object({name:R.literal(t)})}function lm(){return R.object({name:sm()}).strict().describe(`A named type, by its name.`)}function um(e){return R.object({name:sm(),extends:e.length>0?R.enum([...new Set(e)]):R.never(),docs:R.string().optional(),satisfies:R.array(sm()).optional(),generic:R.ref(`Generic`).optional(),options:R.record(R.unknown()).optional(),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional(),init:R.ref(`InitDef`).optional(),constraint:R.ref(`Expr`).optional()}).describe(`A NEW named type declared inline: a name, the type it extends, and what it adds.`)}var dm=R.ref(`TypeDef`),z=R.ref(`Expr`),fm=R.string().optional().describe("Optional one-line note explaining why this expression exists. Travels with the node, surfaces in `toCode` as a `/* … */` annotation, and shows up in error paths. Use for non-obvious steps; skip for trivial reads."),pm={Generic:R.record(dm).describe(`Generic-parameter bindings: parameter name → TypeDef.`),PathStep:R.union([R.object({prop:R.string().describe("Named-property access. First step looks up a scope variable by name; subsequent steps read the previous value's prop / method. Reject if the name isn't on the type's `props()`.")}).describe("PROP step — `.<name>` access (scope var on first step, prop/method on later steps)."),R.object({args:R.record(z).describe("Map of arg-name → ExprDef. Calls the previous step (a method or any callable). Each arg expression is evaluated in the caller scope before the call; the result obj is bound as `args` inside the call body."),generic:R.ref(`Generic`).optional().describe("Optional generic-parameter map for parameterized callables (e.g. `list.map<R>` binds `R` to the element type of the result list). Usually unnecessary — most callables infer generics."),catch:z.optional().describe("Optional handler expression evaluated if this call throws. The thrown value is bound under `error` in the handler scope.")}).describe("CALL step — invoke the previous step, as its OWN step. Comes after a method (e.g. `list.push`) or any callable value; never fused into the prop step as `{prop, args}`."),R.object({key:z.describe("Indexed-access key expression. Evaluated at run time and passed to the previous value's `[key]` get/set surface.")}).describe("INDEX step — `[<key>]` access for types with index signatures (lists by `num`, maps by their key type).")]),PropDef:R.object({docs:R.string().optional(),type:dm,get:z.optional(),default:z.optional(),set:z.optional()}),GetSetDef:R.object({docs:R.string().optional(),key:dm,value:dm,get:z.optional(),set:z.optional(),loop:z.optional(),loopDynamic:R.boolean().optional().describe("When true, `loop over: <this-typed value>` re-evaluates the expression each iteration and exits when the result's raw is falsy. Bool uses this for while-loop semantics. The type may have either `loop` (for static iterables) OR `loopDynamic` set; with loopDynamic, no `loop` ExprDef is required.")}),CallDef:R.object({docs:R.string().optional(),types:R.record(dm).optional().describe('Call-local type aliases. Declare reusable named types here ONCE and reference them inside `args` / `returns` / `throws` / `get` / `set` as a bare `{name: "<alias>"}`. Aliases process AFTER any enclosing generics (so they may reference generic placeholders) and BEFORE the call slots — the call slots resolve them at parse time. Sequential: later aliases may reference earlier ones. Use this whenever the same composite type appears more than once in a signature — instead of writing `num{whole:true, min:1}` four times, declare `{ counter: { name:"num", options:{whole:true,min:1} } }` once and reference `{name:"counter"}`.'),args:dm,returns:dm.optional(),throws:dm.optional(),get:z.optional(),set:z.optional()}),InitDef:R.object({docs:R.string().optional(),args:dm,run:z})},mm=[`any`,`void`,`null`,`bool`,`num`,`text`,`list`,`map`,`tuple`,`obj`,`optional`,`nullable`,`not`,`or`,`and`,`enum`,`literal`,`fn`,`interface`,`typ`,`date`,`timestamp`,`duration`,`color`],hm={Type_any:R.object({name:R.literal(`any`)}),Type_void:R.object({name:R.literal(`void`)}),Type_null:R.object({name:R.literal(`null`)}),Type_bool:R.object({name:R.literal(`bool`),options:R.object({trueText:R.string().optional(),falseText:R.string().optional()}).optional()}),Type_num:R.object({name:R.literal(`num`),options:R.object({min:R.number().optional().describe('Only set when a real lower bound is part of the spec — e.g. "positive count" → min: 1, "age" → min: 0. Do NOT add `min: 0` to every num just because most numbers happen to be non-negative.'),max:R.number().optional().describe(`Only set when there is an actual upper bound — a percentage capped at 100, a year capped at 9999. Do NOT pick a generic ceiling like 1000/9999 to fill the field.`),whole:R.boolean().optional().describe(`Only set to true when the value is genuinely integral (counts, indices, ids). Leave unset (allow fractions) for measurements, ratios, etc.`),minPrecision:R.number().optional().describe(`Decimal-place floor. Almost never needed; omit unless the spec explicitly requires N decimal places.`),maxPrecision:R.number().optional().describe(`Decimal-place ceiling. Same rule as minPrecision — omit unless explicitly required.`),prefix:R.string().optional().describe(`Display-only prefix (e.g. "$"). Has no effect on validation. Omit unless rendering needs it.`),suffix:R.string().optional().describe(`Display-only suffix (e.g. "%"). Same as prefix — omit unless rendering needs it.`)}).optional().describe(`Omit entirely for ordinary numbers. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_text:R.object({name:R.literal(`text`),options:R.object({minLength:R.number().optional().describe(`Only set when a real lower bound is part of the spec — e.g. "non-empty input" → minLength: 1. Do NOT default to 0.`),maxLength:R.number().optional().describe(`Only set when there is an actual upper bound — a database column width, an API limit, an explicit "no longer than X chars" rule. Do NOT pick a generic ceiling like 100/200/1000 just to fill the field.`),pattern:R.string().optional().describe(`Only set for actual format constraints (UUID, ISO date, slug, etc.). Do NOT use ".*" or other accept-anything patterns — they add zero validation and clutter the schema.`),flags:R.string().optional().describe('Regex flags (e.g. "i"). Omit unless `pattern` is set AND requires flags.')}).optional().describe(`Omit entirely for ordinary strings. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_list:R.object({name:R.literal(`list`),generic:R.object({V:dm}).optional(),options:R.object({minLength:R.number().optional(),maxLength:R.number().optional()}).optional()}),Type_map:R.object({name:R.literal(`map`),generic:R.object({K:dm,V:dm}).optional()}),Type_tuple:R.object({name:R.literal(`tuple`),options:R.object({elements:R.array(dm)})}),Type_object:R.object({name:R.literal(`obj`),props:R.record(R.ref(`PropDef`)).optional()}),Type_optional:R.object({name:R.literal(`optional`),generic:R.object({T:dm}).optional()}),Type_nullable:R.object({name:R.literal(`nullable`),generic:R.object({T:dm}).optional()}),Type_not:R.object({name:R.literal(`not`),options:R.object({excluded:dm})}),Type_or:R.object({name:R.literal(`or`),options:R.object({types:R.array(dm)})}),Type_and:R.object({name:R.literal(`and`),options:R.object({types:R.array(dm)})}),Type_enum:R.object({name:R.literal(`enum`),generic:R.object({V:dm}).optional(),options:R.object({values:R.record(R.unknown())})}),Type_literal:R.object({name:R.literal(`literal`),generic:R.object({T:dm}).optional(),options:R.object({value:R.unknown()})}),Type_function:R.object({name:R.literal(`fn`),call:R.ref(`CallDef`).optional()}),Type_interface:R.object({name:R.literal(`interface`),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional()}),Type_typ:R.object({name:R.literal(`typ`),generic:R.object({T:dm}).optional()}),Type_date:R.object({name:R.literal(`date`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional()}).optional()}),Type_timestamp:R.object({name:R.literal(`timestamp`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional(),precision:R.enum([`ms`,`s`,`us`]).optional()}).optional()}),Type_duration:R.object({name:R.literal(`duration`)}),Type_color:R.object({name:R.literal(`color`),options:R.object({hasAlpha:R.boolean().optional()}).optional()})},gm={Expr_block:R.object({kind:R.literal(`block`),comment:fm,lines:R.array(z).describe(`Sequence of expressions evaluated in order. The block's value is the LAST line's value (an empty block returns void). Earlier lines run for their side effects (set, fns.fetch, etc.).`)}),Expr_define:R.object({kind:R.literal(`define`),comment:fm,vars:R.array(R.object({name:R.string().describe(`Variable name. Must NOT be a reserved name (args, recurse, this, super, key, value, yield, error) and must NOT shadow anything already in scope.`),type:dm.optional().describe("Optional declared type. OMIT this field when the value already determines the type — every value Expr (`new`, `get`, `if`, ...) is typed, and the var inherits that type. Set this only when you need to widen / narrow / annotate beyond what the value alone produces; a mismatch with the value's inferred type is reported as `define.var.type-mismatch`."),value:z.describe("The expression whose result is bound under `name`. May reference any earlier var in this define — each var is added to scope before the next var's value is evaluated.")})).describe("Bindings introduced before `body`. Evaluated sequentially, so `vars[i].value` may reference any of `vars[0..i-1]`."),body:z}),Expr_flow:R.object({kind:R.literal(`flow`),action:R.enum([`break`,`continue`,`return`,`exit`,`throw`]).describe("Which control-flow signal to raise. `break`/`continue` only valid inside a loop. `return` only valid inside a fn body / lambda; unwinds to the enclosing call with `value`. `exit` unwinds all the way to `engine.run`, returning `value` as the program result. `throw` raises `error` (caught by a path step's `catch:` handler)."),value:z.optional().describe("Required for `return` and `exit` (the value being returned). Ignored by `break` / `continue` / `throw`."),error:z.optional().describe("Required for `throw` — the value to raise. Ignored otherwise.")}),Expr_get:R.object({kind:R.literal(`get`),path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right starting from a scope variable. Step shapes: `{prop:"name"}` for prop/method access, `{args:{…}}` to call the previous step, `{key:Expr}` for index access. The first step MUST be a prop step (the scope-var name). A step names exactly ONE shape — a call is its own step, so a method with arguments is `[{"prop":"m"},{"args":{…}}]` and never `{"prop":"m","args":{…}}`. Result is the final step\'s value.')}),Expr_if:R.object({kind:R.literal(`if`),comment:fm,ifs:R.array(R.object({condition:z.describe("Bool-typed expression. First branch whose condition is `true` wins; the rest are skipped."),body:z.describe(`Evaluated when this branch's condition is true. The if-expression's value is this body's value.`)})).describe("Ordered list of `{condition, body}` branches — first true condition wins. Each `condition` must be bool-typed (warned otherwise). With multiple branches this is the gin equivalent of `if / else if / else if`."),else:z.optional().describe("Optional fallback evaluated when every `ifs[i].condition` is false. Without an else, a no-match if-expression evaluates to void.")}),Expr_lambda:R.object({kind:R.literal(`lambda`),comment:fm,type:dm.describe('The lambda\'s function type — `{ name: "fn", call: { args, returns } }` (or a registered named fn type). The `args` obj defines what the body sees under the `args` scope variable; `returns` is what the body must produce.'),body:z.describe('The lambda body. At runtime, scope contains the lexical scope at definition site PLUS `args` (the call arguments) and `recurse` (this same lambda, for self-calls). Read params via `[{prop:"args"},{prop:"<name>"}]`.'),constraint:z.optional().describe("Optional bool-typed precondition evaluated before the body on every call (with `args` in scope). If it returns false, the call throws. Use for input invariants you want enforced regardless of caller.")}),Expr_loop:R.object({kind:R.literal(`loop`),comment:fm,over:z.describe("The iterable expression. Two evaluation modes: (1) iterable types (list, map, etc. — anything whose `get().loop` is defined) iterate once; the expression is evaluated ONCE at the start. (2) bool — while-loop semantics: the expression is RE-EVALUATED each iteration; the loop continues while the value is `true` and exits the moment it becomes `false`. Use `flow:break` / `flow:continue` inside the body to control iteration regardless of mode."),body:z.describe("Evaluated once per iteration with the current `key` and `value` bound in scope. Use `{kind:'flow', action:'break'}` or `'continue'` for early-exit. The loop expression itself returns void."),key:R.string().optional().describe("Override the scope-variable name the iteration index/key is bound under (default: `key`). Must NOT be reserved or shadow an outer scope var. Use to disambiguate when looping inside another loop."),value:R.string().optional().describe("Override the scope-variable name the iteration value is bound under (default: `value`). Same rules as `key`."),parallel:R.object({concurrent:z.optional().describe(`Max in-flight iterations as a num (omit / 1 → strictly sequential). Use when iterations are independent I/O — e.g. fetching N URLs concurrently.`),rate:z.optional().describe(`Minimum interval between iteration starts. Accepts a num (milliseconds) or a duration. Use to rate-limit fan-out (e.g. avoid hammering an API).`)}).optional().describe("Opt-in parallelism. Both fields are optional and independent: `concurrent` caps fan-out width, `rate` paces start times. Iterations may finish out of order; the body should not assume sequential ordering. Composes with dynamic (bool while-loop) iteration: the body fans out up to `concurrent`, and `over` is re-evaluated against the outer scope each time a task completes — so accumulating side effects of earlier tasks decide whether more tasks spawn.")}),Expr_native:R.object({kind:R.literal(`native`),comment:fm,id:R.string().describe("Identifier of a native impl registered via `registry.setNative(id, fn)` (e.g. `list.push`, `num.add`). The model should NOT generate `native` expressions directly — methods on built-in types are reached via `get` paths, which gin resolves to natives internally."),type:dm.optional().describe("Optional type to wrap the native's raw return value with when the impl returns a non-Value. Defaults to `any` if omitted.")}),Expr_set:R.object({kind:R.literal(`set`),comment:fm,path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right to a writable target. Single-step `[{prop:"x"}]` re-assigns scope variable `x`. Multi-step targets need the type to support set on the final step (a prop with a `set` ExprDef, an indexed slot, or a method whose call has `set:`).'),value:z.describe("The expression evaluated and assigned to the path target. Its type must be compatible with the target's declared type — checked statically as `set.type-mismatch`.")}),Expr_switch:R.object({kind:R.literal(`switch`),comment:fm,value:z.describe("Expression whose result is compared against each case's `equals` candidates. Evaluated once."),cases:R.array(R.object({equals:R.array(z).describe("Candidate values for this case. The case wins if `value` equals ANY one of them (logical OR). Each candidate's type must be compatible with `value`'s type — checked as `switch.case.type`."),body:z.describe(`Evaluated when this case wins. The switch expression's value is this body's value.`)})).describe(`Ordered list of cases — first match wins. Cases are NOT fall-through; only the matching case's body runs.`),else:z.optional().describe(`Optional fallback evaluated when no case matches. Without an else, a no-match switch evaluates to void.`)}),Expr_template:R.object({kind:R.literal(`template`),template:R.union([z,R.string()]).describe("The template string — either a literal string (auto-wrapped as `new text`) or an Expr that evaluates to text. Placeholders use `{name}` syntax; each `name` is looked up first in `params` (when supplied) and then in the surrounding scope."),params:z.optional().describe("Optional obj-typed expression supplying placeholder values. When omitted or when a key is missing, `{name}` falls back to a scope lookup of the same name — so a `${baseUrl}` placeholder resolves to a surrounding `define baseUrl = ...`. Provide `params` only when placeholders need values not already in scope (or to override scope values).")})},_m=[`new`,`get`,`set`,`define`,`block`,`if`,`switch`,`loop`,`lambda`,`template`,`flow`,`native`],vm={any:R.unknown(),void:R.null(),null:R.null(),bool:R.boolean(),num:R.number(),text:R.string(),list:R.array(z),map:R.array(R.object({key:z,value:z})),tuple:R.array(z),obj:R.record(z),optional:z,nullable:R.nullable(z),not:R.unknown(),or:z,and:z,enum:R.union([R.string(),R.number()]),literal:R.unknown(),fn:R.union([R.string(),R.object({kind:R.string()})]),interface:R.record(z),typ:dm,date:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`),timestamp:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`),duration:R.object({days:R.number().optional(),hours:R.number().optional(),minutes:R.number().optional(),seconds:R.number().optional(),ms:R.number().optional()}),color:R.object({r:R.int().min(0).max(255),g:R.int().min(0).max(255),b:R.int().min(0).max(255),a:R.number().min(0).max(1).optional()})},ym=(e,t,n)=>R.object({kind:R.literal(`new`),type:t.describe(`Full TypeDef for a \`${e}\` instance (name + options + per-class fields).`),value:R.optional(n).describe(`Initial value matching this \`${e}\` instance. Composites accept Expr slots; primitives accept their raw form.`)}),bm=Object.fromEntries(mm.map(e=>[`New_${e}`,ym(e,R.ref(om[e]),vm[e])])),xm=R.object({kind:R.literal(`new`),type:dm.describe("TypeDef of the value being constructed. The `value` field is interpreted relative to this type — primitives take their raw form (`new num` → number), composites take Expr slots (`new list` → Expr[])."),value:R.unknown().optional().describe("Initial value matching `type`. Optional when the type has a defined `init` constructor or a sensible default (empty list, zero num with no constraints, etc.).")}),Sm=new Set([...Object.keys(pm),...Object.keys(hm),...Object.keys(gm),...Object.keys(bm),`TypeDef`,`Type_Extension`,`Expr_new`,`Expr`]),Cm=(e,t)=>t.length===0?R.never():t.length===1?t[0]:R.discriminatedUnion(e,t);function wm(e,t){let n=new Map;for(let e of t?.types??[])n.set(e.name,e);for(let t of e.namedTypeList())n.has(t.name)||n.set(t.name,t);return n}function Tm(e,t){let n=wm(e,t),r=[...n.keys()],i=e.typeClasses(),a=[...r.map(e=>R.object({name:R.literal(e)}).describe(`The registered named type \`${e}\`, by name.`)),...i.map(t=>cm(e,t.NAME)),R.ref(`Type_Extension`)];t?.namedRefs&&a.push(lm());let o=um([...i.map(e=>e.NAME),...r]),s=e.exprClassList().map(e=>_m.includes(e.KIND)&&e.KIND!==`new`?R.ref(`Expr_${e.KIND}`):e.KIND===`new`?R.ref(`Expr_new`):e.toA?.()??R.object({kind:R.literal(e.KIND)}).describe(`A \`${e.KIND}\` expression.`)),c=xm,l={};if(t?.newStrict){let t=[...n].map(([e,t])=>{let r=R.object({kind:R.literal(`new`),type:R.object({name:R.literal(e)}).describe(`Reference to the registered named type \`${e}\` \u2014 name-only, the registry resolves it to its full definition.`),value:R.optional(t.toNewA()).describe(`Initial value for the new \`${e}\` instance. Each composite slot accepts an Expr (Get, NewExpr, etc.); per-slot type correctness is enforced at runtime.`)});return Sm.has(`New_${e}`)||n.has(`New_${e}`)?r:(l[`New_${e}`]=r,R.ref(`New_${e}`))}),r=i.map(t=>om[t.NAME]!==void 0&&mm.includes(t.NAME)?R.ref(`New_${t.NAME}`):ym(t.NAME,cm(e,t.NAME),t.toNewA?.()??R.unknown()));c=R.union([...t,...r])}let u={};for(let[e,t]of n)Sm.has(e)||(u[e]=t.defineA({includeDocs:`all`}));return{...u,...l,TypeDef:Cm(`name`,a),Type_Extension:o,Expr_new:c,Expr:Cm(`kind`,s)}}var Em=new WeakMap,Dm=0,Om=e=>{let t=Em.get(e);return t===void 0&&Em.set(e,t=++Dm),t},km=(e,t)=>`${Om(e)}:${e.version}|${t?.newStrict?`s`:``}${t?.namedRefs?`r`:``}|${(t?.types??[]).map(e=>e.name).join(`,`)}`,Am=R.define(pm).define(hm).define(gm).define(bm).declare(),jm=Am.dynamic((e,t)=>Tm(e,t),{key:km,cacheSize:8});jm.result(`TypeDef`),jm.result(`Expr`);var Mm=class{list=[];stack=[];enter(e){return Array.isArray(e)?this.stack.push(...e):this.stack.push(e),this}leave(e=1){return this.stack.length=Math.max(0,this.stack.length-e),this}at(e,t){let n=Array.isArray(e)?e.length:1;this.enter(e);try{return t()}finally{this.leave(n)}}push(e,t,n=`error`,r){this.list.push({path:this.stack.slice(),code:e,message:t,severity:n,source:r})}error(e,t,n){this.push(e,t,`error`,n)}warn(e,t,n){this.push(e,t,`warning`,n)}info(e,t,n){this.push(e,t,`info`,n)}get hasErrors(){return this.list.some(e=>e.severity===`error`)}},Nm=class extends Error{constructor(e){super(`${e.code}: ${e.message} at ${e.path.join(`.`)}`),this.problem=e,this.name=`TypeError`}problem},B={NONE:0,STATE:1,SYSTEM:2,EXTERNAL:4};function Pm(...e){let t=B.NONE;for(let n of e)t|=n;return t}var V=class e{constructor(e,t=[]){this.text=e,this.spans=t}text;spans;toString(){return this.text}concat(t){if(typeof t==`string`)return new e(this.text+t,this.spans);let n=this.text.length,r=t.spans.map(e=>({...e,start:e.start+n,end:e.end+n}));return new e(this.text+t.text,[...this.spans,...r])}indent(t){if(!t||!this.text.includes(`
|
|
71
|
+
`)},l;if(a){let n={};t.forEach((t,i)=>n[t]=e.nullable(r[i].json())),l={...e.object(n,t),description:`Fill only the field named by "${o}"; set the others to null.`}}else l=r.length===1?r[0].json():{anyOf:r.map(e=>e.json())};return e.object({[o]:n,[s]:l},[o,s])},run:(e,i)=>{let c=Qf(e,i,`object`);if(!Ff(c))return zf(i,c,`Expected an object with "${o}" and "${s}".`);let l=c,u=l[o],d=typeof u==`string`?n.get(u):void 0;if(d===void 0)return i.enter(o),i.fail(`Expected one of: ${Bf(t)}.`,`tool`,u,()=>t),i.leave(),c;let f=l[s];if(a){let e=Qf(f,i,`object`);f=Ff(e)?e[u]:void 0,i.enter(s),i.enter(u,null)}else i.enter(s);let p=f===void 0?zf(i,f,`Required.`,`required`,r[d]):r[d].run(f,i);return a&&i.leave(!1),i.leave(),p!==l[s]&&!i.dry?ep(l,l,s,p,i):l},encode:(e,i)=>{let c=e,l=c[o],u=n.get(l);if(u===void 0)return e;let d=r[u].encode(c[s],i);return i.objects++,a?(i.objects++,{[o]:l,[s]:Object.fromEntries(t.map(e=>[e,e===l?d:null]))}):{[o]:l,[s]:d}}})}},Df=class extends nf{kind=`never`;children(){return[]}print(){return`never`}compile(e){return kf(e,()=>this.ruleHint())}};function Of(e,t){let n=Yf(e,t);return n?n.kind===`never`?!0:n instanceof ff?n.values.length===0:n instanceof xf&&n.options.every(e=>Of(e,t)):!1}function kf(e,t){return e.node({hint:()=>[`No value is allowed here.`,t()].filter(Boolean).join(` `),emit:()=>e.profile.conditionals?{not:{}}:{type:`null`},run:(e,t)=>zf(t,e,`No value is allowed here.`,`not-allowed`),encode:e=>e})}var Af=class extends nf{constructor(e,t){super(),this.inner=e,this.value=t}inner;value;kind=`default`;children(){return[this.inner]}print(e){return e.print(this.inner)}fresh(e){let t=this.value;return typeof t!=`object`||!t?t:(e&&(Array.isArray(t)?e.arrays++:e.objects++),structuredClone(t))}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`,r=this.inner instanceof Mf;return e.node({own:!0,deps:[t],hint:()=>this.hintOf([`Default when left out: ${JSON.stringify(t.encode(this.value))}.`]),emit:()=>n&&!r?e.nullable(t.json()):t.json(),run:(e,i)=>e===void 0||e===null&&n&&!r?this.fresh(i.dry?void 0:i.stats):t.run(e,i),encode:(e,n)=>t.encode(e,n),child:e=>t.child(e)})}},jf=class extends nf{constructor(e){super(),this.inner=e}inner;kind=`optional`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | undefined`}compile(e){let t=e.guarded(this.inner,this),n=e.profile.optional===`null`;return e.node({own:n,deps:[t],emit:()=>n?e.nullable(t.json()):t.json(),run:(e,r)=>e===void 0?e:e===null&&n&&!(this.inner instanceof Mf)?void 0:t.run(e,r),encode:(e,r)=>e===void 0?n?null:void 0:t.encode(e,r),child:e=>t.child(e)})}},Mf=class extends nf{constructor(e){super(),this.inner=e}inner;kind=`nullable`;children(){return[this.inner]}print(e){return`${e.print(this.inner)} | null`}compile(e){let t=e.guarded(this.inner);return e.node({deps:[t],hint:()=>this.ruleHint(),emit:()=>e.nullable(t.json()),run:(e,n)=>e===null?e:t.run(e,n),encode:(e,n)=>e===null?null:t.encode(e,n),child:e=>t.child(e)})}},Nf=class extends nf{constructor(e){super(),this.name=e}name;kind=`ref`;children(){return[]}print(e){return e.ref(this.name)}compile(e){return e.ref(this.name)}},Pf=class extends nf{constructor(e,t){super(),this.wire=e,this.codec=t}wire;codec;kind=`codec`;children(){return[this.wire]}print(e){return e.print(this.wire)}compile(e){let t=e.compile(this.wire);return e.node({own:!0,deps:[t],hint:()=>this.ruleHint(),emit:()=>t.json(),run:(e,n)=>{let r=n.errors.length,i=t.run(e,n);if(n.errors.length!==r)return e;let a=this.codec.decode(i);if(a instanceof Error)return zf(n,e,a.message,`other`);if(a instanceof _d){if(!a.issues.length)return zf(n,e,`Rejected.`,`rule`);for(let e of a.issues)n.failAt(e.path,e.message,`rule`);return e}return a},encode:(e,n)=>t.encode(this.codec.encode(e),n)})}};function Ff(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function If(e){return typeof e==`string`?Lf(e)??`string`:e===null?`null`:Array.isArray(e)?`a list`:typeof e==`object`?`an object`:typeof e}function Lf(e){let t=e.trimStart()[0];if(t===`{`||t===`[`)try{JSON.parse(e);return}catch(e){return`a string of JSON text that doesn't parse (${e.message}); send the value itself, not as a string`}}function Rf(e){return typeof e==`string`?`string`:typeof e==`number`?`number`:typeof e==`boolean`?`boolean`:`null`}function zf(e,t,n,r=`type`,i){return typeof i==`function`?e.fail(n,r,t,i):e.fail(n,r,t,void 0,i),t}function Bf(e,t=30){return e.length<=t?e.join(`, `):`${e.slice(0,t).join(`, `)}, \u2026 (${e.length-t} more)`}function Vf(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Hf(e,t,n,r=0){let i=Yf(e,n);if(i instanceof vf){let e=Yf(i.shape[t],n);return e instanceof df?[e.value]:e instanceof ff?[...e.values]:void 0}if(i instanceof xf&&r<8){let e=[];for(let a of i.options){let i=Hf(a,t,n,r+1);if(!i)return;e.push(...i)}return e}}function Uf(e,t,n=0){let r=[];for(let i of e){let e=Yf(i,t);e instanceof ff?r.push(...e.values):e instanceof df&&typeof e.value==`string`?r.push(e.value):e instanceof xf&&n<8&&r.push(...Uf(e.options,t,n+1))}return r}function Wf(e,t,n=0){let r=Yf(e,t);return r instanceof vf?Object.keys(r.shape):r instanceof xf&&n<8?Wf(r.options[0],t,n+1):[]}var Gf=new WeakMap;function Kf(e,t){let n=Gf.get(e);n||Gf.set(e,n=new WeakMap);let r=n.get(t);if(r===void 0){if(r=null,e.length>1)for(let n of Wf(e[0],t)){let i=new Set,a=!0;for(let r of e){let e=Hf(r,n,t);if(!e||e.some(e=>i.has(e))){a=!1;break}for(let t of e)i.add(t)}if(a){r=n;break}}n.set(t,r)}return r??void 0}function qf(e,t,n){if(!Ff(t))return-1;let r=t,i=-1,a=0,o=!1;if(e.forEach((e,t)=>{let s=0;for(let t of Wf(e,n)){let i=Hf(e,t,n);i&&t in r&&(s+=i.includes(r[t])?1:-1)}s>a?(i=t,a=s,o=!1):s===a&&s>0&&(o=!0)}),!o&&i>=0)return i;let s=Object.keys(r);return s.length?(i=-1,a=0,o=!1,e.forEach((e,t)=>{let r=new Set(Wf(e,n));if(!r.size||s.some(e=>!r.has(e)))return;let c=s.length;c>a?(i=t,a=c,o=!1):c===a&&(o=!0)}),o?-1:i):-1}function Jf(e,t,n=`json`){let r=e.node({own:!0,deps:[t],emit:()=>e.object({[n]:t.json()},[n]),run:(e,r)=>{if(!Ff(e)||!(n in e))return zf(r,e,n===`json`?`Expected {"json": "<JSON text>"}.`:`Expected {"${n}": [...]}.`);r.enter(n,null);let i=t.run(e[n],r);return r.leave(!1),i},encode:(e,r)=>(r.objects++,{[n]:t.encode(e,r)})});return e.nodes.push(r),r}function Yf(e,t){for(let n=0;e instanceof Nf&&n<16;n++)e=t.get(e.name);return e}function Xf(e,t,n){let r=new Td(!1,!0,vd(),!1,!0);return e.lenient().nodeFor(t).run(n,r),r.errors.length===0}function Zf(e,t,n,r,i,a){r!==void 0&&(i?e[n]=r:t.includes(a)||t.push(a))}function Qf(e,t,n){if(!t.repair||typeof e!=`string`)return e;let r=e;for(let t=0;t<2&&typeof r==`string`;t++){let t=r.trim();if(!/^[[{"]/.test(t))return e;try{r=JSON.parse(t)}catch{return e}}return(n===`array`?Array.isArray(r):Ff(r))?(t.dry||t.stats.repaired++,r):e}function $f(e,t,n){let r=e;for(let i=0;i<e.length;i++){let a=t(e[i],i);a!==e[i]&&(r===e&&(r=e.slice(),n.arrays++),r[i]=a)}return r}function ep(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e={...t},i.stats.objects++),e[n]=r,e)}function tp(e,t,n,r){return r.inPlace?(r.saving(t,n,!0),delete t[n],r.stats.edits++,t):(e===t&&(e={...t},r.stats.objects++),delete e[n],e)}function np(e,t,n,r,i){return i.inPlace?(i.saving(t,n),t[n]=r,i.stats.edits++,t):(e===t&&(e=t.slice(),i.stats.arrays++),e[n]=r,e)}function rp(e,t={unsupported:[]}){let n=typeof e==`object`?e:{},r={...n.definitions??{},...n.$defs??{}},i={},a=!1,o=e=>{if(e===`#`)return a=!0,`__root`;let n=/^#\/(?:\$defs|definitions)\/(.+)$/.exec(e);return n?n[1].replace(/~1/g,`/`).replace(/~0/g,`~`):(t.unsupported.push(`$ref ${e}`),`__any`)},s=e=>{if(e===!0||e===void 0)return new pf;if(e===!1)return new xf([new uf]).refine(()=>!1,`No value is allowed here.`);let{allOf:n,not:r,if:i,then:a,else:o,...l}=e,u=Object.keys(l).every(e=>[`description`,`title`,`examples`,`$comment`,`default`].includes(e)),d=c(l);if(Array.isArray(n)&&n.length){let e=n.map(s),t=u?e:[d,...e];d=t.length===1?t[0]:new Sf(t)}r!==void 0&&(d=new Cf(s(r),d)),i!==void 0&&(d=new wf(d,s(i),a===void 0?void 0:s(a),o===void 0?void 0:s(o)));for(let n of[`dependentSchemas`,`dependentRequired`])n in e&&t.unsupported.push(n);return typeof e.description==`string`&&(d=d.describe(e.description)),typeof e.title==`string`&&(d=d.title(e.title)),Array.isArray(e.examples)&&(d=d.example(...e.examples)),d},c=e=>{if(typeof e.$ref==`string`)return new Nf(o(e.$ref));if(`const`in e)return new df(e.const);if(Array.isArray(e.enum)){let t=e.enum,n=t.filter(e=>typeof e==`string`),r=t.includes(null),i=n.length===t.length-+!!r&&n.length?new ff(n):new xf(t.filter(e=>e!==null).map(e=>new df(e)));return r?new Mf(i):i}let t=e.anyOf??e.oneOf;if(Array.isArray(t)){let e=t.map(s),n=e.filter(e=>!(e instanceof uf)),r=n.length===1?n[0]:new xf(n);return n.length<e.length?new Mf(r):r}if(Array.isArray(e.type)){let t=e.type,n=t.filter(e=>e!==`null`).map(t=>c({...e,type:t})),r=n.length===1?n[0]:n.length?new xf(n):new uf;return t.includes(`null`)&&n.length?new Mf(r):r}let n=e.type??ip(e);switch(n){case`string`:{let t=new sf;return typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),typeof e.pattern==`string`&&(t=t.pattern(e.pattern)),typeof e.format==`string`&&(t=t.format(e.format)),t}case`number`:case`integer`:{let t=new cf({int:e.type===`integer`});return typeof e.minimum==`number`&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&(t=t.max(e.maximum)),t}case`boolean`:return new lf;case`null`:return new uf;case`array`:{if(Array.isArray(e.prefixItems)&&e.prefixItems.length)return new _f(e.prefixItems.map(s));let t=new gf(s(e.items??!0));return typeof e.minItems==`number`&&(t=t.min(e.minItems)),typeof e.maxItems==`number`&&(t=t.max(e.maxItems)),t}default:{if(n===void 0&&!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new pf;if(!e.properties&&!e.patternProperties&&e.additionalProperties===void 0&&!e.required)return new yf(new pf);let t=e.properties??{},r=new Set(e.required??[]),i=e.additionalProperties,a=e.patternProperties;if(!Object.keys(t).length&&!a&&i!==void 0&&i!==!1)return new yf(i===!0?new pf:s(i));let o={};for(let[e,n]of Object.entries(t))o[e]=r.has(e)?s(n):new jf(s(n));for(let e of r)e in o||(o[e]=new pf);let c=new vf(o);return a&&(c=c.patterns(Object.fromEntries(Object.entries(a).map(([e,t])=>[e,s(t)])))),i===!0?c=c.rest(new pf):i!==void 0&&typeof i==`object`&&(c=c.rest(s(i))),i===!1?c.strict():c}}};for(let[e,t]of Object.entries(r))i[e]=s(t);let{$defs:l,definitions:u,...d}=n,f=s(d);a&&(i.__root=f),(t.unsupported.includes(`$ref`)||Object.values(i).some(()=>!1))&&(i.__any=new pf);for(let e of[f,...Object.values(i)].flatMap(e=>[...e.refNames()]))e in i||(e.startsWith(`__`)||t.unsupported.push(`$ref to a missing definition "${e}" (any JSON instead)`),i[e]=new pf().describe(`Unknown reference ${e}.`));return new Xd(i,a?new Nf(`__root`):f)}function ip(e){if([`minLength`,`maxLength`,`pattern`,`format`].some(t=>t in e))return`string`;if([`minimum`,`maximum`,`exclusiveMinimum`,`exclusiveMaximum`,`multipleOf`].some(t=>t in e))return`number`;if([`items`,`prefixItems`,`minItems`,`maxItems`].some(t=>t in e))return`array`;if([`properties`,`required`,`patternProperties`,`additionalProperties`].some(t=>t in e))return`object`}var ap=()=>new sf,op=()=>new cf,sp=()=>new cf({int:!0}),cp=()=>new lf,lp=()=>new uf,up=e=>new df(e);function dp(e){return new ff([...e])}var fp=()=>new Df,pp=()=>new pf,mp=()=>new pf,hp=e=>new vf(e),gp=e=>new gf(e),_p=e=>new _f(e);function vp(e,t){return t?new yf(t,e):new yf(e)}function yp(e){return new xf([...e])}function bp(e,t){return new xf([...t],e)}var xp=e=>new Sf(e);function Sp(e,t){return new Cf(e,t??new pf)}function Cp(e,t){return new wf(e,t.if,t.then,t.else)}function wp(e,t,n){return new Tf(e,t,n)}var Tp=e=>new jf(e),Ep=(e,t)=>new Af(e,t),Dp=e=>new Mf(e),Op=e=>new Nf(e),kp=e=>new Nf(e),Ap=(e,t)=>new Pf(e,t),jp=(e,t={})=>new Ef(e,t.tag??`tool`,t.args??`args`),Mp=e=>new qd(e),Np=()=>new qd,Pp=()=>new qd,Fp={optional:[`omit`,`null`],closedObjects:`boolean`,records:[`open`,`pairs`],tuples:[`prefixItems`,`object`,`array`],unions:[`anyOf`,`tagged`],nulls:[`type-array`,`anyOf`,`nullable`],allOf:`boolean`,conditionals:`boolean`,patternProperties:`boolean`,defs:`boolean`,refSiblings:`boolean`,recursion:[!0,!1,`guarded`],any:[`empty`,`flat`,`json-text`],examples:[`keyword`,`description`,`none`],propertyOrdering:`boolean`,rootObject:`boolean`,alwaysStrictOutput:`boolean`,jsonInstruction:`string`,audience:[`model`,`people`]},Ip={properties:`maxProperties`,objectProperties:`maxObjectProperties`,objectOptionals:`maxObjectOptional`,optionals:`maxOptional`,unions:`maxUnions`,depth:`maxDepth`,enumSize:null,enumValues:`maxEnumValues`,stringChars:`maxStringChars`,largeEnumValues:`largeEnumValues`,largeEnumChars:`maxLargeEnumChars`},Lp={tools:[`request`,`maxTools`],strictTools:[`request`,`maxStrictTools`],requestProperties:[`totals`,`maxProperties`],requestOptionals:[`totals`,`maxOptional`],requestUnions:[`totals`,`maxUnions`],requestDepth:[`totals`,`maxDepth`],requestStringChars:[`totals`,`maxStringChars`],requestEnumValues:[`totals`,`maxEnumValues`],requestLargeEnumValues:[`totals`,`largeEnumValues`],requestLargeEnumChars:[`totals`,`maxLargeEnumChars`],requestObjectProperties:[`totals`,`maxObjectProperties`],requestObjectOptionals:[`totals`,`maxObjectOptional`]},Rp={length:`boolean`,range:`boolean`,items:[`all`,`min-0-1`,`none`],pattern:[`full`,`basic`,`none`]},zp=e=>Object.fromEntries(Object.keys(e).map(e=>[e,`number`])),Bp={rules:Fp,limits:zp(Ip),constraints:Rp,formats:`formats`},Vp={strict:`boolean`,dialect:`string`,loose:`string`,...Bp,looseRules:Bp},Hp={base:`string`,tools:Vp,output:Vp,delivery:[`structured`,`prompt`],limits:zp(Lp)},Up=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Wp=e=>JSON.stringify(e)??String(e);function Gp(e,t,n,r){let i=t=>{throw Error(`Schema rules${r}: ${n} is ${Wp(e)}, expected ${t}`)};Array.isArray(t)?t.includes(e)||i(t.map(Wp).join(` | `)):t===`boolean`||t===`string`?typeof e!==t&&i(`a ${t}`):t===`number`?typeof e==`number`&&e>=0||i(`a number of 0 or more`):t===`formats`?e!==`all`&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`))&&i(`"all" or a list of format names`):Kp(e,t,n,r)}function Kp(e,t,n,r){if(!Up(e))throw Error(`Schema rules${r}: ${n||`the rules`} is ${Wp(e)}, expected an object`);for(let[i,a]of Object.entries(e)){let e=n?`${n}.${i}`:i,o=t[i];if(!o)throw Error(`Schema rules${r}: unknown key "${e}" (known: ${Object.keys(t).join(`, `)})`);a!==void 0&&Gp(a,o,e,r)}}var qp=new WeakSet;function Jp(e,t){Up(e)&&qp.has(e)||(Kp(e,Hp,``,t?` of ${t}`:``),qp.add(e))}var Yp=new Map;function Xp(e,t){Jp(t,`base "${e}"`);let n=Object.freeze({...t});qp.add(n),Yp.set(e,n)}var Zp=(e,t)=>({tools:{dialect:e,loose:t},output:{dialect:e,loose:t}});Xp(`lenient`,Zp(`lenient`,`lenient`)),Xp(`openai`,Zp(`openai-strict`,`openai`)),Xp(`openai-finetuned`,{base:`openai`,...Zp(`openai-finetuned-strict`,`openai`)}),Xp(`anthropic`,{tools:{dialect:`anthropic-strict`,loose:`anthropic`},output:{dialect:`anthropic-strict-output`,loose:`anthropic`}}),Xp(`google`,Zp(`google-strict`,`google`)),Xp(`google-openapi`,Zp(`google-openapi`,`google`)),Xp(`xai`,{tools:{strict:!0,dialect:`xai-strict`,loose:`xai`},output:{dialect:`xai-strict`,loose:`xai`}}),Xp(`ollama`,Zp(`ollama`,`ollama`));function Qp(e,t){let n=[];for(let e=0;e<=t.length;e++)n[e]=e;for(let r=1;r<=e.length;r++){let i=n[0];n[0]=r;for(let a=1;a<=t.length;a++){let o=n[a],s=e[r-1]===t[a-1]?0:1;n[a]=Math.min(n[a]+1,n[a-1]+1,i+s),i=o}}return n[t.length]}function $p(e){return Math.min(3,Math.max(1,Math.floor(e/3)))}function em(e,t,n){let r=e.toLowerCase(),i=t.map((t,n)=>({candidate:t,index:n,ci:Qp(r,t.toLowerCase()),exact:Qp(e,t)})).filter(e=>e.ci<=n);return i.sort((e,t)=>e.ci-t.ci||e.exact-t.exact||e.index-t.index),i.map(e=>e.candidate)}function tm(e,t,n=$p(e.length)){return em(e,t,n)[0]}function nm(e,t,n={}){let r=Math.max(1,n.max??1),i=em(e,t,$p(e.length)).slice(0,r);return i.length===0?``:` \u2014 did you mean ${rm(i.map(e=>`\`${e}\``))}?`}function rm(e){return e.length===2?`${e[0]} or ${e[1]}`:e.length>2?`${e.slice(0,-1).join(`, `)}, or ${e[e.length-1]}`:e.join(`, `)}function im(e,t,n=2){let r=e.length,i=t.length,a=[];for(let e=0;e<=i;e++)a[e]=e*n;for(let o=1;o<=r;o++){let r=a[0];a[0]=o*n;let s=e[o-1].toLowerCase();for(let e=1;e<=i;e++){let i=a[e],o=r+Qp(s,t[e-1].toLowerCase());a[e]=Math.min(a[e]+n,a[e-1]+n,o),r=i}}return a[i]}function am(e,t,n,r,i={}){if(r.length===0)return;let a=i.maxDepth??Math.min(6,r.length+1),o=r[r.length-1].toLowerCase(),s=$p(o.length),c=r.reduce((e,t)=>e+$p(t.length),0)+2,l=i.nodeBudget??2e3,u,d=new Set,f=(e,i)=>{if(!(l<=0)){for(let n of t(e)){if(l<=0)return;if(l--,Qp(n.toLowerCase(),o)>s)continue;let e=[...i,n],t=im(e,r);t>c||(!u||t<u.score||t===u.score&&e.length<u.path.length)&&(u={score:t,path:e})}if(!(i.length>=a||d.has(e))){d.add(e);for(let[t,r]of n(e)){if(l<=0)break;f(r,[...i,t])}d.delete(e)}}};return f(e,[]),u?.path}var om=[`name`,`docs`,`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`],sm=[`docs`,`type`,`get`,`default`,`set`],cm=[`docs`,`key`,`value`,`get`,`set`,`loop`,`loopDynamic`],lm=[`docs`,`types`,`args`,`returns`,`throws`,`get`,`set`],um=[`docs`,`args`,`run`];function dm(e,t,n,r){let i=e;for(let n of gm(i))if(!om.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown key '${n}'`+bm(n,i[n],om,t,`top`,r));let a=_m(e.options)?e.options:void 0;if(t?.optionKeys&&a){for(let n of gm(a))if(!t.optionKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown options key '${n}'`+bm(n,a[n],t.optionKeys,t,`options`,r))}let o=_m(e.generic)?e.generic:void 0;if(n&&t?.genericKeys&&o){for(let n of gm(o))if(!t.genericKeys.includes(n))throw Error(`registry.parse: type '${e.name}' has unknown generic parameter '${n}'`+bm(n,o[n],t.genericKeys,t,`generic`,r))}}function fm(e,t,n,r,i){if(_m(t))for(let a of gm(t)){if(n.includes(a))continue;let o=r?.[a],s=typeof o==`function`?o(t[a],i):o,c=tm(a,n);throw Error(`gin.parse: ${e} has unknown key '${a}'`+(s?` \u2014 ${s}`:c?` \u2014 did you mean \`${c}\`?`:` \u2014 valid keys: ${n.join(`, `)}`))}}var pm={generic:`a fn declares its type parameters on the TYPE, not the call: {"name":"fn","generic":{"T":{"name":"any"}},"call":{"args":…,"returns":…}}`},mm=[{by:`prop`,keys:[`prop`],example:`{"prop":"name"}`},{by:`args`,keys:[`args`,`generic`,`catch`],example:`{"args":{…}}`},{by:`key`,keys:[`key`],example:`{"key":<expr>}`}];function hm(e){if(!_m(e))return;let t=mm.filter(t=>e[t.by]!==void 0);if(t.length===0){let t=gm(e),n=mm.map(e=>e.by),r=t.map(e=>tm(e,n)).find(e=>e!==void 0);throw Error(`gin.parse: path step selects no form (keys: ${t.join(`, `)||`none`})`+(r?` \u2014 did you mean \`${r}\`?`:``)+` \u2014 a step is one of ${mm.map(e=>e.example).join(`, `)}`)}if(t.length>1){let n=t.map(e=>`'${e.by}'`).join(` and `),r=t.map(t=>t.by===`prop`?JSON.stringify({prop:e.prop}):t.example).join(`, `);throw Error(`gin.parse: path step names ${t.length} forms (${n}) \u2014 each is its own step: [${r}]`)}fm(`path step`,e,t[0].keys)}function gm(e){return Object.keys(e).filter(t=>e[t]!==void 0)}function _m(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vm(e){return Array.isArray(e)?e.length>0&&vm(e[0]):_m(e)&&typeof e.name==`string`}function ym(e){return _m(e)&&`type`in e}function bm(e,t,n,r,i,a){let o=[],s=tm(e,n);if(s)return` \u2014 did you mean \`${s}\`?`;let c=r?.genericKeys??[],l=i===`options`?Sm(t,r,a):void 0;return l?o.push(l):r&&i!==`generic`&&c.length>0&&vm(t)?o.push(`that value is a TypeDef, and '${r.NAME}' takes its type argument${c.length>1?`s`:``} in \`generic\` (${c.join(`, `)})`):i===`top`&&ym(t)&&(r?.consumes??[]).includes(`props`)&&o.push("that value is a PropDef — declare it under `props`"),o.push(Tm(n,r,i)),` \u2014 ${o.join(`; `)}`}var xm=12;function Sm(e,t,n){if(!(!t||t.NAME===`enum`||(t.genericKeys?.length??0)>0))return wm(e,n,"an `enum` in gin, not an option")}var Cm={values:(e,t)=>t?wm(e,t,`the prop's TYPE in gin, not a key beside it`,e=>`{"type":${e}}`):"a closed set of constants is the prop's TYPE in gin, not a key beside it: declare `type` as an `enum`"};function wm(e,t,n,r=e=>e){let i=!Array.isArray(e)&&_m(e),a=Array.isArray(e)?e:i?Object.values(e):void 0;if(!a||a.length===0)return;let o=typeof a[0];if(!a.every(e=>typeof e===o)||o!==`number`&&o!==`boolean`&&o!==`string`)return;let s=`a closed set of constants is ${n}`;if(a.length>xm)return s;let c=i?e:Object.fromEntries(a.map(e=>[String(e),e])),l=o===`number`?t.enum(c,t.num()):o===`boolean`?t.enum(c,t.bool()):o===`string`?t.enum(c,t.text()):void 0;if(l)return`${s}: ${r(JSON.stringify(l.toJSON()))}`}function Tm(e,t,n){let r=t?`'${t.NAME}'`:`this type`;return n===`top`?`valid keys: ${e.join(`, `)}`:n===`options`?e.length===0?`${r} takes no options`:`valid options for ${r}: ${e.join(`, `)}`:e.length===0?`${r} is not generic`:`valid generic parameters for ${r}: ${e.join(`, `)}`}var Em=/^(?:\w[\w-]*\/)*\w+$/;function Dm(e){return typeof e==`string`&&Em.test(e)}var Om={any:`Type_any`,void:`Type_void`,null:`Type_null`,bool:`Type_bool`,num:`Type_num`,text:`Type_text`,list:`Type_list`,map:`Type_map`,tuple:`Type_tuple`,obj:`Type_object`,optional:`Type_optional`,nullable:`Type_nullable`,not:`Type_not`,or:`Type_or`,and:`Type_and`,enum:`Type_enum`,literal:`Type_literal`,fn:`Type_function`,interface:`Type_interface`,typ:`Type_typ`,date:`Type_date`,timestamp:`Type_timestamp`,duration:`Type_duration`,color:`Type_color`},km=()=>R.string().pattern(Em.source).describe(`A type name: an identifier, optionally namespaced as ns/Name.`);function Am(e,t){let n=Om[t],r=e.typeClass(t);return r!==void 0&&n!==void 0&&e.namedTypeList().every(e=>e.name!==t)?R.ref(n):r===void 0?R.object({name:R.literal(t)}):r.toA?.()??R.object({name:R.literal(t)})}function jm(){return R.object({name:km()}).strict().describe(`A named type, by its name.`)}function Mm(e){return R.object({name:km(),extends:e.length>0?R.enum([...new Set(e)]):R.never(),docs:R.string().optional(),satisfies:R.array(km()).optional(),generic:R.ref(`Generic`).optional(),options:R.record(R.unknown()).optional(),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional(),init:R.ref(`InitDef`).optional(),constraint:R.ref(`Expr`).optional()}).describe(`A NEW named type declared inline: a name, the type it extends, and what it adds.`)}var Nm=R.ref(`TypeDef`),z=R.ref(`Expr`),Pm=R.string().optional().describe("Optional one-line note explaining why this expression exists. Travels with the node, surfaces in `toCode` as a `/* … */` annotation, and shows up in error paths. Use for non-obvious steps; skip for trivial reads."),Fm={Generic:R.record(Nm).describe(`Generic-parameter bindings: parameter name → TypeDef.`),PathStep:R.union([R.object({prop:R.string().describe("Named-property access. First step looks up a scope variable by name; subsequent steps read the previous value's prop / method. Reject if the name isn't on the type's `props()`.")}).describe("PROP step — `.<name>` access (scope var on first step, prop/method on later steps)."),R.object({args:R.record(z).describe("Map of arg-name → ExprDef. Calls the previous step (a method or any callable). Each arg expression is evaluated in the caller scope before the call; the result obj is bound as `args` inside the call body."),generic:R.ref(`Generic`).optional().describe("Optional generic-parameter map for parameterized callables (e.g. `list.map<R>` binds `R` to the element type of the result list). Usually unnecessary — most callables infer generics."),catch:z.optional().describe("Optional handler expression evaluated if this call throws. The thrown value is bound under `error` in the handler scope.")}).describe("CALL step — invoke the previous step, as its OWN step. Comes after a method (e.g. `list.push`) or any callable value; never fused into the prop step as `{prop, args}`."),R.object({key:z.describe("Indexed-access key expression. Evaluated at run time and passed to the previous value's `[key]` get/set surface.")}).describe("INDEX step — `[<key>]` access for types with index signatures (lists by `num`, maps by their key type).")]),PropDef:R.object({docs:R.string().optional(),type:Nm,get:z.optional(),default:z.optional(),set:z.optional()}),GetSetDef:R.object({docs:R.string().optional(),key:Nm,value:Nm,get:z.optional(),set:z.optional(),loop:z.optional(),loopDynamic:R.boolean().optional().describe("When true, `loop over: <this-typed value>` re-evaluates the expression each iteration and exits when the result's raw is falsy. Bool uses this for while-loop semantics. The type may have either `loop` (for static iterables) OR `loopDynamic` set; with loopDynamic, no `loop` ExprDef is required.")}),CallDef:R.object({docs:R.string().optional(),types:R.record(Nm).optional().describe('Call-local type aliases. Declare reusable named types here ONCE and reference them inside `args` / `returns` / `throws` / `get` / `set` as a bare `{name: "<alias>"}`. Aliases process AFTER any enclosing generics (so they may reference generic placeholders) and BEFORE the call slots — the call slots resolve them at parse time. Sequential: later aliases may reference earlier ones. Use this whenever the same composite type appears more than once in a signature — instead of writing `num{whole:true, min:1}` four times, declare `{ counter: { name:"num", options:{whole:true,min:1} } }` once and reference `{name:"counter"}`.'),args:Nm,returns:Nm.optional(),throws:Nm.optional(),get:z.optional(),set:z.optional()}),InitDef:R.object({docs:R.string().optional(),args:Nm,run:z})},Im=[`any`,`void`,`null`,`bool`,`num`,`text`,`list`,`map`,`tuple`,`obj`,`optional`,`nullable`,`not`,`or`,`and`,`enum`,`literal`,`fn`,`interface`,`typ`,`date`,`timestamp`,`duration`,`color`],Lm={Type_any:R.object({name:R.literal(`any`)}),Type_void:R.object({name:R.literal(`void`)}),Type_null:R.object({name:R.literal(`null`)}),Type_bool:R.object({name:R.literal(`bool`),options:R.object({trueText:R.string().optional(),falseText:R.string().optional()}).optional()}),Type_num:R.object({name:R.literal(`num`),options:R.object({min:R.number().optional().describe('Only set when a real lower bound is part of the spec — e.g. "positive count" → min: 1, "age" → min: 0. Do NOT add `min: 0` to every num just because most numbers happen to be non-negative.'),max:R.number().optional().describe(`Only set when there is an actual upper bound — a percentage capped at 100, a year capped at 9999. Do NOT pick a generic ceiling like 1000/9999 to fill the field.`),whole:R.boolean().optional().describe(`Only set to true when the value is genuinely integral (counts, indices, ids). Leave unset (allow fractions) for measurements, ratios, etc.`),minPrecision:R.number().optional().describe(`Decimal-place floor. Almost never needed; omit unless the spec explicitly requires N decimal places.`),maxPrecision:R.number().optional().describe(`Decimal-place ceiling. Same rule as minPrecision — omit unless explicitly required.`),prefix:R.string().optional().describe(`Display-only prefix (e.g. "$"). Has no effect on validation. Omit unless rendering needs it.`),suffix:R.string().optional().describe(`Display-only suffix (e.g. "%"). Same as prefix — omit unless rendering needs it.`)}).optional().describe(`Omit entirely for ordinary numbers. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_text:R.object({name:R.literal(`text`),options:R.object({minLength:R.number().optional().describe(`Only set when a real lower bound is part of the spec — e.g. "non-empty input" → minLength: 1. Do NOT default to 0.`),maxLength:R.number().optional().describe(`Only set when there is an actual upper bound — a database column width, an API limit, an explicit "no longer than X chars" rule. Do NOT pick a generic ceiling like 100/200/1000 just to fill the field.`),pattern:R.string().optional().describe(`Only set for actual format constraints (UUID, ISO date, slug, etc.). Do NOT use ".*" or other accept-anything patterns — they add zero validation and clutter the schema.`),flags:R.string().optional().describe('Regex flags (e.g. "i"). Omit unless `pattern` is set AND requires flags.')}).optional().describe(`Omit entirely for ordinary strings. Only include when the value has a real, named constraint worth enforcing on every parse.`)}),Type_list:R.object({name:R.literal(`list`),generic:R.object({V:Nm}).optional(),options:R.object({minLength:R.number().optional(),maxLength:R.number().optional()}).optional()}),Type_map:R.object({name:R.literal(`map`),generic:R.object({K:Nm,V:Nm}).optional()}),Type_tuple:R.object({name:R.literal(`tuple`),options:R.object({elements:R.array(Nm)})}),Type_object:R.object({name:R.literal(`obj`),props:R.record(R.ref(`PropDef`)).optional()}),Type_optional:R.object({name:R.literal(`optional`),generic:R.object({T:Nm}).optional()}),Type_nullable:R.object({name:R.literal(`nullable`),generic:R.object({T:Nm}).optional()}),Type_not:R.object({name:R.literal(`not`),options:R.object({excluded:Nm})}),Type_or:R.object({name:R.literal(`or`),options:R.object({types:R.array(Nm)})}),Type_and:R.object({name:R.literal(`and`),options:R.object({types:R.array(Nm)})}),Type_enum:R.object({name:R.literal(`enum`),generic:R.object({V:Nm}).optional(),options:R.object({values:R.record(R.unknown())})}),Type_literal:R.object({name:R.literal(`literal`),generic:R.object({T:Nm}).optional(),options:R.object({value:R.unknown()})}),Type_function:R.object({name:R.literal(`fn`),call:R.ref(`CallDef`).optional()}),Type_interface:R.object({name:R.literal(`interface`),props:R.record(R.ref(`PropDef`)).optional(),get:R.ref(`GetSetDef`).optional(),call:R.ref(`CallDef`).optional()}),Type_typ:R.object({name:R.literal(`typ`),generic:R.object({T:Nm}).optional()}),Type_date:R.object({name:R.literal(`date`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional()}).optional()}),Type_timestamp:R.object({name:R.literal(`timestamp`),options:R.object({min:R.string().optional(),max:R.string().optional(),utc:R.boolean().optional(),precision:R.enum([`ms`,`s`,`us`]).optional()}).optional()}),Type_duration:R.object({name:R.literal(`duration`)}),Type_color:R.object({name:R.literal(`color`),options:R.object({hasAlpha:R.boolean().optional()}).optional()})},Rm={Expr_block:R.object({kind:R.literal(`block`),comment:Pm,lines:R.array(z).describe(`Sequence of expressions evaluated in order. The block's value is the LAST line's value (an empty block returns void). Earlier lines run for their side effects (set, fns.fetch, etc.).`)}),Expr_define:R.object({kind:R.literal(`define`),comment:Pm,vars:R.array(R.object({name:R.string().describe(`Variable name. Must NOT be a reserved name (args, recurse, this, super, key, value, yield, error) and must NOT shadow anything already in scope.`),type:Nm.optional().describe("Optional declared type. OMIT this field when the value already determines the type — every value Expr (`new`, `get`, `if`, ...) is typed, and the var inherits that type. Set this only when you need to widen / narrow / annotate beyond what the value alone produces; a mismatch with the value's inferred type is reported as `define.var.type-mismatch`."),value:z.describe("The expression whose result is bound under `name`. May reference any earlier var in this define — each var is added to scope before the next var's value is evaluated.")})).describe("Bindings introduced before `body`. Evaluated sequentially, so `vars[i].value` may reference any of `vars[0..i-1]`."),body:z}),Expr_flow:R.object({kind:R.literal(`flow`),action:R.enum([`break`,`continue`,`return`,`exit`,`throw`]).describe("Which control-flow signal to raise. `break`/`continue` only valid inside a loop. `return` only valid inside a fn body / lambda; unwinds to the enclosing call with `value`. `exit` unwinds all the way to `engine.run`, returning `value` as the program result. `throw` raises `error` (caught by a path step's `catch:` handler)."),value:z.optional().describe("Required for `return` and `exit` (the value being returned). Ignored by `break` / `continue` / `throw`."),error:z.optional().describe("Required for `throw` — the value to raise. Ignored otherwise.")}),Expr_get:R.object({kind:R.literal(`get`),path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right starting from a scope variable. Step shapes: `{prop:"name"}` for prop/method access, `{args:{…}}` to call the previous step, `{key:Expr}` for index access. The first step MUST be a prop step (the scope-var name). A step names exactly ONE shape — a call is its own step, so a method with arguments is `[{"prop":"m"},{"args":{…}}]` and never `{"prop":"m","args":{…}}`. Result is the final step\'s value.')}),Expr_if:R.object({kind:R.literal(`if`),comment:Pm,ifs:R.array(R.object({condition:z.describe("Bool-typed expression. First branch whose condition is `true` wins; the rest are skipped."),body:z.describe(`Evaluated when this branch's condition is true. The if-expression's value is this body's value.`)})).describe("Ordered list of `{condition, body}` branches — first true condition wins. Each `condition` must be bool-typed (warned otherwise). With multiple branches this is the gin equivalent of `if / else if / else if`."),else:z.optional().describe("Optional fallback evaluated when every `ifs[i].condition` is false. Without an else, a no-match if-expression evaluates to void.")}),Expr_lambda:R.object({kind:R.literal(`lambda`),comment:Pm,type:Nm.describe('The lambda\'s function type — `{ name: "fn", call: { args, returns } }` (or a registered named fn type). The `args` obj defines what the body sees under the `args` scope variable; `returns` is what the body must produce.'),body:z.describe('The lambda body. At runtime, scope contains the lexical scope at definition site PLUS `args` (the call arguments) and `recurse` (this same lambda, for self-calls). Read params via `[{prop:"args"},{prop:"<name>"}]`.'),constraint:z.optional().describe("Optional bool-typed precondition evaluated before the body on every call (with `args` in scope). If it returns false, the call throws. Use for input invariants you want enforced regardless of caller.")}),Expr_loop:R.object({kind:R.literal(`loop`),comment:Pm,over:z.describe("The iterable expression. Two evaluation modes: (1) iterable types (list, map, etc. — anything whose `get().loop` is defined) iterate once; the expression is evaluated ONCE at the start. (2) bool — while-loop semantics: the expression is RE-EVALUATED each iteration; the loop continues while the value is `true` and exits the moment it becomes `false`. Use `flow:break` / `flow:continue` inside the body to control iteration regardless of mode."),body:z.describe("Evaluated once per iteration with the current `key` and `value` bound in scope. Use `{kind:'flow', action:'break'}` or `'continue'` for early-exit. The loop expression itself returns void."),key:R.string().optional().describe("Override the scope-variable name the iteration index/key is bound under (default: `key`). Must NOT be reserved or shadow an outer scope var. Use to disambiguate when looping inside another loop."),value:R.string().optional().describe("Override the scope-variable name the iteration value is bound under (default: `value`). Same rules as `key`."),parallel:R.object({concurrent:z.optional().describe(`Max in-flight iterations as a num (omit / 1 → strictly sequential). Use when iterations are independent I/O — e.g. fetching N URLs concurrently.`),rate:z.optional().describe(`Minimum interval between iteration starts. Accepts a num (milliseconds) or a duration. Use to rate-limit fan-out (e.g. avoid hammering an API).`)}).optional().describe("Opt-in parallelism. Both fields are optional and independent: `concurrent` caps fan-out width, `rate` paces start times. Iterations may finish out of order; the body should not assume sequential ordering. Composes with dynamic (bool while-loop) iteration: the body fans out up to `concurrent`, and `over` is re-evaluated against the outer scope each time a task completes — so accumulating side effects of earlier tasks decide whether more tasks spawn.")}),Expr_native:R.object({kind:R.literal(`native`),comment:Pm,id:R.string().describe("Identifier of a native impl registered via `registry.setNative(id, fn)` (e.g. `list.push`, `num.add`). The model should NOT generate `native` expressions directly — methods on built-in types are reached via `get` paths, which gin resolves to natives internally."),type:Nm.optional().describe("Optional type to wrap the native's raw return value with when the impl returns a non-Value. Defaults to `any` if omitted.")}),Expr_set:R.object({kind:R.literal(`set`),comment:Pm,path:R.array(R.ref(`PathStep`)).describe('Steps walked left-to-right to a writable target. Single-step `[{prop:"x"}]` re-assigns scope variable `x`. Multi-step targets need the type to support set on the final step (a prop with a `set` ExprDef, an indexed slot, or a method whose call has `set:`).'),value:z.describe("The expression evaluated and assigned to the path target. Its type must be compatible with the target's declared type — checked statically as `set.type-mismatch`.")}),Expr_switch:R.object({kind:R.literal(`switch`),comment:Pm,value:z.describe("Expression whose result is compared against each case's `equals` candidates. Evaluated once."),cases:R.array(R.object({equals:R.array(z).describe("Candidate values for this case. The case wins if `value` equals ANY one of them (logical OR). Each candidate's type must be compatible with `value`'s type — checked as `switch.case.type`."),body:z.describe(`Evaluated when this case wins. The switch expression's value is this body's value.`)})).describe(`Ordered list of cases — first match wins. Cases are NOT fall-through; only the matching case's body runs.`),else:z.optional().describe(`Optional fallback evaluated when no case matches. Without an else, a no-match switch evaluates to void.`)}),Expr_template:R.object({kind:R.literal(`template`),template:R.union([z,R.string()]).describe("The template string — either a literal string (auto-wrapped as `new text`) or an Expr that evaluates to text. Placeholders use `{name}` syntax; each `name` is looked up first in `params` (when supplied) and then in the surrounding scope."),params:z.optional().describe("Optional obj-typed expression supplying placeholder values. When omitted or when a key is missing, `{name}` falls back to a scope lookup of the same name — so a `${baseUrl}` placeholder resolves to a surrounding `define baseUrl = ...`. Provide `params` only when placeholders need values not already in scope (or to override scope values).")})},zm=[`new`,`get`,`set`,`define`,`block`,`if`,`switch`,`loop`,`lambda`,`template`,`flow`,`native`],Bm={any:R.unknown(),void:R.null(),null:R.null(),bool:R.boolean(),num:R.number(),text:R.string(),list:R.array(z),map:R.array(R.object({key:z,value:z})),tuple:R.array(z),obj:R.record(z),optional:z,nullable:R.nullable(z),not:R.unknown(),or:z,and:z,enum:R.union([R.string(),R.number()]),literal:R.unknown(),fn:R.union([R.string(),R.object({kind:R.string()})]),interface:R.record(z),typ:Nm,date:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`),timestamp:R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`),duration:R.object({days:R.number().optional(),hours:R.number().optional(),minutes:R.number().optional(),seconds:R.number().optional(),ms:R.number().optional()}),color:R.object({r:R.int().min(0).max(255),g:R.int().min(0).max(255),b:R.int().min(0).max(255),a:R.number().min(0).max(1).optional()})},Vm=(e,t,n)=>R.object({kind:R.literal(`new`),type:t.describe(`Full TypeDef for a \`${e}\` instance (name + options + per-class fields).`),value:R.optional(n).describe(`Initial value matching this \`${e}\` instance. Composites accept Expr slots; primitives accept their raw form.`)}),Hm=Object.fromEntries(Im.map(e=>[`New_${e}`,Vm(e,R.ref(Om[e]),Bm[e])])),Um=R.object({kind:R.literal(`new`),type:Nm.describe("TypeDef of the value being constructed. The `value` field is interpreted relative to this type — primitives take their raw form (`new num` → number), composites take Expr slots (`new list` → Expr[])."),value:R.unknown().optional().describe("Initial value matching `type`. Optional when the type has a defined `init` constructor or a sensible default (empty list, zero num with no constraints, etc.).")}),Wm=new Set([...Object.keys(Fm),...Object.keys(Lm),...Object.keys(Rm),...Object.keys(Hm),`TypeDef`,`Type_Extension`,`Expr_new`,`Expr`]),Gm=(e,t)=>t.length===0?R.never():t.length===1?t[0]:R.discriminatedUnion(e,t);function Km(e,t){let n=new Map;for(let e of t?.types??[])n.set(e.name,e);for(let t of e.namedTypeList())n.has(t.name)||n.set(t.name,t);return n}function qm(e,t){let n=Km(e,t),r=[...n.keys()],i=e.typeClasses(),a=[...r.map(e=>R.object({name:R.literal(e)}).describe(`The registered named type \`${e}\`, by name.`)),...i.map(t=>Am(e,t.NAME)),R.ref(`Type_Extension`)];t?.namedRefs&&a.push(jm());let o=Mm([...i.map(e=>e.NAME),...r]),s=e.exprClassList().map(e=>zm.includes(e.KIND)&&e.KIND!==`new`?R.ref(`Expr_${e.KIND}`):e.KIND===`new`?R.ref(`Expr_new`):e.toA?.()??R.object({kind:R.literal(e.KIND)}).describe(`A \`${e.KIND}\` expression.`)),c=Um,l={};if(t?.newStrict){let t=[...n].map(([e,t])=>{let r=R.object({kind:R.literal(`new`),type:R.object({name:R.literal(e)}).describe(`Reference to the registered named type \`${e}\` \u2014 name-only, the registry resolves it to its full definition.`),value:R.optional(t.toNewA()).describe(`Initial value for the new \`${e}\` instance. Each composite slot accepts an Expr (Get, NewExpr, etc.); per-slot type correctness is enforced at runtime.`)});return Wm.has(`New_${e}`)||n.has(`New_${e}`)?r:(l[`New_${e}`]=r,R.ref(`New_${e}`))}),r=i.map(t=>Om[t.NAME]!==void 0&&Im.includes(t.NAME)?R.ref(`New_${t.NAME}`):Vm(t.NAME,Am(e,t.NAME),t.toNewA?.()??R.unknown()));c=R.union([...t,...r])}let u={};for(let[e,t]of n)Wm.has(e)||(u[e]=t.defineA({includeDocs:`all`}));return{...u,...l,TypeDef:Gm(`name`,a),Type_Extension:o,Expr_new:c,Expr:Gm(`kind`,s)}}var Jm=new WeakMap,Ym=0,Xm=e=>{let t=Jm.get(e);return t===void 0&&Jm.set(e,t=++Ym),t},Zm=(e,t)=>`${Xm(e)}:${e.version}|${t?.newStrict?`s`:``}${t?.namedRefs?`r`:``}|${(t?.types??[]).map(e=>e.name).join(`,`)}`,Qm=R.define(Fm).define(Lm).define(Rm).define(Hm).declare(),$m=Qm.dynamic((e,t)=>qm(e,t),{key:Zm,cacheSize:8});$m.result(`TypeDef`),$m.result(`Expr`);var eh=class{list=[];stack=[];enter(e){return Array.isArray(e)?this.stack.push(...e):this.stack.push(e),this}leave(e=1){return this.stack.length=Math.max(0,this.stack.length-e),this}at(e,t){let n=Array.isArray(e)?e.length:1;this.enter(e);try{return t()}finally{this.leave(n)}}push(e,t,n=`error`,r){this.list.push({path:this.stack.slice(),code:e,message:t,severity:n,source:r})}error(e,t,n){this.push(e,t,`error`,n)}warn(e,t,n){this.push(e,t,`warning`,n)}info(e,t,n){this.push(e,t,`info`,n)}get hasErrors(){return this.list.some(e=>e.severity===`error`)}},th=class extends Error{constructor(e){super(`${e.code}: ${e.message} at ${e.path.join(`.`)}`),this.problem=e,this.name=`TypeError`}problem},B={NONE:0,STATE:1,SYSTEM:2,EXTERNAL:4};function nh(...e){let t=B.NONE;for(let n of e)t|=n;return t}var V=class e{constructor(e,t=[]){this.text=e,this.spans=t}text;spans;toString(){return this.text}concat(t){if(typeof t==`string`)return new e(this.text+t,this.spans);let n=this.text.length,r=t.spans.map(e=>({...e,start:e.start+n,end:e.end+n}));return new e(this.text+t.text,[...this.spans,...r])}indent(t){if(!t||!this.text.includes(`
|
|
72
72
|
`))return this;let n=this.text.length,r=new Int32Array(n+1),i=0;for(let e=0;e<n;e++)r[e]=i,this.text[e]===`
|
|
73
73
|
`&&(i+=t.length);r[n]=i;let a=this.text.replace(/\n/g,`
|
|
74
|
-
${t}`),o=this.spans.map(e=>({...e,start:e.start+r[e.start],end:e.end+r[e.end]}));return new e(a,o)}static jsonObject(t,n,r=0,i=2){let a=t.filter(e=>e.value!==void 0);if(a.length===0)return
|
|
75
|
-
`)}\n${s}}`,n)}static jsonArray(t,n,r=0,i=2){if(t.length===0)return
|
|
76
|
-
`)}\n${o}]`,n)}static jsonString(e){return JSON.stringify(e)}formatProblems(e,t={}){return
|
|
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
|
|
78
|
-
`)}var
|
|
74
|
+
${t}`),o=this.spans.map(e=>({...e,start:e.start+r[e.start],end:e.end+r[e.end]}));return new e(a,o)}static jsonObject(t,n,r=0,i=2){let a=t.filter(e=>e.value!==void 0);if(a.length===0)return rh(`{}`,n);let o=` `.repeat((r+1)*i),s=` `.repeat(r*i);return rh(H`{\n${ih(a.map(({key:t,value:n})=>{let r=typeof n==`string`?new e(n):n;return H`${o}${JSON.stringify(t)}: ${r}`}),`,
|
|
75
|
+
`)}\n${s}}`,n)}static jsonArray(t,n,r=0,i=2){if(t.length===0)return rh(`[]`,n);let a=` `.repeat((r+1)*i),o=` `.repeat(r*i);return rh(H`[\n${ih(t.map(t=>{let n=typeof t==`string`?new e(t):t;return H`${a}${n}`}),`,
|
|
76
|
+
`)}\n${o}]`,n)}static jsonString(e){return JSON.stringify(e)}formatProblems(e,t={}){return lh(this,e.list,t)}formatProblem(e,t={}){return lh(this,[e],{...t,sectionHeaders:!1,lineNumbers:!1,contextLines:0})}spanFor(e){let t,n=-1,r=1/0;for(let i of this.spans){if(!ph(i.path,e))continue;let a=i.end-i.start;(i.path.length>n||i.path.length===n&&a<r)&&(t=i,n=i.path.length,r=a)}return t}toLines(){let e=[],t=this.text.split(`
|
|
77
|
+
`),n=0;for(let r=0;r<t.length;r++){let i=t[r],a=n,o=n+i.length,s=[];for(let e of this.spans){if(e.end<=a||e.start>=o)continue;let t=Math.max(e.start,a)-a,n=Math.min(e.end,o)-a;s.push({...e,start:t,end:n})}e.push({text:i,spans:s,lineNum:r+1}),n=o+1}return e}};function rh(e,t){let n=typeof e==`string`?new V(e):e,r={start:0,end:n.text.length,path:t.path,expr:t.expr,type:t.type};return new V(n.text,[r,...n.spans])}function H(e,...t){let n=``,r=[];for(let i=0;i<e.length;i++)if(n+=e[i],i<t.length){let e=t[i];if(typeof e==`string`)n+=e;else{let t=n.length;n+=e.text;for(let n of e.spans)r.push({...n,start:n.start+t,end:n.end+t})}}return new V(n,r)}function ih(e,t=``){if(e.length===0)return new V(``);let n=typeof t==`string`?new V(t):t,r=typeof e[0]==`string`?new V(e[0]):e[0];for(let t=1;t<e.length;t++)r=r.concat(n).concat(e[t]);return r}function ah(e){return ih(e,`
|
|
78
|
+
`)}var oh={reset:`\x1B[0m`,bold:`\x1B[1m`,dim:`\x1B[2m`,red:`\x1B[31m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,cyan:`\x1B[36m`},sh={error:`error`,warning:`warning`,info:`info`},ch={error:oh.red,warning:oh.yellow,info:oh.blue};function lh(e,t,n){if(t.length===0)return``;let r=n.color??!1,i=n.contextLines??2,a=n.sectionHeaders??!0,o=n.lineNumbers??!0,s=n.maxProblems??1/0,c=(e,t)=>r?`${e}${t}${oh.reset}`:t,l=e.toLines(),u=[],d=[],f=0;for(let n=0;n<t.length;n++){if(n>=s){f=t.length-n;break}let r=t[n],i=uh(e,l,r);if(i)u.push(i);else{let e=ch[r.severity],t=`${sh[r.severity]}:`,n=r.path.length>0?` @ ${r.path.join(`.`)}`:``;d.push(`${c(e,t)} ${r.message}${n}`)}}let p=dh(u,l.length,i),m=l.length,h=o?String(m).length:0,ee=p.map(e=>fh(e,l,{color:r,sectionHeaders:a,lineNumbers:o,gutterWidth:h,c}));return d.length>0&&ee.push(d.join(`
|
|
79
79
|
`)),f>0&&ee.push(`\u2026 (${f} more problem${f===1?``:`s`} suppressed)`),ee.join(`
|
|
80
80
|
|
|
81
|
-
`)}function
|
|
82
|
-
`)}function
|
|
83
|
-
`:`/* ${this.comment} */ `}withCommentOn(e){return this.comment?{...e,comment:this.comment}:e}validate(e,t){let n=new
|
|
84
|
-
${
|
|
81
|
+
`)}function uh(e,t,n){let r=e.spanFor(n.path);if(!r)return null;let i=new Map,a=0,o=-1,s=-1;for(let e=0;e<t.length;e++){let n=t[e].text,c=a,l=a+n.length;if(r.end>c&&r.start<=l){let t=Math.max(r.start,c)-c,n=Math.min(r.end,l)-c;i.set(e,{startCol:t,endCol:n}),o<0&&(o=e),s=e}a=l+1}return o<0?null:{problem:n,firstLine:o,lastLine:s,hits:i}}function dh(e,t,n){if(e.length===0)return[];let r=[...e].sort((e,t)=>e.firstLine-t.firstLine),i=[];for(let e of r){let r=Math.max(0,e.firstLine-n),a=Math.min(t-1,e.lastLine+n),o=i[i.length-1];o&&r<=o.lastLine+1?(o.lastLine=Math.max(o.lastLine,a),o.problems.push(e)):i.push({firstLine:r,lastLine:a,problems:[e]})}return i}function fh(e,t,n){let{color:r,sectionHeaders:i,lineNumbers:a,gutterWidth:o,c:s}=n,c=[],l=e=>a?s(oh.dim,`${String(e).padStart(o)} \u2502 `):``,u=()=>a?s(oh.dim,`${` `.repeat(o)} \u2502 `):``;if(i){let t=e.firstLine===e.lastLine?`line ${e.firstLine+1}`:`lines ${e.firstLine+1}-${e.lastLine+1}`,n=`─`.repeat(Math.max(3,60-t.length-4));c.push(s(oh.dim,`\u2500\u2500 ${t} ${n}`))}let d={error:0,warning:1,info:2};for(let n=e.firstLine;n<=e.lastLine;n++){c.push(l(n+1)+t[n].text);let r=new Map;for(let t of e.problems){let e=t.hits.get(n);if(!e)continue;let i=`${e.startCol}:${e.endCol}`,a=r.get(i);(!a||d[t.problem.severity]<d[a])&&r.set(i,t.problem.severity)}for(let[e,t]of r){let[n,r]=e.split(`:`),i=Number(n),a=Number(r),o=` `.repeat(i)+`^`.repeat(Math.max(1,a-i));c.push(u()+s(ch[t],o))}for(let t of e.problems){if(t.lastLine!==n)continue;let e=t.problem.severity,r=s(ch[e],`${sh[e]}:`);c.push(u()+`${r} ${t.problem.message}`)}}return c.join(`
|
|
82
|
+
`)}function ph(e,t){if(e.length>t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function mh(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}var hh=new WeakMap,gh=0,_h=e=>{let t=hh.get(e);return t===void 0&&hh.set(e,t=++gh),t},vh=new WeakMap;function yh(e){let t=vh.get(e);return t===void 0&&(t=e instanceof bh?`${yh(e.parent)}/${_h(e.bindingsRecord)}`:String(_h(e)),vh.set(e,t)),t}var bh=class{parent;registry;local;constructor(e,t={}){this.parent=e,this.registry=e.registry,this.local=t}lookup(e){return this.local[e]??this.parent.lookup(e)}localLookup(e){return this.local[e]}get bindingsRecord(){return this.local}parse(e){return this.registry.parse(e,this)}parseExpr(e){return this.registry.parseExpr(e,this)}bind(e,t){this.local[e]=t}ownNames(){return Object.keys(this.local)}},xh=class e{comment;withComment(e){return e&&(this.comment=e),this}useLineComment(e={}){return e.expectsValue===!1}commentPrefix(e={}){return!this.comment||e.includeComments===!1?``:this.useLineComment(e)?`// ${this.comment}
|
|
83
|
+
`:`/* ${this.comment} */ `}withCommentOn(e){return this.comment?{...e,comment:this.comment}:e}validate(e,t){let n=new eh,r=t??e.globalTypeScope();return this.validateWalk(e,r,n,{inLoop:!1,inLambda:!1}),n}toCode(e,t){return this.toGinCode(e,t).toString()}toGinCode(e,t,n=[]){return rh(this._toCodeFallback(e,t),{path:n,expr:this})}renderStatementBody(e,t={},n=!1){let r=this.kind;if(r===`flow`)return`${this.toCode(e,{...t,expectsValue:!1})};`;if(n&&r===`if`)return this.toCode(e,{...t,expectsValue:!1});if(r===`block`){let n=this.toCode(e,{...t,expectsValue:!1});return n.startsWith(`{`)?n:`{
|
|
84
|
+
${Sh(n)}
|
|
85
85
|
}`}return r===`if`||r===`switch`||r===`loop`?`{
|
|
86
|
-
${
|
|
86
|
+
${Sh(this.toCode(e,{...t,expectsValue:!1}))}
|
|
87
87
|
}`:`{
|
|
88
|
-
${
|
|
88
|
+
${Sh(this.toCode(e,{...t,expectsValue:!0}))};
|
|
89
89
|
}`}renderStatementBodyRich(e,t={},n=[],r=!1){let i=this.kind;if(i===`flow`)return H`${this.toGinCode(e,{...t,expectsValue:!1},n)};`;if(r&&i===`if`)return this.toGinCode(e,{...t,expectsValue:!1},n);if(i===`block`){let r=this.toGinCode(e,{...t,expectsValue:!1},n);return r.text.startsWith(`{`)?r:H`{\n ${r.indent(` `)}\n}`}return i===`if`||i===`switch`||i===`loop`?H`{\n ${this.toGinCode(e,{...t,expectsValue:!1},n).indent(` `)}\n}`:H`{\n ${this.toGinCode(e,{...t,expectsValue:!0},n).indent(` `)};\n}`}toJSONCode(e=[],t=2,n=0){let r=JSON.stringify(this.toJSON(),null,t);if(n>0){let e=` `.repeat(n*t);r=r.replace(/\n/g,`
|
|
90
|
-
`+e)}return
|
|
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=>
|
|
90
|
+
`+e)}return rh(r,{path:e,expr:this})}_toCodeFallback(t,n){let r=Object.getPrototypeOf(this).toCode;return r&&r!==e.prototype.toCode?r.call(this,t,n):`<unrendered:${this.kind??`?`}>`}forEachChild(e){}};function Sh(e){return e.replace(/\n/g,`
|
|
91
|
+
`)}var Ch=new Set([`args`,`recurse`,`this`,`super`,`key`,`value`,`yield`,`error`]),wh=class e{parent;vars;control;constructor(e=null,t,n){this.parent=e,this.vars=new Map(t?Object.entries(t):[]),this.control=n??e?.control}async checkpoint(){this.control&&await this.control.checkpoint()}get(e){let t=this.vars.get(e);return t===void 0?this.parent?.get(e):t}set(e,t){this.vars.has(e)?this.vars.set(e,t):this.parent&&this.parent.has(e)?this.parent.set(e,t):this.vars.set(e,t)}has(e){return this.vars.has(e)?!0:this.parent?.has(e)??!1}child(t){return new e(this,t)}names(){let e=new Set;for(let t=this;t;t=t.parent)for(let n of t.vars.keys())e.add(n);return[...e]}};function Th(e,t,n){let r=t instanceof xh?t:Eh(e,t);return r?r.typeOf(e,n):e.registry.any()}function Eh(e,t){try{return e.registry.parseExpr(t)}catch{return}}function Dh(e,t,n,r={inLoop:!1,inLambda:!1}){let i=new eh;return Oh(e,t,n,i,r),i}function Oh(e,t,n,r,i){let a;if(t instanceof xh)a=t;else try{a=e.registry.parseExpr(t)}catch{return r.warn(`expr.unknown-kind`,`unknown expr kind '${t.kind}'`),e.registry.any()}return a.validateWalk(e,n,r,i)}function kh(e,t,n){Ch.has(e)?n.error(`binding.reserved`,`'${e}' is a reserved name (gin binds it automatically in fn/loop/path contexts) \u2014 pick a different name`):t.has(e)&&n.error(`binding.shadow`,`'${e}' is already in scope \u2014 pick a different name to avoid shadowing`)}var Ah=class{constructor(e){this.action=e}action},jh=class extends Ah{constructor(){super(`break`)}},Mh=class extends Ah{constructor(){super(`continue`)}},Nh=class extends Ah{constructor(e){super(`return`),this.value=e}value},Ph=class extends Ah{constructor(e){super(`exit`),this.value=e}value},Fh=class extends Ah{constructor(e){super(`throw`),this.error=e}error};function Ih(e,t){let n=new Bh(t);n.type(e,zh);let r=new Set(n.defines);return{refs:n.refs.filter(e=>!r.has(e)),defines:n.defines}}function Lh(e,t,n){let r=new Map,i=[],a=[],o=new Map,s=new Set;for(let n of e)for(let e of Ih(n,t).defines)s.add(e);let c=e=>{if(o.has(e)||s.has(e))return;let l=n(e);if(!l)o.set(e,`done`),i.push(e);else{o.set(e,`visiting`),r.set(e,l);for(let e of Ih(l,t).refs)c(e);o.set(e,`done`),a.push(e)}};for(let n of e)for(let e of Ih(n,t).refs)c(e);return{order:a,defs:r,missing:i}}var Rh=new Set([`enum`,`literal`]),zh=new Set,Bh=class{constructor(e){this.registry=e}registry;refs=[];defines=[];seenRefs=new Set;seenDefines=new Set;type(e,t){let n=this.registry.typeClass(e.name),r=e.extends!==void 0||n?.declaresGenerics===!0;e.extends===void 0?n||this.name(e.name,t):(this.define(e.name),this.name(e.extends,t));for(let n of e.satisfies??[])this.name(n,t);let i=r&&e.generic?Uh(t,Object.keys(e.generic)):t;for(let t of Object.values(e.generic??{}))this.type(t,i);n&&Rh.has(n.NAME)||this.options(e.options,i);for(let t of Object.values(e.props??{}))this.prop(t,i);e.get&&this.getSet(e.get,i),e.call&&this.call(e.call,i),e.init&&(this.type(e.init.args,i),this.expr(e.init.run,i)),e.constraint&&this.expr(e.constraint,i)}name(e,t){t.has(e)||this.registry.typeClass(e)||this.seenRefs.has(e)||(this.seenRefs.add(e),this.refs.push(e))}define(e){this.seenDefines.has(e)||(this.seenDefines.add(e),this.defines.push(e))}options(e,t){if(Vh(e))for(let n of Object.values(e))if(Array.isArray(n))for(let e of n)Hh(e)&&this.type(e,t);else Hh(n)&&this.type(n,t)}prop(e,t){this.type(e.type,t),this.expr(e.get,t),this.expr(e.set,t),this.expr(e.default,t)}getSet(e,t){this.type(e.key,t),this.type(e.value,t),this.expr(e.get,t),this.expr(e.set,t),this.expr(e.loop,t)}call(e,t){let n=t;for(let[t,r]of Object.entries(e.types??{}))this.type(r,n),n=Uh(n,[t]);this.type(e.args,n),e.returns&&this.type(e.returns,n),e.throws&&this.type(e.throws,n),this.expr(e.get,n),this.expr(e.set,n)}expr(e,t){if(Array.isArray(e)){for(let n of e)this.expr(n,t);return}if(!Vh(e))return;let n=Hh(e.type)&&this.registry.typeClass(e.type.name)?.valuesAreTypes===!0;for(let[r,i]of Object.entries(e))if(r===`type`&&Hh(i))this.type(i,t);else if(r===`generic`&&Vh(i))for(let e of Object.values(i))Hh(e)&&this.type(e,t);else r===`value`?n&&Hh(i)?this.type(i,t):this.data(i,t):this.expr(i,t)}data(e,t){if(Array.isArray(e))for(let n of e)this.data(n,t);else if(Vh(e)){if(this.isExpr(e))this.expr(e,t);else for(let n of Object.values(e))this.data(n,t)}}isExpr(e){return typeof e.kind==`string`&&this.registry.exprClass(e.kind)!==void 0}};function Vh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Hh(e){return Vh(e)&&typeof e.name==`string`}function Uh(e,t){return t.length===0?e:new Set([...e,...t])}function Wh(e,t,n){if(e===t||e.compatible(t,void 0,n))return!0;for(let r=Gh(t);r;r=Gh(r))if(e.compatible(r,void 0,n))return!0;return!1}function Gh(e){let t=e.base;return t instanceof U&&t!==e?t:void 0}function Kh(e){if(e.name!==`or`)return;let t=e.variants;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function qh(e){if(e.name!==`and`)return;let t=e.parts;if(Array.isArray(t)&&t.every(e=>e instanceof U))return t}function Jh(e,t,n){let r=e.type.encodeAs(e.raw,t,n);return t.form===`logical`?r:{type:e.type.toJSONRef(t),value:r}}function Yh(e,t,n,r,i){n instanceof W&&n.raw!==void 0&&(e[t]=Jh(n,r,i))}var Xh={form:`envelope`,typeRefs:`definition`};function Zh(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&!(e instanceof W)}function Qh(e,t){if(!e||typeof e!=`object`||Array.isArray(e))return;let n=e.kind;if(typeof n==`string`&&t.registry.exprClass(n))try{return t.registry.parseExpr(e,t)}catch{return}}var $h=class e{type;get;set;default;docs;constructor(e){this.type=e.type,this.get=e.get,this.set=e.set,this.default=e.default,this.docs=e.docs}static from(t,n,r){if(t instanceof U)return new e({type:t});t instanceof e||fm(r?`prop '${r}'`:`prop`,t,sm,Cm,n?.registry);let i=t.type,a=i instanceof U?i:(()=>{if(!n)throw Error(`Prop.from: type is TypeDef but no scope provided to parse it`);return n.parse(i)})(),o=e=>e instanceof xh?e:n?.parseExpr(e),s=o(t.get),c=o(t.set),l=o(t.default);return t instanceof e&&t.type===a&&t.get===s&&t.set===c&&t.default===l?t:new e({type:a,get:s,set:c,default:l,docs:t.docs})}static fromMap(t,n){let r={};for(let[i,a]of Object.entries(t))r[i]=e.from(a,n,i);return r}static toJSONMap(t){let n={};for(let[r,i]of Object.entries(t))n[r]=e.from(i).toJSON();return n}toJSON(){return mh({docs:this.docs,type:this.type.toJSON(),get:this.get?.toJSON(),default:this.default?.toJSON(),set:this.set?.toJSON()})}async read(e,t,n,r,i=this.type){if(this.get){let i={this:e},a=e.type.propSuperFor(e,t,`get`,n,r);return a&&(i.super=a),this.get.evaluate(r,n.child(i))}return e.type.propGet(e,t,i)}async write(e,t,n,r,i){if(this.set){let a={this:e,value:n},o=e.type.propSuperFor(e,t,`set`,r,i);o&&(a.super=o),await this.set.evaluate(i,r.child(a))}else{if(this.get&&!this.type.call())throw Error(`path: prop '${t}' is computed (has 'get', no 'set') \u2014 cannot assign to it`);e.type.propSet(e,t,n)}}async invokeMethod(e,t,n,r,i,a){let o=a??this.type;if(!this.get){let a=e.raw?.[t],o=a instanceof W?a.raw:a;if(typeof o==`function`)return await o(n);if(o&&typeof o==`object`&&`kind`in o){let e=await i.evaluate(o,r);if(typeof e.raw==`function`)return await e.raw(n)}throw Error(`path: callable prop '${t}' has no get expression and raw is not a callable`)}let s=this.get,c=async n=>{let a={this:e,args:n,recurse:new W(o,c)},l=e.type.propSuperFor(e,t,`get`,r,i);l&&(a.super=l);try{return await s.evaluate(i,r.child(a))}catch(e){if(e instanceof Nh)return e.value??new W(i.registry.void(),void 0);throw e}};return c(n)}async invokeMethodSet(e,t,n,r,i,a,o){let s=o??this.type,c=s.call?.();if(!c?.set)throw Error(`path: method '${t}' has no call.set`);let l=async n=>{let o={this:e,args:n,value:r,recurse:new W(s,l)},u=e.type.propSuperFor(e,t,`callSet`,i,a);return u&&(o.super=u),await c.set.evaluate(a,i.child(o)),G(a.registry.void(),void 0)};await l(n)}},eg=class e{key;value;get;set;loop;loopDynamic;docs;constructor(e){this.key=e.key,this.value=e.value,this.get=e.get,this.set=e.set,this.loop=e.loop,this.loopDynamic=e.loopDynamic,this.docs=e.docs}static from(t,n){t instanceof e||fm(`get/set surface`,t,cm);let r=t.key,i=t.value,a=r instanceof U?r:(()=>{if(!n)throw Error(`GetSet.from: key is TypeDef but no scope provided`);return n.parse(r)})(),o=i instanceof U?i:(()=>{if(!n)throw Error(`GetSet.from: value is TypeDef but no scope provided`);return n.parse(i)})(),s=e=>e instanceof xh?e:n?.parseExpr(e),c=s(t.get),l=s(t.set),u=s(t.loop);return t instanceof e&&t.key===a&&t.value===o&&t.get===c&&t.set===l&&t.loop===u?t:new e({key:a,value:o,get:c,set:l,loop:u,loopDynamic:t.loopDynamic,docs:t.docs})}toJSON(){return mh({docs:this.docs,key:this.key.toJSON(),value:this.value.toJSON(),get:this.get?.toJSON(),set:this.set?.toJSON(),loop:this.loop?.toJSON(),loopDynamic:this.loopDynamic})}async indexRead(e,t,n,r){if(!this.get)throw Error(`path: type '${e.type.name}' has no index get`);let i={this:e,key:t},a=e.type.indexSuperFor(e,`get`,n,r);return a&&(i.super=a),this.get.evaluate(r,n.child(i))}async indexWrite(e,t,n,r,i){if(!this.set)throw Error(`path: type '${e.type.name}' has no index set`);let a={this:e,key:t,value:n},o=e.type.indexSuperFor(e,`set`,r,i);o&&(a.super=o),await this.set.evaluate(i,r.child(a))}},tg=class e{args;returns;throws;get;set;docs;types;constructor(e){this.args=e.args,this.returns=e.returns,this.throws=e.throws,this.get=e.get,this.set=e.set,this.docs=e.docs,this.types=e.types}static from(t,n){t instanceof e||fm(`call signature`,t,lm,pm);let r=t.types,i=n,a;if(r&&Object.keys(r).length>0){if(Object.values(r).every(e=>e instanceof U))a=r;else{if(!n)throw Error(`Call.from: types contain TypeDef but no scope provided`);let e=new bh(n);i=e,a={};for(let[t,n]of Object.entries(r)){let r=n instanceof U?n:e.parse(n);e.bind(t,r),a[t]=r}}}let o=t.args,s=t.returns,c=t.throws,l=o instanceof U?o:(()=>{if(!i)throw Error(`Call.from: args is TypeDef but no scope provided`);return i.parse(o)})(),u=s===void 0?void 0:s instanceof U?s:(()=>{if(!i)throw Error(`Call.from: returns is TypeDef but no scope provided`);return i.parse(s)})(),d=c===void 0?void 0:c instanceof U?c:(()=>{if(!i)throw Error(`Call.from: throws is TypeDef but no scope provided`);return i.parse(c)})(),f=e=>e instanceof xh?e:i?.parseExpr(e),p=f(t.get),m=f(t.set),h=t.docs;return t instanceof e&&t.args===l&&t.returns===u&&t.throws===d&&t.get===p&&t.set===m&&t.types===a?t:new e({args:l,returns:u,throws:d,get:p,set:m,docs:h,types:a})}toJSON(){let e=this.types&&Object.keys(this.types).length>0?Object.fromEntries(Object.entries(this.types).map(([e,t])=>[e,t.toJSON()])):void 0;return mh({docs:this.docs,types:e,args:this.args.toJSON(),returns:this.returns?.toJSON(),throws:this.throws?.toJSON(),get:this.get?.toJSON(),set:this.set?.toJSON()})}renderTypes(e){if(!this.types)return``;let t=Object.keys(this.types);return t.length===0?``:`{${cg(t.map(t=>`${t}: ${this.types[t].toCode(void 0,e)}`),{sep:`; `})}}`}effects(){let e=0;return this.get&&(e|=this.get.effects()),this.set&&(e|=this.set.effects()),e}},ng=class e{args;run;docs;constructor(e){this.args=e.args,this.run=e.run,this.docs=e.docs}static from(t,n){t instanceof e||fm(`init constructor`,t,um);let r=t.args,i=r instanceof U?r:(()=>{if(!n)throw Error(`Init.from: args is TypeDef but no scope provided`);return n.parse(r)})(),a=t.run,o=a instanceof xh?a:(()=>{if(!n)throw Error(`Init.from: run is ExprDef but no scope provided`);return n.parseExpr(a)})();return t instanceof e&&t.args===i&&t.run===o?t:new e({args:i,run:o,docs:t.docs})}toJSON(){return mh({docs:this.docs,args:this.args.toJSON(),run:this.run.toJSON()})}},U=class e{constructor(e,t,n={}){this.scope=e,this.options=t,this.generic=n}scope;options;generic;get registry(){return this.scope.registry}priority=0;docs;parsesExprValue(e){return!1}encodeAs(e,t,n){return this.encode(e,n)}toJSONRef(e){if(e?.typeRefs!==`name`)return this.toJSON();if(this.registry.lookup(this.name)===this)return{name:this.name};let t=this.toJSON(),n=Object.keys(this.generic);if(n.length===0)return t;let r={...t.generic??{}};for(let t of n)r[t]=this.generic[t].toJSONRef(e);return{...t,generic:r}}toDefinitionJSON(){let e=ag.depth;ag.active++,ag.depth=this.registry.lookup(this.name)===this?0:1;try{return this.toJSON()}finally{ag.active--,ag.depth=e}}references(){return Ih(this.toDefinitionJSON(),this.registry)}closure(e=this.scope){return Lh([this.toDefinitionJSON()],this.registry,t=>e.lookup(t)?.toDefinitionJSON())}compatibleWithParts(e,t,n){let r=qh(e);if(!r)return!1;if(r.some(e=>this.compatible(e,t,n)))return!0;let i=e.simplify(n);return i!==e&&this.compatible(i,t,n)}compatible(e,t,n){for(let t=0;e.name===`alias`&&t<8;t++){let t=e.simplify(n);if(t===e)break;e=t}if(e===this)return!0;let r=rg,i=ig(t,n),a=r.active.get(this)?.get(e);if(a!==void 0&&a.key===i)return r.lowWater=Math.min(r.lowWater,a.depth),!0;let o=r.memo.get(this)?.get(e)?.get(i);if(o!==void 0)return o;let s=r.depth++,c=r.active.get(this);c||r.active.set(this,c=new Map),c.set(e,{depth:s,key:i});let l=r.lowWater;r.lowWater=1/0;let u=!1;try{let a=Kh(e);if(u=a?a.every(e=>this.compatible(e,t,n)):this.compatibleType(e,t,n)||this.compatibleWithParts(e,t,n)||this.compatibleWithBase(e,t,n),!u||r.lowWater>=s){let t=r.memo.get(this);t||r.memo.set(this,t=new Map);let n=t.get(e);n||t.set(e,n=new Map),n.set(i,u)}return u}finally{c.delete(e),r.lowWater=Math.min(l,r.lowWater),--r.depth===0&&(r.memo=new Map,r.active=new Map,r.lowWater=1/0)}}compatibleWithBase(t,n,r){if(n?.strict||n?.exact)return!1;let i=t.base;return i instanceof e&&i!==t&&this.compatible(i,n,r)}accepts(e,t){return this.compatible(e,{strict:!0},t)}exact(e,t){return this.compatible(e,{strict:!0,exact:!0},t)}flexible(){return!1}like(e,t){return this}isUniversal(){return!1}simplify(e){return this}required(){return this}isOptional(){return!1}props(e){let t={toAny:this.registry.method({},this.registry.any(),`type.toAny`)},n=this.registry.augmentation(this.name);return n?.props?{...t,...n.props}:t}static UNIVERSAL_PROP_NAMES=new Set([`toAny`]);constraints(){return[]}get(e){return this.registry.augmentation(this.name)?.get}call(e){return this.registry.augmentation(this.name)?.call}init(e){return this.registry.augmentation(this.name)?.init}prop(e,t){let n=this.props(t)[e];return n?$h.from(n):void 0}follow(e,t){if(`prop`in e)return this.prop(e.prop,t)?.type;if(`args`in e)return this.call(t)?.returns;if(`key`in e)return this.get(t)?.value}at(e,t){let n=this;for(let r of e){if(!n)return;n=n.follow(r,t)}return n}toA(e){return e?.override?.(this)||(this.isRegisteredNamed()?R.ref(this.name):this.defineA(e))}defineA(e){return this.describeA(this.valueA(e),e)}valueA(e){return R.unknown()}toNewA(e){let t=this.init(e?.scope);return t?this.describeA(t.args.toA(e),e):this.toA(e)}isRegisteredNamed(){let e=this.registry;return e.typeClass(this.name)===void 0&&e.namedTypeList().includes(this)}objectA(e,t){let n=R.object(e);return t?.unknownKeys===`refuse`?n.strict():n}describeA(e,t){let n=t?.includeDocs??`none`,r=[];n!==`none`&&this.docs&&r.push(this.docs);let i=this.constraints();return i.length>0&&r.push(i.map(e=>`must satisfy ${e.toCode(this.registry,{expectsValue:!0})}`).join(`; `)),r.length>0?e.describe(r.join(` — `)):e}newEffects(e){let t=this.initEffects();return this.forEachNewSlot(e,{slot:(e,n)=>{t|=e.newEffects(n)},missing:e=>{t|=e.effects()}})?t:t|this.exprValueEffects(e)}exprValueEffects(e){if(!e||typeof e!=`object`||Array.isArray(e))return B.NONE;let t=e.kind;if(typeof t!=`string`||!this.registry.exprClass(t))return B.NONE;try{return this.registry.parseExpr(e,this.scope).effects()}catch{return B.NONE}}initEffects(){let e=this.init();if(!e)return B.NONE;try{return this.registry.parseExpr(e.run,this.scope).effects()}catch{return B.NONE}}newComplexity(e){let t=1+this.initComplexity();return this.forEachNewSlot(e,{slot:(e,n)=>{t+=e.elementComplexity(n)},missing:e=>{t+=e.complexity()}})?t:t+this.exprValueComplexity(e)}exprValueComplexity(e){if(!e||typeof e!=`object`||Array.isArray(e))return 0;let t=e.kind;if(typeof t!=`string`||!this.registry.exprClass(t))return 0;try{return this.registry.parseExpr(e,this.scope).complexity()}catch{return 0}}initComplexity(){let e=this.init();if(!e)return 0;try{return this.registry.parseExpr(e.run,this.scope).complexity()}catch{return 0}}elementComplexity(e){let t=this.exprValueComplexity(e);return t>0?t:1}forEachNewSlot(e,t){return!1}validateNewValue(e,t,n,r,i){if(this.forEachNewSlot(e,{slot:(e,a,o)=>{r.at([o],()=>e.validateNewValue(a,t,n,r,i))}}))return;let a=Qh(e,this.scope);if(!a)return;let o=a.validateWalk(t,n,r,i);o.name!==`any`&&(Wh(this,o)||r.error(`new.slot.type`,`this slot is declared \`${this.toCode()}\` but the expression here produces \`${o.toCode()}\``))}async newFill(e,t,n){let r=Qh(e,this.scope);return r?r.evaluate(t,n):e}toGinCode(e,t,n=[]){return rh(this.toCode(e,t),{path:n,type:this})}toJSONCode(e=[],t=2,n=0){return gg(this.toJSON(),this.registry,e,t,n,this)}docsPrefix(e){return``}extendsClause(e){return``}toCodeRef(e,t){return this.toCode(e,t)}refProps(){return{}}refGet(){}refCall(){}static renderGenerics(e,t){let n=Object.keys(e);return n.length===0?``:`<${cg(n.map(n=>{let r=e[n],i=r.name===`alias`&&r.options?.name===n;return r.name===`any`||i?n:`${n}: ${r.toCode(void 0,t)}`}),{indent:lg(t)})}>`}static renderGenericArgs(t,n){let r=Object.keys(t);return r.length===0||!r.some(n=>!e.isGenericPlaceholder(n,t[n]))?``:`<${cg(r.map(e=>t[e].toCode(void 0,n)),{indent:lg(n)})}>`}static isGenericPlaceholder(e,t){return t.name===`any`||t.name===`alias`&&t.options?.name===e}static formatParams(e,t,n=`auto`){let r=e.fields;if(!r)return e.name===`void`||e.name===`any`?``:`args: ${e.toCode(void 0,t)}`;let i=Object.entries(r).map(([e,n])=>{let r=n.type.isOptional(),i=r?n.type.required():n.type;return`${n.docs&&t?.includeComments!==!1?`/* ${n.docs} */ `:``}${e}${r?`?`:``}: ${i.toCode(void 0,t)}`}),a=lg(t);return n===`auto`?cg(i,{indent:a}):i.length<=1?i.join(``):`
|
|
92
|
+
${i.map(e=>ug(e,a)).join(`
|
|
93
93
|
`)}
|
|
94
|
-
`}definitionInit(){return this.init()}definitionCall(){return this.call()}definitionGet(){return this.get()}definitionProps(){return this.props()}toCodeDefinition(t){let n=[],r=t?.includeComments!==!1,i=
|
|
94
|
+
`}definitionInit(){return this.init()}definitionCall(){return this.call()}definitionGet(){return this.get()}definitionProps(){return this.props()}toCodeDefinition(t){let n=[],r=t?.includeComments!==!1,i=lg(t),a=e=>`/// ${e}`,o=this.definitionCall();if(o?.types)for(let[e,r]of Object.entries(o.types))n.push(`type ${e} = ${r.toCode(void 0,t)};`);let s=this.definitionInit();if(s&&(s.docs&&r&&n.push(a(s.docs)),n.push(`new(${e.formatParams(s.args,t,`lines`)})`)),o){let r=o.returns?.toCode(void 0,t)??`void`;n.push(`(${e.formatParams(o.args,t,`lines`)}): ${r}`)}let c=this.definitionGet();c&&n.push(`[key: ${c.key.toCode(void 0,t)}]: ${c.value.toCode(void 0,t)}`);let l=new Set(Object.keys(this.generic));for(let[i,o]of Object.entries(this.definitionProps())){let s=o instanceof $h?o:$h.from(o);s.docs&&r&&n.push(a(s.docs));let c=s.type.isOptional(),u=c?s.type.required():s.type,d=c?`?`:``,f=u.call(),p=Object.keys(u.props()).filter(t=>!e.UNIVERSAL_PROP_NAMES.has(t));if(f&&!u.get()&&p.length===0){let r=f.returns?.toCode(void 0,t)??`void`,a=Object.fromEntries(Object.entries(u.generic).filter(([e])=>!l.has(e))),o=e.renderGenerics(a,t);n.push(`${i}${d}${o}(${e.formatParams(f.args,t,`lines`)}): ${r}`)}else n.push(`${i}${d}: ${u.toCode(void 0,t)}`)}let u=`${this.docs&&r?`${a(this.docs)}
|
|
95
95
|
`:``}type ${this.name}${e.renderGenerics(this.generic,t)}${this.extendsClause(t)}`;return n.length===0?`${u} {}`:`${u} {
|
|
96
|
-
${n.map(e=>
|
|
96
|
+
${n.map(e=>ug(e,i)).join(`
|
|
97
97
|
`)}
|
|
98
|
-
}`}propSuperFor(e,t,n,r,i){}indexSuperFor(e,t,n,r){}propGet(e,t,n){let r=e.raw&&typeof e.raw==`object`?e.raw[t]:void 0;return r instanceof W?r:G(n,r)}propSet(e,t,n){if(e.raw&&typeof e.raw==`object`)e.raw[t]=n;else throw Error(`type '${this.name}': cannot set prop '${t}' \u2014 value's raw is not an object`)}validate(e){let t=new
|
|
98
|
+
}`}propSuperFor(e,t,n,r,i){}indexSuperFor(e,t,n,r){}propGet(e,t,n){let r=e.raw&&typeof e.raw==`object`?e.raw[t]:void 0;return r instanceof W?r:G(n,r)}propSet(e,t,n){if(e.raw&&typeof e.raw==`object`)e.raw[t]=n;else throw Error(`type '${this.name}': cannot set prop '${t}' \u2014 value's raw is not an object`)}validate(e){let t=new eh;try{this.registry.parse(this.toDefinitionJSON())}catch(e){t.error(`type.invalid`,e.message)}return dg(this,e,t),t}},rg={depth:0,lowWater:1/0,active:new Map,memo:new Map};function ig(e,t){return`${+!!e?.strict}${+!!e?.value}${+!!e?.exact}:${t?yh(t):``}`}var ag={active:0,depth:0};function og(e,t){if(!e)return``;let n=Object.entries(e).filter(([e,n])=>!(n===void 0||n===``||t&&e in t&&sg(t[e],n)));return n.length===0?``:`{${cg(n.map(([e,t])=>`${e}=${typeof t==`string`?JSON.stringify(t):typeof t==`number`||typeof t==`boolean`?String(t):t===null?`null`:JSON.stringify(t)}`))}}`}function sg(e,t){if(e===t)return!0;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function cg(e,t={}){if(e.length===0)return``;let n=t.sep??`, `,r=t.threshold??32,i=t.totalThreshold??80,a=e.join(n);if(!(a.length>i||e.some(e=>e.length>r||e.includes(`
|
|
99
99
|
`))))return a;let o=n.replace(/\s+$/,``),s=t.indent??` `;return`
|
|
100
|
-
${e.map(e=>
|
|
100
|
+
${e.map(e=>ug(e,s)).join(`${o}
|
|
101
101
|
`)}
|
|
102
|
-
`}function
|
|
103
|
-
${t}`)}function
|
|
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:
|
|
106
|
-
`),`[${a}]`}if(e&&typeof e==`object`){let a=n?.fields,o=Object.entries(e);if(o.length===0)return`new ${i}()`;let s=
|
|
107
|
-
`)?`new ${i} {${s}}`:`new ${i} { ${s} }`}return JSON.stringify(e)}function
|
|
108
|
-
`)?H`({\n ${
|
|
109
|
-
`)}\n})`:H`({ ${
|
|
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
|
|
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=
|
|
112
|
-
`)}function
|
|
113
|
-
`} ${a} (${s}) return ${c.indent(` `)};`}let r=``;return this.otherwise&&(r=H`\n return ${this.otherwise.toGinCode(e,o,[...n,`else`]).indent(` `)};`),
|
|
114
|
-
break;`}`})),u=``;return this.otherwise&&(u=H`\n default:\n ${c(this.otherwise,[...n,`else`]).indent(` `)}`),
|
|
115
|
-
${
|
|
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
|
|
117
|
-
`)?H`${o} => {\n ${s.indent(` `)}\n}`:H`${o} => ${s}`,
|
|
118
|
-
`)?new V(e.text.replace(/\n\s*/g,` `),e.spans):e}function
|
|
102
|
+
`}function lg(e){return e?.indent??` `}function ug(e,t){return t+e.replace(/\n/g,`
|
|
103
|
+
${t}`)}function dg(e,t,n){let r=e.registry,i={inLoop:!1,inLambda:!1},a=e.props();for(let[o,s]of Object.entries(a)){let a=s instanceof $h?s:$h.from(s);n.at([`props`,o],()=>{hg(a.get,fg(a,e,r),mg(a),`get`,t,n,i),hg(a.set,pg(a,e,r),r.void(),`set`,t,n,i),hg(a.default,new Map,a.type,`default`,t,n,i)})}let o=e.get();o&&n.at(`get`,()=>{let a=new Map([[`this`,e],[`key`,o.key]]),s=new Map([[`this`,e],[`key`,o.key],[`value`,o.value]]);hg(o.get,a,o.value,`get`,t,n,i),hg(o.set,s,r.void(),`set`,t,n,i),hg(o.loop,a,void 0,`loop`,t,n,i)});let s=e.call();s&&n.at(`call`,()=>{let a=new Map([[`this`,e],[`args`,s.args],[`recurse`,r.fn({args:s.args,returns:s.returns??r.any()})]]);hg(s.get,a,s.returns,`get`,t,n,{...i,inLambda:!0});let o=new Map([[`this`,e],[`args`,s.args],[`value`,s.returns??r.any()],[`recurse`,r.fn({args:s.args,returns:s.returns??r.any()})]]);hg(s.set,o,r.void(),`set`,t,n,{...i,inLambda:!0})});let c=e.init();c&&n.at(`init`,()=>{let r=new Map([[`this`,e],[`args`,c.args]]);hg(c.run,r,void 0,`run`,t,n,i)});for(let a of e.constraints())n.at(`constraint`,()=>{let o=Oh(t,a,new Map([[`this`,e]]),n,i),s=r.bool();o.name!==`any`&&!s.compatible(o)&&n.warn(`type.surface.return-type`,`constraint must return bool, got '${o.name}'`)})}function fg(e,t,n){let r=new Map([[`this`,t]]),i=e.type.call?.();return i&&(r.set(`args`,i.args),r.set(`recurse`,n.fn({args:i.args,returns:i.returns??n.any()}))),r}function pg(e,t,n){return new Map([[`this`,t],[`value`,e.type]])}function mg(e){let t=e.type.call?.();return t?t.returns:e.type}function hg(e,t,n,r,i,a,o){e&&a.at(r,()=>{let s=Oh(i,e,t,a,o);n&&s.name!==`any`&&!n.compatible(s)&&a.warn(`type.surface.return-type`,`${r} body returns '${s.name}', not compatible with declared '${n.name}'`)})}function gg(e,t,n,r,i,a){let o=i+1,s=[];return e.name!==void 0&&s.push({key:`name`,value:V.jsonString(e.name)}),e.extends!==void 0&&s.push({key:`extends`,value:V.jsonString(e.extends)}),e.satisfies!==void 0&&e.satisfies.length>0&&s.push({key:`satisfies`,value:wg(e.satisfies,[...n,`satisfies`],r,o)}),e.docs!==void 0&&s.push({key:`docs`,value:V.jsonString(e.docs)}),e.options!==void 0&&Object.keys(e.options).length>0&&s.push({key:`options`,value:wg(e.options,[...n,`options`],r,o)}),e.generic!==void 0&&Object.keys(e.generic).length>0&&s.push({key:`generic`,value:_g(e.generic,t,[...n,`generic`],r,o)}),e.props!==void 0&&Object.keys(e.props).length>0&&s.push({key:`props`,value:vg(e.props,t,[...n,`props`],r,o)}),e.get!==void 0&&s.push({key:`get`,value:bg(e.get,t,[...n,`get`],r,o)}),e.call!==void 0&&s.push({key:`call`,value:xg(e.call,t,[...n,`call`],r,o)}),e.init!==void 0&&s.push({key:`init`,value:Sg(e.init,t,[...n,`init`],r,o)}),e.constraint!==void 0&&s.push({key:`constraint`,value:Cg(e.constraint,t,[...n,`constraint`],r,o)}),V.jsonObject(s,{path:n,type:a},i,r)}function _g(e,t,n,r,i){let a=Object.entries(e).map(([e,a])=>({key:e,value:gg(a,t,[...n,e],r,i+1,void 0)}));return V.jsonObject(a,{path:n},i,r)}function vg(e,t,n,r,i){let a=Object.entries(e).map(([e,a])=>({key:e,value:yg(a,t,[...n,e],r,i+1)}));return V.jsonObject(a,{path:n},i,r)}function yg(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`type`,value:gg(e.type,t,[...n,`type`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:Cg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:Cg(e.set,t,[...n,`set`],r,a)}),e.default!==void 0&&o.push({key:`default`,value:Cg(e.default,t,[...n,`default`],r,a)}),V.jsonObject(o,{path:n},i,r)}function bg(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`key`,value:gg(e.key,t,[...n,`key`],r,a,void 0)}),o.push({key:`value`,value:gg(e.value,t,[...n,`value`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:Cg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:Cg(e.set,t,[...n,`set`],r,a)}),e.loop!==void 0&&o.push({key:`loop`,value:Cg(e.loop,t,[...n,`loop`],r,a)}),e.loopDynamic!==void 0&&o.push({key:`loopDynamic`,value:String(e.loopDynamic)}),V.jsonObject(o,{path:n},i,r)}function xg(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),e.types!==void 0&&Object.keys(e.types).length>0&&o.push({key:`types`,value:_g(e.types,t,[...n,`types`],r,a)}),o.push({key:`args`,value:gg(e.args,t,[...n,`args`],r,a,void 0)}),e.returns!==void 0&&o.push({key:`returns`,value:gg(e.returns,t,[...n,`returns`],r,a,void 0)}),e.throws!==void 0&&o.push({key:`throws`,value:gg(e.throws,t,[...n,`throws`],r,a,void 0)}),e.get!==void 0&&o.push({key:`get`,value:Cg(e.get,t,[...n,`get`],r,a)}),e.set!==void 0&&o.push({key:`set`,value:Cg(e.set,t,[...n,`set`],r,a)}),V.jsonObject(o,{path:n},i,r)}function Sg(e,t,n,r,i){let a=i+1,o=[];return e.docs!==void 0&&o.push({key:`docs`,value:V.jsonString(e.docs)}),o.push({key:`args`,value:gg(e.args,t,[...n,`args`],r,a,void 0)}),o.push({key:`run`,value:Cg(e.run,t,[...n,`run`],r,a)}),V.jsonObject(o,{path:n},i,r)}function Cg(e,t,n,r,i){try{return t.parseExpr(e).toJSONCode(n,r,i)}catch{return wg(e,n,r,i)}}function wg(e,t,n,r){let i=JSON.stringify(e,null,n);if(r>0){let e=` `.repeat(r*n);i=i.replace(/\n/g,`
|
|
104
|
+
`+e)}return rh(i,{path:t})}var W=class{type;raw;constructor(e,t){this.type=e,this.raw=t}toLogical(){return Tg(this.raw)}encode(){return this.type.encode(this.raw)}toJSON(e=Xh){return{type:this.type.toJSONRef(e),value:this.type.encodeAs(this.raw,e)}}encodeLogical(){return this.type.encodeAs(this.raw,Og)}toJSONRefs(){return this.toJSON({form:`envelope`,typeRefs:`name`})}toJSONLogical(){return this.toJSON(Og)}};function Tg(e){if(e instanceof W)return e.toLogical();if(Array.isArray(e))return e.map(Tg);if(e instanceof Map){let t=new Map;for(let n of e.values())Eg(n)&&t.set(n[0].toLogical(),n[1].toLogical());return t}if(Dg(e)){let t={};for(let[n,r]of Object.entries(e))t[n]=Tg(r);return t}return e}function Eg(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function Dg(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var Og={form:`logical`,typeRefs:`name`};function G(e,t){return new W(e,t)}var kg=class extends Error{constructor(){super(`The run was stopped.`),this.name=`RunStoppedError`}},Ag=class{signal;slice;#e=Date.now();constructor(e={}){this.signal=e.signal,this.slice=e.slice??10}check(){let e=this.signal;if(e?.aborted!==!0)return;let t=e.reason;throw t instanceof Error?t:new kg}async checkpoint(){this.check(),Date.now()-this.#e<this.slice||(await new Promise(e=>{setTimeout(e,0)}),this.#e=Date.now(),this.check())}},jg=new Set([`text`,`num`,`bool`,`enum`,`literal`,`date`,`timestamp`,`duration`,`color`,`null`]);function Mg(e){let t=e;for(let e=0;e<16;e+=1){let e=t.inner??t.base;if(e===void 0||e===t)return t;t=e}return t}function Ng(e){return jg.has(Mg(e).name)}function Pg(e,t){let n=e.isOptional()?e.inner??e:e;return Ng(n)?R.union([n.toA(t),R.ref(`Expr`)]):R.ref(`Expr`)}function Fg(e,t){if(e===t)return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;let n=e,r=t,i=Object.keys(n);return i.length===Object.keys(r).length&&i.every(e=>n[e]===r[e])}function Ig(e,t,n){let r=Object.keys(e);return r.length===0?t?$h.toJSONMap(t):void 0:{...n&&Object.keys(n).length===r.length&&r.every(e=>e in n)?n:$h.toJSONMap(e),...t?$h.toJSONMap(t):{}}}function Lg(e,t){return{...e,props:e.props?$h.fromMap(e.props,t):void 0,get:e.get?eg.from(e.get,t):void 0,call:e.call?tg.from(e.call,t):void 0,init:e.init?ng.from(e.init,t):void 0}}var Rg=class e extends U{name;docs;base;original;local;bindings;constructor(e,t,n,r,i){let a=n.options?t.narrow(n.options):t.options,o=n.options&&!Fg(a,t.options)?e.parse({...t.toJSON(),options:a},i):t;super(r??e,a,n.generic??{}),this.original=t,this.base=o,this.local=Lg(n,e),this.name=n.name,this.docs=n.docs;let s=Object.entries(n.generic??{}).filter(([e,t])=>!U.isGenericPlaceholder(e,t));this.bindings=s.length>0?Object.fromEntries(s):void 0}storedLocalProps(){let e=[];for(let[t,n]of Object.entries(this.local.props??{})){let r=n instanceof $h?n:$h.from(n);r.get||r.type.call()||e.push([t,r])}return e}valid(e,t){let n=this.bindScope(t);if(!this.base.valid(e,n))return!1;let r=this.storedLocalProps();if(r.length===0||!Zh(e))return!0;let i=e;for(let[e,t]of r){let r=i[e];if(!(r instanceof W))return t.type.isOptional();if(!r.type.valid(r.raw,n)||!Wh(t.type,r.type,n))return!1}return!0}parse(e,t){let n=this.bindScope(t),r=this.base.parse(e,n),i=this.storedLocalProps();if(i.length===0||!Zh(r.raw))return new W(this,r.raw);let a=Zh(e)?e:{},o={...r.raw};for(let[e,t]of i)o[e]=this.registry.parseValue(a[e],t.type,n);return new W(this,o)}parsesExprValue(e){return this.base.parsesExprValue(this.bindScope(e))}encode(e,t){return this.encodeAs(e,Xh,t)}encodeAs(e,t,n){let r=this.bindScope(n),i=this.base.encodeAs(e,t,r),a=this.storedLocalProps();if(a.length===0||!Zh(i)||!Zh(e))return i;let o=e,s={...i};for(let[e]of a)Yh(s,e,o[e],t,r);return s}create(){return this.withLocalSlots(this.base.create(),e=>e.create())}random(e){return this.withLocalSlots(this.base.random(e),t=>t.random(e))}withLocalSlots(e,t){let n=this.storedLocalProps();if(n.length===0||!Zh(e))return e;let r={...e};for(let[e,i]of n)r[e]=new W(i.type,t(i.type));return r}forEachNewSlot(e,t){let n=this.base.forEachNewSlot(e,t),r=this.storedLocalProps();if(r.length===0||!Zh(e))return n;let i=e;for(let[e,n]of r)e in i?t.slot(n.type,i[e],e):n.default!==void 0&&t.missing?.(n.default,e);return!0}async newFill(e,t,n){let r=await this.base.newFill(e,t,n),i=this.storedLocalProps();if(i.length===0||!Zh(r))return r;let a=r,o;for(let[e,r]of i)if(e in a){let i=await r.type.newFill(a[e],t,n);i!==a[e]&&(o??={...a},o[e]=i)}else r.default!==void 0&&(o??={...a},o[e]=await r.default.evaluate(t,n));return o??a}compatibleType(t,n,r){return n?.exact?t instanceof e&&t.name===this.name&&this.base.compatible(t.base,n,r):t instanceof e?this.base.compatible(t.base,n,r):this.base.compatible(t,n,r)}or(t){if(t instanceof e&&t.name===this.name){let n={name:this.name,docs:this.docs??t.docs,options:{...this.local.options??{},...t.local.options??{}},props:{...this.local.props??{},...t.local.props??{}},get:this.local.get??t.local.get,call:this.local.call??t.local.call,init:this.local.init??t.local.init};return new e(this.registry,this.original,n)}return this.base.or(t)}simplify(){return this}required(){return this.base.required()}isOptional(){return this.base.isOptional()}narrow(e){return this.base.narrow(e)}props(e){let t=this.registry.augmentation(this.name);return{...this.base.props(this.bindScope(e)),...t?.props??{},...this.local.props??{}}}get(e){return this.local.get??this.registry.augmentation(this.name)?.get??this.base.get(this.bindScope(e))}call(e){return this.local.call??this.registry.augmentation(this.name)?.call??this.base.call(this.bindScope(e))}init(e){return this.local.init??this.registry.augmentation(this.name)?.init??this.base.init(this.bindScope(e))}toJSON(){if(ag.active>0&&ag.depth>0&&!this.local.useSite&&this.registry.lookup(this.name)!==void 0&&(this.registry.lookup(this.name)===this||this.bindings)){let e=Object.entries(this.bindings??{});return e.length>0?{name:this.name,generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{name:this.name}}ag.depth++;try{return this.toJSONInner()}finally{ag.depth--}}toJSONInner(){if(this.local.useSite){let e=Object.entries(this.bindings??{});return{name:this.name,...e.length>0?{generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{},options:{...this.local.options}}}let e=this.original.toJSON(),t=this.original.name!==this.name,n={...e.options,...this.local.options},r={...e.generic??{}};if(this.local.generic)for(let[e,t]of Object.entries(this.local.generic))r[e]=t.toJSON();return mh({name:this.name,extends:t?this.original.name:void 0,docs:this.docs,generic:Object.keys(r).length>0?r:void 0,options:n&&Object.keys(n).length>0?n:void 0,props:Ig(t?this.original.refProps():{},this.local.props,e.props),get:(this.local.get??(t?this.original.refGet():void 0))?.toJSON(),call:(this.local.call??(t?this.original.refCall():void 0))?.toJSON(),init:this.local.init?.toJSON(),constraint:this.local.constraint?this.local.constraint.toJSON():void 0})}clone(){let t=this.local.generic?Object.fromEntries(Object.entries(this.local.generic).map(([e,t])=>[e,t.clone()])):void 0;return new e(this.registry,this.original.clone(),{name:this.local.name,docs:this.local.docs,options:this.local.options?{...this.local.options}:void 0,generic:t,props:this.local.props?{...this.local.props}:void 0,get:this.local.get,call:this.local.call,init:this.local.init,constraint:this.local.constraint?.clone(),useSite:this.local.useSite},this.bindings?this.scope:void 0)}toCode(e,t){return this.docsPrefix(t)+this.name+U.renderGenericArgs(this.generic,t)+(this.local.useSite?og(this.local.options):``)}extendsClause(e){return` extends ${this.base.toCodeRef(void 0,e)}`}baseMembersElided(e){return this.base.toCodeRef(void 0,e)!==this.base.toCode(void 0,e)}ownAugmentation(){return this.registry.augmentation(this.name)}definitionInit(){return this.local.init??this.ownAugmentation()?.init}definitionCall(){return this.local.call??this.ownAugmentation()?.call??(this.baseMembersElided()?this.base.refCall():void 0)}definitionGet(){return this.local.get??this.ownAugmentation()?.get??(this.baseMembersElided()?this.base.refGet():void 0)}definitionProps(){return{...this.baseMembersElided()?this.base.refProps():{},...this.ownAugmentation()?.props??{},...this.local.props??{}}}specialize(t){let n={...this.local.generic??{}},r={};for(let e of Object.keys(this.local.generic??{})){let i=t[e];i&&(n[e]=i,r[e]=i)}return Object.keys(r).length===0?this:new e(this.registry,this.original,{...this.local,generic:n},new bh(this.scope,r))}bindScope(e){return this.bindings?e?new bh(e,this.bindings):this.scope:e}constraints(){let e=this.base.constraints();return this.local.constraint?[this.local.constraint,...e]:e}valueA(e){return this.mergeLocalPropsA(this.base.defineA(e),e,t=>t.type.toA(e))}toNewA(e){return this.describeA(this.mergeLocalPropsA(this.base.toNewA(e),e,t=>Pg(t.type,e)),e)}mergeLocalPropsA(e,t,n){if(!(e instanceof vf))return e;let r=t?.includeDocs??`none`,i={};for(let[e,t]of this.storedLocalProps()){let a=n(t);r===`all`&&t.docs&&(a=a.describe(t.docs)),i[e]=t.type.isOptional()&&a.kind!==`optional`?R.optional(a):a}return Object.keys(i).length===0?e:e.extend(i)}propSuperFor(e,t,n,r,i){let a=this.local.props;if(!(a&&Object.hasOwn(a,t)))return;let o=this.base.prop(t);if(!o)return;let s=new W(this.base,e.raw);if(n===`get`){if(o.type.call()&&o.get){let e=o.type;return new W(e,async e=>{let n={this:s,args:e},a=s.type.propSuperFor(s,t,`get`,r,i);return a&&(n.super=a),i.evaluate(o.get,r.child(n))})}return new W(i.registry.fn({args:i.registry.obj({}),returns:o.type}),async e=>{if(!o.get)return G(o.type,s.raw?.[t]);let n={this:s},a=s.type.propSuperFor(s,t,`get`,r,i);return a&&(n.super=a),i.evaluate(o.get,r.child(n))})}if(n===`set`)return o.set?new W(i.registry.fn({args:i.registry.obj({value:{type:o.type}}),returns:i.registry.void()}),async e=>{let n=e.raw.value,a={this:s,value:n},c=s.type.propSuperFor(s,t,`set`,r,i);return c&&(a.super=c),await i.evaluate(o.set,r.child(a)),G(i.registry.void(),void 0)}):void 0;let c=o.type.call();return c?.set?new W(i.registry.fn({args:i.registry.obj({args:{type:c.args},value:{type:c.returns??i.registry.any()}}),returns:i.registry.void()}),async e=>{let n=e.raw,a={this:s,args:n.args,value:n.value},o=s.type.propSuperFor(s,t,`callSet`,r,i);return o&&(a.super=o),await i.evaluate(c.set,r.child(a)),G(i.registry.void(),void 0)}):void 0}indexSuperFor(e,t,n,r){let i=this.local.get;if(!i)return;let a=this.base.get();if(!a)return;let o=new W(this.base,e.raw);return t===`get`?!i.get||!a.get?void 0:new W(r.registry.fn({args:r.registry.obj({key:{type:a.key}}),returns:a.value}),async e=>{let t=e.raw.key,n=r.createRootScope();return n.vars.set(`this`,o),n.vars.set(`key`,t),r.evaluate(a.get,n)}):!i.set||!a.set?void 0:new W(r.registry.fn({args:r.registry.obj({key:{type:a.key},value:{type:a.value}}),returns:r.registry.void()}),async e=>{let t=e.raw,n=r.createRootScope();return n.vars.set(`this`,o),n.vars.set(`key`,t.key),n.vars.set(`value`,t.value),await r.evaluate(a.set,n),G(r.registry.void(),void 0)})}},zg=class e extends U{static NAME=`any`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return!0}parse(e){return new W(this,e)}encode(e){return e}create(){return null}random(e){return null}compatibleType(e,t){return!0}flexible(){return!0}isUniversal(){return!0}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new th({path:[],code:`any.no-options`,message:`any has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),typeOf:e.method({},e.text(),`any.typeOf`),is:e.method({},e.bool(),`any.is`,{generic:{T:e.any()}}),as:e.method({},e.optional(e.alias(`T`)),`any.as`,{generic:{T:e.any()}}),toText:e.method({},e.text(),`any.toText`),toBool:e.method({},e.bool(),`any.toBool`),eq:e.method({other:e.any()},e.bool(),`any.eq`),neq:e.method({other:e.any()},e.bool(),`any.neq`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`any`}valueA(){return R.unknown()}},Bg=class e extends U{static NAME=`obj`;static consumes=[`props`];name=e.NAME;static optionKeys=[];static genericKeys=[];fields;static from(t,n){let r=$h.fromMap(t.props??{},n);return new e(n,r)}constructor(e,t){super(e,{});let n={};for(let[e,r]of Object.entries(t))n[e]=$h.from(r);this.fields=n}valid(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let[n,r]of Object.entries(this.fields)){let i=e[n];if(!(i instanceof W)||!i.type.valid(i.raw,t)||!Wh(r.type,i.type,t))return!1}return!0}parse(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new th({path:[],code:`object.invalid`,message:`object.parse: expected object, got ${typeof e}`,severity:`error`});let n={};for(let[r,i]of Object.entries(this.fields)){let a=e[r];n[r]=this.registry.parseValue(a,i.type,t)}return new W(this,n)}encode(e,t){return this.encodeAs(e,Xh,t)}encodeAs(e,t,n){let r=e,i={};for(let[e]of Object.entries(this.fields))Yh(i,e,r[e],t,n);return i}create(){let e={};for(let[t,n]of Object.entries(this.fields))e[t]=new W(n.type,n.type.create());return e}random(e){let t={};for(let[n,r]of Object.entries(this.fields))t[n]=new W(r.type,r.type.random(e));return t}forEachNewSlot(e,t){if(!Vg(e)||Qh(e,this.scope))return!1;let n=e;for(let[e,r]of Object.entries(this.fields))e in n?t.slot(r.type,n[e],e):r.default!==void 0&&t.missing?.(r.default,e);return!0}async newFill(e,t,n){if(!Vg(e)||Qh(e,this.scope))return super.newFill(e,t,n);let r=e,i;for(let[e,a]of Object.entries(this.fields))if(e in r){let o=await a.type.newFill(r[e],t,n);o!==r[e]&&(i??={...r},i[e]=o)}else a.default!==void 0&&(i??={...r},i[e]=await a.default.evaluate(t,n));return i??r}like(t){if(!(t instanceof e))return this;let n={};for(let[e,r]of Object.entries(t.fields)){let t=this.registry.like(r.type);if(t.name===`null`)return this.registry.null();n[e]={type:t}}return this.registry.obj(n)}compatibleType(t,n,r){if(!(t instanceof e))return!1;for(let[e,i]of Object.entries(this.fields)){let a=t.fields[e];if(!a){if(n?.exact)return!1;if(i.type.isOptional())continue;return!1}if(!i.type.compatible(a.type,n,r))return!1}if(n?.exact){let e=new Set(Object.keys(this.fields));for(let n of Object.keys(t.fields))if(!e.has(n))return!1}return!0}or(t){if(!(t instanceof e))return this;let n={};for(let[e,r]of Object.entries(this.fields)){let i=t.fields[e];i&&(n[e]={type:r.type.or(i.type)})}return new e(this.registry,n)}narrow(e){return{}}props(){let e=this.registry,t=Object.values(this.fields).map(e=>e.type),n=t.length===0?e.any():t.length===1?t[0]:e.or(t),r={keys:e.method({},e.list(e.text()),`object.keys`),values:e.method({},e.list(n),`object.values`),entries:e.method({},e.list(e.tuple([e.text(),n])),`object.entries`),has:e.method({key:e.text()},e.bool(),`object.has`),eq:e.method({other:e.any()},e.bool(),`object.eq`),neq:e.method({other:e.any()},e.bool(),`object.neq`),toText:e.method({},e.text(),`object.toText`)};return{...super.props(),...r,...this.fields}}get(){let e=Object.keys(this.fields);if(e.length===0)return;let t=this.registry.text(),n=e.map(e=>this.registry.literal(t,e)),r=n.length===1?n[0]:this.registry.or(n),i=Object.values(this.fields).map(e=>e.type),a=i.length===1?i[0]:this.registry.or(i),o=this.registry;return new eg({key:r,value:a,get:o.nativeExpr(`object.indexGet`),set:o.nativeExpr(`object.indexSet`),loop:o.nativeExpr(`object.iterate`)})}toJSON(){return{name:e.NAME,props:$h.toJSONMap(this.fields)}}clone(){let t={};for(let[e,n]of Object.entries(this.fields))t[e]={...n,type:n.type.clone()};return new e(this.registry,t)}toCode(e,t){let n=Object.entries(this.fields);if(n.length===0)return this.docsPrefix(t)+`obj`;let r=t?.includeComments!==!1,i=n.map(([e,n])=>{let i=n.type.isOptional(),a=i?n.type.required():n.type,o=i?`${e}?`:e;return`${n.docs&&r?`/* ${n.docs} */ `:``}${o}: ${a.toCode(void 0,t)}`});return this.docsPrefix(t)+`obj{${cg(i,{indent:lg(t)})}}`}toCodeRef(e,t){return this.docsPrefix(t)+`obj`}refProps(){return this.fields}valueA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this.fields)){let a=i.type.toA(e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=a}return this.objectA(n,e)}toNewA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this.fields)){let a=Pg(i.type,e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=i.type.isOptional()?R.optional(a):a}return this.describeA(R.object(n),e)}describe(t){if(typeof t!=`object`||!t||Array.isArray(t))return;let n={};for(let[e,r]of Object.entries(t))n[e]={type:this.registry.any().describe?.(r)??this.registry.any()};return new e(this.registry,n)}};function Vg(e){return Zh(e)}var Hg=class e extends U{static NAME=`and`;name=e.NAME;static optionKeys=[`types`];static genericKeys=[];static from(t,n){n.registry;let r=(t.options?.types??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,{parts:t})}get parts(){return this.options.parts}valid(e,t){return this.parts.every(n=>n.valid(e,t))}effective(){let e=this.parts;if(e.length===0)return;if(e.length===1)return e[0];let t=this.mergedObjFields();return t?this.registry.obj(t):e[0]}mergedObjFields(){let e=[];for(let t of this.parts){if(!(t instanceof Bg))return;e.push(t)}let t={};for(let n of e)for(let[e,r]of Object.entries(n.fields)){let n=t[e];t[e]=n?{type:this.registry.and([n.type,r.type])}:r}return t}parse(e,t){let n=this.effective();if(!n)return new W(this,e);let r=n.parse(e,t).raw;for(let e of this.parts)if(!e.valid(r,t))throw new th({path:[],code:`and.constraint`,message:`and: value fails part ${e.name}`,severity:`error`});return new W(this,r)}encode(e,t){return this.effective()?.encode(e,t)??e}parsesExprValue(e){return this.effective()?.parsesExprValue(e)??!1}encodeAs(e,t,n){return this.effective()?.encodeAs(e,t,n)??e}forEachNewSlot(e,t){return this.effective()?.forEachNewSlot(e,t)??!1}async newFill(e,t,n){let r=this.effective();return r?r.newFill(e,t,n):super.newFill(e,t,n)}create(){let e=this.effective();if(!e)return null;for(let t of[e,...this.parts]){let e=t.create();if(this.valid(e))return e}return e.create()}random(e){let t=this.effective();if(!t)return null;for(let n of[t,...this.parts]){let t=n.random(e);if(this.valid(t))return t}return t.random(e)}like(t){if(!(t instanceof e))return this;let n=t.parts.map(e=>this.registry.like(e)).filter(e=>e.name!==`null`);return n.length===0?this.registry.null():n.length===1?n[0]:this.registry.and(n)}compatibleType(e,t,n){return this.parts.every(r=>r.compatible(e,t,n))}isUniversal(){return this.parts.length===0||this.parts.every(e=>e.isUniversal())}or(t){return t instanceof e?new e(this.registry,[...this.parts,...t.parts]):this}simplify(){if(this.parts.length===1)return this.parts[0];if(this.parts.length===0)return this;let e=this.mergedObjFields();return e?this.registry.obj(e):this}narrow(e){return this.options}props(){let e={};for(let t of this.parts)for(let[n,r]of Object.entries(t.props()))e[n]=n in e?{type:this.registry.and([e[n].type,r.type])}:r;return e}get(){let e=this.parts.map(e=>e.get()).filter(e=>!!e);if(e.length!==0)return new eg({key:this.registry.or(e.map(e=>e.key)),value:this.registry.and(e.map(e=>e.value))})}call(){let e=this.parts.map(e=>e.call()).filter(e=>!!e);if(e.length===0)return;let t=e.map(e=>e.returns).filter(e=>!!e);return new tg({args:this.registry.or(e.map(e=>e.args)),returns:t.length>0?this.registry.and(t):void 0})}toJSON(){return{name:e.NAME,options:{types:this.parts.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.parts.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`and<${this.parts.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){return this.parts.length===0?R.unknown():this.parts.length===1?this.parts[0].toA(e):R.intersection(this.parts.map(t=>t.toA(e)))}toNewA(e){return this.parts.length===0?this.describeA(R.unknown(),e):this.parts.length===1?this.describeA(this.parts[0].toNewA(e),e):this.describeA(R.intersection(this.parts.map(t=>t.toNewA(e))),e)}},Ug=new Set,Wg=class e extends U{static NAME=`alias`;name=e.NAME;constructor(e,t,n={}){super(e,t,n)}get hasUse(){return Object.keys(this.generic).length>0||this.options.options!==void 0}applied;static from(t,n){return new e(n,{name:t.name})}resolve(e){let t=(e?e.lookup(this.options.name):void 0)??this.scope.lookup(this.options.name);if(!t||!this.hasUse)return t;this.applied??=new WeakMap;let n=this.applied.get(t);return n||(n=this.registry.applyUse(t,this.generic,this.options.options),this.applied.set(t,n)),n}valid(e,t){let n=this.resolve(t);return!n||n.valid(e,t)}parse(e,t){let n=this.resolve(t);if(!n)return new W(this,e);let r=n.parse(e,t);return new W(this,r.raw)}encode(e,t){let n=this.resolve(t);return n?n.encode(e,t):e}parsesExprValue(e){return this.resolve(e)?.parsesExprValue(e)??!1}encodeAs(e,t,n){let r=this.resolve(n);return r?r.encodeAs(e,t,n):e}create(){let e=this.resolve();return e?e.create():null}random(e){let t=this.resolve();return t?t.random(e):null}compatibleType(e,t,n){let r=this.resolve(n);return!r||r.compatible(e,t,n)}flexible(){return!0}isUniversal(){let e=this.resolve();return!e||e.isUniversal()}or(e){let t=this.resolve();return t?t.or(e):this}simplify(e){return this.resolve(e)??this}narrow(e){return{...this.options,name:e.name??this.options.name}}props(e){let t=this.resolve(e);return t?t.props(e):super.props(e)}get(e){return this.resolve(e)?.get(e)}call(e){return this.resolve(e)?.call(e)}init(e){return this.resolve(e)?.init(e)}follow(e,t){return this.resolve(t)?.follow(e,t)}forEachNewSlot(e,t){return this.resolve()?.forEachNewSlot(e,t)??!1}async newFill(e,t,n){let r=this.resolve();return r?r.newFill(e,t,n):super.newFill(e,t,n)}toJSON(){if(!this.hasUse)return{name:this.options.name};let e=Object.entries(this.generic);return{name:this.options.name,...e.length>0?{generic:Object.fromEntries(e.map(([e,t])=>[e,t.toJSON()]))}:{},...this.options.options===void 0?{}:{options:{...this.options.options}}}}clone(){return new e(this.scope,{...this.options},{...this.generic})}toCode(e,t){return this.docsPrefix(t)+this.options.name+U.renderGenericArgs(this.generic,t)+og(this.options.options)}valueA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(Ug.has(this.options.name))return R.json().describe(`A value of the named type ${this.options.name}.`);Ug.add(this.options.name);try{return t.toA(e)}finally{Ug.delete(this.options.name)}}toNewA(e){let t=this.resolve(e?.scope);if(!t)return R.unknown();if(Ug.has(this.options.name))return R.ref(`Expr`);Ug.add(this.options.name);try{return t.toNewA(e)}finally{Ug.delete(this.options.name)}}},Gg=class e extends U{static NAME=`bool`;name=e.NAME;static optionKeys=[`trueText`,`falseText`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return typeof e==`boolean`}parse(e){if(typeof e==`boolean`)return new W(this,e);if(e===this.options.trueText)return new W(this,!0);if(e===this.options.falseText)return new W(this,!1);throw Error(`bool.parse: expected boolean, got ${typeof e}`)}encode(e){return e}create(){return!1}random(e){return e(0,1,!0)===1}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e?new e(this.registry,{trueText:this.options.trueText??t.options.trueText,falseText:this.options.falseText??t.options.falseText}):this}narrow(e){return{...this.options,...e}}props(){let e=this.registry;return{...super.props(),eq:e.method({other:e.bool()},e.bool(),`bool.eq`),neq:e.method({other:e.bool()},e.bool(),`bool.neq`),and:e.method({other:e.bool()},e.bool(),`bool.and`),or:e.method({other:e.bool()},e.bool(),`bool.or`),xor:e.method({other:e.bool()},e.bool(),`bool.xor`),not:e.method({},e.bool(),`bool.not`),toText:e.method({},e.text(),`bool.toText`),toNum:e.method({},e.num(),`bool.toNum`)}}get(){let e=this.registry;return new eg({key:e.num({whole:!0,min:0}),value:e.bool(),loopDynamic:!0})}toJSON(){return mh({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`bool`+og(this.options)}valueA(){return R.boolean()}describe(e){return typeof e==`boolean`?this:void 0}},Kg=class e extends U{static NAME=`color`;name=e.NAME;static optionKeys=[`hasAlpha`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=4294967295}parse(e){let t=typeof e==`number`?e:Number(e);if(!this.valid(t))throw new th({path:[],code:`color.invalid`,message:`color.parse: not a valid 32-bit color int: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e}create(){return 255}random(e){return e(0,4294967295,!0)}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e?new e(this.registry,{hasAlpha:this.options.hasAlpha===t.options.hasAlpha?this.options.hasAlpha:void 0}):this}narrow(e){return{...this.options,...e}}init(){let e=this.registry,t=e.num({whole:!0,min:0,max:255}),n=e.optional(e.num({min:0,max:1}));return new ng({args:e.obj({r:{type:t},g:{type:t},b:{type:t},a:{type:n}}),run:e.nativeExpr(`color.init`)})}props(){let e=this.registry,t=e.num(),n=e.bool(),r=e.text(),i=e.color();return{...super.props(),r:e.prop(t,`color.r`),g:e.prop(t,`color.g`),b:e.prop(t,`color.b`),a:e.prop(t,`color.a`),hue:e.prop(t,`color.hue`),saturation:e.prop(t,`color.saturation`),lightness:e.prop(t,`color.lightness`),eq:e.method({other:i},n,`color.eq`),neq:e.method({other:i},n,`color.neq`),lighten:e.method({amount:t},i,`color.lighten`),darken:e.method({amount:t},i,`color.darken`),saturate:e.method({amount:t},i,`color.saturate`),desaturate:e.method({amount:t},i,`color.desaturate`),opacity:e.method({alpha:t},i,`color.opacity`),invert:e.method({},i,`color.invert`),mix:e.method({other:i,weight:e.optional(t)},i,`color.mix`),complement:e.method({},i,`color.complement`),toHex:e.method({},r,`color.toHex`),toRgb:e.method({},r,`color.toRgb`),toHsl:e.method({},r,`color.toHsl`),toText:e.method({},r,`color.toText`)}}toJSON(){return mh({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`color`+og(this.options)}valueA(){return R.int().min(0).max(4294967295).describe(this.options.hasAlpha?`A color as a 32-bit integer 0xRRGGBBAA.`:`A color as an integer 0xRRGGBB.`)}},qg=class e extends U{static NAME=`date`;name=e.NAME;static optionKeys=[`min`,`max`,`utc`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}boundDate(e){return e?new Date(e):void 0}valid(e){if(!(e instanceof Date)||Number.isNaN(e.getTime()))return!1;let t=this.boundDate(this.options.min),n=this.boundDate(this.options.max);return!(t&&e<t||n&&e>n)}parse(e){let t=e instanceof Date?e:typeof e==`string`?new Date(e):new Date(NaN);if(!this.valid(t))throw new th({path:[],code:`date.invalid`,message:`date.parse: invalid or out-of-range: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e.toISOString().slice(0,10)}create(){return new Date}random(e){let t=this.boundDate(this.options.min)?.getTime()??Date.UTC(2e3,0,1),n=this.boundDate(this.options.max)?.getTime()??Date.UTC(2050,11,31);return new Date(e(t,n,!0))}compatibleType(t,n){return t instanceof e}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{min:n.min&&r.min?n.min<r.min?n.min:r.min:void 0,max:n.max&&r.max?n.max>r.max?n.max:r.max:void 0,utc:n.utc===r.utc?n.utc:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new th({path:[],code:e,message:t,severity:`error`})},r={...t};return e.min!==void 0&&(t.min&&e.min<t.min&&n(`date.widen.min`,`cannot move min earlier`),r.min=e.min),e.max!==void 0&&(t.max&&e.max>t.max&&n(`date.widen.max`,`cannot move max later`),r.max=e.max),e.utc!==void 0&&(r.utc=e.utc),r}props(){let e=this.registry,t=e.num({whole:!0}),n=e.bool(),r=e.text(),i=e.date();return{...super.props(),year:e.prop(t,`date.year`),month:e.prop(t,`date.month`),day:e.prop(t,`date.day`),dayOfWeek:e.prop(t,`date.dayOfWeek`),dayOfYear:e.prop(t,`date.dayOfYear`),eq:e.method({other:i},n,`date.eq`),neq:e.method({other:i},n,`date.neq`),before:e.method({other:i},n,`date.before`),after:e.method({other:i},n,`date.after`),addDays:e.method({days:t},i,`date.addDays`),addMonths:e.method({months:t},i,`date.addMonths`),addYears:e.method({years:t},i,`date.addYears`),diffDays:e.method({other:i},t,`date.diffDays`),diffMonths:e.method({other:i},t,`date.diffMonths`),diffYears:e.method({other:i},t,`date.diffYears`),toText:e.method({format:e.optional(r)},r,`date.toText`)}}toJSON(){return mh({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`date`+og(this.options)}valueA(){return R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}`).describe(`An ISO 8601 date (YYYY-MM-DD).`)}describe(e){return e instanceof Date?this:void 0}},Jg=class e extends U{static NAME=`duration`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return typeof e==`number`&&!Number.isNaN(e)}parse(e){let t=typeof e==`number`?e:Number(e);return new W(this,t)}encode(e){return e}create(){return 0}random(e){return e(0,864e5,!0)}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){return{}}init(){let e=this.registry,t=e.num();return new ng({args:e.obj({days:{type:e.optional(t)},hours:{type:e.optional(t)},minutes:{type:e.optional(t)},seconds:{type:e.optional(t)},ms:{type:e.optional(t)}}),run:e.nativeExpr(`duration.init`)})}props(){let e=this.registry,t=e.num({whole:!0}),n=e.text();return{...super.props(),totalSeconds:e.prop(e.num(),`duration.totalSeconds`),totalMinutes:e.prop(e.num(),`duration.totalMinutes`),totalHours:e.prop(e.num(),`duration.totalHours`),totalDays:e.prop(e.num(),`duration.totalDays`),days:e.prop(t,`duration.days`),hours:e.prop(t,`duration.hours`),minutes:e.prop(t,`duration.minutes`),seconds:e.prop(t,`duration.seconds`),ms:e.prop(t,`duration.ms`),toText:e.method({format:e.optional(n)},n,`duration.toText`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`duration`}valueA(){return R.number().describe(`A duration in milliseconds.`)}},Yg=class e extends U{static NAME=`enum`;name=e.NAME;static optionKeys=[`values`];static genericKeys=[`V`];static from(t,n){let r=n.registry,i=t.generic?.V?n.parse(t.generic.V):r.text(),a=t.options?.values??{};return new e(n,i,{values:a})}constructor(e,t,n){super(e,n,{V:t})}get value(){return this.generic.V}valid(e,t){return this.value.valid(e,t)?Object.values(this.options.values).some(t=>t===e):!1}parse(e,t){let n=this.value.parse(e,t);if(!this.valid(n.raw,t))throw new th({path:[],code:`enum.not-a-member`,message:`enum.parse: ${String(n.raw)} is not one of ${Object.values(this.options.values).join(`, `)}`,severity:`error`});return new W(this,n.raw)}encode(e,t){return this.value.encode(e,t)}encodeAs(e,t,n){return this.value.encodeAs(e,t,n)}create(){let e=Object.values(this.options.values)[0];return e===void 0?this.value.create():e}random(e){let t=Object.values(this.options.values);return t.length===0?this.value.random(e):t[e(0,t.length-1,!0)]}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.value);return n.name===`null`?this.registry.null():this.registry.enum(t.options.values,n)}compatibleType(t,n,r){return!(t instanceof e)||!this.value.compatible(t.value,n,r)?!1:!n?.value||Object.values(t.options.values).every(e=>Object.values(this.options.values).some(t=>t===e))}or(t){return t instanceof e?new e(this.registry,this.value.or(t.value),{values:{...t.options.values,...this.options.values}}):this}narrow(e){let t=this.options.values;if(e.values===void 0)return this.options;for(let[n,r]of Object.entries(e.values))if(!Object.values(t).some(e=>e===r))throw new th({path:[],code:`enum.widen`,message:`enum.narrow: ${n}=${String(r)} not in base values`,severity:`error`});return{values:e.values}}props(){let e=this.registry,t=this.value;return{...super.props(),name:e.prop(e.text(),`enum.name`),value:e.prop(t,`enum.value`),eq:e.method({other:t},e.bool(),`enum.eq`),neq:e.method({other:t},e.bool(),`enum.neq`),toText:e.method({},e.text(),`enum.toText`)}}toJSON(){return{name:e.NAME,generic:{V:this.value.toJSON()},options:{values:this.options.values}}}clone(){return new e(this.registry,this.value.clone(),{values:{...this.options.values}})}toCode(e,t){let n=`enum<${this.value.toCode(void 0,t)}>`+Zg(this.options.values,t);return this.docsPrefix(t)+n}valueA(){let e=Object.values(this.options.values);return e.length>0&&e.every(e=>typeof e==`string`)?R.enum(e):R.union(e.map(e=>R.literal(e)))}},Xg=/^[A-Za-z_$][A-Za-z0-9_$]*$/;function Zg(e,t){let n=Object.entries(e);return n.length===0?``:`{${cg(n.map(([e,t])=>{let n=Xg.test(e)?e:JSON.stringify(e);return t===e?n:`${n}=${typeof t==`number`||typeof t==`boolean`?String(t):JSON.stringify(t??null)}`}),{indent:lg(t)})}}`}var Qg=class e extends U{static NAME=`fn`;static consumes=[`call`];name=e.NAME;static optionKeys=[];static declaresGenerics=!0;_call;static from(t,n){let r=n.registry,i={},a=new bh(n);if(t.generic)for(let[e,n]of Object.entries(t.generic))i[e]=a.parse(n);return t.call?new e(a,tg.from(t.call,a),i):new e(a,new tg({args:r.any(),returns:r.any()}),i)}constructor(e,t,n={}){super(e,{},n),this._call=t instanceof tg?t:new tg(t)}parsesExprValue(e){return!0}valid(e,t){return!!(typeof e==`function`||typeof e==`string`||e&&typeof e==`object`&&`kind`in e)}parse(e,t){return typeof e==`string`||e&&typeof e==`object`&&`kind`in e||typeof e==`function`?new W(this,e):new W(this,null)}encode(e,t){return typeof e==`function`?null:e}create(){return{kind:`new`,type:(this._call.returns??this.registry.void()).toJSON()}}random(e){return this.create()}like(t){if(!(t instanceof e))return this;let n=this.registry,r=n.like(t._call.args);if(r.name===`null`)return n.null();let i=t._call.returns?n.like(t._call.returns):void 0;if(i&&i.name===`null`)return n.null();let a=t._call.throws?n.like(t._call.throws):void 0;return a&&a.name===`null`?n.null():n.fn({args:r,returns:i,throws:a,generic:this.generic})}compatibleType(t,n,r){return!(!(t instanceof e)||!this._call.args.compatible(t._call.args,n,r)||this._call.returns&&t._call.returns&&!this._call.returns.compatible(t._call.returns,n,r))}or(t){return t instanceof e?new e(this.registry,{args:this._call.args.or(t._call.args),returns:this._call.returns&&t._call.returns?this._call.returns.or(t._call.returns):this._call.returns??t._call.returns,throws:this._call.throws&&t._call.throws?this._call.throws.or(t._call.throws):this._call.throws??t._call.throws}):this}narrow(e){return{}}call(e){return this._call}props(e){return super.props(e)}toJSON(){let t=Object.keys(this.generic),n=t.length===0?void 0:Object.fromEntries(t.map(e=>[e,this.generic[e].toJSON()]));return mh({name:e.NAME,call:this._call.toJSON(),generic:n})}clone(){let t={};for(let[e,n]of Object.entries(this.generic))t[e]=n.clone();return new e(this.registry,{args:this._call.args.clone(),returns:this._call.returns?.clone(),throws:this._call.throws?.clone(),get:this._call.get,set:this._call.set},t)}toCode(e,t){let n=this._call.returns?.toCode(void 0,t)??`void`;return this.docsPrefix(t)+`${U.renderGenerics(this.generic,t)}${this._call.renderTypes(t)}(${U.formatParams(this._call.args,t)}): ${n}`}valueA(){return R.union([R.string(),R.ref(`Expr`)])}},$g=class e extends U{static NAME=`interface`;static consumes=[`props`,`get`,`call`];name=e.NAME;static optionKeys=[];static genericKeys=[];_props;_get;_call;static from(t,n){return n.registry,new e(n,{props:t.props?$h.fromMap(t.props,n):{},get:t.get?eg.from(t.get,n):void 0,call:t.call?tg.from(t.call,n):void 0})}constructor(e,t){super(e,{});let n={};if(t.props)for(let[e,r]of Object.entries(t.props))n[e]=$h.from(r);this._props=n,this._get=t.get,this._call=t.call}valid(e,t){return!0}parse(e,t){return new W(this,e)}encode(e,t){return e}create(){return null}random(e){return null}like(t){if(!(t instanceof e))return this;let n=this.registry,r={};for(let[e,i]of Object.entries(t._props)){let t=n.like(i.type);if(t.name===`null`)return n.null();r[e]={type:t}}let i;if(t._get){let e=n.like(t._get.key),r=n.like(t._get.value);if(e.name===`null`||r.name===`null`)return n.null();i=new eg({key:e,value:r})}let a;if(t._call){let e=n.like(t._call.args);if(e.name===`null`)return n.null();let r=t._call.returns?n.like(t._call.returns):void 0;if(r&&r.name===`null`)return n.null();a=new tg({args:e,returns:r})}return new e(n,{props:r,get:i,call:a})}compatibleType(e,t,n){let r=e.props(n);for(let[e,i]of Object.entries(this._props)){let a=r[e];if(!a||!i.type.compatible(a.type,t,n))return!1}if(this._get){let r=e.get(n);if(!r||!this._get.key.compatible(r.key,t,n)||!this._get.value.compatible(r.value,t,n))return!1}if(this._call){let r=e.call(n);if(!r||!this._call.args.compatible(r.args,t,n)||this._call.returns&&r.returns&&!this._call.returns.compatible(r.returns,t,n))return!1}return!0}flexible(){return!0}isUniversal(){return Object.keys(this._props).length===0&&!this._get&&!this._call}or(t){if(!(t instanceof e))return this;let n={};for(let e of Object.keys(this._props))e in t._props&&(n[e]={type:this._props[e].type.or(t._props[e].type)});return new e(this.registry,{props:n})}narrow(e){return{}}props(e){return{...super.props(e),...this._props}}get(e){return this._get}call(e){return this._call}toJSON(){return mh({name:e.NAME,props:Object.keys(this._props).length>0?$h.toJSONMap(this._props):void 0,get:this._get?.toJSON(),call:this._call?.toJSON()})}clone(){let t={};for(let[e,n]of Object.entries(this._props))t[e]={...n,type:n.type.clone()};return new e(this.registry,{props:t,get:this._get,call:this._call})}toCode(e,t){let n=t?.includeComments!==!1,r=[];for(let[e,i]of Object.entries(this._props)){let a=i.type.isOptional(),o=a?i.type.required():i.type,s=a?`${e}?`:e,c=i.docs&&n?`/* ${i.docs} */ `:``;r.push(`${c}${s}: ${o.toCode(void 0,t)}`)}if(this._get&&r.push(`[key: ${this._get.key.toCode(void 0,t)}]: ${this._get.value.toCode(void 0,t)}`),this._call){let e=this._call.returns?.toCode(void 0,t)??`void`;r.push(`(${this._call.args.toCode(void 0,t)}): ${e}`)}let i=r.length===0?`iface`:`iface{${cg(r,{indent:lg(t)})}}`;return this.docsPrefix(t)+i}toCodeRef(e,t){return this.docsPrefix(t)+`iface`}refProps(){return this._props}refGet(){return this._get}refCall(){return this._call}valueA(e){let t=e?.includeDocs??`none`,n={};for(let[r,i]of Object.entries(this._props)){let a=i.type.toA(e);t===`all`&&i.docs&&(a=a.describe(i.docs)),n[r]=a}return this.objectA(n,e)}toNewA(e){let t=e?.includeDocs??`none`,n={};for(let[e,r]of Object.entries(this._props)){let i=R.ref(`Expr`);t===`all`&&r.docs&&(i=i.describe(r.docs)),n[e]=i}return this.describeA(R.object(n),e)}},e_=class e extends U{static NAME=`literal`;name=e.NAME;static optionKeys=[`value`];static genericKeys=[`T`];inner;static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any(),a=t.options?.value;return new e(n,i,a)}constructor(e,t,n){super(e,{value:n},{T:t}),this.inner=t}get literal(){return this.options.value}valid(e,t){return this.inner.valid(e,t)&&e===this.literal}parse(e,t){let n=this.inner.parse(e,t);if(n.raw!==this.literal)throw new th({path:[],code:`literal.not-match`,message:`literal: expected ${String(this.literal)}, got ${String(n.raw)}`,severity:`error`});return new W(this,n.raw)}encode(e,t){return this.inner.encode(e,t)}encodeAs(e,t,n){return this.inner.encodeAs(e,t,n)}create(){return this.literal}random(e){return this.literal}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r)&&this.literal===t.literal:!n?.exact&&this.inner.compatible(t,n,r)}isUniversal(){return this.inner.isUniversal()}or(t){return t instanceof e&&(t.literal,this.literal),this}narrow(e){if(e.value!==void 0&&e.value!==this.literal)throw new th({path:[],code:`literal.narrow`,message:`literal value cannot change via narrow`,severity:`error`});return this.options}props(){return this.inner.props()}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()},options:{value:this.literal}}}clone(){return new e(this.registry,this.inner.clone(),this.literal)}toCode(e,t){return this.docsPrefix(t)+`literal<${this.inner.toCode(void 0,t)}>`+og({value:this.literal})}valueA(){return R.literal(this.literal)}},t_=class e extends U{static NAME=`list`;name=e.NAME;static optionKeys=[`minLength`,`maxLength`];static genericKeys=[`V`];static from(t,n){let r=n.registry,i=t.generic?.V?n.parse(t.generic.V):r.any();return new e(n,i,t.options??{})}constructor(e,t,n={}){super(e,n,{V:t})}get item(){return this.generic.V}valid(e,t){if(!Array.isArray(e))return!1;let{minLength:n,maxLength:r}=this.options;return n!==void 0&&e.length<n||r!==void 0&&e.length>r?!1:e.every(e=>e instanceof W&&e.type.valid(e.raw,t)&&Wh(this.item,e.type,t))}parse(e,t){if(!Array.isArray(e))throw new th({path:[],code:`list.invalid`,message:`list.parse: expected array, got ${typeof e}`,severity:`error`});let n=e.map(e=>this.registry.parseValue(e,this.item,t));if(!this.valid(n,t))throw new th({path:[],code:`list.constraint`,message:`list.parse: length constraints violated`,severity:`error`});return new W(this,n)}encode(e,t){return this.encodeAs(e,Xh,t)}encodeAs(e,t,n){return e.map(e=>Jh(e,t,n))}create(){let e=this.options.minLength??0;return Array.from({length:e},()=>new W(this.item,this.item.create()))}random(e){let t=this.options.minLength??0,n=e(t,this.options.maxLength??Math.max(t,5),!0);return Array.from({length:n},()=>new W(this.item,this.item.random(e)))}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<e.length;n++)t.slot(this.item,e[n],n);return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i of e)r.push(await this.item.newFill(i,t,n));return r}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.item);return n.name===`null`?n:this.registry.list(n)}compatibleType(t,n,r){if(!(t instanceof e)||!this.item.compatible(t.item,n,r))return!1;if(!n?.value)return!0;let i=this.options,a=t.options;return!(i.minLength!==void 0&&(a.minLength===void 0||a.minLength<i.minLength)||i.maxLength!==void 0&&(a.maxLength===void 0||a.maxLength>i.maxLength))}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,this.item.or(t.item),{minLength:n.minLength!==void 0&&r.minLength!==void 0?Math.min(n.minLength,r.minLength):void 0,maxLength:n.maxLength!==void 0&&r.maxLength!==void 0?Math.max(n.maxLength,r.maxLength):void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new th({path:[],code:e,message:t,severity:`error`})},r={...t};return e.minLength!==void 0&&(t.minLength!==void 0&&e.minLength<t.minLength&&n(`list.widen.minLength`,`local ${e.minLength} < base ${t.minLength}`),r.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength!==void 0&&e.maxLength>t.maxLength&&n(`list.widen.maxLength`,`local ${e.maxLength} > base ${t.maxLength}`),r.maxLength=e.maxLength),r}get(){let e=this.registry;return new eg({key:e.num({whole:!0,min:0}),value:this.item,get:e.nativeExpr(`list.indexGet`),set:e.nativeExpr(`list.indexSet`),loop:e.nativeExpr(`list.iterate`)})}props(){let e=this.registry,t=this.item,n=e.num(),r=e.bool(),i=e.text(),a=e.void(),o=e.optional(t),s=e.list(t),c=r=>e.fn({args:e.obj({value:{type:t},index:{type:n}}),returns:r});return{...super.props(),length:e.prop(n,`list.length`),at:e.method({index:n},o,`list.at`),push:e.method({value:t},a,`list.push`),pop:e.method({},o,`list.pop`),shift:e.method({},o,`list.shift`),unshift:e.method({value:t},a,`list.unshift`),insert:e.method({index:n,value:t},a,`list.insert`),remove:e.method({index:n},t,`list.remove`),clear:e.method({},a,`list.clear`),slice:e.method({start:e.optional(n),end:e.optional(n)},s,`list.slice`),concat:e.method({other:s},s,`list.concat`),reverse:e.method({},s,`list.reverse`),join:e.method({separator:e.optional(i)},i,`list.join`),indexOf:e.method({value:t},n,`list.indexOf`),contains:e.method({value:t},r,`list.contains`),unique:e.method({},s,`list.unique`),duplicates:e.method({},s,`list.duplicates`),map:e.method({fn:c(e.alias(`R`))},e.list(e.alias(`R`)),`list.map`,{generic:{R:e.any()}}),filter:e.method({fn:c(r)},s,`list.filter`),find:e.method({fn:c(r)},o,`list.find`),reduce:e.method({fn:e.fn({args:e.obj({acc:{type:e.alias(`R`)},value:{type:t},index:{type:n}}),returns:e.alias(`R`)}),initial:e.alias(`R`)},e.alias(`R`),`list.reduce`,{generic:{R:e.any()}}),some:e.method({fn:c(r)},r,`list.some`),every:e.method({fn:c(r)},r,`list.every`),sort:e.method({fn:e.optional(e.fn({args:e.obj({a:{type:t},b:{type:t}}),returns:n}))},s,`list.sort`),isEmpty:e.method({},r,`list.isEmpty`),isNotEmpty:e.method({},r,`list.isNotEmpty`),first:e.prop(o,`list.first`),last:e.prop(o,`list.last`)}}toJSON(){return mh({name:e.NAME,generic:{V:this.item.toJSON()},options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,this.item.clone(),{...this.options})}toCode(e,t){return this.docsPrefix(t)+`list<${this.item.toCode(void 0,t)}>`+og(this.options,{minLength:0})}valueA(e){let t=R.array(this.item.toA(e));return this.options.minLength!==void 0&&(t=t.min(this.options.minLength)),this.options.maxLength!==void 0&&(t=t.max(this.options.maxLength)),t}toNewA(e){let t=R.array(R.ref(`Expr`));return this.options.minLength!==void 0&&(t=t.min(this.options.minLength)),this.options.maxLength!==void 0&&(t=t.max(this.options.maxLength)),this.describeA(t,e)}describe(t){if(Array.isArray(t))return new e(this.registry,this.registry.any(),{})}};function n_(e){return Array.isArray(e)&&e.length===2&&e[0]instanceof W&&e[1]instanceof W}function r_(e){if(Array.isArray(e))return[e[0],e[1]];let t=e;return[t?.key,t?.value]}function i_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var a_=class e extends U{static NAME=`map`;name=e.NAME;static optionKeys=[];static genericKeys=[`K`,`V`];static from(t,n){let r=n.registry,i=t.generic?.K?n.parse(t.generic.K):r.text(),a=t.generic?.V?n.parse(t.generic.V):r.any();return new e(n,i,a)}constructor(e,t,n){super(e,{},{K:t,V:n})}get key(){return this.generic.K}get value(){return this.generic.V}valid(e,t){if(!(e instanceof Map))return!1;for(let[,n]of e){if(!Array.isArray(n)||n.length!==2)return!1;let[e,r]=n;if(!(e instanceof W)||!(r instanceof W)||!e.type.valid(e.raw,t)||!r.type.valid(r.raw,t)||!Wh(this.key,e.type,t)||!Wh(this.value,r.type,t))return!1}return!0}parse(e,t){let n=e instanceof Map?Array.from(e,([e,t])=>n_(t)?t:[e,t]):this.textKeyed()&&i_(e)?Object.entries(e):e;if(!Array.isArray(n))throw new th({path:[],code:`map.invalid`,message:`map.parse: expected array of [key, value] pairs`,severity:`error`});let r=new Map;for(let e of n){let[n,i]=Array.isArray(e)?e:[e.key,e.value],a=this.registry.parseValue(n,this.key,t),o=this.registry.parseValue(i,this.value,t);r.set(a.raw,[a,o])}return new W(this,r)}encode(e,t){return this.encodeAs(e,Xh,t)}encodeAs(e,t,n){return t.form===`logical`&&this.textKeyed()?Object.fromEntries(Array.from(e,([,[e,r]])=>[String(Jh(e,t,n)),Jh(r,t,n)])):Array.from(e,([,[e,r]])=>({key:Jh(e,t,n),value:Jh(r,t,n)}))}textKeyed(){return this.key.name===`text`}create(){return new Map}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<e.length;n++){let[r,i]=r_(e[n]);t.slot(this.key,r,`${n}.key`),t.slot(this.value,i,`${n}.value`)}return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i of e){let[e,a]=r_(i);r.push({key:await this.key.newFill(e,t,n),value:await this.value.newFill(a,t,n)})}return r}random(e){let t=e(0,5,!0),n=new Map;for(let r=0;r<t;r++){let t=this.key.random(e),r=this.value.random(e);n.set(t,[new W(this.key,t),new W(this.value,r)])}return n}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.key),r=this.registry.like(t.value);return n.name===`null`||r.name===`null`?this.registry.null():this.registry.map(n,r)}compatibleType(t,n,r){return t instanceof e&&this.key.compatible(t.key,n,r)&&this.value.compatible(t.value,n,r)}or(t){return t instanceof e?new e(this.registry,this.key.or(t.key),this.value.or(t.value)):this}narrow(e){return{}}get(){let e=this.registry;return new eg({key:this.key,value:this.value,get:e.nativeExpr(`map.indexGet`),set:e.nativeExpr(`map.indexSet`),loop:e.nativeExpr(`map.iterate`)})}props(){let e=this.registry,t=this.key,n=this.value,r=e.num(),i=e.bool(),a=e.void(),o=e.optional(n);return{...super.props(),size:e.prop(r,`map.size`),at:e.method({key:t},o,`map.at`),has:e.method({key:t},i,`map.has`),delete:e.method({key:t},i,`map.delete`),clear:e.method({},a,`map.clear`),keys:e.method({},e.list(t),`map.keys`),values:e.method({},e.list(n),`map.values`),isEmpty:e.method({},i,`map.isEmpty`),isNotEmpty:e.method({},i,`map.isNotEmpty`)}}toJSON(){return{name:e.NAME,generic:{K:this.key.toJSON(),V:this.value.toJSON()}}}clone(){return new e(this.registry,this.key.clone(),this.value.clone())}toCode(e,t){return this.docsPrefix(t)+`map<${this.key.toCode(void 0,t)}, ${this.value.toCode(void 0,t)}>`}valueA(e){return this.key.name===`text`?R.record(this.value.toA(e)):R.array(this.objectA({key:this.key.toA(e),value:this.value.toA(e)},e))}toNewA(e){return this.describeA(R.array(R.object({key:R.ref(`Expr`),value:R.ref(`Expr`)})),e)}describe(t){return t instanceof Map?new e(this.registry,this.registry.any(),this.registry.any()):void 0}},o_=class e extends U{constructor(e,t){super(e,{excluded:t.toJSON()}),this.excluded=t}excluded;static NAME=`not`;name=e.NAME;static optionKeys=[`excluded`];static genericKeys=[];static from(t,n){let r=n.registry,i=t.options?.excluded?n.parse(t.options.excluded):r.any();return new e(n,i)}valid(e,t){return!this.excluded.valid(e,t)}parse(e,t){if(this.excluded.valid(e,t))throw new th({path:[],code:`not.excluded`,message:`not: value matches excluded type ${this.excluded.name}`,severity:`error`});return new W(this,e)}encode(e,t){return e}create(){return null}random(e){return null}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.excluded);return n.name===`null`?n:this.registry.not(n)}compatibleType(t,n,r){return n?.exact?t instanceof e&&this.excluded.exact(t.excluded,r):!this.excluded.compatible(t,n,r)}flexible(){return!0}or(t){return t instanceof e?new e(this.registry,this.registry.or([this.excluded,t.excluded])):this}narrow(e){return{excluded:e.excluded??this.options.excluded}}props(){let e=this.registry;return{...super.props(),typeOf:e.method({},e.text(),`not.typeOf`),toText:e.method({},e.text(),`not.toText`)}}toJSON(){return{name:e.NAME,options:{excluded:this.excluded.toJSON()}}}clone(){return new e(this.registry,this.excluded.clone())}toCode(e,t){return this.docsPrefix(t)+`not<${this.excluded.toCode(void 0,t)}>`}valueA(e){return R.not(this.excluded.toA(e))}},s_=class e extends U{static NAME=`null`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return e===null}parse(e){if(e!==null)throw new th({path:[],code:`null.invalid`,message:`null expects null, got ${typeof e}`,severity:`error`});return new W(this,null)}encode(e){return null}create(){return null}random(e){return null}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new th({path:[],code:`null.no-options`,message:`null has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),toText:e.method({},e.text(),`null.toText`),toBool:e.method({},e.bool(),`null.toBool`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`null`}valueA(){return R.null()}},c_=class e extends U{constructor(e,t){super(e,{},{T:t}),this.inner=t}inner;static NAME=`nullable`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e===null||this.inner.valid(e,t)}parse(e,t){if(e===null)return new W(this,null);let n=this.inner.parse(e,t);return new W(this,n.raw)}parsesExprValue(e){return this.inner.parsesExprValue(e)}encode(e,t){return this.encodeAs(e,Xh,t)}encodeAs(e,t,n){return e===null?null:this.inner.encodeAs(e,t,n)}forEachNewSlot(e,t){return e!=null&&this.inner.forEachNewSlot(e,t)}async newFill(e,t,n){return e==null?e:this.inner.newFill(e,t,n)}create(){return null}random(e){return e(0,9,!0)<3?null:this.inner.random(e)}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.inner);return n.name===`null`?n:this.registry.nullable(n)}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r):!n?.exact&&this.inner.compatible(t,n,r)}or(t){return t instanceof e?new e(this.registry,this.inner.or(t.inner)):this}required(){return this.inner}isUniversal(){return this.inner.isUniversal()}narrow(e){if(e&&Object.keys(e).length>0)throw new th({path:[],code:`nullable.no-options`,message:`nullable has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry,t=this.inner;return{...super.props(),value:e.prop(t,`nullable.value`),isNull:e.method({},e.bool(),`nullable.isNull`),or:e.method({fallback:t},t,`nullable.or`),map:e.method({fn:e.fn({args:e.obj({value:{type:t}}),returns:e.alias(`R`)})},e.nullable(e.alias(`R`)),`nullable.map`,{generic:{R:e.any()}})}}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()}}}clone(){return new e(this.registry,this.inner.clone())}toCode(e,t){return this.docsPrefix(t)+`nullable<${this.inner.toCode(void 0,t)}>`}valueA(e){return R.nullable(this.inner.toA(e))}toNewA(e){return this.describeA(R.nullable(this.inner.toNewA(e)),e)}},l_=class e extends U{static NAME=`num`;name=e.NAME;static optionKeys=[`min`,`max`,`whole`,`minPrecision`,`maxPrecision`,`prefix`,`suffix`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){if(typeof e!=`number`||Number.isNaN(e))return!1;let{min:t,max:n,whole:r}=this.options;return!(t!==void 0&&e<t||n!==void 0&&e>n||r&&!Number.isInteger(e))}parse(e){let t=typeof e==`string`?Number(e):e;if(typeof t!=`number`||Number.isNaN(t))throw new th({path:[],code:`num.invalid`,message:`num.parse: not a number \u2014 ${String(e)}`,severity:`error`});if(!this.valid(t))throw new th({path:[],code:`num.out-of-range`,message:`num.parse: ${t} violates options ${JSON.stringify(this.options)}`,severity:`error`});return new W(this,t)}encode(e){return e}create(){let{min:e,max:t,whole:n}=this.options,r=0;if(e!==void 0&&r<e&&(r=e),t!==void 0&&r>t&&(r=t),n&&!Number.isInteger(r)){let e=Math.ceil(r);r=t!==void 0&&e>t?Math.floor(r):e}return r}random(e){return e(this.options.min??0,this.options.max??100,this.options.whole??!1)}compatibleType(t,n){if(!(t instanceof e))return!1;if(!n?.value)return!0;let r=this.options,i=t.options;return!(r.min!==void 0&&(i.min===void 0||i.min<r.min)||r.max!==void 0&&(i.max===void 0||i.max>r.max)||r.whole&&!i.whole)}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{min:n.min!==void 0&&r.min!==void 0?Math.min(n.min,r.min):void 0,max:n.max!==void 0&&r.max!==void 0?Math.max(n.max,r.max):void 0,whole:n.whole&&r.whole,minPrecision:n.minPrecision!==void 0&&r.minPrecision!==void 0?Math.min(n.minPrecision,r.minPrecision):void 0,maxPrecision:n.maxPrecision!==void 0&&r.maxPrecision!==void 0?Math.max(n.maxPrecision,r.maxPrecision):void 0,prefix:n.prefix===r.prefix?n.prefix:void 0,suffix:n.suffix===r.suffix?n.suffix:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new th({path:[],code:e,message:t,severity:`error`})},r={...t};return e.min!==void 0&&(t.min!==void 0&&e.min<t.min&&n(`num.widen.min`,`local.min ${e.min} < base.min ${t.min}`),r.min=e.min),e.max!==void 0&&(t.max!==void 0&&e.max>t.max&&n(`num.widen.max`,`local.max ${e.max} > base.max ${t.max}`),r.max=e.max),e.whole!==void 0&&(t.whole===!0&&!e.whole&&n(`num.widen.whole`,`base requires whole; local cannot remove`),r.whole=e.whole),e.minPrecision!==void 0&&(t.minPrecision!==void 0&&e.minPrecision<t.minPrecision&&n(`num.widen.minPrecision`,`minPrecision cannot decrease`),r.minPrecision=e.minPrecision),e.maxPrecision!==void 0&&(t.maxPrecision!==void 0&&e.maxPrecision>t.maxPrecision&&n(`num.widen.maxPrecision`,`maxPrecision cannot increase`),r.maxPrecision=e.maxPrecision),e.prefix!==void 0&&(r.prefix=e.prefix),e.suffix!==void 0&&(r.suffix=e.suffix),r}get(){let e=this.registry;return new eg({key:e.num({whole:!0,min:0}),value:e.num(),loop:e.nativeExpr(`num.loop`)})}props(){let e=this.registry,t=e.num(),n=e.bool(),r=e.text(),i=e.optional(t);return{...super.props(),eq:e.method({other:t,epsilon:i},n,`num.eq`),neq:e.method({other:t,epsilon:i},n,`num.neq`),lt:e.method({other:t},n,`num.lt`),lte:e.method({other:t},n,`num.lte`),gt:e.method({other:t},n,`num.gt`),gte:e.method({other:t},n,`num.gte`),add:e.method({other:t},t,`num.add`),sub:e.method({other:t},t,`num.sub`),mul:e.method({other:t},t,`num.mul`),div:e.method({other:t},t,`num.div`),mod:e.method({other:t},t,`num.mod`),pow:e.method({other:t},t,`num.pow`),abs:e.method({},t,`num.abs`),neg:e.method({},t,`num.neg`),sign:e.method({},t,`num.sign`),sqrt:e.method({},t,`num.sqrt`),min:e.method({other:t},t,`num.min`),max:e.method({other:t},t,`num.max`),clamp:e.method({min:t,max:t},t,`num.clamp`),floor:e.method({},t,`num.floor`),ceil:e.method({},t,`num.ceil`),round:e.method({},t,`num.round`),isZero:e.method({},n,`num.isZero`),isPositive:e.method({},n,`num.isPositive`),isNegative:e.method({},n,`num.isNegative`),isInteger:e.method({},n,`num.isInteger`),isEven:e.method({},n,`num.isEven`),isOdd:e.method({},n,`num.isOdd`),toText:e.method({precision:i},r,`num.toText`),toBool:e.method({},n,`num.toBool`)}}toJSON(){return mh({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`num`+og(this.options,{minPrecision:1,maxPrecision:7,prefix:``,suffix:``})}valueA(){let e=this.options.whole?R.int():R.number();return this.options.min!==void 0&&(e=e.min(this.options.min)),this.options.max!==void 0&&(e=e.max(this.options.max)),e}describe(t){if(!(typeof t!=`number`||Number.isNaN(t)))return new e(this.registry,{whole:Number.isInteger(t)})}},u_=class e extends U{constructor(e,t){super(e,{},{T:t}),this.inner=t}inner;static NAME=`optional`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e===void 0||this.inner.valid(e,t)}parse(e,t){if(e==null)return new W(this,void 0);let n=this.inner.parse(e,t);return new W(this,n.raw)}parsesExprValue(e){return this.inner.parsesExprValue(e)}encode(e,t){return this.encodeAs(e,Xh,t)}encodeAs(e,t,n){return e===void 0?null:this.inner.encodeAs(e,t,n)}forEachNewSlot(e,t){return e!=null&&this.inner.forEachNewSlot(e,t)}async newFill(e,t,n){return e==null?e:this.inner.newFill(e,t,n)}create(){}random(e){if(!(e(0,9,!0)<3))return this.inner.random(e)}like(t){if(!(t instanceof e))return this;let n=this.registry.like(t.inner);return n.name===`null`?n:this.registry.optional(n)}compatibleType(t,n,r){return t instanceof e?this.inner.compatible(t.inner,n,r):!n?.exact&&this.inner.compatible(t,n,r)}or(t){return t instanceof e?new e(this.registry,this.inner.or(t.inner)):this}required(){return this.inner}isOptional(){return!0}isUniversal(){return this.inner.isUniversal()}narrow(e){if(e&&Object.keys(e).length>0)throw new th({path:[],code:`optional.no-options`,message:`optional has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry,t=this.inner;return{...super.props(),value:e.prop(t,`optional.value`),has:e.method({},e.bool(),`optional.has`),or:e.method({fallback:t},t,`optional.or`),map:e.method({fn:e.fn({args:e.obj({value:{type:t}}),returns:e.alias(`R`)})},e.optional(e.alias(`R`)),`optional.map`,{generic:{R:e.any()}})}}toJSON(){return{name:e.NAME,generic:{T:this.inner.toJSON()}}}clone(){return new e(this.registry,this.inner.clone())}toCode(e,t){return this.docsPrefix(t)+`optional<${this.inner.toCode(void 0,t)}>`}valueA(e){return R.optional(this.inner.toA(e))}toNewA(e){return this.describeA(R.optional(this.inner.toNewA(e)),e)}},d_=class e extends U{static NAME=`or`;name=e.NAME;static optionKeys=[`types`];static genericKeys=[];static from(t,n){n.registry;let r=(t.options?.types??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,{variants:t})}get variants(){return this.options.variants}valid(e,t){return this.variants.some(n=>n.valid(e,t))}parse(e,t){for(let n of this.variants)try{let r=n.parse(e,t);return new W(this,r.raw)}catch{continue}throw new th({path:[],code:`or.no-match`,message:`or: no variant matched (${this.variants.map(e=>e.name).join(` | `)})`,severity:`error`})}encode(e,t){let n=this.variants.find(n=>n.valid(e,t));if(!n)throw new th({path:[],code:`or.dump.no-match`,message:`or.dump: value does not satisfy any variant`,severity:`error`});return n.encode(e,t)}parsesExprValue(e){return this.variants.some(t=>t.parsesExprValue(e))}encodeAs(e,t,n){let r=this.variants.find(t=>t.valid(e,n));if(!r)throw new th({path:[],code:`or.dump.no-match`,message:`or.dump: value does not satisfy any variant`,severity:`error`});return r.encodeAs(e,t,n)}create(){return this.variants[0]?.create()??null}random(e){let t=e(0,this.variants.length-1,!0);return this.variants[t]?.random(e)??null}like(t){if(!(t instanceof e))return this;let n=t.variants.map(e=>this.registry.like(e)).filter(e=>e.name!==`null`);return n.length===0?this.registry.null():n.length===1?n[0]:this.registry.or(n)}compatibleType(e,t,n){return this.variants.some(r=>r.compatible(e,t,n))}or(t){return t instanceof e?new e(this.registry,[...this.variants,...t.variants]):new e(this.registry,[...this.variants,t])}simplify(){return this.variants.length===1?this.variants[0]:this}narrow(e){return this.options}props(){let e=super.props();if(this.variants.length===0)return e;let t=this.variants.map(e=>e.props()),n=Object.keys(t[0]).filter(e=>t.every(t=>e in t)),r={...e};for(let e of n){let n=t.map(t=>t[e].type);r[e]={type:this.registry.or(n)}}return r}get(){let e=this.variants.map(e=>e.get());if(e.some(e=>!e))return;let t=e;return new eg({key:this.registry.and(t.map(e=>e.key)),value:this.registry.or(t.map(e=>e.value))})}call(){let e=this.variants.map(e=>e.call());if(e.some(e=>!e))return;let t=e,n=t.map(e=>e.returns).filter(e=>!!e),r=t.map(e=>e.throws).filter(e=>!!e);return new tg({args:this.registry.and(t.map(e=>e.args)),returns:n.length===t.length?this.registry.or(n):void 0,throws:r.length>0?this.registry.or(r):void 0})}toJSON(){return{name:e.NAME,options:{types:this.variants.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.variants.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`or<${this.variants.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){return this.variants.length===0?R.never():this.variants.length===1?this.variants[0].toA(e):R.union(this.variants.map(t=>t.toA(e)))}toNewA(e){return this.variants.length===0?this.describeA(R.never(),e):this.variants.length===1?this.describeA(this.variants[0].toNewA(e),e):this.describeA(R.union(this.variants.map(t=>t.toNewA(e))),e)}},f_=class e extends U{static NAME=`text`;name=e.NAME;static optionKeys=[`minLength`,`maxLength`,`pattern`,`flags`];static genericKeys=[];_regex;static from(t,n){return n.registry,new e(n,t.options??{})}regex(){if(this._regex)return this._regex;if(this.options.pattern)return this._regex=new RegExp(this.options.pattern,this.options.flags),this._regex}valid(e){if(typeof e!=`string`)return!1;let{minLength:t,maxLength:n}=this.options;if(t!==void 0&&e.length<t||n!==void 0&&e.length>n)return!1;let r=this.regex();return!(r&&!r.test(e))}parse(e){if(typeof e!=`string`)throw new th({path:[],code:`text.invalid`,message:`text.parse: expected string, got ${typeof e}`,severity:`error`});if(!this.valid(e))throw new th({path:[],code:`text.constraint`,message:`text.parse: value violates constraints`,severity:`error`});return new W(this,e)}encode(e){return e}create(){let e=this.options.minLength??0;return e>0?`a`.repeat(e):``}random(e){let t=e(this.options.minLength??0,this.options.maxLength??16,!0),n=``;for(let r=0;r<t;r++)n+=`abcdefghijklmnopqrstuvwxyz0123456789`[e(0,35,!0)];return n}compatibleType(t,n){if(!(t instanceof e))return!1;if(!n?.value)return!0;let r=this.options,i=t.options;return!(r.minLength!==void 0&&(i.minLength===void 0||i.minLength<r.minLength)||r.maxLength!==void 0&&(i.maxLength===void 0||i.maxLength>r.maxLength)||r.pattern&&r.pattern!==i.pattern)}or(t){if(!(t instanceof e))return this;let n=this.options,r=t.options;return new e(this.registry,{minLength:n.minLength!==void 0&&r.minLength!==void 0?Math.min(n.minLength,r.minLength):void 0,maxLength:n.maxLength!==void 0&&r.maxLength!==void 0?Math.max(n.maxLength,r.maxLength):void 0,pattern:n.pattern===r.pattern?n.pattern:void 0,flags:n.pattern===r.pattern?n.flags:void 0})}narrow(e){let t=this.options,n=(e,t)=>{throw new th({path:[],code:e,message:t,severity:`error`})},r={...t};return e.minLength!==void 0&&(t.minLength!==void 0&&e.minLength<t.minLength&&n(`text.widen.minLength`,`local ${e.minLength} < base ${t.minLength}`),r.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength!==void 0&&e.maxLength>t.maxLength&&n(`text.widen.maxLength`,`local ${e.maxLength} > base ${t.maxLength}`),r.maxLength=e.maxLength),e.pattern!==void 0&&(t.pattern!==void 0&&(e.pattern!==t.pattern||e.flags!==t.flags)&&n(`text.widen.pattern`,`pattern narrowing is only allowed when base has no pattern or matches exactly`),r.pattern=e.pattern,r.flags=e.flags),r}get(){let e=this.registry;return new eg({key:e.num(),value:e.text({minLength:1,maxLength:1}),get:e.nativeExpr(`text.charAt`),loop:e.nativeExpr(`text.chars`)})}props(){let e=this.registry,t=e.text(),n=e.num(),r=e.bool(),i=e.optional(n);return{...super.props(),length:e.prop(n,`text.length`),eq:e.method({other:t},r,`text.eq`),neq:e.method({other:t},r,`text.neq`),contains:e.method({search:t},r,`text.contains`),startsWith:e.method({prefix:t},r,`text.startsWith`),endsWith:e.method({suffix:t},r,`text.endsWith`),trim:e.method({},t,`text.trim`),trimStart:e.method({},t,`text.trimStart`),trimEnd:e.method({},t,`text.trimEnd`),upper:e.method({},t,`text.upper`),lower:e.method({},t,`text.lower`),slice:e.method({start:n,end:i},t,`text.slice`),replace:e.method({search:t,replacement:t},t,`text.replace`),split:e.method({separator:t},e.list(t),`text.split`),concat:e.method({other:t},t,`text.concat`),repeat:e.method({count:n},t,`text.repeat`),indexOf:e.method({search:t,from:i},n,`text.indexOf`),lastIndexOf:e.method({search:t,from:i},n,`text.lastIndexOf`),match:e.method({pattern:t},e.list(t),`text.match`),test:e.method({pattern:t},r,`text.test`),isEmpty:e.method({},r,`text.isEmpty`),isNotEmpty:e.method({},r,`text.isNotEmpty`),toNum:e.method({},n,`text.toNum`),toBool:e.method({},r,`text.toBool`)}}toJSON(){return mh({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`text`+og(this.options)}valueA(){let e=R.string();return this.options.minLength!==void 0&&(e=e.min(this.options.minLength)),this.options.maxLength!==void 0&&(e=e.max(this.options.maxLength)),this.options.pattern&&(e=e.pattern(this.options.pattern,this.options.flags)),e}describe(e){return typeof e==`string`?this:void 0}},p_=class e extends U{static NAME=`timestamp`;name=e.NAME;static optionKeys=[`min`,`max`,`utc`,`precision`];static genericKeys=[];static from(t,n){return n.registry,new e(n,t.options??{})}valid(e){return e instanceof Date&&!Number.isNaN(e.getTime())}parse(e){let t=e instanceof Date?e:typeof e==`string`?new Date(e):new Date(NaN);if(!this.valid(t))throw new th({path:[],code:`timestamp.invalid`,message:`timestamp.parse: invalid: ${String(e)}`,severity:`error`});return new W(this,t)}encode(e){return e.toISOString()}create(){return new Date}random(e){return new Date(e(Date.UTC(2e3,0,1),Date.UTC(2050,11,31),!0))}compatibleType(t,n){return t instanceof e}or(t){return t instanceof e,this}narrow(e){return this.options}props(){let e=this.registry,t=e.num({whole:!0}),n=e.bool(),r=e.text(),i=e.timestamp(),a=e.duration();return{...super.props(),year:e.prop(t,`timestamp.year`),month:e.prop(t,`timestamp.month`),day:e.prop(t,`timestamp.day`),hour:e.prop(t,`timestamp.hour`),minute:e.prop(t,`timestamp.minute`),second:e.prop(t,`timestamp.second`),millisecond:e.prop(t,`timestamp.millisecond`),eq:e.method({other:i},n,`timestamp.eq`),before:e.method({other:i},n,`timestamp.before`),after:e.method({other:i},n,`timestamp.after`),addDuration:e.method({duration:a},i,`timestamp.addDuration`),subDuration:e.method({duration:a},i,`timestamp.subDuration`),diff:e.method({other:i},a,`timestamp.diff`),toDate:e.method({},e.date(),`timestamp.toDate`),toEpoch:e.method({},t,`timestamp.toEpoch`),toText:e.method({format:e.optional(r)},r,`timestamp.toText`)}}toJSON(){return mh({name:e.NAME,options:Object.keys(this.options).length>0?{...this.options}:void 0})}clone(){return new e(this.registry,{...this.options})}toCode(e,t){return this.docsPrefix(t)+`timestamp`+og(this.options)}valueA(){return R.string().pattern(`^\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})?$`).describe(`An ISO 8601 timestamp (YYYY-MM-DD HH:MM[:SS][Z]).`)}describe(e){return e instanceof Date?this:void 0}};function m_(e){let t,n={};return Object.defineProperty(n,"elements",{enumerable:!0,get:()=>t??=e.map(e=>e.toJSON())}),n}var h_=class e extends U{static NAME=`tuple`;name=e.NAME;static optionKeys=[`elements`];static genericKeys=[];elements;static from(t,n){n.registry;let r=(t.options?.elements??[]).map(e=>n.parse(e));return new e(n,r)}constructor(e,t){super(e,m_(t)),this.elements=t}valid(e,t){return!Array.isArray(e)||e.length!==this.elements.length?!1:e.every((e,n)=>e instanceof W&&e.type.valid(e.raw,t)&&Wh(this.elements[n],e.type,t))}parse(e,t){if(!Array.isArray(e)||e.length!==this.elements.length)throw new th({path:[],code:`tuple.invalid`,message:`tuple.parse: expected array of length ${this.elements.length}`,severity:`error`});let n=this.elements.map((n,r)=>this.registry.parseValue(e[r],n,t));return new W(this,n)}encode(e,t){return this.encodeAs(e,Xh,t)}encodeAs(e,t,n){if(!Array.isArray(e))throw new th({path:[],code:`tuple.invalid`,message:`tuple.encode: expected an array of cells`,severity:`error`});return e.map(e=>Jh(e,t,n))}create(){return this.elements.map(e=>new W(e,e.create()))}forEachNewSlot(e,t){if(!Array.isArray(e))return!1;for(let n=0;n<this.elements.length&&n<e.length;n++)t.slot(this.elements[n],e[n],n);return!0}async newFill(e,t,n){if(!Array.isArray(e))return super.newFill(e,t,n);let r=[];for(let i=0;i<e.length;i++){let a=this.elements[i];r.push(a?await a.newFill(e[i],t,n):e[i])}return r}random(e){return this.elements.map(t=>new W(t,t.random(e)))}like(t){if(!(t instanceof e)||t.elements.length!==this.elements.length)return this;let n=t.elements.map(e=>this.registry.like(e));return n.some(e=>e.name===`null`)?this.registry.null():this.registry.tuple(n)}compatibleType(t,n,r){return!(t instanceof e)||t.elements.length!==this.elements.length?!1:this.elements.every((e,i)=>e.compatible(t.elements[i],n,r))}or(t){return!(t instanceof e)||t.elements.length!==this.elements.length?this:new e(this.registry,this.elements.map((e,n)=>e.or(t.elements[n])))}narrow(e){return e.elements===void 0?this.options:{elements:e.elements}}get(){let e=this.elements.length===1?this.elements[0]:this.registry.or(this.elements),t=this.registry;return new eg({key:t.num({whole:!0,min:0,max:this.elements.length-1}),value:e,get:t.nativeExpr(`tuple.at`),set:t.nativeExpr(`tuple.setAt`),loop:t.nativeExpr(`tuple.iterate`)})}follow(e,t){if(`key`in e&&!(`args`in e)){let t=e.key,n=t?.kind===`new`?t.value:void 0;if(typeof n==`number`&&Number.isInteger(n))return this.elements[n]}return super.follow(e,t)}props(){let e=this.registry;e.num();let t=this.elements[0]??e.any(),n=this.elements[this.elements.length-1]??e.any();return{...super.props(),length:e.prop(e.num({whole:!0,min:this.elements.length,max:this.elements.length}),`tuple.length`),first:e.prop(t,`tuple.first`),last:e.prop(n,`tuple.last`),toList:e.method({},e.list(this.elements.length===0?e.any():e.or(this.elements)),`tuple.toList`)}}toJSON(){return{name:e.NAME,options:{elements:this.elements.map(e=>e.toJSON())}}}clone(){return new e(this.registry,this.elements.map(e=>e.clone()))}toCode(e,t){return this.docsPrefix(t)+`tuple<${this.elements.map(e=>e.toCode(void 0,t)).join(`, `)}>`}valueA(e){let t=this.elements.map(t=>t.toA(e));return t.length>0?R.tuple(t):R.array(R.unknown()).max(0)}toNewA(e){let t=this.elements.map(()=>R.ref(`Expr`));return this.describeA(t.length>0?R.tuple(t):R.array(R.ref(`Expr`)).max(0),e)}},g_=class e extends U{constructor(e,t){super(e,{},{T:t}),this.constraint=t}constraint;static NAME=`typ`;name=e.NAME;static optionKeys=[];static genericKeys=[`T`];static valuesAreTypes=!0;static from(t,n){let r=n.registry,i=t.generic?.T?n.parse(t.generic.T):r.any();return new e(n,i)}valid(e,t){return e instanceof U?e.compatible(this.constraint,void 0,t)||this.constraint.compatible(e,void 0,t):!1}parse(t,n){if(t instanceof W&&t.type instanceof e)return t;if(t instanceof U){if(!this.valid(t,n))throw Error(`typ.parse: Type '${t.name}' is not compatible with ${this.constraint.toCode()}`);return new W(this,t)}if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`typ.parse: expected TypeDef or Type, got ${typeof t}`);if(!(`name`in t)||typeof t.name!=`string`)throw Error(`typ.parse: TypeDef missing 'name' field`);let r;try{r=this.registry.parse(t,n)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`typ.parse: ${t}`)}if(!this.valid(r,n))throw Error(`typ.parse: Type '${r.name}' is not compatible with ${this.constraint.toCode()}`);let i=n??this.registry,a=r.references().refs.filter(e=>i.lookup(e)===void 0);if(a.length>0)throw Error(`typ.parse: no type named ${a.join(`, `)}`);return new W(this,r)}encode(e,t){return e.toJSON()}create(){return this.constraint}random(e){return this.constraint}compatibleType(t,n,r){return t instanceof e&&this.constraint.compatible(t.constraint,n,r)}or(t){return t instanceof e?new e(this.registry,this.registry.or([this.constraint,t.constraint])):this}narrow(e){return{}}props(){return{...super.props()}}toJSON(){return{name:e.NAME,generic:{T:this.constraint.toJSON()}}}clone(){return new e(this.registry,this.constraint.clone())}toCode(e,t){return this.docsPrefix(t)+`typ<${this.constraint.toCode(void 0,t)}>`}valueA(e){let t=this.registry.compatible(this.constraint);if(t.length===0&&this.constraint.name!==`any`)return R.never();let n;if(this.constraint.name===`any`)n=R.ref(`TypeDef`);else{let e=t.map(e=>Am(this.registry,e.name));e.push(jm()),e.push(Mm(t.map(e=>e.name))),n=R.union(e).describe(`A gin type definition ({ "name": ..., ... }) whose type fits ${this.constraint.toCode()}.`)}return n.refine(t=>{try{return this.parse(t,e?.scope),!0}catch(e){return e instanceof Error?e.message:String(e)}})}toNewA(e){return this.describeA(this.toA(e),e)}},__=class e extends U{static NAME=`void`;name=e.NAME;static optionKeys=[];static genericKeys=[];static from(t,n){return n.registry,new e(n,{})}valid(e){return e===void 0}parse(e){if(e!=null)throw new th({path:[],code:`void.invalid`,message:`void expects undefined/null, got ${typeof e}`,severity:`error`});return new W(this,void 0)}encode(e){return null}create(){}random(e){}compatibleType(t,n){return t instanceof e}or(e){return this}narrow(e){if(e&&Object.keys(e).length>0)throw new th({path:[],code:`void.no-options`,message:`void has no narrowable options`,severity:`error`});return{}}props(){let e=this.registry;return{...super.props(),toText:e.method({},e.text(),`void.toText`),toBool:e.method({},e.bool(),`void.toBool`)}}toJSON(){return{name:e.NAME}}clone(){return new e(this.registry,{})}toCode(e,t){return this.docsPrefix(t)+`void`}valueA(){return R.null()}};function K(e){return e.get(`this`).raw}function v_(e){return e.get(`this`)}function q(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];return r==null?r:x_(r)?r.raw:r}function y_(e,t){let n=e.get(`args`);if(!n)return;let r=n.raw?.[t];if(x_(r))return r}function b_(e){let t=q(e,`epsilon`);return typeof t==`number`?t:0}function x_(e){return!!e&&typeof e==`object`&&`type`in e&&`raw`in e}function S_(e,t,n,r){let i=e.get(`yield`).raw,a=t.obj({key:{type:n},value:{type:r}});return(e,t)=>i(new W(a,{key:e,value:t}))}var C_={"type.toAny":(e,t)=>G(t.any(),K(e)),"any.typeOf":(e,t)=>G(t.text(),v_(e).type.name),"any.is":(e,t)=>G(t.bool(),!0),"any.as":(e,t)=>{let n=v_(e);return G(t.optional(n.type),n.raw)},"any.toText":(e,t)=>G(t.text(),String(K(e))),"any.toBool":(e,t)=>G(t.bool(),!!K(e)),"any.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"any.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`))},w_={"void.toText":(e,t)=>G(t.text(),`void`),"void.toBool":(e,t)=>G(t.bool(),!1)},T_={"null.toText":(e,t)=>G(t.text(),`null`),"null.toBool":(e,t)=>G(t.bool(),!1)},E_={"bool.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"bool.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"bool.and":(e,t)=>G(t.bool(),K(e)&&q(e,`other`)),"bool.or":(e,t)=>G(t.bool(),K(e)||q(e,`other`)),"bool.xor":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"bool.not":(e,t)=>G(t.bool(),!K(e)),"bool.toText":(e,t)=>{let n=K(e),r=q(e,`trueText`),i=q(e,`falseText`);return G(t.text(),n?r??`true`:i??`false`)},"bool.toNum":(e,t)=>{let n=K(e),r=q(e,`trueValue`),i=q(e,`falseValue`);return G(t.num(),n?r??1:i??0)}},D_={"num.eq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))<=b_(e)),"num.neq":(e,t)=>G(t.bool(),Math.abs(K(e)-q(e,`other`))>b_(e)),"num.lt":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"num.lte":(e,t)=>G(t.bool(),K(e)<=q(e,`other`)),"num.gt":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"num.gte":(e,t)=>G(t.bool(),K(e)>=q(e,`other`)),"num.add":(e,t)=>G(t.num(),K(e)+q(e,`other`)),"num.sub":(e,t)=>G(t.num(),K(e)-q(e,`other`)),"num.mul":(e,t)=>G(t.num(),K(e)*q(e,`other`)),"num.div":(e,t)=>G(t.num(),K(e)/q(e,`other`)),"num.mod":(e,t)=>G(t.num(),K(e)%q(e,`other`)),"num.pow":(e,t)=>G(t.num(),K(e)**q(e,`other`)),"num.abs":(e,t)=>G(t.num(),Math.abs(K(e))),"num.neg":(e,t)=>G(t.num(),-K(e)),"num.sign":(e,t)=>G(t.num(),Math.sign(K(e))),"num.sqrt":(e,t)=>G(t.num(),Math.sqrt(K(e))),"num.min":(e,t)=>G(t.num(),Math.min(K(e),q(e,`other`))),"num.max":(e,t)=>G(t.num(),Math.max(K(e),q(e,`other`))),"num.clamp":(e,t)=>G(t.num(),Math.min(Math.max(K(e),q(e,`min`)),q(e,`max`))),"num.floor":(e,t)=>G(t.num(),Math.floor(K(e))),"num.ceil":(e,t)=>G(t.num(),Math.ceil(K(e))),"num.round":(e,t)=>G(t.num(),Math.round(K(e))),"num.isZero":(e,t)=>G(t.bool(),Math.abs(K(e))<=b_(e)),"num.isPositive":(e,t)=>G(t.bool(),K(e)>b_(e)),"num.isNegative":(e,t)=>G(t.bool(),K(e)<-b_(e)),"num.isInteger":(e,t)=>G(t.bool(),Number.isInteger(K(e))),"num.isEven":(e,t)=>G(t.bool(),K(e)%2==0),"num.isOdd":(e,t)=>G(t.bool(),Math.abs(K(e))%2==1),"num.toText":(e,t)=>{let n=q(e,`precision`),r=n==null?String(K(e)):K(e).toFixed(n);return G(t.text(),r)},"num.toBool":(e,t)=>G(t.bool(),K(e)!==0),"num.loop":async(e,t)=>{let n=K(e),r=t.num(),i=S_(e,t,r,r),a=Math.abs(Math.trunc(n)),o=n<0?-1:1;for(let e=0;e<a;e++){let t=e*o,n=Object.is(t,-0)?0:t;await i(G(r,e),G(r,n))}return G(t.void(),void 0)}},O_={"text.length":(e,t)=>G(t.num({whole:!0,min:0}),K(e).length),"text.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"text.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"text.contains":(e,t)=>G(t.bool(),K(e).includes(q(e,`search`))),"text.startsWith":(e,t)=>G(t.bool(),K(e).startsWith(q(e,`prefix`))),"text.endsWith":(e,t)=>G(t.bool(),K(e).endsWith(q(e,`suffix`))),"text.trim":(e,t)=>G(t.text(),K(e).trim()),"text.trimStart":(e,t)=>G(t.text(),K(e).trimStart()),"text.trimEnd":(e,t)=>G(t.text(),K(e).trimEnd()),"text.upper":(e,t)=>G(t.text(),K(e).toUpperCase()),"text.lower":(e,t)=>G(t.text(),K(e).toLowerCase()),"text.slice":(e,t)=>{let n=q(e,`start`),r=q(e,`end`);return G(t.text(),K(e).slice(n,r))},"text.replace":(e,t)=>{let n=q(e,`search`),r=q(e,`replacement`);return G(t.text(),K(e).split(n).join(r))},"text.split":(e,t)=>{let n=K(e).split(q(e,`separator`));return G(t.list(t.text()),n.map(e=>G(t.text(),e)))},"text.concat":(e,t)=>G(t.text(),K(e)+q(e,`other`)),"text.repeat":(e,t)=>G(t.text(),K(e).repeat(q(e,`count`))),"text.indexOf":(e,t)=>{let n=q(e,`from`);return G(t.num(),K(e).indexOf(q(e,`search`),n))},"text.lastIndexOf":(e,t)=>{let n=q(e,`from`);return G(t.num(),K(e).lastIndexOf(q(e,`search`),n))},"text.match":(e,t)=>{let n=q(e,`pattern`),r=K(e).match(new RegExp(n,`g`))??[];return G(t.list(t.text()),r.map(e=>G(t.text(),e)))},"text.test":(e,t)=>{let n=q(e,`pattern`);return G(t.bool(),new RegExp(n).test(K(e)))},"text.isEmpty":(e,t)=>G(t.bool(),K(e).length===0),"text.isNotEmpty":(e,t)=>G(t.bool(),K(e).length>0),"text.toNum":(e,t)=>G(t.num(),Number(K(e))),"text.toBool":(e,t)=>G(t.bool(),K(e).length>0),"text.charAt":(e,t)=>{let n=e.get(`key`).raw,r=K(e)[n];if(r===void 0)throw Error(`text[${n}]: index out of range`);return G(t.text({minLength:1,maxLength:1}),r)},"text.chars":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=t.text({minLength:1,maxLength:1}),a=S_(e,t,r,i);for(let e=0;e<n.length;e++)await a(G(r,e),G(i,n[e]));return G(t.void(),void 0)}},k_=e=>v_(e).type.item,A_={"list.length":(e,t)=>G(t.num({whole:!0,min:0}),K(e).length),"list.indexGet":e=>{let t=e.get(`key`).raw,n=K(e);if(t<0||t>=n.length)throw Error(`list[${t}]: index out of range`);return n[t]},"list.indexSet":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`),i=K(e);if(n<0||n>=i.length)throw Error(`list[${n}] =: index out of range`);return i[n]=r,G(t.void(),void 0)},"list.iterate":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=S_(e,t,r,k_(e)),a=G(t.void(),void 0);for(let e=0;e<n.length;e++)await i(G(r,e),n[e]);return a},"list.at":(e,t)=>{let n=q(e,`index`),r=K(e);return n<0||n>=r.length?G(t.optional(k_(e)),void 0):G(t.optional(k_(e)),r[n].raw)},"list.push":(e,t)=>(K(e).push(y_(e,`value`)),G(t.void(),void 0)),"list.pop":(e,t)=>{let n=K(e).pop();return G(t.optional(k_(e)),n?n.raw:void 0)},"list.shift":(e,t)=>{let n=K(e).shift();return G(t.optional(k_(e)),n?n.raw:void 0)},"list.unshift":(e,t)=>(K(e).unshift(y_(e,`value`)),G(t.void(),void 0)),"list.insert":(e,t)=>(K(e).splice(q(e,`index`),0,y_(e,`value`)),G(t.void(),void 0)),"list.remove":e=>K(e).splice(q(e,`index`),1)[0],"list.clear":(e,t)=>(K(e).length=0,G(t.void(),void 0)),"list.slice":e=>{let t=v_(e).type,n=q(e,`start`),r=q(e,`end`);return G(t,K(e).slice(n,r))},"list.concat":e=>{let t=v_(e).type,n=q(e,`other`);return G(t,K(e).concat(n))},"list.reverse":e=>{let t=v_(e).type;return G(t,[...K(e)].reverse())},"list.join":(e,t)=>{let n=q(e,`separator`)??`,`;return G(t.text(),K(e).map(e=>String(e.raw)).join(n))},"list.indexOf":(e,t)=>{let n=y_(e,`value`).raw,r=K(e).findIndex(e=>e.raw===n);return G(t.num(),r)},"list.contains":(e,t)=>{let n=y_(e,`value`).raw,r=K(e);return G(t.bool(),r.some(e=>e.raw===n))},"list.unique":e=>{let t=v_(e).type,n=new Set,r=[];for(let t of K(e))n.has(t.raw)||(n.add(t.raw),r.push(t));return G(t,r)},"list.duplicates":e=>{let t=v_(e).type,n=new Set,r=new Set,i=[];for(let t of K(e))n.has(t.raw)?r.has(t.raw)||(r.add(t.raw),i.push(t)):n.add(t.raw);return G(t,i)},"list.map":async(e,t)=>{let n=K(e),r=y_(e,`fn`).raw,i=k_(e),a=[],o=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++){let i=new W(o,{value:n[e],index:G(t.num(),e)});a.push(await r(i))}return G(t.list(t.any()),a)},"list.filter":async e=>{let t=v_(e).type,n=K(e),r=y_(e,`fn`).raw,i=[],a=t.registry.obj({value:{type:t.item},index:{type:t.registry.num()}});for(let e=0;e<n.length;e++)(await r(new W(a,{value:n[e],index:G(t.registry.num(),e)}))).raw&&i.push(n[e]);return G(t,i)},"list.find":async(e,t)=>{let n=K(e),r=y_(e,`fn`).raw,i=k_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if((await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.optional(i),n[e].raw);return G(t.optional(i),void 0)},"list.reduce":async(e,t)=>{let n=K(e),r=y_(e,`fn`),i=y_(e,`initial`),a=r.raw,o=k_(e),s=i,c=t.obj({acc:{type:t.any()},value:{type:o},index:{type:t.num()}});for(let e=0;e<n.length;e++)s=await a(new W(c,{acc:s,value:n[e],index:G(t.num(),e)}));return s},"list.some":async(e,t)=>{let n=K(e),r=y_(e,`fn`).raw,i=k_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if((await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.bool(),!0);return G(t.bool(),!1)},"list.every":async(e,t)=>{let n=K(e),r=y_(e,`fn`).raw,i=k_(e),a=t.obj({value:{type:i},index:{type:t.num()}});for(let e=0;e<n.length;e++)if(!(await r(new W(a,{value:n[e],index:G(t.num(),e)}))).raw)return G(t.bool(),!1);return G(t.bool(),!0)},"list.sort":async e=>{let t=v_(e).type,n=[...K(e)],r=y_(e,`fn`);if(r&&typeof r.raw==`function`){let e=r.raw,i=t.registry.obj({a:{type:t.item},b:{type:t.item}}),a=[];for(let t=0;t<n.length;t++){let r=0;for(let a=0;a<n.length;a++)t!==a&&(await e(new W(i,{a:n[t],b:n[a]}))).raw>0&&r++;a.push({index:t,key:r})}return a.sort((e,t)=>e.key-t.key),G(t,a.map(e=>n[e.index]))}return G(t,n.sort((e,t)=>{let n=e.raw,r=t.raw;return n<r?-1:+(n>r)}))},"list.isEmpty":(e,t)=>G(t.bool(),K(e).length===0),"list.isNotEmpty":(e,t)=>G(t.bool(),K(e).length>0),"list.first":(e,t)=>{let n=K(e);return G(t.optional(k_(e)),n.length>0?n[0].raw:void 0)},"list.last":(e,t)=>{let n=K(e);return G(t.optional(k_(e)),n.length>0?n[n.length-1].raw:void 0)}},j_={"list.indexSet":B.STATE,"list.push":B.STATE,"list.pop":B.STATE,"list.shift":B.STATE,"list.unshift":B.STATE,"list.insert":B.STATE,"list.remove":B.STATE,"list.clear":B.STATE},M_=e=>v_(e).type.value,N_={"map.size":(e,t)=>G(t.num({whole:!0,min:0}),K(e).size),"map.indexGet":e=>{let t=e.get(`key`).raw,n=K(e).get(t);if(!n)throw Error(`map[${String(t)}]: key not found`);return n[1]},"map.indexSet":(e,t)=>{let n=e.get(`key`),r=e.get(`value`);return K(e).set(n.raw,[n,r]),G(t.void(),void 0)},"map.iterate":async(e,t)=>{let n=K(e),r=n.values().next().value,i=S_(e,t,r?r[0].type:t.any(),r?r[1].type:t.any());for(let[,[e,t]]of n)await i(e,t);return G(t.void(),void 0)},"map.at":(e,t)=>{let n=q(e,`key`),r=K(e).get(n);return G(t.optional(M_(e)),r?r[1].raw:void 0)},"map.has":(e,t)=>G(t.bool(),K(e).has(q(e,`key`))),"map.delete":(e,t)=>G(t.bool(),K(e).delete(q(e,`key`))),"map.clear":(e,t)=>(K(e).clear(),G(t.void(),void 0)),"map.keys":(e,t)=>{let n=K(e),r=v_(e).type.key,i=[];for(let[,[e]]of n)i.push(e);return G(t.list(r),i)},"map.values":(e,t)=>{let n=K(e),r=v_(e).type.value,i=[];for(let[,[,e]]of n)i.push(e);return G(t.list(r),i)},"map.isEmpty":(e,t)=>G(t.bool(),K(e).size===0),"map.isNotEmpty":(e,t)=>G(t.bool(),K(e).size>0)},P_={"map.indexSet":B.STATE,"map.delete":B.STATE,"map.clear":B.STATE},F_=e=>v_(e).type.elements,I_={"tuple.at":e=>{let t=e.get(`key`).raw,n=K(e)[t];return n instanceof W?n:G(F_(e)[t]??G.prototype,n)},"tuple.setAt":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`);return K(e)[n]=r,G(t.void(),void 0)},"tuple.iterate":async(e,t)=>{let n=K(e),r=t.num({whole:!0,min:0}),i=n.map(e=>e.type),a=S_(e,t,r,i.length===0?t.any():i.length===1?i[0]:t.or(i));for(let e=0;e<n.length;e++)await a(G(r,e),n[e]);return G(t.void(),void 0)},"tuple.length":(e,t)=>G(t.num({whole:!0}),K(e).length),"tuple.first":e=>{let t=K(e),n=F_(e),r=t[0];return r instanceof W?r:G(n[0],r)},"tuple.last":e=>{let t=K(e),n=F_(e),r=t[t.length-1];return r instanceof W?r:G(n[n.length-1],r)},"tuple.toList":(e,t)=>G(t.list(t.any()),[...K(e)])},L_={"tuple.setAt":B.STATE},R_=e=>v_(e).type.fields,z_={"object.indexGet":e=>{let t=e.get(`key`).raw,n=R_(e)[t];if(!n)throw Error(`object[${t}]: no such field`);let r=K(e)[t];return r instanceof W?r:G(n.type,r)},"object.indexSet":(e,t)=>{let n=e.get(`key`).raw,r=e.get(`value`);return K(e)[n]=r,G(t.void(),void 0)},"object.iterate":async(e,t)=>{let n=K(e),r=R_(e),i=t.text(),a=Object.values(r).map(e=>e.type),o=S_(e,t,i,a.length===0?t.any():a.length===1?a[0]:t.or(a));for(let[e]of Object.entries(r)){let t=n[e];t instanceof W&&await o(G(i,e),t)}return G(t.void(),void 0)},"object.keys":(e,t)=>{let n=Object.keys(R_(e));return G(t.list(t.text()),n.map(e=>G(t.text(),e)))},"object.values":(e,t)=>{let n=K(e),r=Object.keys(R_(e)).map(e=>n[e]??G(t.any(),void 0));return G(t.list(t.any()),r)},"object.entries":(e,t)=>{let n=K(e),r=Object.keys(R_(e)).map(e=>G(t.any(),[e,n[e]?.raw]));return G(t.list(t.any()),r)},"object.has":(e,t)=>G(t.bool(),Object.hasOwn(R_(e),q(e,`key`))),"object.eq":(e,t)=>G(t.bool(),V_(v_(e),e.get(`args`).raw)),"object.neq":(e,t)=>G(t.bool(),!V_(v_(e),e.get(`args`).raw)),"object.toText":(e,t)=>{let n=K(e),r=R_(e),i={};for(let[e]of Object.entries(r)){let t=n[e];i[e]=t?t.type.encode(t.raw):void 0}return G(t.text(),JSON.stringify(i))}},B_={"object.indexSet":B.STATE};function V_(e,t){let n=t.other,r=n instanceof W?n.raw:n;return H_(e.raw,r)}function H_(e,t){if(e instanceof W&&(e=e.raw),t instanceof W&&(t=t.raw),e===t)return!0;if(typeof e!=`object`||typeof t!=`object`||e===null||t===null||Array.isArray(e)!==Array.isArray(t))return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!H_(e[n],t[n]))return!1;return!0}let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!H_(e[r],t[r]))return!1;return!0}var U_={"optional.value":e=>{let t=K(e);if(t===void 0)throw Error(`optional.value: value is undefined`);return G(v_(e).type.inner,t)},"optional.has":(e,t)=>G(t.bool(),K(e)!==void 0),"optional.or":e=>{let t=K(e),n=v_(e).type.inner;return t===void 0?y_(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"optional.map":async(e,t)=>{let n=K(e),r=v_(e).type.inner;if(n===void 0)return G(t.optional(t.any()),void 0);let i=y_(e,`fn`).raw,a=await i(new W(t.obj({value:{type:r}}),{value:G(r,n)}));return G(t.optional(t.any()),a.raw)}},W_={"nullable.value":e=>{let t=K(e);if(t===null)throw Error(`nullable.value: value is null`);return G(v_(e).type.inner,t)},"nullable.isNull":(e,t)=>G(t.bool(),K(e)===null),"nullable.or":e=>{let t=K(e),n=v_(e).type.inner;return t===null?y_(e,`fallback`)??G(n,q(e,`fallback`)):G(n,t)},"nullable.map":async(e,t)=>{let n=K(e),r=v_(e).type.inner;if(n===null)return G(t.nullable(t.any()),null);let i=y_(e,`fn`).raw,a=await i(new W(t.obj({value:{type:r}}),{value:G(r,n)}));return G(t.nullable(t.any()),a.raw)}},G_={"not.typeOf":(e,t)=>G(t.text(),v_(e).type.name),"not.toText":(e,t)=>G(t.text(),String(K(e)))},K_={"enum.name":(e,t)=>{let n=K(e),r=v_(e).type,i=Object.entries(r.options.values).find(([,e])=>e===n);return G(t.text(),i?i[0]:``)},"enum.value":e=>{let t=v_(e).type;return G(t.value,K(e))},"enum.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"enum.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"enum.toText":(e,t)=>G(t.text(),String(K(e)))},q_={"date.year":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()),"date.month":(e,t)=>G(t.num({whole:!0,min:1,max:12}),K(e).getUTCMonth()+1),"date.day":(e,t)=>G(t.num({whole:!0,min:1,max:31}),K(e).getUTCDate()),"date.dayOfWeek":(e,t)=>G(t.num({whole:!0,min:0,max:6}),K(e).getUTCDay()),"date.dayOfYear":(e,t)=>{let n=K(e),r=Date.UTC(n.getUTCFullYear(),0,0);return G(t.num({whole:!0,min:1,max:366}),Math.floor((n.getTime()-r)/864e5))},"date.eq":(e,t)=>G(t.bool(),K(e).getTime()===q(e,`other`).getTime()),"date.neq":(e,t)=>G(t.bool(),K(e).getTime()!==q(e,`other`).getTime()),"date.before":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"date.after":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"date.addDays":(e,t)=>{let n=new Date(K(e));return n.setUTCDate(n.getUTCDate()+q(e,`days`)),G(t.date(),n)},"date.addMonths":(e,t)=>{let n=new Date(K(e));return n.setUTCMonth(n.getUTCMonth()+q(e,`months`)),G(t.date(),n)},"date.addYears":(e,t)=>{let n=new Date(K(e));return n.setUTCFullYear(n.getUTCFullYear()+q(e,`years`)),G(t.date(),n)},"date.diffDays":(e,t)=>G(t.num({whole:!0}),Math.round((K(e).getTime()-q(e,`other`).getTime())/864e5)),"date.diffMonths":(e,t)=>{let n=K(e),r=q(e,`other`);return G(t.num({whole:!0}),(n.getUTCFullYear()-r.getUTCFullYear())*12+(n.getUTCMonth()-r.getUTCMonth()))},"date.diffYears":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()-q(e,`other`).getUTCFullYear()),"date.toText":(e,t)=>G(t.text(),K(e).toISOString().slice(0,10))},J_={"timestamp.year":(e,t)=>G(t.num({whole:!0}),K(e).getUTCFullYear()),"timestamp.month":(e,t)=>G(t.num({whole:!0}),K(e).getUTCMonth()+1),"timestamp.day":(e,t)=>G(t.num({whole:!0}),K(e).getUTCDate()),"timestamp.hour":(e,t)=>G(t.num({whole:!0,min:0,max:23}),K(e).getUTCHours()),"timestamp.minute":(e,t)=>G(t.num({whole:!0,min:0,max:59}),K(e).getUTCMinutes()),"timestamp.second":(e,t)=>G(t.num({whole:!0,min:0,max:59}),K(e).getUTCSeconds()),"timestamp.millisecond":(e,t)=>G(t.num({whole:!0,min:0,max:999}),K(e).getUTCMilliseconds()),"timestamp.eq":(e,t)=>G(t.bool(),K(e).getTime()===q(e,`other`).getTime()),"timestamp.before":(e,t)=>G(t.bool(),K(e)<q(e,`other`)),"timestamp.after":(e,t)=>G(t.bool(),K(e)>q(e,`other`)),"timestamp.addDuration":(e,t)=>G(t.timestamp(),new Date(K(e).getTime()+q(e,`duration`))),"timestamp.subDuration":(e,t)=>G(t.timestamp(),new Date(K(e).getTime()-q(e,`duration`))),"timestamp.diff":(e,t)=>G(t.duration(),K(e).getTime()-q(e,`other`).getTime()),"timestamp.toDate":(e,t)=>G(t.date(),new Date(K(e).toISOString().slice(0,10))),"timestamp.toEpoch":(e,t)=>G(t.num(),K(e).getTime()),"timestamp.toText":(e,t)=>G(t.text(),K(e).toISOString())},Y_=864e5,X_=36e5,Z_=6e4,Q_=1e3,$_={"duration.init":(e,t)=>{let n=q(e,`days`)??0,r=q(e,`hours`)??0,i=q(e,`minutes`)??0,a=q(e,`seconds`)??0,o=q(e,`ms`)??0;return G(t.duration(),n*Y_+r*X_+i*Z_+a*Q_+o)},"duration.totalSeconds":(e,t)=>G(t.num(),K(e)/1e3),"duration.totalMinutes":(e,t)=>G(t.num(),K(e)/6e4),"duration.totalHours":(e,t)=>G(t.num(),K(e)/36e5),"duration.totalDays":(e,t)=>G(t.num(),K(e)/864e5),"duration.days":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/Y_)),"duration.hours":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/X_)%24),"duration.minutes":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/Z_)%60),"duration.seconds":(e,t)=>G(t.num({whole:!0}),Math.trunc(K(e)/Q_)%60),"duration.ms":(e,t)=>G(t.num({whole:!0}),K(e)%Q_),"duration.toText":(e,t)=>{let n=K(e),r=Math.trunc(n/Y_),i=Math.trunc(n%Y_/X_),a=Math.trunc(n%X_/Z_),o=Math.trunc(n%Z_/Q_),s=[];return r&&s.push(`${r}d`),i&&s.push(`${i}h`),a&&s.push(`${a}m`),(o||s.length===0)&&s.push(`${o}s`),G(t.text(),s.join(` `))}},ev=e=>e>>>24&255,tv=e=>e>>>16&255,nv=e=>e>>>8&255,rv=e=>(e&255)/255,iv=(e,t,n,r)=>(Math.round(e)&255)<<24|(Math.round(t)&255)<<16|(Math.round(n)&255)<<8|Math.round(r*255)&255,av={"color.init":(e,t)=>{let n=q(e,`r`),r=q(e,`g`),i=q(e,`b`),a=q(e,`a`)??1;return G(t.color(),iv(n,r,i,a)>>>0)},"color.r":(e,t)=>G(t.num(),ev(K(e))),"color.g":(e,t)=>G(t.num(),tv(K(e))),"color.b":(e,t)=>G(t.num(),nv(K(e))),"color.a":(e,t)=>G(t.num(),rv(K(e))),"color.hue":(e,t)=>G(t.num(),ov(K(e)).h),"color.saturation":(e,t)=>G(t.num(),ov(K(e)).s),"color.lightness":(e,t)=>G(t.num(),ov(K(e)).l),"color.eq":(e,t)=>G(t.bool(),K(e)===q(e,`other`)),"color.neq":(e,t)=>G(t.bool(),K(e)!==q(e,`other`)),"color.lighten":(e,t)=>G(t.color(),cv(K(e),q(e,`amount`))),"color.darken":(e,t)=>G(t.color(),cv(K(e),-q(e,`amount`))),"color.saturate":(e,t)=>G(t.color(),lv(K(e),q(e,`amount`))),"color.desaturate":(e,t)=>G(t.color(),lv(K(e),-q(e,`amount`))),"color.opacity":(e,t)=>G(t.color(),K(e)&4294967040|Math.round(q(e,`alpha`)*255)&255),"color.invert":(e,t)=>{let n=K(e);return G(t.color(),iv(255-ev(n),255-tv(n),255-nv(n),rv(n))>>>0)},"color.mix":(e,t)=>{let n=K(e),r=q(e,`other`),i=q(e,`weight`)??.5;return G(t.color(),iv(ev(n)*(1-i)+ev(r)*i,tv(n)*(1-i)+tv(r)*i,nv(n)*(1-i)+nv(r)*i,rv(n)*(1-i)+rv(r)*i)>>>0)},"color.complement":(e,t)=>G(t.color(),uv(K(e),180)),"color.toHex":(e,t)=>G(t.text(),`#`+K(e).toString(16).padStart(8,`0`)),"color.toRgb":(e,t)=>{let n=K(e);return G(t.text(),`rgb(${ev(n)},${tv(n)},${nv(n)})`)},"color.toHsl":(e,t)=>{let{h:n,s:r,l:i}=ov(K(e));return G(t.text(),`hsl(${Math.round(n)},${Math.round(r*100)}%,${Math.round(i*100)}%)`)},"color.toText":(e,t)=>G(t.text(),`#`+K(e).toString(16).padStart(8,`0`))};function ov(e){let t=ev(e)/255,n=tv(e)/255,r=nv(e)/255,i=Math.max(t,n,r),a=Math.min(t,n,r),o=(i+a)/2,s=0,c=0;if(i!==a){let e=i-a;switch(c=o>.5?e/(2-i-a):e/(i+a),i){case t:s=(n-r)/e+(n<r?6:0);break;case n:s=(r-t)/e+2;break;case r:s=(t-n)/e+4}s*=60}return{h:s,s:c,l:o}}function sv(e,t,n,r){let i=(1-Math.abs(2*n-1))*t,a=i*(1-Math.abs(e/60%2-1)),o=n-i/2,s=0,c=0,l=0;return e<60?[s,c,l]=[i,a,0]:e<120?[s,c,l]=[a,i,0]:e<180?[s,c,l]=[0,i,a]:e<240?[s,c,l]=[0,a,i]:e<300?[s,c,l]=[a,0,i]:[s,c,l]=[i,0,a],iv((s+o)*255,(c+o)*255,(l+o)*255,r)}function cv(e,t){let{h:n,s:r,l:i}=ov(e);return sv(n,r,Math.max(0,Math.min(1,i+t)),rv(e))>>>0}function lv(e,t){let{h:n,s:r,l:i}=ov(e);return sv(n,Math.max(0,Math.min(1,r+t)),i,rv(e))>>>0}function uv(e,t){let{h:n,s:r,l:i}=ov(e);return sv((n+t+360)%360,r,i,rv(e))>>>0}function dv(e){let t=[{impls:C_},{impls:w_},{impls:T_},{impls:E_},{impls:D_},{impls:O_},{impls:A_,effects:j_},{impls:N_,effects:P_},{impls:I_,effects:L_},{impls:z_,effects:B_},{impls:U_},{impls:W_},{impls:G_},{impls:K_},{impls:q_},{impls:J_},{impls:$_},{impls:av}];for(let n of t)for(let[t,r]of Object.entries(n.impls)){let i=n.effects?.[t]??B.NONE;e.setNative(t,r,i)}return e}var fv=class e extends xh{constructor(e,t){super(),this.type=e,this.value=t}type;value;static KIND=`new`;kind=e.KIND;static from(t,n){return new e(n.registry.parse(t.type,n),t.value).withComment(t.comment)}async evaluate(e,t){let n=this.type,r=n.init();if(this.value!==void 0){if(r){let i=r.args.parse(this.value),a=G(n,n.create()),o=t.child({this:a,args:i}),s=await r.run.evaluate(e,o);return s===void 0||s.raw===void 0?a:new W(n,s.raw)}let i=await n.newFill(this.value,e,t);if(i instanceof W)return e.registry.parseValue(i,n);let a=n.parse(i);return a.type===n?a:new W(n,a.raw)}return G(n,n.create())}typeOf(e,t){return this.type}validateWalk(e,t,n,r){return this.value===void 0&&gv(this.type)&&n.warn(`new.value.missing`,`\`new ${this.type.name}\` has no \`value\` \u2014 every field will fall to its type default (0 / "" / null). Provide a \`value\` matching the type's shape.`),this.value!==void 0&&n.at([`value`],()=>this.type.validateNewValue(this.value,e,t,n,r)),this.type}toCode(e,t={}){let n=this.type.toCode(void 0,t),r;return r=this.value===void 0?this.type.isOptional()?`undefined`:`new ${n}()`:typeof this.value==`number`||typeof this.value==`boolean`?String(this.value):typeof this.value==`string`?JSON.stringify(this.value):this.value===null?`null`:pv(this.value,e,this.type,t),this.commentPrefix(t)+r}toJSON(){return this.withCommentOn({kind:`new`,type:this.type.toJSON(),value:this.value})}toJSONCode(e=[],t=2,n=0){let r=this.type.toJSONCode([...e,`type`],t,n+1),i=this.value===void 0?void 0:(()=>{let e=JSON.stringify(this.value,null,t),r=n+1;return r>0?e.replace(/\n/g,`
|
|
105
|
+
`+` `.repeat(r*t)):e})(),a=i===void 0?void 0:rh(i,{path:[...e,`value`]});return V.jsonObject([{key:`kind`,value:V.jsonString(`new`)},{key:`type`,value:r},{key:`value`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.type.clone(),this.value).withComment(this.comment)}effects(){return this.type.newEffects(this.value)}complexity(){return this.type.newComplexity(this.value)}};function pv(e,t,n,r={}){if(t&&e&&typeof e==`object`&&!Array.isArray(e)&&`kind`in e&&typeof e.kind==`string`){let n=e.kind;if(t.exprClass(n))try{return t.parseExpr(e).toCode(t,{...r,expectsValue:!0})}catch{}}let i=n?n.toCode(void 0,r):`<inferred>`;if(Array.isArray(e)){let i=n?.item,a=cg(e.map(e=>mv(e,t,i,r)));return a.startsWith(`
|
|
106
|
+
`),`[${a}]`}if(e&&typeof e==`object`){let a=n?.fields,o=Object.entries(e);if(o.length===0)return`new ${i}()`;let s=cg(o.map(([e,n])=>`${e}: ${mv(n,t,a?.[e]?.type,r)}`));return s.startsWith(`
|
|
107
|
+
`)?`new ${i} {${s}}`:`new ${i} { ${s} }`}return JSON.stringify(e)}function mv(e,t,n,r={}){return e===null?`null`:e===void 0?`undefined`:typeof e==`string`?JSON.stringify(e):typeof e==`number`||typeof e==`boolean`?String(e):pv(e,t,n,r)}function hv(e){if(e instanceof Bg)return e;let t=e.base;return t?hv(t):void 0}function gv(e){let t=hv(e);if(!t)return!1;for(let e of Object.values(t.fields))if(!e.type.isOptional())return!0;return!1}function _v(e,t){let n=e.call(t);if(!n)return!1;let r=n.args;if(!(r instanceof Bg))return!0;for(let e of Object.values(r.fields))if(!e.type.isOptional())return!1;return!0}function vv(e,t,n,r){if(!e)return;let i=e.args;if(i instanceof Bg)for(let[e,a]of Object.entries(i.fields))a.type.isOptional()||e in t||n.at(r,()=>n.error(`call.missing-arg`,`missing required argument '${e}'`))}function yv(e,t){return t.type instanceof Wg?t.type.simplify(e.scope):t.type}function bv(e,t){let n=e.raw;if(!n||typeof n!=`object`)return;let r=n[t];return r instanceof W?r:void 0}function xv(e){return e instanceof Bg||e instanceof $g||e instanceof Rg&&xv(e.base)}function Sv(e,t,n){let r=[];for(let e=n;e<t.length;e++){let n=t[e];if(n instanceof wv)r.push(n.prop);else break}if(r.length===0)return``;let i=am(e,e=>Object.keys(e.props()),e=>{let t=[];for(let n of Object.keys(e.props())){let r=e.prop(n)?.type;r&&xv(r)&&t.push([n,r])}return t},r);if(!i||i.length===0)return``;if(i.length===1)return` \u2014 did you mean \`${i[0]}\`?`;let a=[];for(let e=0;e<n;e++){let n=t[e];if(n instanceof wv)a.push(n.prop);else{a.length=0;break}}return` \u2014 did you mean \`${[...a,...i].join(`.`)}\`?`}var Cv=class{static from(e,t){if(hm(e),`prop`in e)return new wv(e.prop);let n=t.registry;if(`args`in e){let r={};for(let[i,a]of Object.entries(e.args??{}))r[i]=n.parseExpr(a,t);return new Tv(r,e.generic,e.catch?n.parseExpr(e.catch,t):void 0)}if(`key`in e)return new Ev(n.parseExpr(e.key,t));throw Error(`PathStep.from: unknown step shape`)}},wv=class e extends Cv{constructor(e){super(),this.prop=e}prop;toJSON(){return{prop:this.prop}}clone(){return new e(this.prop)}complexity(){return 1}},Tv=class e extends Cv{constructor(e,t,n){super(),this.args=e,this.generic=t,this.catch_=n}args;generic;catch_;resolvedEffects;toJSON(){let e={};for(let[t,n]of Object.entries(this.args))e[t]=n.toJSON();let t={args:e};return this.generic&&(t.generic=this.generic),this.catch_&&(t.catch=this.catch_.toJSON()),t}clone(){let t={};for(let[e,n]of Object.entries(this.args))t[e]=n.clone();return new e(t,this.generic,this.catch_?.clone())}callSiteScope(e){if(!this.generic||Object.keys(this.generic).length===0)return e.scope;let t={},n=e.generic??{};for(let[r,i]of Object.entries(this.generic)){let a=e.scope.parse(i),o=n[r];if(o&&(o.name!==`alias`||o.options?.name!==r)&&!o.compatible(a))throw Error(`path: generic '${r}' binding '${a.toCode()}' does not satisfy constraint '${o.toCode()}'`);t[r]=a}return new bh(e.scope,t)}complexity(){let e=1;for(let t of Object.values(this.args))e+=t.complexity();return this.catch_&&(e+=this.catch_.complexity()),e}async buildArgsValue(e,t,n){let r=this.callSiteScope(e),i=e.call?.(r)?.args??n.registry.obj({}),a={};for(let[e,r]of Object.entries(this.args))a[e]=await r.evaluate(n,t);return new W(i,a)}},Ev=class e extends Cv{constructor(e){super(),this.key=e}key;toJSON(){return{key:this.key.toJSON()}}clone(){return new e(this.key.clone())}complexity(){return 1+this.key.complexity()}},Dv=class e{constructor(e){this.steps=e}steps;static from(t,n){return new e(t.map(e=>Cv.from(e,n)))}toJSON(){return this.steps.map(e=>e.toJSON())}toJSONCode(e=[],t=2,n=0){let r=this.steps.map((r,i)=>kv(r,[...e,i],t,n+1));return V.jsonArray(r,{path:e},n,t)}clone(){return new e(this.steps.map(e=>e.clone()))}complexity(){let e=0;for(let t of this.steps)e+=t.complexity();return e}forEachExpr(e){for(let t of this.steps)if(t instanceof Tv){for(let n of Object.values(t.args))e(n);t.catch_&&e(t.catch_)}else t instanceof Ev&&e(t.key)}toCode(e,t={}){return this.toGinCode(e,t).toString()}toGinCode(e,t={},n=[]){if(this.steps.length===0)return new V(``);let r=new V(``);for(let i=0;i<this.steps.length;i++){let a=this.steps[i],o=[...n,`path`,i];if(a instanceof wv){let e=i===0?a.prop:`.${a.prop}`;r=i===0?rh(e,{path:o}):H`${r}${rh(e,{path:o})}`}else if(a instanceof Tv){let n=Object.entries(a.args),i;if(n.length===0)i=new V(`()`);else{let r=n.map(([n,r])=>{let i=[...o,`args`,n];return H`${n}: ${r.toGinCode(e,{...t,expectsValue:!0},i)}`});i=cg(r.map(e=>e.toString())).startsWith(`
|
|
108
|
+
`)?H`({\n ${ih(r,`,
|
|
109
|
+
`)}\n})`:H`({ ${ih(r,`, `)} })`}if(r=H`${r}${rh(i,{path:o})}`,a.catch_){let n=a.catch_.toGinCode(e,{...t,expectsValue:!0},[...o,`catch`]);r=H`${r}.catch((error) => ${n})`}}else if(a instanceof Ev){let n=a.key.toGinCode(e,{...t,expectsValue:!0},[...o,`key`]);r=H`${r}${rh(H`[${n}]`,{path:o})}`}}return r}async walk(e,t,n={mode:`get`}){if(this.steps.length===0)throw Error(`Path.walk: empty path`);let r=()=>G(t.registry.bool(),!1),i=()=>G(t.registry.bool(),!0),a=null,o=0;for(;o<this.steps.length;){let s=this.steps[o],c=o===this.steps.length-1;if(n.mode===`set`&&a!==null&&Ov(a)&&!(s instanceof Tv))return r();if(s instanceof wv){if(a===null){let t=e.get(s.prop);if(t===void 0)throw Error(`path: unknown variable '${s.prop}'${nm(s.prop,e.names())}`);a=t,o++;continue}let r=a.type.prop(s.prop);if(!r){let e=n.mode===`get`?bv(a,s.prop):void 0;if(e){a=e,o++;continue}throw Error(`path: no prop '${s.prop}' on type '${a.type.name}'${Sv(a.type,this.steps,o)}`)}let l=yv(a.type,r),u=this.steps[o+1],d=u instanceof Tv;if(d&&l.call()){let c=await u.buildArgsValue(l,e,t);if(o+1===this.steps.length-1&&n.mode===`set`)return await r.invokeMethodSet(a,s.prop,c,n.setValue,e,t,l),i();try{a=await r.invokeMethod(a,s.prop,c,e,t,l)}catch(n){if(n instanceof Fh&&u.catch_){let r=e.child({error:n.error});a=await u.catch_.evaluate(t,r)}else throw n}o+=2;continue}if(!d&&_v(l)){let u=await new Tv({},void 0,void 0).buildArgsValue(l,e,t);if(c&&n.mode===`set`)return await r.invokeMethodSet(a,s.prop,u,n.setValue,e,t,l),i();a=await r.invokeMethod(a,s.prop,u,e,t,l),o++;continue}if(c&&n.mode===`set`)return await r.write(a,s.prop,n.setValue,e,t),i();a=await r.read(a,s.prop,e,t,l),o++}else if(s instanceof Ev){if(a===null)throw Error(`path: [key] cannot be the first step`);let r=a.type.get();if(!r)throw Error(`path: type '${a.type.name}' has no indexed access`);let l=await s.key.evaluate(t,e);if(c&&n.mode===`set`)return await r.indexWrite(a,l,n.setValue,e,t),i();a=await r.indexRead(a,l,e,t),o++}else if(s instanceof Tv){if(a===null)throw Error(`path: (args) cannot be the first step`);let r=a.raw,l=a.type,u=l.call(),d=await s.buildArgsValue(l,e,t);if(c&&n.mode===`set`){if(!u?.set)throw Error(`path: call on type '${l.name}' has no call.set`);let r=u.set,a=async i=>{let o=new W(l,a);return await r.evaluate(t,e.child({args:i,value:n.setValue,recurse:o})),G(t.registry.void(),void 0)};return await a(d),i()}try{if(typeof r==`function`)a=await r(d);else if(u?.get){let n=u.get,r=async i=>{let a=new W(l,r);try{return await n.evaluate(t,e.child({args:i,recurse:a}))}catch(e){if(e instanceof Nh)return e.value??G(t.registry.void(),void 0);throw e}};a=await r(d)}else throw Error(`path: value of type '${l.name}' is not callable`)}catch(n){if(n instanceof Fh&&s.catch_){let r=e.child({error:n.error});a=await s.catch_.evaluate(t,r)}else throw n}o++}else throw Error(`path: unknown step at index ${o}`)}return a}typeOf(e,t){if(this.steps.length===0)return e.registry.any();let n=null,r=0;for(;r<this.steps.length;){let i=this.steps[r];if(i instanceof wv){if(n===null){n=t.get(i.prop)??e.registry.any(),r++;continue}let a=n.prop(i.prop);if(!a)return e.registry.any();let o=yv(n,a),s=this.steps[r+1];if(s instanceof Tv&&o.call()){let t=s.callSiteScope(o),i=o.call(t)?.returns;n=i?.simplify(t)??i??e.registry.any(),r+=2;continue}if(!(s instanceof Tv)&&_v(o)){n=o.call()?.returns??e.registry.any(),r++;continue}n=o,r++}else if(i instanceof Ev)n=n?.get()?.value??e.registry.any(),r++;else if(i instanceof Tv){if(n){let t=i.callSiteScope(n),r=n.call(t)?.returns;n=r?.simplify(t)??r??e.registry.any()}else n=e.registry.any();r++}else r++}return n??e.registry.any()}validateWalk(e,t,n,r,i=`get`){if(this.steps.length===0)return n.error(`path.empty`,`path is empty`),e.registry.any();if(i===`set`&&this.steps.length===1&&this.steps[0]instanceof wv)return e.registry.any();let a=null,o=0;for(;o<this.steps.length;){let s=this.steps[o],c=o===this.steps.length-1;if(s instanceof wv){if(a===null){let r=t.get(s.prop);r?a=r:(n.at([`path`,o],()=>n.error(`var.unknown`,`unknown variable '${s.prop}'${nm(s.prop,[...t.keys()])}`)),a=e.registry.any()),o++;continue}let l=a.prop(s.prop);if(!l){n.at([`path`,o],()=>n.error(`prop.unknown`,`no prop '${s.prop}' on type '${a.name}'${Sv(a,this.steps,o)}`)),a=e.registry.any(),o++;continue}let u=yv(a,l),d=this.steps[o+1];if(d instanceof Tv&&u.call()){for(let[i,a]of Object.entries(d.args))n.at([`path`,o+1,`args`,i],()=>a.validateWalk(e,t,n,r));d.catch_&&n.at([`path`,o+1,`catch`],()=>d.catch_.validateWalk(e,t,n,r));let c=d.callSiteScope(u),l=u.call(c);vv(l,d.args,n,[`path`,o+1]),i===`set`&&o+1===this.steps.length-1&&(l?.set||n.at([`path`,o+1],()=>n.error(`set.call.no-set`,`method '${s.prop}' has no call.set`))),d.resolvedEffects=l?.effects()??0;let f=l?.returns;a=f?.simplify(c)??f??e.registry.any(),o+=2;continue}if(!(d instanceof Tv)&&_v(u)){a=u.call()?.returns??e.registry.any(),o++;continue}i===`set`&&c&&!l.set&&l.get&&!u.call()&&n.at([`path`,o],()=>n.error(`set.prop.computed`,`prop '${s.prop}' is computed (read-only); cannot assign to it`));let f=i===`get`?u.call():void 0;if(f&&!_v(u)){n.at([`path`,o],()=>n.error(`call.uncalled`,`method '${s.prop}' needs arguments \u2014 add an {args:{\u2026}} step to call it`)),a=f.returns??e.registry.any(),o++;continue}a=u,o++}else if(s instanceof Ev){n.at([`path`,o,`key`],()=>s.key.validateWalk(e,t,n,r));let l=a?.get();i===`set`&&c?l?.set||n.at([`path`,o],()=>n.error(`set.index.no-set`,`type '${a?.name??`?`}' has no index set`)):l?.get||n.at([`path`,o],()=>n.error(`index.unsupported`,`type '${a?.name??`?`}' has no indexed access`)),a=l?.value??e.registry.any(),o++}else if(s instanceof Tv){for(let[i,a]of Object.entries(s.args))n.at([`path`,o,`args`,i],()=>a.validateWalk(e,t,n,r));if(a){let t=s.callSiteScope(a),r=a.call(t);vv(r,s.args,n,[`path`,o]),i===`set`&&c&&(r?.set||n.at([`path`,o],()=>n.error(`set.call.no-set`,`call on type '${a?.name??`?`}' has no call.set`))),s.resolvedEffects=r?.effects()??0;let l=r?.returns;a=l?.simplify(t)??l??e.registry.any()}else s.resolvedEffects=0,a=e.registry.any();o++}else o++}return a??e.registry.any()}};function Ov(e){return e.raw===null||e.raw===void 0}function kv(e,t,n,r){if(e instanceof wv)return V.jsonObject([{key:`prop`,value:V.jsonString(e.prop)}],{path:t},r,n);if(e instanceof Tv){let i=Object.entries(e.args).map(([e,i])=>({key:e,value:i.toJSONCode([...t,`args`,e],n,r+2)})),a=[{key:`args`,value:V.jsonObject(i,{path:[...t,`args`]},r+1,n)}];return e.generic&&a.push({key:`generic`,value:JSON.stringify(e.generic,null,n).replace(/\n/g,`
|
|
110
|
+
`+` `.repeat(r*n))}),e.catch_&&a.push({key:`catch`,value:e.catch_.toJSONCode([...t,`catch`],n,r+1)}),V.jsonObject(a,{path:t},r,n)}return e instanceof Ev?V.jsonObject([{key:`key`,value:e.key.toJSONCode([...t,`key`],n,r+1)}],{path:t},r,n):new V(JSON.stringify(e.toJSON(),null,n))}var Av=class e extends xh{constructor(e){super(),this.path=e}path;static KIND=`get`;kind=e.KIND;static from(t,n){return new e(Dv.from(t.path,n)).withComment(t.comment)}async evaluate(e,t){return this.path.walk(t,e,{mode:`get`})}typeOf(e,t){return this.path.typeOf(e,t)}validateWalk(e,t,n,r){return this.path.validateWalk(e,t,n,r,`get`)}toGinCode(e,t={},n=[]){let r=this.path.toGinCode(e,t,n);return rh(H`${this.commentPrefix(t)}${r}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`get`,path:this.path.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.path.toJSONCode([...e,`path`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`get`)},{key:`path`,value:r},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.path.clone()).withComment(this.comment)}forEachChild(e){this.path.forEachExpr(t=>e(t,`inherit`))}effects(){let e=[];this.path.forEachExpr(t=>{e.push(t.effects())});for(let t of this.path.steps)t instanceof Tv&&t.resolvedEffects!==void 0&&e.push(t.resolvedEffects);return nh(...e)}complexity(){return this.path.complexity()}},jv=class e extends xh{constructor(e,t){super(),this.path=e,this.value=t}path;value;static KIND=`set`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){return new e(Dv.from(t.path,n),n.registry.parseExpr(t.value,n)).withComment(t.comment)}async evaluate(e,t){let n=await this.value.evaluate(e,t);return this.path.steps.length===1&&this.path.steps[0]instanceof wv?(t.set(this.path.steps[0].prop,n),G(e.registry.bool(),!0)):this.path.walk(t,e,{mode:`set`,setValue:n})}typeOf(e,t){return e.registry.bool()}validateWalk(e,t,n,r){let i=n.at(`value`,()=>this.value.validateWalk(e,t,n,r)),a=this.path.validateWalk(e,t,n,r,`set`);return a.name!==`any`&&!a.compatible(i)&&n.at(`value`,()=>n.warn(`set.type-mismatch`,`value type '${i.name}' not compatible with target '${a.name}'`)),e.registry.bool()}toGinCode(e,t={},n=[]){let r=this.path.toGinCode(e,t,n),i=this.value.toGinCode(e,{...t,expectsValue:!0},[...n,`value`]);return rh(H`${this.commentPrefix(t)}${r} = ${i}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`set`,path:this.path.toJSON(),value:this.value.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.path.toJSONCode([...e,`path`],t,n+1),i=this.value.toJSONCode([...e,`value`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`set`)},{key:`path`,value:r},{key:`value`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.path.clone(),this.value.clone()).withComment(this.comment)}forEachChild(e){this.path.forEachExpr(t=>e(t,`inherit`)),e(this.value,`inherit`)}effects(){let e=B.STATE|this.value.effects();this.path.forEachExpr(t=>{e|=t.effects()});for(let t of this.path.steps)t instanceof Tv&&t.resolvedEffects!==void 0&&(e|=t.resolvedEffects);return e}complexity(){return this.path.complexity()+this.value.complexity()}},Mv=class e extends xh{constructor(e,t){super(),this.vars=e,this.body=t}vars;body;static KIND=`define`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.vars.map(e=>({name:e.name,type:e.type?r.parse(e.type,n):void 0,value:r.parseExpr(e.value,n)}));return new e(i,r.parseExpr(t.body,n)).withComment(t.comment)}async evaluate(e,t){let n=t.child();for(let t of this.vars){let r=await t.value.evaluate(e,n);n.vars.set(t.name,r)}return this.body.evaluate(e,n)}typeOf(e,t){let n=new Map(t);for(let t of this.vars){let r=t.type??Th(e,t.value,n);n.set(t.name,r)}return Th(e,this.body,n)}validateWalk(e,t,n,r){let i=new Map(t);for(let t=0;t<this.vars.length;t++){let a=this.vars[t];n.at([`vars`,t,`name`],()=>kh(a.name,i,n));let o=n.at([`vars`,t,`value`],()=>Oh(e,a.value,i,n,r));if(a.type&&!o.isUniversal()&&!a.type.compatible(o)){let e=Nv(a.type),r=Nv(o),i=o.name===`alias`?` (hint: '${r}' is an unbound generic \u2014 either bind it via \`generic: {${r}: ...}\` on the call site, pass \`output: typ<...>\`, or omit the declared type so the alias flows through)`:``;n.at([`vars`,t,`value`],()=>n.error(`define.var.type-mismatch`,`var '${a.name}' value type '${r}' not compatible with declared '${e}'${i}`))}i.set(a.name,a.type??o)}return n.at(`body`,()=>Oh(e,this.body,i,n,r))}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i={...t,expectsValue:!0},a={...t,expectsValue:!1},o=this.vars.map((r,a)=>{let o=r.type?H`: ${r.type.toGinCode(void 0,t,[...n,`vars`,a,`type`])}`:``,s=r.value.toGinCode(e,i,[...n,`vars`,a,`value`]),c=H`let ${r.name}${o} = ${s};`;return c.text.split(`
|
|
111
|
+
`,1)[0].length<=80?c:H`let ${r.name}${o} =\n ${s.indent(` `)};`});if(r){let r=this.body.toGinCode(e,i,[...n,`body`]),a=o.map(e=>H` ${e}`),s=H` return ${r.indent(` `)};`,c=ah([...a,s]);return rh(H`${this.commentPrefix(t)}(() => {\n${c}\n})()`,{path:n,expr:this})}let s=this.body.kind,c=this.body.toGinCode(e,a,[...n,`body`]),l=s===`if`||s===`switch`||s===`loop`||s===`block`?c:H`${c};`;return rh(H`${this.commentPrefix(t)}${ah([...o,l])}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`define`,vars:this.vars.map(e=>{let t={name:e.name,value:e.value.toJSON()};return e.type&&(t.type=e.type.toJSON()),t}),body:this.body.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.vars.map((r,i)=>{let a=[...e,`vars`,i],o=r.value.toJSONCode([...a,`value`],t,n+3),s=r.type?r.type.toJSONCode([...a,`type`],t,n+3):void 0;return V.jsonObject([{key:`name`,value:V.jsonString(r.name)},{key:`value`,value:o},{key:`type`,value:s}],{path:a},n+2,t)}),i=this.body.toJSONCode([...e,`body`],t,n+1);return V.jsonObject([{key:`kind`,value:V.jsonString(`define`)},{key:`vars`,value:V.jsonArray(r,{path:[...e,`vars`]},n+1,t)},{key:`body`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.vars.map(e=>({name:e.name,type:e.type?.clone(),value:e.value.clone()})),this.body.clone()).withComment(this.comment)}forEachChild(e){for(let t of this.vars)e(t.value,`inherit`);e(this.body,`inherit`)}effects(){let e=this.body.effects();for(let t of this.vars)e|=t.value.effects();return e}complexity(){let e=1+this.body.complexity();for(let t of this.vars)e+=1+t.value.complexity();return e}};function Nv(e){try{return e.toCode()}catch{return e.name}}var Pv=class e extends xh{constructor(e){super(),this.lines=e}lines;static KIND=`block`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(t.lines.map(e=>r.parseExpr(e,n))).withComment(t.comment)}async evaluate(e,t){let n=G(e.registry.void(),void 0);for(let r of this.lines)n=await r.evaluate(e,t);return n}typeOf(e,t){return this.lines.length===0?e.registry.void():Th(e,this.lines[this.lines.length-1],t)}validateWalk(e,t,n,r){let i=e.registry.void();for(let a=0;a<this.lines.length;a++)i=n.at(a,()=>Oh(e,this.lines[a],t,n,r));return i}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1;if(this.lines.length===0)return rh(r?`undefined`:``,{path:n,expr:this});if(this.lines.length===1)return rh(this.lines[0].toGinCode(e,t,[...n,0]),{path:n,expr:this});let i=this.commentPrefix(t);return rh(r?H`${i}(() => {\n${ah(this.lines.map((r,i)=>{let a=i===this.lines.length-1,o=r.toGinCode(e,{...t,expectsValue:a},[...n,i]).indent(` `);return a?H` return ${o};`:H` ${o};`}))}\n})()`:H`${i}${ah(this.lines.map((r,i)=>{let a=r.kind,o=r.toGinCode(e,{...t,expectsValue:!1},[...n,i]);return a===`if`||a===`switch`||a===`loop`||a===`block`?o:H`${o};`}))}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`block`,lines:this.lines.map(e=>e.toJSON())})}toJSONCode(e=[],t=2,n=0){let r=this.lines.map((r,i)=>r.toJSONCode([...e,i],t,n+2));return V.jsonObject([{key:`kind`,value:V.jsonString(`block`)},{key:`lines`,value:V.jsonArray(r,{path:[...e,`lines`]},n+1,t)},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.lines.map(e=>e.clone())).withComment(this.comment)}forEachChild(e){for(let t of this.lines)e(t,`inherit`)}effects(){let e=B.NONE;for(let t of this.lines)e|=t.effects();return e}complexity(){let e=1;for(let t of this.lines)e+=t.complexity();return e}},Fv=class e extends xh{constructor(e,t,n){super(),this.action=e,this.value=t,this.error=n}action;value;error;static KIND=`flow`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(t.action,t.value?r.parseExpr(t.value,n):void 0,t.error?r.parseExpr(t.error,n):void 0).withComment(t.comment)}async evaluate(e,t){switch(this.action){case`break`:throw new jh;case`continue`:throw new Mh;case`return`:throw new Nh(this.value?await this.value.evaluate(e,t):void 0);case`exit`:throw new Ph(this.value?await this.value.evaluate(e,t):void 0);case`throw`:throw this.error?new Fh(await this.error.evaluate(e,t)):Error("flow.throw requires `error`")}}typeOf(e,t){return e.registry.void()}validateWalk(e,t,n,r){return this.action!==`break`&&this.action!==`continue`||r.inLoop||n.error(`flow.outside-loop`,`${this.action} used outside a loop`),this.action===`return`&&!r.inLambda&&n.warn(`flow.outside-lambda`,`return used outside a lambda`),this.action===`throw`&&!this.error&&n.error(`flow.throw.no-error`,"throw requires an `error` expression"),this.value&&n.at(`value`,()=>Oh(e,this.value,t,n,r)),this.error&&n.at(`error`,()=>Oh(e,this.error,t,n,r)),e.registry.void()}toGinCode(e,t={},n=[]){let r=this.commentPrefix(t),i={...t,expectsValue:!0},a;switch(this.action){case`break`:a=new V(`break`);break;case`continue`:a=new V(`continue`);break;case`return`:a=this.value?H`return ${this.value.toGinCode(e,i,[...n,`value`])}`:new V(`return`);break;case`throw`:a=this.error?H`throw ${this.error.toGinCode(e,i,[...n,`error`])}`:new V(`throw`);break;case`exit`:a=this.value?H`exit ${this.value.toGinCode(e,i,[...n,`value`])}`:new V(`exit`);break;default:a=new V(``)}return rh(H`${r}${a}`,{path:n,expr:this})}toJSONCode(e=[],t=2,n=0){let r=this.value?this.value.toJSONCode([...e,`value`],t,n+1):void 0,i=this.error?this.error.toJSONCode([...e,`error`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`flow`)},{key:`action`,value:V.jsonString(this.action)},{key:`value`,value:r},{key:`error`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}toJSON(){let e={kind:`flow`,action:this.action};return this.value&&(e.value=this.value.toJSON()),this.error&&(e.error=this.error.toJSON()),this.withCommentOn(e)}clone(){return new e(this.action,this.value?.clone(),this.error?.clone()).withComment(this.comment)}forEachChild(e){this.value&&e(this.value,`inherit`),this.error&&e(this.error,`inherit`)}effects(){return B.STATE|(this.value?.effects()??B.NONE)|(this.error?.effects()??B.NONE)}complexity(){return 1+(this.value?.complexity()??0)+(this.error?.complexity()??0)}};function Iv(e){return e.replace(/\n/g,`
|
|
112
|
+
`)}function Lv(e,t=`inherit`){if(e instanceof Fv)return e.action===`throw`||e.action===`exit`?e:e.action===`return`?t===`lambda`?void 0:e:e.action===`break`||e.action===`continue`?t===`loop`?void 0:e:void 0;let n;return e.forEachChild((e,r)=>{if(n)return;let i=Lv(e,r===`inherit`?t:r);i&&(n=i)}),n}var Rv=class e extends xh{constructor(e,t){super(),this.ifs=e,this.otherwise=t}ifs;otherwise;static KIND=`if`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.ifs.map(e=>({condition:r.parseExpr(e.condition,n),body:r.parseExpr(e.body,n)}));return new e(i,t.else?r.parseExpr(t.else,n):void 0).withComment(t.comment)}async evaluate(e,t){for(let n of this.ifs)if((await n.condition.evaluate(e,t)).raw)return n.body.evaluate(e,t);return this.otherwise?this.otherwise.evaluate(e,t):G(e.registry.void(),void 0)}typeOf(e,t){let n=this.ifs.map(n=>Th(e,n.body,t));return this.otherwise&&n.push(Th(e,this.otherwise,t)),n.length===1?n[0]:e.registry.or(n)}validateWalk(e,t,n,r){let i=e.registry.bool(),a=[];for(let o=0;o<this.ifs.length;o++){let s=this.ifs[o],c=n.at([`ifs`,o,`condition`],()=>Oh(e,s.condition,t,n,r));if(!i.compatible(c)){let e;try{e=c.toCode()}catch{e=c.name}n.at([`ifs`,o,`condition`],()=>n.warn(`if.condition.type`,`if condition should be bool, got '${e}' (did you forget to call a method?)`))}a.push(n.at([`ifs`,o,`body`],()=>Oh(e,s.body,t,n,r)))}for(let e=0;e<this.ifs.length;e++)this.ifs[e].body.effects()===B.NONE&&n.at([`ifs`,e,`body`],()=>n.warn(`if.branch.no-effect`,"if branch body has no observable effect — when this branch matches, nothing happens. Either give it a `set`/`flow`/native call, or drop the branch entirely"));return this.otherwise&&(a.push(n.at(`else`,()=>Oh(e,this.otherwise,t,n,r))),this.otherwise.effects()===B.NONE&&n.at(`else`,()=>n.warn(`if.else.no-effect`,"else arm has no observable effect — `else` is optional; OMIT it entirely when its only purpose is producing a placeholder value"))),a.length===1?a[0]:e.registry.or(a)}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i=this.ifs.some(e=>!!Lv(e.body))||(this.otherwise?!!Lv(this.otherwise):!1),a=this.commentPrefix(t),o={...t,expectsValue:!0};if(r&&!i){if(this.ifs.length===1&&this.otherwise){let t=this.ifs[0];return rh(H`${a}(${t.condition.toGinCode(e,o,[...n,`ifs`,0,`condition`])} ? ${t.body.toGinCode(e,o,[...n,`ifs`,0,`body`])} : ${this.otherwise.toGinCode(e,o,[...n,`else`])})`,{path:n,expr:this})}let t=H``;for(let r=0;r<this.ifs.length;r++){let i=this.ifs[r],a=r===0?`if`:`else if`,s=i.condition.toGinCode(e,o,[...n,`ifs`,r,`condition`]),c=i.body.toGinCode(e,o,[...n,`ifs`,r,`body`]);t=H`${t}${r===0?``:`
|
|
113
|
+
`} ${a} (${s}) return ${c.indent(` `)};`}let r=``;return this.otherwise&&(r=H`\n return ${this.otherwise.toGinCode(e,o,[...n,`else`]).indent(` `)};`),rh(H`${a}(() => {\n${t}${r}\n})()`,{path:n,expr:this})}let s=H``;for(let r=0;r<this.ifs.length;r++){let i=this.ifs[r],a=r===0?`if`:`else if`,c=r===0?``:` `,l=i.condition.toGinCode(e,o,[...n,`ifs`,r,`condition`]),u=i.body.renderStatementBodyRich(e,t,[...n,`ifs`,r,`body`]);s=H`${s}${c}${a} (${l}) ${u}`}if(this.otherwise){let r=this.otherwise.renderStatementBodyRich(e,t,[...n,`else`],!0);s=H`${s} else ${r}`}return rh(H`${a}${s}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`if`,ifs:this.ifs.map(e=>({condition:e.condition.toJSON(),body:e.body.toJSON()})),else:this.otherwise?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.ifs.map((r,i)=>{let a=[...e,`ifs`,i];return V.jsonObject([{key:`condition`,value:r.condition.toJSONCode([...a,`condition`],t,n+3)},{key:`body`,value:r.body.toJSONCode([...a,`body`],t,n+3)}],{path:a},n+2,t)}),i=this.otherwise?this.otherwise.toJSONCode([...e,`else`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`if`)},{key:`ifs`,value:V.jsonArray(r,{path:[...e,`ifs`]},n+1,t)},{key:`else`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.ifs.map(e=>({condition:e.condition.clone(),body:e.body.clone()})),this.otherwise?.clone()).withComment(this.comment)}forEachChild(e){for(let t of this.ifs)e(t.condition,`inherit`),e(t.body,`inherit`);this.otherwise&&e(this.otherwise,`inherit`)}effects(){let e=B.NONE;for(let t of this.ifs)e|=t.condition.effects()|t.body.effects();return this.otherwise&&(e|=this.otherwise.effects()),e}complexity(){let e=1;for(let t of this.ifs)e+=t.condition.complexity()+t.body.complexity();return this.otherwise&&(e+=this.otherwise.complexity()),e}},zv=class e extends xh{constructor(e,t,n){super(),this.value=e,this.cases=t,this.otherwise=n}value;cases;otherwise;static KIND=`switch`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry;return new e(r.parseExpr(t.value,n),t.cases.map(e=>({equals:e.equals.map(e=>r.parseExpr(e,n)),body:r.parseExpr(e.body,n)})),t.else?r.parseExpr(t.else,n):void 0).withComment(t.comment)}async evaluate(e,t){let n=await this.value.evaluate(e,t);for(let r of this.cases)for(let i of r.equals)if((await i.evaluate(e,t)).raw===n.raw)return r.body.evaluate(e,t);return this.otherwise?this.otherwise.evaluate(e,t):G(e.registry.void(),void 0)}typeOf(e,t){let n=this.cases.map(n=>Th(e,n.body,t));return this.otherwise&&n.push(Th(e,this.otherwise,t)),n.length===0?e.registry.void():n.length===1?n[0]:e.registry.or(n)}validateWalk(e,t,n,r){let i=n.at(`value`,()=>Oh(e,this.value,t,n,r)),a=[];for(let o=0;o<this.cases.length;o++){let s=this.cases[o];for(let a=0;a<s.equals.length;a++){let c=n.at([`cases`,o,`equals`,a],()=>Oh(e,s.equals[a],t,n,r));i.compatible(c)||n.at([`cases`,o,`equals`,a],()=>n.warn(`switch.case.type`,`case value type '${c.name}' not compatible with switch value '${i.name}'`))}a.push(n.at([`cases`,o,`body`],()=>Oh(e,s.body,t,n,r))),s.body.effects()===B.NONE&&n.at([`cases`,o,`body`],()=>n.warn(`switch.case.no-effect`,"switch case body has no observable effect — when this case matches, nothing happens. Either give it a `set`/`flow`/native call, or drop the case"))}return this.otherwise&&(a.push(n.at(`else`,()=>Oh(e,this.otherwise,t,n,r))),this.otherwise.effects()===B.NONE&&n.at(`else`,()=>n.warn(`switch.else.no-effect`,`switch default has no observable effect — OMIT it instead of carrying a placeholder fallback`))),a.length===0?e.registry.void():a.length===1?a[0]:e.registry.or(a)}toGinCode(e,t={},n=[]){let r=t.expectsValue??!1,i=this.cases.some(e=>!!Lv(e.body))||(this.otherwise?!!Lv(this.otherwise):!1),a={...t,expectsValue:!0},o=this.value.toGinCode(e,a,[...n,`value`]),s=this.commentPrefix(t);if(r&&!i){let t=ah(this.cases.map((t,r)=>H`${ah(t.equals.map((t,i)=>H` case ${t.toGinCode(e,a,[...n,`cases`,r,`equals`,i])}:`))}\n return ${t.body.toGinCode(e,a,[...n,`cases`,r,`body`]).indent(` `)};`)),r=``;return this.otherwise&&(r=H`\n default:\n return ${this.otherwise.toGinCode(e,a,[...n,`else`]).indent(` `)};`),rh(H`${s}(() => {\n switch (${o}) {\n${t}${r}\n }\n})()`,{path:n,expr:this})}let c=(n,r)=>{let i=n.kind;return n instanceof Fv?H`${n.toGinCode(e,{...t,expectsValue:!1},r)};`:i===`block`||i===`if`||i===`switch`||i===`loop`?n.toGinCode(e,{...t,expectsValue:!1},r):H`${n.toGinCode(e,{...t,expectsValue:!0},r)};`},l=ah(this.cases.map((t,r)=>{let i=ah(t.equals.map((t,i)=>H` case ${t.toGinCode(e,a,[...n,`cases`,r,`equals`,i])}:`)),o=[...n,`cases`,r,`body`];return H`${i}\n ${c(t.body,o).indent(` `)}${t.body instanceof Fv?``:`
|
|
114
|
+
break;`}`})),u=``;return this.otherwise&&(u=H`\n default:\n ${c(this.otherwise,[...n,`else`]).indent(` `)}`),rh(H`${s}switch (${o}) {\n${l}${u}\n}`,{path:n,expr:this})}toJSON(){return this.withCommentOn({kind:`switch`,value:this.value.toJSON(),cases:this.cases.map(e=>({equals:e.equals.map(e=>e.toJSON()),body:e.body.toJSON()})),else:this.otherwise?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.value.toJSONCode([...e,`value`],t,n+1),i=this.cases.map((r,i)=>{let a=[...e,`cases`,i],o=r.equals.map((e,r)=>e.toJSONCode([...a,`equals`,r],t,n+4));return V.jsonObject([{key:`equals`,value:V.jsonArray(o,{path:[...a,`equals`]},n+3,t)},{key:`body`,value:r.body.toJSONCode([...a,`body`],t,n+3)}],{path:a},n+2,t)}),a=this.otherwise?this.otherwise.toJSONCode([...e,`else`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`switch`)},{key:`value`,value:r},{key:`cases`,value:V.jsonArray(i,{path:[...e,`cases`]},n+1,t)},{key:`else`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.value.clone(),this.cases.map(e=>({equals:e.equals.map(e=>e.clone()),body:e.body.clone()})),this.otherwise?.clone()).withComment(this.comment)}forEachChild(e){e(this.value,`inherit`);for(let t of this.cases){for(let n of t.equals)e(n,`inherit`);e(t.body,`inherit`)}this.otherwise&&e(this.otherwise,`inherit`)}effects(){let e=this.value.effects();for(let t of this.cases){for(let n of t.equals)e|=n.effects();e|=t.body.effects()}return this.otherwise&&(e|=this.otherwise.effects()),e}complexity(){let e=1+this.value.complexity();for(let t of this.cases){for(let n of t.equals)e+=n.complexity();e+=t.body.complexity()}return this.otherwise&&(e+=this.otherwise.complexity()),e}},Bv=class e extends xh{constructor(e,t,n,r,i){super(),this.over=e,this.body=t,this.keyName=n,this.valueName=r,this.parallel=i}over;body;keyName;valueName;parallel;static KIND=`loop`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=t.parallel?{concurrent:t.parallel.concurrent?r.parseExpr(t.parallel.concurrent,n):void 0,rate:t.parallel.rate?r.parseExpr(t.parallel.rate,n):void 0}:void 0;return new e(r.parseExpr(t.over,n),r.parseExpr(t.body,n),t.key,t.value,i).withComment(t.comment)}async evaluate(e,t){let n=await this.over.evaluate(e,t),r=n.type.get();if(!(r?.loop||r?.loopDynamic))throw Error(`loop: type '${n.type.name}' has no loop or loopDynamic defined on its GetSet`);let i=this.keyName??`key`,a=this.valueName??`value`,o=this.parallel?.concurrent?Number((await this.parallel.concurrent.evaluate(e,t)).raw):void 0,s=this.parallel?.rate?Number((await this.parallel.rate.evaluate(e,t)).raw):void 0,c=o!==void 0||s!==void 0;if(r.loopDynamic){let r=e.registry.num({whole:!0,min:0});if(!c){let o=n,s=0;for(;o.raw;){await t.checkpoint();let n=t.child({[i]:G(r,s),[a]:o});try{await this.body.evaluate(e,n)}catch(e){if(e instanceof jh)break;if(!(e instanceof Mh))throw e}s++,o=await this.over.evaluate(e,t)}return G(e.registry.void(),void 0)}let l=new Set,u=o??1/0,d=!1,f=0,p=0,m=async()=>{if(d)return!1;await t.checkpoint();let n=await this.over.evaluate(e,t);if(!n.raw)return!1;if(s&&s>0){let e=Date.now()-f;e<s&&await new Promise(t=>setTimeout(t,s-e)),f=Date.now()}let o=t.child({[i]:G(r,p),[a]:n}),c=(async()=>{try{await this.body.evaluate(e,o)}catch(e){if(e instanceof Mh)return;if(e instanceof jh){d=!0;return}throw e}})().finally(()=>l.delete(c));return l.add(c),p++,!0},h=Number.isFinite(u)?u:1;for(;l.size<h&&await m(););for(;l.size>0;)for(await Promise.race(l);!d&&l.size<h&&await m(););return G(e.registry.void(),void 0)}let l=r.loop;if(!l)throw Error(`loop: type '${n.type.name}' has no loop ExprDef on its GetSet`);if(!c)return await Vv(l,t,e,n,async(n,r)=>{let o=t.child({[i]:n,[a]:r});try{return await this.body.evaluate(e,o)}catch(t){if(t instanceof Mh)return G(e.registry.void(),void 0);throw t}}),G(e.registry.void(),void 0);let u=new Set,d=o??1/0,f=!1,p=0;return await Vv(r.loop,t,e,n,async(n,r)=>{if(f)return G(e.registry.void(),void 0);if(s&&s>0){let e=Date.now()-p;e<s&&await new Promise(t=>setTimeout(t,s-e)),p=Date.now()}for(;u.size>=d;)await Promise.race(u);let o=t.child({[i]:n,[a]:r}),c=(async()=>{try{await this.body.evaluate(e,o)}catch(e){if(e instanceof Mh)return;if(e instanceof jh){f=!0;return}throw e}})().finally(()=>u.delete(c));return u.add(c),G(e.registry.void(),void 0)}),await Promise.all(u),G(e.registry.void(),void 0)}typeOf(e,t){return e.registry.void()}validateWalk(e,t,n,r){let i=n.at(`over`,()=>Oh(e,this.over,t,n,r)),a=i.get();if(a?.loop||a?.loopDynamic||n.error(`loop.not-iterable`,`type '${i.name}' has no loop defined`),this.parallel?.concurrent){let i=n.at([`parallel`,`concurrent`],()=>Oh(e,this.parallel.concurrent,t,n,r));e.registry.num().compatible(i)||n.at([`parallel`,`concurrent`],()=>n.error(`loop.parallel.concurrent.type`,`parallel.concurrent must be a number, got '${i.name}'`))}if(this.parallel?.rate){let i=n.at([`parallel`,`rate`],()=>Oh(e,this.parallel.rate,t,n,r)),a=e.registry.num().compatible(i),o=e.registry.duration().compatible(i);!a&&!o&&n.at([`parallel`,`rate`],()=>n.error(`loop.parallel.rate.type`,`parallel.rate must be a number or duration, got '${i.name}'`))}this.keyName===void 0?t.has(`key`)&&n.error(`loop.key.shadow`,`loop's default 'key' is already in scope from an enclosing loop — set the \`key\` field on this loop to a distinct name (e.g. "i", "j", "outerKey") so the inner loop doesn't shadow the outer iteration index`):n.at(`key`,()=>kh(this.keyName,t,n)),this.valueName===void 0?t.has(`value`)&&n.error(`loop.value.shadow`,`loop's default 'value' is already in scope from an enclosing loop — set the \`value\` field on this loop to a distinct name (e.g. "v", "row", "outerValue") so the inner loop doesn't shadow the outer iteration value`):n.at(`value`,()=>kh(this.valueName,t,n));let o=a?.key??e.registry.any(),s=a?.value??e.registry.any(),c=new Map(t);return c.set(this.keyName??`key`,o),c.set(this.valueName??`value`,s),n.at(`body`,()=>Oh(e,this.body,c,n,{...r,inLoop:!0})),this.body.effects()===B.NONE&&n.at(`body`,()=>n.warn(`loop.body.no-effect`,"loop body has no observable effect — the iteration's computed value is discarded. Add a `set` to accumulate into an outer var, a `flow` to control iteration, or invoke a side-effecting native (e.g. `fns.log`, `fns.fetch`)")),e.registry.void()}toCode(e,t={}){let n=t.expectsValue??!1,r={...t,expectsValue:!0},i={...t,expectsValue:!1},a=this.over.toCode(e,r),o=this.keyName??`key`,s=this.valueName??`value`,c=``;t.includeComments!==!1&&(this.parallel?.concurrent&&(c+=`/* parallel.concurrent: ${this.parallel.concurrent.toCode(e,r)} */ `),this.parallel?.rate&&(c+=`/* parallel.rate: ${this.parallel.rate.toCode(e,r)} */ `));let l=(()=>{let t=this.body.kind;if(t===`flow`)return`${this.body.toCode(e,i)};`;if(t===`block`){let t=this.body.toCode(e,i);return t.startsWith(`{`)?t.slice(1,-1).trim():t}return t===`if`||t===`switch`||t===`loop`?this.body.toCode(e,i):`${this.body.toCode(e,i)};`})(),u=`${c}for (const [${o}, ${s}] of ${a}) {
|
|
115
|
+
${Iv(l)}
|
|
116
|
+
}`,d=this.commentPrefix(t);return n?d+`(() => { ${u}; return undefined; })()`:d+u}toJSON(){let e={kind:`loop`,over:this.over.toJSON(),body:this.body.toJSON()};return this.keyName!==void 0&&(e.key=this.keyName),this.valueName!==void 0&&(e.value=this.valueName),this.parallel&&(e.parallel={concurrent:this.parallel.concurrent?.toJSON(),rate:this.parallel.rate?.toJSON()}),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.over.toJSONCode([...e,`over`],t,n+1),i=this.body.toJSONCode([...e,`body`],t,n+1),a=this.parallel?V.jsonObject([{key:`concurrent`,value:this.parallel.concurrent?.toJSONCode([...e,`parallel`,`concurrent`],t,n+2)},{key:`rate`,value:this.parallel.rate?.toJSONCode([...e,`parallel`,`rate`],t,n+2)}],{path:[...e,`parallel`]},n+1,t):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`loop`)},{key:`over`,value:r},{key:`body`,value:i},{key:`key`,value:this.keyName===void 0?void 0:V.jsonString(this.keyName)},{key:`value`,value:this.valueName===void 0?void 0:V.jsonString(this.valueName)},{key:`parallel`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.over.clone(),this.body.clone(),this.keyName,this.valueName,this.parallel?{concurrent:this.parallel.concurrent?.clone(),rate:this.parallel.rate?.clone()}:void 0).withComment(this.comment)}forEachChild(e){e(this.over,`inherit`),e(this.body,`loop`),this.parallel?.concurrent&&e(this.parallel.concurrent,`inherit`),this.parallel?.rate&&e(this.parallel.rate,`inherit`)}effects(){return this.over.effects()|this.body.effects()|(this.parallel?.concurrent?.effects()??B.NONE)|(this.parallel?.rate?.effects()??B.NONE)}complexity(){return 6+this.over.complexity()+this.body.complexity()+(this.parallel?.concurrent?.complexity()??0)+(this.parallel?.rate?.complexity()??0)}};async function Vv(e,t,n,r,i){let a=n.registry,o=new W(a.fn({args:a.obj({key:{type:a.any()},value:{type:a.any()}}),returns:a.void()}),async e=>{let t=e.raw;if(!t)throw Error(`yield: missing args`);return await s.checkpoint(),i(t.key,t.value)}),s=t.child({this:r,yield:o});try{await e.evaluate(n,s)}catch(e){if(!(e instanceof jh))throw e}}var Hv=class e extends xh{constructor(e,t,n){super(),this.fnType=e,this.body=t,this.constraint=n}fnType;body;constraint;static KIND=`lambda`;kind=e.KIND;useLineComment(e={}){return!e.expectsValue}static from(t,n){let r=n.registry,i=r.parse(t.type,n),a=Gv(n,i),o=r.parseExpr(t.body,a),s=t.constraint?r.parseExpr(t.constraint,a):void 0;return new e(i,o,s).withComment(t.comment)}async evaluate(e,t){let n=this.fnType,r=this.body,i=t,a=this.constraint,o=async t=>{await i.checkpoint();let s=new W(n,o),c=i.child({args:t,recurse:s});if(a&&(await a.evaluate(e,c)).raw!==!0)throw Error(`lambda constraint failed: ${a.toCode(e.registry,{expectsValue:!0})}`);try{return await r.evaluate(e,c)}catch(t){if(t instanceof Nh)return t.value??new W(e.registry.void(),void 0);throw t}};return new W(n,o)}typeOf(e,t){return this.fnType}validateWalk(e,t,n,r){let i=this.fnType.call(),a=new Map(t);a.set(`args`,i?.args??e.registry.any());let o=n.at(`body`,()=>Oh(e,this.body,a,n,{...r,inLambda:!0}));if(i?.returns&&!i.returns.compatible(o)&&n.at(`body`,()=>n.warn(`lambda.returns.type`,`body type '${o.name}' not compatible with declared returns '${i.returns.name}'`)),this.constraint){let t=e.registry.bool(),i=n.at(`constraint`,()=>Oh(e,this.constraint,a,n,{...r,inLambda:!0}));t.compatible(i)||n.at(`constraint`,()=>n.warn(`lambda.constraint.type`,`constraint must return bool, got '${i.name}'`))}return this.fnType}toGinCode(e,t={},n=[]){let r=this.fnType.call(),i={...t,expectsValue:!0},a=this.commentPrefix(t),o=`(${Uv(r?.args,t)})${r?.returns?`: ${r.returns.toCode(void 0,t)}`:``}`,s=this.body.toGinCode(e,i,[...n,`body`]),c=s.text,l;return l=this.constraint?H`${o} => {\n if (!(${Wv(this.constraint.toGinCode(e,i,[...n,`constraint`]))})) throw new Error('constraint');\n return ${s.indent(` `)};\n}`:c.includes(`
|
|
117
|
+
`)?H`${o} => {\n ${s.indent(` `)}\n}`:H`${o} => ${s}`,rh(a?H`${a}${l}`:l,{path:n,expr:this})}toCode(e,t={}){return this.toGinCode(e,t).toString()}toJSON(){return this.withCommentOn({kind:`lambda`,type:this.fnType.toJSON(),body:this.body.toJSON(),constraint:this.constraint?.toJSON()})}toJSONCode(e=[],t=2,n=0){let r=this.fnType.toJSONCode([...e,`type`],t,n+1),i=this.body.toJSONCode([...e,`body`],t,n+1),a=this.constraint?this.constraint.toJSONCode([...e,`constraint`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`lambda`)},{key:`type`,value:r},{key:`body`,value:i},{key:`constraint`,value:a},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.fnType.clone(),this.body.clone(),this.constraint?.clone()).withComment(this.comment)}forEachChild(e){e(this.body,`lambda`),this.constraint&&e(this.constraint,`lambda`)}effects(){return B.NONE}complexity(){return 10+this.body.complexity()+(this.constraint?.complexity()??0)}};function Uv(e,t){if(!e||e.name===`void`||e.name===`any`)return``;let n=e.fields;if(!n)return`args: ${e.toCode(void 0,t)}`;let r=Object.entries(n);return r.length===0?``:r.map(([e,n])=>{let r=n.type.isOptional?.()??!1,i=r&&typeof n.type.required==`function`?n.type.required():n.type;return`${n.docs&&t.includeComments!==!1?`/* ${n.docs} */ `:``}${e}${r?`?`:``}: ${i.toCode(void 0,t)}`}).join(`, `)}function Wv(e){return e.text.includes(`
|
|
118
|
+
`)?new V(e.text.replace(/\n\s*/g,` `),e.spans):e}function Gv(e,t){let n=new bh(e),r=t.call();if(r?.types)for(let[e,t]of Object.entries(r.types))n.bind(e,t);return n}var Kv=class e extends xh{constructor(e,t){super(),this.template=e,this.params=t}template;params;static KIND=`template`;kind=e.KIND;static from(t,n){let r=n.registry,i=t.template,a=i&&typeof i==`object`&&`kind`in i?r.parseExpr(i,n):r.parseExpr({kind:`new`,type:{name:`text`},value:String(i)},n),o=t.params?r.parseExpr(t.params,n):void 0;return new e(a,o).withComment(t.comment)}async evaluate(e,t){let n=await this.template.evaluate(e,t),r=String(n.raw),i;this.params&&(i=(await this.params.evaluate(e,t)).raw);let a=r.replace(/\{(\w+)\}/g,(e,n)=>{if(i&&Object.prototype.hasOwnProperty.call(i,n)){let e=i[n];return e==null?``:e instanceof W?String(e.raw??``):String(e)}let r=t.get(n);return r===void 0?``:r instanceof W?String(r.raw??``):String(r)});return G(e.registry.text(),a)}typeOf(e,t){return e.registry.text()}validateWalk(e,t,n,r){let i=e.registry.text(),a=n.at(`template`,()=>Oh(e,this.template,t,n,r));i.compatible(a)||n.at(`template`,()=>n.warn(`template.template.type`,`template should resolve to text, got '${a.name}'`));let o,s=!1;if(this.params){let i=n.at(`params`,()=>Oh(e,this.params,t,n,r));if(i.name===`any`)s=!0;else if(i.name===`obj`||i.name===`iface`){let e=i.props(),t=Object.entries(e).filter(([,e])=>!e.type.call()).map(([e])=>e);o=new Set(t)}else n.at(`params`,()=>n.warn(`template.params.type`,`template params should be an object, got '${i.name}'`)),s=!0}let c=this.template instanceof fv&&typeof this.template.value==`string`?this.template.value:void 0;if(c!==void 0){let e=new Set,r=/\{(\w+)\}/g,i;for(;(i=r.exec(c))!==null;){let r=i[1];if(e.has(r))continue;e.add(r);let a=o?.has(r)??!1,c=t.has(r);s?c||n.error(`template.placeholder.unresolved`,`placeholder '{${r}}' isn't a scope variable; either define '${r}' in scope or pass a typed obj as \`params\` so it can be checked`):!a&&!c&&n.error(`template.placeholder.unresolved`,this.params?`placeholder '{${r}}' is not a key of \`params\` (keys: [${[...o??[]].join(`, `)||`none`}]) and not a scope variable`:`placeholder '{${r}}' does not match any scope variable; either \`define ${r} = ...\` first or pass it via \`params\``)}}return e.registry.text()}toCode(e,t={}){let n=this.commentPrefix(t),r=this.template instanceof fv&&typeof this.template.value==`string`?this.template.value:void 0;if(r===void 0){let r=e.toCode(this.template,{...t,expectsValue:!0});return this.params?`${n}template(${r}, ${e.toCode(this.params,{...t,expectsValue:!0})})`:`${n}template(${r})`}let i=this.params?qv(this.params,e):void 0;return`${n}${`\`${r.replace(/\{(\w+)\}/g,(e,t)=>{if(i&&Object.prototype.hasOwnProperty.call(i,t)){let e=i[t];return e.length>64?`\${
|
|
119
119
|
`+e+`
|
|
120
|
-
}`:"${"+e+`}`}return"${"+t+`}`}).replace(/`/g,"\\`")}\``}`}toJSON(){return this.withCommentOn({kind:`template`,template:this.template.toJSON(),...this.params?{params:this.params.toJSON()}:{}})}toJSONCode(e=[],t=2,n=0){let r=this.template.toJSONCode([...e,`template`],t,n+1),i=this.params?this.params.toJSONCode([...e,`params`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`template`)},{key:`template`,value:r},{key:`params`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.template.clone(),this.params?.clone()).withComment(this.comment)}forEachChild(e){e(this.template,`inherit`),this.params&&e(this.params,`inherit`)}effects(){return this.template.effects()|(this.params?.effects()??B.NONE)}complexity(){return 1+this.template.complexity()+(this.params?.complexity()??0)}};function Tv(e,t){if(!(e instanceof W_))return;let n=e.value;if(!n||typeof n!=`object`||Array.isArray(n))return;let r={};for(let[e,i]of Object.entries(n))if(typeof i==`string`)r[e]=JSON.stringify(i);else if(typeof i==`number`||typeof i==`boolean`)r[e]=String(i);else if(i===null)r[e]=`null`;else if(i&&typeof i==`object`&&`kind`in i&&typeof i.kind==`string`&&t.exprClass(i.kind))try{r[e]=t.parseExpr(i).toCode(t,{expectsValue:!0})}catch{return}else return;return r}var Ev=class e extends $m{constructor(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){super(),this.id=e,this.type=t,this.resolvedEffects=n}id;type;resolvedEffects;static KIND=`native`;kind=e.KIND;static from(t,n){return new e(t.id,t.type?n.registry.parse(t.type,n):void 0,n.registry.nativeEffects(t.id)).withComment(t.comment)}async evaluate(e,t){let n=e.registry.getNative(this.id);if(!n)throw Error(`native: no impl registered for '${this.id}'`);let r=await n(t,e.registry);return r instanceof W?r:G(this.type??e.registry.any(),r)}typeOf(e,t){return this.type??e.registry.any()}validateWalk(e,t,n,r){return e.registry.getNative(this.id)||n.warn(`native.unknown`,`native impl '${this.id}' is not registered`),this.type??e.registry.any()}toCode(e,t={}){return this.commentPrefix(t)+`/* native: ${this.id} */`}toJSON(){let e={kind:`native`,id:this.id};return this.type&&(e.type=this.type.toJSON()),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.type?this.type.toJSONCode([...e,`type`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`native`)},{key:`id`,value:V.jsonString(this.id)},{key:`type`,value:r},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.id,this.type?.clone(),this.resolvedEffects).withComment(this.comment)}effects(){return this.resolvedEffects}complexity(){return 1}},Dv=[`props`,`get`,`call`,`init`],Ov=class{classes=new Map;namedTypes=new Map;natives=new Map;nativeEffectsMap=new Map;exprClasses=new Map;augments=new Map;_version=0;get version(){return this._version}parent=void 0;get registry(){return this}define(e){return this.classes.set(e.NAME,e),this._version++,this}register(e){return this.namedTypes.set(e.name,e),this._version++,this}scope(e){return new Qm(this,{...e})}augment(e,t){this._version++;let n={props:t.props?jh.fromMap(t.props,this):void 0,get:t.get?Mh.from(t.get,this):void 0,call:t.call?Nh.from(t.call,this):void 0,init:t.init?Ph.from(t.init,this):void 0},r=this.augments.get(e);return r?(this.augments.set(e,{props:n.props?{...r.props??{},...n.props}:r.props,get:r.get??n.get,call:r.call??n.call,init:r.init??n.init}),this):(this.augments.set(e,{props:n.props?{...n.props}:void 0,get:n.get,call:n.call,init:n.init}),this)}augmentation(e){return this.augments.get(e)}lookup(e){if(this.namedTypes.has(e))return this.namedTypes.get(e);let t=this.classes.get(e);if(t)return t.from({name:e},this)}localLookup(e){}setNative(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){return this.natives.set(e,t),this.nativeEffectsMap.set(e,n),this}getNative(e){return this.natives.get(e)}nativeEffects(e){let t=this.nativeEffectsMap.get(e);return t===void 0?B.STATE|B.SYSTEM|B.EXTERNAL:t}defineExpr(e){return this.exprClasses.set(e.KIND,e),this._version++,this}exprClass(e){return this.exprClasses.get(e)}typeClasses(){return Array.from(this.classes.values())}typeClass(e){return this.classes.get(e)}namedTypeList(){return Array.from(this.namedTypes.values())}exprClassList(){return Array.from(this.exprClasses.values())}typeNameCandidates(){return[...this.typeClasses().map(e=>e.NAME),...this.namedTypeList().map(e=>e.name)]}parseExpr(e,t=this){if(e==null)return;if(e instanceof $m)return e;if(typeof e!=`object`||!(`kind`in e))throw Error(`registry.parseExpr: expected ExprDef with kind, got ${typeof e}`);let n=e,r=this.exprClasses.get(n.kind);if(!r)throw Error(`registry.parseExpr: unknown expr kind '${n.kind}'`);return r.from(n,t)}toCode(e,t){return(e instanceof $m?e:this.parseExpr(e)).toCode(this,t)}toGinCode(e,t){return(e instanceof $m?e:this.parseExpr(e)).toGinCode(this,t,[])}toJSONCode(e,t=2){return(e instanceof $m?e:this.parseExpr(e)).toJSONCode([],t)}validate(e){let t=new Mm,n=new Set,r=(r,i)=>{if(n.has(r))return;n.add(r);let a=i.validate(e);for(let e of a.list)t.list.push({...e,path:[r,...e.path]})};for(let[e,t]of this.namedTypes)r(e,t);for(let e of this.augments.keys()){let t=this.lookup(e);t&&r(e,t)}return t}parseValue(e,t,n=this){if(e instanceof W)return this.checkSlot(e,t,n);if(t?.parsesExprValue(n)&&this.exprShaped(e))return t.parse(e,n);if(e&&typeof e==`object`&&`type`in e&&`value`in e&&this.typeDefShaped(e.type)){let r=e.kind;if(typeof r==`string`&&this.exprClass(r))throw TypeError(`registry.parseValue: this node is an EXPRESSION (kind:'${r}'), not a value envelope \u2014 an Expr only evaluates inside a program (\`Engine.run\`/\`Engine.evaluate\`); a bare \`parse\` takes data. Drop the \`kind\` to mean the literal ${JSON.stringify(e.type)} value.`+(t?` (This slot is declared \`${t.toCode()}\`.)`:``));return this.checkSlot(this.parse(e.type,n).parse(e.value,n),t,n)}if(!t)throw TypeError(`registry.parseValue: expected Value or JSONValue, got ${typeof e}`);return t.parse(e,n)}typeDefShaped(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&typeof e.name==`string`}exprShaped(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e.kind;return typeof t==`string`&&!!this.exprClass(t)}checkSlot(e,t,n){if(!t||Sh(t,e.type,n))return e;throw TypeError(`registry.parseValue: this slot is declared \`${t.toCode()}\` but the value carries \`${e.type.toCode()}\``)}parse(e,t=this){if(!e||typeof e!=`object`)throw Error(`registry.parse: expected object, got ${typeof e}`);if(e instanceof U)throw Error(`registry.parse: expected a serialized TypeDef, got a LIVE ${e.constructor.name} instance (\`${e.name}\`) \u2014 pass \`type.toJSON()\`, or use the type as it stands.`);let n=e;if(!am(n.name))throw Error(`registry.parse: type 'name' must match ${im}, got ${JSON.stringify(n.name)}`);if(n.extends!==void 0&&!am(n.extends))throw Error(`registry.parse: type 'extends' must match ${im}, got ${JSON.stringify(n.extends)}`);if(n.satisfies){for(let e of n.satisfies)if(!am(e))throw Error(`registry.parse: 'satisfies' entries must match ${im}, got ${JSON.stringify(e)}`)}let r=n.extends??n.name;Up(n,this.namedTypes.has(r)?void 0:this.classes.get(r),n.extends===void 0,this);let i=this.parseInner(n,t);if(n.satisfies&&n.satisfies.length>0)for(let e of n.satisfies){let r=t.lookup(e)??this.lookup(e);if(!r)throw Error(`registry.parse: satisfies references unknown interface '${e}'${Pp(e,this.typeNameCandidates())}`);if(!r.compatible(i))throw Error(`registry.parse: type '${n.name}' claims to satisfy '${e}' but does not structurally match`)}return i}isUseSiteDef(e){return e.generic===void 0&&e.options===void 0?!1:[`extends`,`satisfies`,`init`,`props`,`get`,`call`,`constraint`].every(t=>e[t]===void 0)}boundAboveRegistry(e,t){for(let n=t;n&&n!==this;n=n.parent)if(n.localLookup(e)!==void 0)return!0;return!1}parseGenericArgs(e,t){return Object.fromEntries(Object.entries(e.generic??{}).map(([e,n])=>[e,this.parse(n,t)]))}useSiteAlias(e,t){return new Sg(t,e.options===void 0?{name:e.name}:{name:e.name,options:e.options},this.parseGenericArgs(e,t))}applyUse(e,t,n,r){let i=e;return Object.keys(t).length>0&&i instanceof gg&&(i=i.specialize(t)),n!==void 0&&Object.keys(n).length>0&&!pg(i.narrow(n),i.options)&&(i=new gg(this,i,{name:i.name,docs:i.docs,options:n,generic:i instanceof gg?i.local.generic:void 0,useSite:!0},i instanceof gg&&i.bindings?i.scope:void 0,r)),i}nearBuiltin(e){return e[0]===e[0]?.toLowerCase()&&Pp(e,this.typeClasses().map(e=>e.NAME))!==``}isBareNameDef(e){for(let t of[`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`])if(e[t]!==void 0)return!1;return!0}parseInner(e,t){if(e.extends){let n=t.lookup(e.extends)??this.lookup(e.extends);if(!n)throw Error(`registry.parse: extends references unknown type '${e.extends}'${Pp(e.extends,this.typeNameCandidates())}`);let r=this.classes.get(e.extends),i=e.generic!==void 0&&Object.keys(e.generic).length>0,a=r&&!i?Dv.filter(t=>e[t]!==void 0&&(r.consumes??[]).includes(t)):[];if(r&&a.length>0){let n={name:e.extends,...a.includes(`props`)?{props:e.props}:{},...a.includes(`get`)?{get:e.get}:{},...a.includes(`call`)?{call:e.call}:{},...a.includes(`init`)?{init:e.init}:{}},i=r.from(n,t),o={...e};delete o.extends;for(let e of a)delete o[e];return new gg(this,i,this.buildLocal(o,t))}return new gg(this,n,this.buildLocal(e,t))}if(this.isBareNameDef(e)){let n=t;for(;n&&n!==this;){if(n.localLookup(e.name)!==void 0)return new Sg(t,{name:e.name});n=n.parent}if(this.namedTypes.has(e.name))return this.namedTypes.get(e.name);let r=this.classes.get(e.name);return r?r.from(e,t):new Sg(t,{name:e.name})}let n=this.isUseSiteDef(e);if(n&&this.boundAboveRegistry(e.name,t))return this.useSiteAlias(e,t);if(this.namedTypes.has(e.name)){let r=this.namedTypes.get(e.name);return n?this.applyUse(r,this.parseGenericArgs(e,t),e.options,t):e.generic&&r instanceof gg?r.specialize(this.parseGenericArgs(e,t)):r}let r=this.classes.get(e.name);if(!r){if(n&&!this.nearBuiltin(e.name))return this.useSiteAlias(e,t);throw Error(`registry.parse: unknown type '${e.name}'${Pp(e.name,this.typeNameCandidates())}`)}let i=new Set(r.consumes??[]),a=Dv.filter(t=>e[t]!==void 0&&!i.has(t));if(a.length===0)return r.from(e,t);let o={...e};for(let e of a)delete o[e];let s=r.from(o,t),c={name:e.name,docs:e.docs,props:a.includes(`props`)&&e.props?jh.fromMap(e.props,t):void 0,get:a.includes(`get`)&&e.get?Mh.from(e.get,t):void 0,call:a.includes(`call`)&&e.call?Nh.from(e.call,t):void 0,init:a.includes(`init`)&&e.init?Ph.from(e.init,t):void 0};return new gg(this,s,c)}getTypesFor(e){let t=this.lookup(e);if(!t)return[];let n=[];for(let e of this.namedTypes.values())if(e!==t)try{t.compatible(e)&&n.push(e)}catch{}for(let[r,i]of this.classes){if(r===e)continue;let a;try{a=i.from({name:r},this)}catch{continue}try{t.compatible(a)&&n.push(a)}catch{}}return n}buildLocal(e,t){let n=e.generic?Object.fromEntries(Object.entries(e.generic).map(([e,n])=>[e,this.parse(n,t)])):void 0;return{name:e.name,docs:e.docs,options:e.options,generic:n,props:e.props?jh.fromMap(e.props,t):void 0,get:e.get?Mh.from(e.get,t):void 0,call:e.call?Nh.from(e.call,t):void 0,init:e.init?Ph.from(e.init,t):void 0,constraint:e.constraint?this.parseExpr(e.constraint,t):void 0}}any(){return new _g(this,{})}void(){return new Yg(this,{})}null(){return new zg(this,{})}bool(e){return new Cg(this,e??{})}num(e){return new Vg(this,e??{})}text(e){return new Wg(this,e??{})}list(e,t){return new Ng(this,e,t??{})}map(e,t){return new Lg(this,e,t)}tuple(e){return new qg(this,[...e])}obj(e){return new vg(this,e)}field(e,t){return{type:e,docs:t?.docs,default:t?.default===void 0?void 0:this.parseExpr(t.default)}}optional(e){return new Hg(this,e)}nullable(e){return new Bg(this,e)}not(e){return new Rg(this,e)}or(e){return new Ug(this,[...e])}and(e){return new bg(this,[...e])}enum(e,t){return kv(e)?new Dg(this,this.text(),{values:Object.fromEntries(e.map(e=>[e,e]))}):new Dg(this,t??this.text(),{values:e})}literal(e,t){if(e instanceof U)return new Mg(this,e,t);let n=this.primitiveOf(e);return new Mg(this,n,e)}primitiveOf(e){switch(typeof e){case`string`:return this.text();case`number`:return this.num();case`boolean`:return this.bool()}}date(e){return new Tg(this,e??{})}timestamp(e){return new Gg(this,e??{})}duration(){return new Eg(this,{})}color(e){return new wg(this,e??{})}fn(e){return new Ag(this,{args:e.args,returns:e.returns,throws:e.throws,get:e.call},e.generic??{})}iface(e){return new jg(this,{props:e.props?jh.fromMap(e.props,this):{},get:e.get?Mh.from(e.get,this):void 0,call:e.call?Nh.from(e.call,this):void 0})}alias(e){return new Sg(this,{name:e})}typ(e){return new Jg(this,e)}compatible(e){let t=[],n=new Set,r=e=>{n.has(e.name)||(n.add(e.name),t.push(e))};for(let t of this.typeClasses()){let n;try{n=t.from({name:t.NAME},this)}catch{continue}if(!(n.isUniversal()&&e.name!==t.NAME))try{n.compatible(e)&&r(n)}catch{continue}}for(let t of this.namedTypeList())try{t.compatible(e)&&r(t)}catch{continue}return t}like(e){let t=this.compatible(e).map(t=>t.like(e));return t.length===0?this.null():t.length===1?t[0]:this.or(t)}extend(e,t){let n=typeof e==`string`?this.lookup(e)??(()=>{throw Error(`extend: unknown base '${e}'`)})():e;return new gg(this,n,t)}nativeExpr(e){return this.parseExpr({kind:`native`,id:e})}prop(e,t,n){return Av(new jh({type:e,get:this.nativeExpr(t),docs:n}))}method(e,t,n,r){return Av(new jh({type:this.fn({args:this.obj(e),returns:t,generic:r?.generic}),get:this.nativeExpr(n),docs:r?.docs}))}};function kv(e){return Array.isArray(e)}function Av(e){if(!jv(e))throw Error(`registry: a computed prop must carry a get expression`);return e}function jv(e){return e.get!==void 0}var Mv=[_g,Yg,zg,Cg,Vg,Wg,Ng,Lg,qg,vg,Hg,Bg,Rg,Ug,bg,Dg,Mg,Ag,jg,Jg,Tg,Gg,Eg,wg],Nv=[W_,cv,lv,uv,fv,gv,_v,vv,bv,wv,pv,Ev];function Pv(){let e=new Ov;for(let t of Mv)e.define(t);for(let t of Nv)e.defineExpr(t);return U_(e),e}var Fv={$Exit:{code:"/** gin `flow: exit` — unwinds to the outermost exported function, whose result becomes `value`. */\nclass $Exit {\n constructor(readonly value: unknown) {}\n}"},$Throw:{code:"/** gin `flow: throw` — a thrown gin value; a call step's `catch` handler receives `error`. */\nclass $Throw extends Error {\n constructor(readonly error: unknown) { super(typeof error === 'string' ? error : 'gin throw'); }\n}"},$str:{code:"/** Template placeholder text — `null`/`undefined` read as the empty string. */\nfunction $str(v: unknown): string {\n return v === undefined || v === null ? '' : String(v);\n}"},$template:{code:`/** A template whose text is only known at run time: \`{name}\` reads \`params.name\`. */
|
|
120
|
+
}`:"${"+e+`}`}return"${"+t+`}`}).replace(/`/g,"\\`")}\``}`}toJSON(){return this.withCommentOn({kind:`template`,template:this.template.toJSON(),...this.params?{params:this.params.toJSON()}:{}})}toJSONCode(e=[],t=2,n=0){let r=this.template.toJSONCode([...e,`template`],t,n+1),i=this.params?this.params.toJSONCode([...e,`params`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`template`)},{key:`template`,value:r},{key:`params`,value:i},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.template.clone(),this.params?.clone()).withComment(this.comment)}forEachChild(e){e(this.template,`inherit`),this.params&&e(this.params,`inherit`)}effects(){return this.template.effects()|(this.params?.effects()??B.NONE)}complexity(){return 1+this.template.complexity()+(this.params?.complexity()??0)}};function qv(e,t){if(!(e instanceof fv))return;let n=e.value;if(!n||typeof n!=`object`||Array.isArray(n))return;let r={};for(let[e,i]of Object.entries(n))if(typeof i==`string`)r[e]=JSON.stringify(i);else if(typeof i==`number`||typeof i==`boolean`)r[e]=String(i);else if(i===null)r[e]=`null`;else if(i&&typeof i==`object`&&`kind`in i&&typeof i.kind==`string`&&t.exprClass(i.kind))try{r[e]=t.parseExpr(i).toCode(t,{expectsValue:!0})}catch{return}else return;return r}var Jv=class e extends xh{constructor(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){super(),this.id=e,this.type=t,this.resolvedEffects=n}id;type;resolvedEffects;static KIND=`native`;kind=e.KIND;static from(t,n){return new e(t.id,t.type?n.registry.parse(t.type,n):void 0,n.registry.nativeEffects(t.id)).withComment(t.comment)}async evaluate(e,t){let n=e.registry.getNative(this.id);if(!n)throw Error(`native: no impl registered for '${this.id}'`);let r=await n(t,e.registry);return r instanceof W?r:G(this.type??e.registry.any(),r)}typeOf(e,t){return this.type??e.registry.any()}validateWalk(e,t,n,r){return e.registry.getNative(this.id)||n.warn(`native.unknown`,`native impl '${this.id}' is not registered`),this.type??e.registry.any()}toCode(e,t={}){return this.commentPrefix(t)+`/* native: ${this.id} */`}toJSON(){let e={kind:`native`,id:this.id};return this.type&&(e.type=this.type.toJSON()),this.withCommentOn(e)}toJSONCode(e=[],t=2,n=0){let r=this.type?this.type.toJSONCode([...e,`type`],t,n+1):void 0;return V.jsonObject([{key:`kind`,value:V.jsonString(`native`)},{key:`id`,value:V.jsonString(this.id)},{key:`type`,value:r},...this.comment?[{key:`comment`,value:V.jsonString(this.comment)}]:[]],{path:e,expr:this},n,t)}clone(){return new e(this.id,this.type?.clone(),this.resolvedEffects).withComment(this.comment)}effects(){return this.resolvedEffects}complexity(){return 1}},Yv=[`props`,`get`,`call`,`init`],Xv=class{classes=new Map;namedTypes=new Map;natives=new Map;nativeEffectsMap=new Map;exprClasses=new Map;augments=new Map;_version=0;get version(){return this._version}parent=void 0;get registry(){return this}define(e){return this.classes.set(e.NAME,e),this._version++,this}register(e){return this.namedTypes.set(e.name,e),this._version++,this}scope(e){return new bh(this,{...e})}augment(e,t){this._version++;let n={props:t.props?$h.fromMap(t.props,this):void 0,get:t.get?eg.from(t.get,this):void 0,call:t.call?tg.from(t.call,this):void 0,init:t.init?ng.from(t.init,this):void 0},r=this.augments.get(e);return r?(this.augments.set(e,{props:n.props?{...r.props??{},...n.props}:r.props,get:r.get??n.get,call:r.call??n.call,init:r.init??n.init}),this):(this.augments.set(e,{props:n.props?{...n.props}:void 0,get:n.get,call:n.call,init:n.init}),this)}augmentation(e){return this.augments.get(e)}lookup(e){if(this.namedTypes.has(e))return this.namedTypes.get(e);let t=this.classes.get(e);if(t)return t.from({name:e},this)}localLookup(e){}setNative(e,t,n=B.STATE|B.SYSTEM|B.EXTERNAL){return this.natives.set(e,t),this.nativeEffectsMap.set(e,n),this}getNative(e){return this.natives.get(e)}nativeEffects(e){let t=this.nativeEffectsMap.get(e);return t===void 0?B.STATE|B.SYSTEM|B.EXTERNAL:t}defineExpr(e){return this.exprClasses.set(e.KIND,e),this._version++,this}exprClass(e){return this.exprClasses.get(e)}typeClasses(){return Array.from(this.classes.values())}typeClass(e){return this.classes.get(e)}namedTypeList(){return Array.from(this.namedTypes.values())}exprClassList(){return Array.from(this.exprClasses.values())}typeNameCandidates(){return[...this.typeClasses().map(e=>e.NAME),...this.namedTypeList().map(e=>e.name)]}parseExpr(e,t=this){if(e==null)return;if(e instanceof xh)return e;if(typeof e!=`object`||!(`kind`in e))throw Error(`registry.parseExpr: expected ExprDef with kind, got ${typeof e}`);let n=e,r=this.exprClasses.get(n.kind);if(!r)throw Error(`registry.parseExpr: unknown expr kind '${n.kind}'`);return r.from(n,t)}toCode(e,t){return(e instanceof xh?e:this.parseExpr(e)).toCode(this,t)}toGinCode(e,t){return(e instanceof xh?e:this.parseExpr(e)).toGinCode(this,t,[])}toJSONCode(e,t=2){return(e instanceof xh?e:this.parseExpr(e)).toJSONCode([],t)}validate(e){let t=new eh,n=new Set,r=(r,i)=>{if(n.has(r))return;n.add(r);let a=i.validate(e);for(let e of a.list)t.list.push({...e,path:[r,...e.path]})};for(let[e,t]of this.namedTypes)r(e,t);for(let e of this.augments.keys()){let t=this.lookup(e);t&&r(e,t)}return t}parseValue(e,t,n=this){if(e instanceof W)return this.checkSlot(e,t,n);if(t?.parsesExprValue(n)&&this.exprShaped(e))return t.parse(e,n);if(e&&typeof e==`object`&&`type`in e&&`value`in e&&this.typeDefShaped(e.type)){let r=e.kind;if(typeof r==`string`&&this.exprClass(r))throw TypeError(`registry.parseValue: this node is an EXPRESSION (kind:'${r}'), not a value envelope \u2014 an Expr only evaluates inside a program (\`Engine.run\`/\`Engine.evaluate\`); a bare \`parse\` takes data. Drop the \`kind\` to mean the literal ${JSON.stringify(e.type)} value.`+(t?` (This slot is declared \`${t.toCode()}\`.)`:``));return this.checkSlot(this.parse(e.type,n).parse(e.value,n),t,n)}if(!t)throw TypeError(`registry.parseValue: expected Value or JSONValue, got ${typeof e}`);return t.parse(e,n)}typeDefShaped(e){return!!e&&typeof e==`object`&&!Array.isArray(e)&&typeof e.name==`string`}exprShaped(e){if(!e||typeof e!=`object`||Array.isArray(e))return!1;let t=e.kind;return typeof t==`string`&&!!this.exprClass(t)}checkSlot(e,t,n){if(!t||Wh(t,e.type,n))return e;throw TypeError(`registry.parseValue: this slot is declared \`${t.toCode()}\` but the value carries \`${e.type.toCode()}\``)}parse(e,t=this){if(!e||typeof e!=`object`)throw Error(`registry.parse: expected object, got ${typeof e}`);if(e instanceof U)throw Error(`registry.parse: expected a serialized TypeDef, got a LIVE ${e.constructor.name} instance (\`${e.name}\`) \u2014 pass \`type.toJSON()\`, or use the type as it stands.`);let n=e;if(!Dm(n.name))throw Error(`registry.parse: type 'name' must match ${Em}, got ${JSON.stringify(n.name)}`);if(n.extends!==void 0&&!Dm(n.extends))throw Error(`registry.parse: type 'extends' must match ${Em}, got ${JSON.stringify(n.extends)}`);if(n.satisfies){for(let e of n.satisfies)if(!Dm(e))throw Error(`registry.parse: 'satisfies' entries must match ${Em}, got ${JSON.stringify(e)}`)}let r=n.extends??n.name;dm(n,this.namedTypes.has(r)?void 0:this.classes.get(r),n.extends===void 0,this);let i=this.parseInner(n,t);if(n.satisfies&&n.satisfies.length>0)for(let e of n.satisfies){let r=t.lookup(e)??this.lookup(e);if(!r)throw Error(`registry.parse: satisfies references unknown interface '${e}'${nm(e,this.typeNameCandidates())}`);if(!r.compatible(i))throw Error(`registry.parse: type '${n.name}' claims to satisfy '${e}' but does not structurally match`)}return i}isUseSiteDef(e){return e.generic===void 0&&e.options===void 0?!1:[`extends`,`satisfies`,`init`,`props`,`get`,`call`,`constraint`].every(t=>e[t]===void 0)}boundAboveRegistry(e,t){for(let n=t;n&&n!==this;n=n.parent)if(n.localLookup(e)!==void 0)return!0;return!1}parseGenericArgs(e,t){return Object.fromEntries(Object.entries(e.generic??{}).map(([e,n])=>[e,this.parse(n,t)]))}useSiteAlias(e,t){return new Wg(t,e.options===void 0?{name:e.name}:{name:e.name,options:e.options},this.parseGenericArgs(e,t))}applyUse(e,t,n,r){let i=e;return Object.keys(t).length>0&&i instanceof Rg&&(i=i.specialize(t)),n!==void 0&&Object.keys(n).length>0&&!Fg(i.narrow(n),i.options)&&(i=new Rg(this,i,{name:i.name,docs:i.docs,options:n,generic:i instanceof Rg?i.local.generic:void 0,useSite:!0},i instanceof Rg&&i.bindings?i.scope:void 0,r)),i}nearBuiltin(e){return e[0]===e[0]?.toLowerCase()&&nm(e,this.typeClasses().map(e=>e.NAME))!==``}isBareNameDef(e){for(let t of[`extends`,`satisfies`,`generic`,`options`,`init`,`props`,`get`,`call`,`constraint`])if(e[t]!==void 0)return!1;return!0}parseInner(e,t){if(e.extends){let n=t.lookup(e.extends)??this.lookup(e.extends);if(!n)throw Error(`registry.parse: extends references unknown type '${e.extends}'${nm(e.extends,this.typeNameCandidates())}`);let r=this.classes.get(e.extends),i=e.generic!==void 0&&Object.keys(e.generic).length>0,a=r&&!i?Yv.filter(t=>e[t]!==void 0&&(r.consumes??[]).includes(t)):[];if(r&&a.length>0){let n={name:e.extends,...a.includes(`props`)?{props:e.props}:{},...a.includes(`get`)?{get:e.get}:{},...a.includes(`call`)?{call:e.call}:{},...a.includes(`init`)?{init:e.init}:{}},i=r.from(n,t),o={...e};delete o.extends;for(let e of a)delete o[e];return new Rg(this,i,this.buildLocal(o,t))}return new Rg(this,n,this.buildLocal(e,t))}if(this.isBareNameDef(e)){let n=t;for(;n&&n!==this;){if(n.localLookup(e.name)!==void 0)return new Wg(t,{name:e.name});n=n.parent}if(this.namedTypes.has(e.name))return this.namedTypes.get(e.name);let r=this.classes.get(e.name);return r?r.from(e,t):new Wg(t,{name:e.name})}let n=this.isUseSiteDef(e);if(n&&this.boundAboveRegistry(e.name,t))return this.useSiteAlias(e,t);if(this.namedTypes.has(e.name)){let r=this.namedTypes.get(e.name);return n?this.applyUse(r,this.parseGenericArgs(e,t),e.options,t):e.generic&&r instanceof Rg?r.specialize(this.parseGenericArgs(e,t)):r}let r=this.classes.get(e.name);if(!r){if(n&&!this.nearBuiltin(e.name))return this.useSiteAlias(e,t);throw Error(`registry.parse: unknown type '${e.name}'${nm(e.name,this.typeNameCandidates())}`)}let i=new Set(r.consumes??[]),a=Yv.filter(t=>e[t]!==void 0&&!i.has(t));if(a.length===0)return r.from(e,t);let o={...e};for(let e of a)delete o[e];let s=r.from(o,t),c={name:e.name,docs:e.docs,props:a.includes(`props`)&&e.props?$h.fromMap(e.props,t):void 0,get:a.includes(`get`)&&e.get?eg.from(e.get,t):void 0,call:a.includes(`call`)&&e.call?tg.from(e.call,t):void 0,init:a.includes(`init`)&&e.init?ng.from(e.init,t):void 0};return new Rg(this,s,c)}getTypesFor(e){let t=this.lookup(e);if(!t)return[];let n=[];for(let e of this.namedTypes.values())if(e!==t)try{t.compatible(e)&&n.push(e)}catch{}for(let[r,i]of this.classes){if(r===e)continue;let a;try{a=i.from({name:r},this)}catch{continue}try{t.compatible(a)&&n.push(a)}catch{}}return n}buildLocal(e,t){let n=e.generic?Object.fromEntries(Object.entries(e.generic).map(([e,n])=>[e,this.parse(n,t)])):void 0;return{name:e.name,docs:e.docs,options:e.options,generic:n,props:e.props?$h.fromMap(e.props,t):void 0,get:e.get?eg.from(e.get,t):void 0,call:e.call?tg.from(e.call,t):void 0,init:e.init?ng.from(e.init,t):void 0,constraint:e.constraint?this.parseExpr(e.constraint,t):void 0}}any(){return new zg(this,{})}void(){return new __(this,{})}null(){return new s_(this,{})}bool(e){return new Gg(this,e??{})}num(e){return new l_(this,e??{})}text(e){return new f_(this,e??{})}list(e,t){return new t_(this,e,t??{})}map(e,t){return new a_(this,e,t)}tuple(e){return new h_(this,[...e])}obj(e){return new Bg(this,e)}field(e,t){return{type:e,docs:t?.docs,default:t?.default===void 0?void 0:this.parseExpr(t.default)}}optional(e){return new u_(this,e)}nullable(e){return new c_(this,e)}not(e){return new o_(this,e)}or(e){return new d_(this,[...e])}and(e){return new Hg(this,[...e])}enum(e,t){return Zv(e)?new Yg(this,this.text(),{values:Object.fromEntries(e.map(e=>[e,e]))}):new Yg(this,t??this.text(),{values:e})}literal(e,t){if(e instanceof U)return new e_(this,e,t);let n=this.primitiveOf(e);return new e_(this,n,e)}primitiveOf(e){switch(typeof e){case`string`:return this.text();case`number`:return this.num();case`boolean`:return this.bool()}}date(e){return new qg(this,e??{})}timestamp(e){return new p_(this,e??{})}duration(){return new Jg(this,{})}color(e){return new Kg(this,e??{})}fn(e){return new Qg(this,{args:e.args,returns:e.returns,throws:e.throws,get:e.call},e.generic??{})}iface(e){return new $g(this,{props:e.props?$h.fromMap(e.props,this):{},get:e.get?eg.from(e.get,this):void 0,call:e.call?tg.from(e.call,this):void 0})}alias(e){return new Wg(this,{name:e})}typ(e){return new g_(this,e)}compatible(e){let t=[],n=new Set,r=e=>{n.has(e.name)||(n.add(e.name),t.push(e))};for(let t of this.typeClasses()){let n;try{n=t.from({name:t.NAME},this)}catch{continue}if(!(n.isUniversal()&&e.name!==t.NAME))try{n.compatible(e)&&r(n)}catch{continue}}for(let t of this.namedTypeList())try{t.compatible(e)&&r(t)}catch{continue}return t}like(e){let t=this.compatible(e).map(t=>t.like(e));return t.length===0?this.null():t.length===1?t[0]:this.or(t)}extend(e,t){let n=typeof e==`string`?this.lookup(e)??(()=>{throw Error(`extend: unknown base '${e}'`)})():e;return new Rg(this,n,t)}nativeExpr(e){return this.parseExpr({kind:`native`,id:e})}prop(e,t,n){return Qv(new $h({type:e,get:this.nativeExpr(t),docs:n}))}method(e,t,n,r){return Qv(new $h({type:this.fn({args:this.obj(e),returns:t,generic:r?.generic}),get:this.nativeExpr(n),docs:r?.docs}))}};function Zv(e){return Array.isArray(e)}function Qv(e){if(!$v(e))throw Error(`registry: a computed prop must carry a get expression`);return e}function $v(e){return e.get!==void 0}var ey=[zg,__,s_,Gg,l_,f_,t_,a_,h_,Bg,u_,c_,o_,d_,Hg,Yg,e_,Qg,$g,g_,qg,p_,Jg,Kg],ty=[fv,Av,jv,Mv,Pv,Rv,zv,Bv,Hv,Kv,Fv,Jv];function ny(){let e=new Xv;for(let t of ey)e.define(t);for(let t of ty)e.defineExpr(t);return dv(e),e}var ry={$Exit:{code:"/** gin `flow: exit` — unwinds to the outermost exported function, whose result becomes `value`. */\nclass $Exit {\n constructor(readonly value: unknown) {}\n}"},$Throw:{code:"/** gin `flow: throw` — a thrown gin value; a call step's `catch` handler receives `error`. */\nclass $Throw extends Error {\n constructor(readonly error: unknown) { super(typeof error === 'string' ? error : 'gin throw'); }\n}"},$str:{code:"/** Template placeholder text — `null`/`undefined` read as the empty string. */\nfunction $str(v: unknown): string {\n return v === undefined || v === null ? '' : String(v);\n}"},$template:{code:`/** A template whose text is only known at run time: \`{name}\` reads \`params.name\`. */
|
|
121
121
|
function $template(tmpl: string, params: Record<string, unknown> | undefined): string {
|
|
122
122
|
return tmpl.replace(/\\{(\\w+)\\}/g, (_, name: string) =>
|
|
123
123
|
params && Object.prototype.hasOwnProperty.call(params, name) ? $str(params[name]) : '');
|
|
@@ -366,37 +366,37 @@ const $color = {
|
|
|
366
366
|
const { h, s, l } = $color.hsl(c);
|
|
367
367
|
return \`hsl(\${Math.round(h)},\${Math.round(s * 100)}%,\${Math.round(l * 100)}%)\`;
|
|
368
368
|
},
|
|
369
|
-
};`}},Iv=new Set(`any.unknown.never.object.string.number.boolean.symbol.bigint.undefined.null.void.true.false.this.keyof.typeof.infer.is.asserts.readonly.unique.type.interface.enum.class.function.let.const.var.new.in.of.as.extends.implements.namespace.module.declare.abstract.async.await.yield.import.export.default.return.if.else.for.while.do.switch.case.break.continue.try.catch.finally.throw.delete.instanceof.super.with.debugger.package.private.protected.public.static.global.require.Array.ArrayBuffer.ArrayLike.AsyncGenerator.AsyncIterable.AsyncIterator.Atomics.Awaited.BigInt.BigInt64Array.BigUint64Array.Boolean.Capitalize.ConstructorParameters.DataView.Date.Error.EvalError.Exclude.Extract.Float32Array.Float64Array.Function.Generator.Infinity.InstanceType.Int16Array.Int32Array.Int8Array.Intl.Iterable.IterableIterator.Iterator.JSON.Lowercase.Map.Math.NaN.NonNullable.Number.Object.Omit.OmitThisParameter.Parameters.Partial.Pick.Promise.PromiseLike.PropertyKey.Proxy.RangeError.Readonly.ReadonlyArray.ReadonlyMap.ReadonlySet.Record.ReferenceError.Reflect.RegExp.Required.ReturnType.Set.SharedArrayBuffer.String.Symbol.SyntaxError.TemplateStringsArray.ThisParameterType.ThisType.TypeError.URIError.Uint16Array.Uint32Array.Uint8Array.Uint8ClampedArray.Uncapitalize.Uppercase.WeakMap.WeakRef.WeakSet.globalThis.console.eval.arguments`.split(`.`));function Lv(e){return/^[A-Za-z_][\w$]*$/.test(e)&&!Iv.has(e)&&!(e in Fv)}function Rv(e){let t=e.replace(/[^\w]/g,`_`);return/^[A-Za-z_]/.test(t)||(t=`_`+t),Lv(t)?t:`${t}_`}var zv=class{taken=new Set;types=new Map;data=new Map;constructor(e,t){let n=e.namedTypeList().filter(e=>e instanceof gg&&!e.local.useSite).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of n)Lv(e.name)&&!this.taken.has(e.name)&&this.claim(this.types,e.name,e.name);for(let e of n)this.types.has(e.name)||this.type(e.name);for(let e of n){let n=!1;try{n=t(e)}catch{n=!1}n&&this.dataName(e.name)}}claim(e,t,n){let r=n;for(let e=2;this.taken.has(r);e++)r=`${n.replace(/_$/,``)}_${e}`;return this.taken.add(r),e.set(t,r),r}type(e){return this.types.get(e)??this.claim(this.types,e,Rv(e))}dataName(e){return this.data.get(e)??this.claim(this.data,e,`${this.type(e)}Data`)}fresh(e){return this.claim(new Map,e,Rv(e))}},Bv=(e,t)=>e===void 0||e===`undefined`||e===`null`?t:/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false)$/.test(e)?e:`(${e} ?? ${t})`,J=(e,t)=>e.arg(t)??`undefined`,Vv=e=>t=>`(${t.self()} ${e} ${J(t,`other`)})`,Hv=(e,...t)=>n=>`${e}(${[n.self(),...t.map(e=>J(n,e))].join(`, `)})`,Uv=(e,...t)=>n=>`${n.self()}.${e}(${t.map(e=>J(n,e)).join(`, `)})`,Wv=e=>t=>`${t.self()}.${e}`,Gv=e=>t=>`void ${e(t)}`,Kv=(e,...t)=>{let n=t.map(t=>e.arg(t));for(;n.length>0&&n[n.length-1]===void 0;)n.pop();return n.map(e=>e??`undefined`).join(`, `)},qv=(e,...t)=>n=>{let r=n.fn(`fn`),i=t.map(e=>J(n,e));return r?r.sync?`${n.helper(`$`+e)}(${[n.self(),r.code,...i].join(`, `)})`:n.aw(`${n.helper(`$`+e+`Async`)}(${[n.self(),r.code,...i].join(`, `)})`):`${n.helper(`$`+e)}(${[n.self(),`undefined as any`,...i].join(`, `)})`},Jv=e=>t=>{let n=t.once(),r=t.fn(`fn`);if(!r)return n;let i=`(${r.code})({ value: ${n} })`;return`(${n} === ${e} ? ${e} : ${r.sync?i:t.aw(i)})`},Yv={"type.toAny":e=>e.self(),"any.typeOf":e=>{let t=e.staticTypeName();return t===void 0?`${e.helper(`$typeOf`)}(${e.self()})`:(e.discard(),JSON.stringify(t))},"any.is":e=>{let t=e.guard();return t?`${t}(${e.self()})`:(e.discard(),`true`)},"any.as":e=>{let t=e.guard();if(!t)return e.self();let n=e.once();return`(${t}(${n}) ? ${n} : undefined)`},"any.toText":e=>`String(${e.self()})`,"any.toBool":e=>`Boolean(${e.self()})`,"any.eq":Vv(`===`),"any.neq":Vv(`!==`),"void.toText":e=>(e.discard(),`"void"`),"void.toBool":e=>(e.discard(),`false`),"null.toText":e=>(e.discard(),`"null"`),"null.toBool":e=>(e.discard(),`false`),"not.typeOf":e=>`${e.helper(`$typeOf`)}(${e.self()})`,"not.toText":e=>`String(${e.self()})`,"bool.eq":Vv(`===`),"bool.neq":Vv(`!==`),"bool.and":Vv(`&&`),"bool.or":Vv(`||`),"bool.xor":Vv(`!==`),"bool.not":e=>`!${e.self()}`,"bool.toText":e=>{let t=e.arg(`trueText`),n=e.arg(`falseText`);return t===void 0&&n===void 0?`String(${e.self()})`:`(${e.self()} ? ${Bv(t,`"true"`)} : ${Bv(n,`"false"`)})`},"bool.toNum":e=>{let t=e.arg(`trueValue`),n=e.arg(`falseValue`);return`(${e.self()} ? ${Bv(t,`1`)} : ${Bv(n,`0`)})`},"num.eq":e=>e.arg(`epsilon`)===void 0?`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.neq":e=>e.arg(`epsilon`)===void 0?`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.lt":Vv(`<`),"num.lte":Vv(`<=`),"num.gt":Vv(`>`),"num.gte":Vv(`>=`),"num.add":Vv(`+`),"num.sub":Vv(`-`),"num.mul":Vv(`*`),"num.div":Vv(`/`),"num.mod":Vv(`%`),"num.pow":Vv(`**`),"num.abs":Hv(`Math.abs`),"num.neg":e=>`(-${e.self()})`,"num.sign":Hv(`Math.sign`),"num.sqrt":Hv(`Math.sqrt`),"num.min":Hv(`Math.min`,`other`),"num.max":Hv(`Math.max`,`other`),"num.clamp":e=>`Math.min(Math.max(${e.self()}, ${J(e,`min`)}), ${J(e,`max`)})`,"num.floor":Hv(`Math.floor`),"num.ceil":Hv(`Math.ceil`),"num.round":Hv(`Math.round`),"num.isZero":e=>`(Math.abs(${e.self()}) <= 0)`,"num.isPositive":e=>`(${e.self()} > 0)`,"num.isNegative":e=>`(${e.self()} < 0)`,"num.isInteger":Hv(`Number.isInteger`),"num.isEven":e=>`(${e.self()} % 2 === 0)`,"num.isOdd":e=>`(Math.abs(${e.self()}) % 2 === 1)`,"num.toText":e=>e.arg(`precision`)===void 0?`String(${e.self()})`:`${e.helper(`$numText`)}(${e.self()}, ${e.arg(`precision`)})`,"num.toBool":e=>`(${e.self()} !== 0)`,"text.length":Wv(`length`),"text.eq":Vv(`===`),"text.neq":Vv(`!==`),"text.contains":Uv(`includes`,`search`),"text.startsWith":Uv(`startsWith`,`prefix`),"text.endsWith":Uv(`endsWith`,`suffix`),"text.trim":Uv(`trim`),"text.trimStart":Uv(`trimStart`),"text.trimEnd":Uv(`trimEnd`),"text.upper":Uv(`toUpperCase`),"text.lower":Uv(`toLowerCase`),"text.slice":e=>`${e.self()}.slice(${Kv(e,`start`,`end`)})`,"text.replace":e=>`${e.self()}.split(${J(e,`search`)}).join(${J(e,`replacement`)})`,"text.split":Uv(`split`,`separator`),"text.concat":Vv(`+`),"text.repeat":Uv(`repeat`,`count`),"text.indexOf":e=>`${e.self()}.indexOf(${Kv(e,`search`,`from`)})`,"text.lastIndexOf":e=>`${e.self()}.lastIndexOf(${Kv(e,`search`,`from`)})`,"text.match":e=>`(${e.self()}.match(new RegExp(${J(e,`pattern`)}, "g")) ?? [] as string[])`,"text.test":e=>`new RegExp(${J(e,`pattern`)}).test(${e.self()})`,"text.isEmpty":e=>`(${e.self()}.length === 0)`,"text.isNotEmpty":e=>`(${e.self()}.length > 0)`,"text.toNum":Hv(`Number`),"text.toBool":e=>`(${e.self()}.length > 0)`,"list.length":Wv(`length`),"list.at":e=>`${e.helper(`$listAt`)}(${e.self()}, ${J(e,`index`)})`,"list.push":Gv(Uv(`push`,`value`)),"list.pop":Uv(`pop`),"list.shift":Uv(`shift`),"list.unshift":Gv(Uv(`unshift`,`value`)),"list.insert":e=>`void ${e.self()}.splice(${J(e,`index`)}, 0, ${J(e,`value`)})`,"list.remove":e=>`${e.self()}.splice(${J(e,`index`)}, 1)[0]!`,"list.clear":e=>`void (${e.self()}.length = 0)`,"list.slice":e=>`${e.self()}.slice(${Kv(e,`start`,`end`)})`,"list.concat":Uv(`concat`,`other`),"list.reverse":e=>`[...${e.self()}].reverse()`,"list.join":e=>`${e.self()}.map(String).join(${Bv(e.arg(`separator`),`","`)})`,"list.indexOf":Uv(`indexOf`,`value`),"list.contains":e=>`(${e.self()}.indexOf(${J(e,`value`)}) !== -1)`,"list.unique":e=>`[...new Set(${e.self()})]`,"list.duplicates":e=>`${e.helper(`$duplicates`)}(${e.self()})`,"list.map":qv(`map`),"list.filter":qv(`filter`),"list.find":qv(`find`),"list.reduce":qv(`reduce`,`initial`),"list.some":qv(`some`),"list.every":qv(`every`),"list.sort":e=>e.arg(`fn`)===void 0?`${e.helper(`$sortNatural`)}(${e.self()})`:qv(`sort`)(e),"list.isEmpty":e=>`(${e.self()}.length === 0)`,"list.isNotEmpty":e=>`(${e.self()}.length > 0)`,"list.first":e=>`${e.self()}[0]`,"list.last":e=>`${e.self()}.at(-1)`,"map.size":Wv(`size`),"map.at":Uv(`get`,`key`),"map.has":Uv(`has`,`key`),"map.delete":Uv(`delete`,`key`),"map.clear":Gv(Uv(`clear`)),"map.keys":e=>`[...${e.self()}.keys()]`,"map.values":e=>`[...${e.self()}.values()]`,"map.isEmpty":e=>`(${e.self()}.size === 0)`,"map.isNotEmpty":e=>`(${e.self()}.size > 0)`,"object.keys":e=>(e.discard(),JSON.stringify(e.fields())),"object.values":e=>{let t=e.once();return`[${e.fields().map(e=>Qv(t,e)).join(`, `)}]`},"object.entries":e=>{let t=e.once();return`[${e.fields().map(e=>`[${JSON.stringify(e)}, ${Qv(t,e)}] as [string, unknown]`).join(`, `)}]`},"object.has":e=>(e.discard(),`(${JSON.stringify(e.fields())} as string[]).includes(${J(e,`key`)})`),"object.eq":e=>`${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.neq":e=>`!${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.toText":e=>`${e.helper(`$objText`)}(${e.self()} as any, ${JSON.stringify(e.fields())})`,"tuple.length":Wv(`length`),"tuple.first":e=>`${e.self()}[0]`,"tuple.last":e=>{let t=e.once();return`${t}[${t}.length - 1]`},"tuple.toList":e=>`[...${e.self()}]`,"optional.value":e=>`${e.helper(`$optValue`)}(${e.self()})`,"optional.has":e=>`(${e.self()} !== undefined)`,"optional.or":e=>{let t=e.once();return`(${t} !== undefined ? ${t} : ${J(e,`fallback`)})`},"optional.map":Jv(`undefined`),"nullable.value":e=>`${e.helper(`$nullValue`)}(${e.self()})`,"nullable.isNull":e=>`(${e.self()} === null)`,"nullable.or":e=>{let t=e.once();return`(${t} !== null ? ${t} : ${J(e,`fallback`)})`},"nullable.map":Jv(`null`),"enum.name":e=>{let t=ey(e.selfType),n={};for(let[e,r]of Object.entries(t?.options.values??{}))n[String(r)]=e;return`((${JSON.stringify(n)} as Record<string, string>)[String(${e.self()})] ?? "")`},"enum.value":e=>e.self(),"enum.eq":Vv(`===`),"enum.neq":Vv(`!==`),"enum.toText":e=>`String(${e.self()})`,"date.year":Uv(`getUTCFullYear`),"date.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"date.day":Uv(`getUTCDate`),"date.dayOfWeek":Uv(`getUTCDay`),"date.dayOfYear":e=>`${e.helper(`$date`)}.dayOfYear(${e.self()})`,"date.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"date.neq":e=>`(${e.self()}.getTime() !== ${J(e,`other`)}.getTime())`,"date.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"date.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"date.addDays":e=>`${e.helper(`$date`)}.addDays(${e.self()}, ${J(e,`days`)})`,"date.addMonths":e=>`${e.helper(`$date`)}.addMonths(${e.self()}, ${J(e,`months`)})`,"date.addYears":e=>`${e.helper(`$date`)}.addYears(${e.self()}, ${J(e,`years`)})`,"date.diffDays":e=>`${e.helper(`$date`)}.diffDays(${e.self()}, ${J(e,`other`)})`,"date.diffMonths":e=>`${e.helper(`$date`)}.diffMonths(${e.self()}, ${J(e,`other`)})`,"date.diffYears":e=>`(${e.self()}.getUTCFullYear() - ${J(e,`other`)}.getUTCFullYear())`,"date.toText":e=>`${e.self()}.toISOString().slice(0, 10)`,"timestamp.year":Uv(`getUTCFullYear`),"timestamp.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"timestamp.day":Uv(`getUTCDate`),"timestamp.hour":Uv(`getUTCHours`),"timestamp.minute":Uv(`getUTCMinutes`),"timestamp.second":Uv(`getUTCSeconds`),"timestamp.millisecond":Uv(`getUTCMilliseconds`),"timestamp.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"timestamp.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"timestamp.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"timestamp.addDuration":e=>`new Date(${e.self()}.getTime() + ${J(e,`duration`)})`,"timestamp.subDuration":e=>`new Date(${e.self()}.getTime() - ${J(e,`duration`)})`,"timestamp.diff":e=>`(${e.self()}.getTime() - ${J(e,`other`)}.getTime())`,"timestamp.toDate":e=>`${e.helper(`$date`)}.toDate(${e.self()})`,"timestamp.toEpoch":Uv(`getTime`),"timestamp.toText":Uv(`toISOString`),"duration.init":e=>`${e.helper(`$duration`)}.init(${e.self()})`,"duration.totalSeconds":e=>`(${e.self()} / 1000)`,"duration.totalMinutes":e=>`(${e.self()} / 60000)`,"duration.totalHours":e=>`(${e.self()} / 3600000)`,"duration.totalDays":e=>`(${e.self()} / 86400000)`,"duration.days":e=>`Math.trunc(${e.self()} / 86400000)`,"duration.hours":e=>`(Math.trunc(${e.self()} / 3600000) % 24)`,"duration.minutes":e=>`(Math.trunc(${e.self()} / 60000) % 60)`,"duration.seconds":e=>`(Math.trunc(${e.self()} / 1000) % 60)`,"duration.ms":e=>`(${e.self()} % 1000)`,"duration.toText":e=>`${e.helper(`$duration`)}.toText(${e.self()})`,"color.init":e=>`${e.helper(`$color`)}.init(${e.self()})`,"color.hue":e=>`${e.helper(`$color`)}.hsl(${e.self()}).h`,"color.saturation":e=>`${e.helper(`$color`)}.hsl(${e.self()}).s`,"color.lightness":e=>`${e.helper(`$color`)}.hsl(${e.self()}).l`,"color.eq":Vv(`===`),"color.neq":Vv(`!==`),"color.lighten":e=>`${e.helper(`$color`)}.lighten(${e.self()}, ${J(e,`amount`)})`,"color.darken":e=>`${e.helper(`$color`)}.lighten(${e.self()}, -${J(e,`amount`)})`,"color.saturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, ${J(e,`amount`)})`,"color.desaturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, -${J(e,`amount`)})`,"color.opacity":e=>`${e.helper(`$color`)}.opacity(${e.self()}, ${J(e,`alpha`)})`,"color.invert":e=>`${e.helper(`$color`)}.invert(${e.self()})`,"color.mix":e=>`${e.helper(`$color`)}.mix(${e.self()}, ${Kv(e,`other`,`weight`)})`,"color.complement":e=>`${e.helper(`$color`)}.complement(${e.self()})`,"color.toHex":e=>`${e.helper(`$color`)}.toHex(${e.self()})`,"color.toRgb":e=>`${e.helper(`$color`)}.toRgb(${e.self()})`,"color.toHsl":e=>`${e.helper(`$color`)}.toHsl(${e.self()})`,"color.toText":e=>`${e.helper(`$color`)}.toHex(${e.self()})`};for(let e of[`color.r`,`color.g`,`color.b`,`color.a`]){let t=e.slice(-1);Yv[e]=e=>`${e.helper(`$color`)}.${t}(${e.self()})`}var Xv={"list.indexGet":e=>`${e.helper(`$listGet`)}(${e.self}, ${e.key})`,"text.charAt":e=>`${e.helper(`$charAt`)}(${e.self}, ${e.key})`,"map.indexGet":e=>`${e.helper(`$mapGet`)}(${e.self}, ${e.key})`,"object.indexGet":e=>`(${e.self} as any)[${e.key}]`,"tuple.at":e=>`${e.self}[${e.key}]`},Zv={"list.indexSet":e=>`${e.helper(`$listSet`)}(${e.self}, ${e.key}, ${e.value})`,"map.indexSet":e=>`${e.self}.set(${e.key}, ${e.value})`,"object.indexSet":e=>`(${e.self} as any)[${e.key}] = ${e.value}`,"tuple.setAt":e=>`${e.self}[${e.key}] = ${e.value}`};function Qv(e,t){return $v(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function $v(e){return/^[A-Za-z_$][\w$]*$/.test(e)}function ey(e){let t=e;for(let e=0;e<10&&t;e++){if(t instanceof Dg)return t;t=t.base}}var ty=class extends Error{constructor(e){super(`gin \u2192 TypeScript: ${e.length} problem${e.length===1?``:`s`}
|
|
369
|
+
};`}},iy=new Set(`any.unknown.never.object.string.number.boolean.symbol.bigint.undefined.null.void.true.false.this.keyof.typeof.infer.is.asserts.readonly.unique.type.interface.enum.class.function.let.const.var.new.in.of.as.extends.implements.namespace.module.declare.abstract.async.await.yield.import.export.default.return.if.else.for.while.do.switch.case.break.continue.try.catch.finally.throw.delete.instanceof.super.with.debugger.package.private.protected.public.static.global.require.Array.ArrayBuffer.ArrayLike.AsyncGenerator.AsyncIterable.AsyncIterator.Atomics.Awaited.BigInt.BigInt64Array.BigUint64Array.Boolean.Capitalize.ConstructorParameters.DataView.Date.Error.EvalError.Exclude.Extract.Float32Array.Float64Array.Function.Generator.Infinity.InstanceType.Int16Array.Int32Array.Int8Array.Intl.Iterable.IterableIterator.Iterator.JSON.Lowercase.Map.Math.NaN.NonNullable.Number.Object.Omit.OmitThisParameter.Parameters.Partial.Pick.Promise.PromiseLike.PropertyKey.Proxy.RangeError.Readonly.ReadonlyArray.ReadonlyMap.ReadonlySet.Record.ReferenceError.Reflect.RegExp.Required.ReturnType.Set.SharedArrayBuffer.String.Symbol.SyntaxError.TemplateStringsArray.ThisParameterType.ThisType.TypeError.URIError.Uint16Array.Uint32Array.Uint8Array.Uint8ClampedArray.Uncapitalize.Uppercase.WeakMap.WeakRef.WeakSet.globalThis.console.eval.arguments`.split(`.`));function ay(e){return/^[A-Za-z_][\w$]*$/.test(e)&&!iy.has(e)&&!(e in ry)}function oy(e){let t=e.replace(/[^\w]/g,`_`);return/^[A-Za-z_]/.test(t)||(t=`_`+t),ay(t)?t:`${t}_`}var sy=class{taken=new Set;types=new Map;data=new Map;constructor(e,t){let n=e.namedTypeList().filter(e=>e instanceof Rg&&!e.local.useSite).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let e of n)ay(e.name)&&!this.taken.has(e.name)&&this.claim(this.types,e.name,e.name);for(let e of n)this.types.has(e.name)||this.type(e.name);for(let e of n){let n=!1;try{n=t(e)}catch{n=!1}n&&this.dataName(e.name)}}claim(e,t,n){let r=n;for(let e=2;this.taken.has(r);e++)r=`${n.replace(/_$/,``)}_${e}`;return this.taken.add(r),e.set(t,r),r}type(e){return this.types.get(e)??this.claim(this.types,e,oy(e))}dataName(e){return this.data.get(e)??this.claim(this.data,e,`${this.type(e)}Data`)}fresh(e){return this.claim(new Map,e,oy(e))}},cy=(e,t)=>e===void 0||e===`undefined`||e===`null`?t:/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false)$/.test(e)?e:`(${e} ?? ${t})`,J=(e,t)=>e.arg(t)??`undefined`,ly=e=>t=>`(${t.self()} ${e} ${J(t,`other`)})`,uy=(e,...t)=>n=>`${e}(${[n.self(),...t.map(e=>J(n,e))].join(`, `)})`,dy=(e,...t)=>n=>`${n.self()}.${e}(${t.map(e=>J(n,e)).join(`, `)})`,fy=e=>t=>`${t.self()}.${e}`,py=e=>t=>`void ${e(t)}`,my=(e,...t)=>{let n=t.map(t=>e.arg(t));for(;n.length>0&&n[n.length-1]===void 0;)n.pop();return n.map(e=>e??`undefined`).join(`, `)},hy=(e,...t)=>n=>{let r=n.fn(`fn`),i=t.map(e=>J(n,e));return r?r.sync?`${n.helper(`$`+e)}(${[n.self(),r.code,...i].join(`, `)})`:n.aw(`${n.helper(`$`+e+`Async`)}(${[n.self(),r.code,...i].join(`, `)})`):`${n.helper(`$`+e)}(${[n.self(),`undefined as any`,...i].join(`, `)})`},gy=e=>t=>{let n=t.once(),r=t.fn(`fn`);if(!r)return n;let i=`(${r.code})({ value: ${n} })`;return`(${n} === ${e} ? ${e} : ${r.sync?i:t.aw(i)})`},_y={"type.toAny":e=>e.self(),"any.typeOf":e=>{let t=e.staticTypeName();return t===void 0?`${e.helper(`$typeOf`)}(${e.self()})`:(e.discard(),JSON.stringify(t))},"any.is":e=>{let t=e.guard();return t?`${t}(${e.self()})`:(e.discard(),`true`)},"any.as":e=>{let t=e.guard();if(!t)return e.self();let n=e.once();return`(${t}(${n}) ? ${n} : undefined)`},"any.toText":e=>`String(${e.self()})`,"any.toBool":e=>`Boolean(${e.self()})`,"any.eq":ly(`===`),"any.neq":ly(`!==`),"void.toText":e=>(e.discard(),`"void"`),"void.toBool":e=>(e.discard(),`false`),"null.toText":e=>(e.discard(),`"null"`),"null.toBool":e=>(e.discard(),`false`),"not.typeOf":e=>`${e.helper(`$typeOf`)}(${e.self()})`,"not.toText":e=>`String(${e.self()})`,"bool.eq":ly(`===`),"bool.neq":ly(`!==`),"bool.and":ly(`&&`),"bool.or":ly(`||`),"bool.xor":ly(`!==`),"bool.not":e=>`!${e.self()}`,"bool.toText":e=>{let t=e.arg(`trueText`),n=e.arg(`falseText`);return t===void 0&&n===void 0?`String(${e.self()})`:`(${e.self()} ? ${cy(t,`"true"`)} : ${cy(n,`"false"`)})`},"bool.toNum":e=>{let t=e.arg(`trueValue`),n=e.arg(`falseValue`);return`(${e.self()} ? ${cy(t,`1`)} : ${cy(n,`0`)})`},"num.eq":e=>e.arg(`epsilon`)===void 0?`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.neq":e=>e.arg(`epsilon`)===void 0?`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)})`:`!${e.helper(`$numEq`)}(${e.self()}, ${J(e,`other`)}, ${e.arg(`epsilon`)})`,"num.lt":ly(`<`),"num.lte":ly(`<=`),"num.gt":ly(`>`),"num.gte":ly(`>=`),"num.add":ly(`+`),"num.sub":ly(`-`),"num.mul":ly(`*`),"num.div":ly(`/`),"num.mod":ly(`%`),"num.pow":ly(`**`),"num.abs":uy(`Math.abs`),"num.neg":e=>`(-${e.self()})`,"num.sign":uy(`Math.sign`),"num.sqrt":uy(`Math.sqrt`),"num.min":uy(`Math.min`,`other`),"num.max":uy(`Math.max`,`other`),"num.clamp":e=>`Math.min(Math.max(${e.self()}, ${J(e,`min`)}), ${J(e,`max`)})`,"num.floor":uy(`Math.floor`),"num.ceil":uy(`Math.ceil`),"num.round":uy(`Math.round`),"num.isZero":e=>`(Math.abs(${e.self()}) <= 0)`,"num.isPositive":e=>`(${e.self()} > 0)`,"num.isNegative":e=>`(${e.self()} < 0)`,"num.isInteger":uy(`Number.isInteger`),"num.isEven":e=>`(${e.self()} % 2 === 0)`,"num.isOdd":e=>`(Math.abs(${e.self()}) % 2 === 1)`,"num.toText":e=>e.arg(`precision`)===void 0?`String(${e.self()})`:`${e.helper(`$numText`)}(${e.self()}, ${e.arg(`precision`)})`,"num.toBool":e=>`(${e.self()} !== 0)`,"text.length":fy(`length`),"text.eq":ly(`===`),"text.neq":ly(`!==`),"text.contains":dy(`includes`,`search`),"text.startsWith":dy(`startsWith`,`prefix`),"text.endsWith":dy(`endsWith`,`suffix`),"text.trim":dy(`trim`),"text.trimStart":dy(`trimStart`),"text.trimEnd":dy(`trimEnd`),"text.upper":dy(`toUpperCase`),"text.lower":dy(`toLowerCase`),"text.slice":e=>`${e.self()}.slice(${my(e,`start`,`end`)})`,"text.replace":e=>`${e.self()}.split(${J(e,`search`)}).join(${J(e,`replacement`)})`,"text.split":dy(`split`,`separator`),"text.concat":ly(`+`),"text.repeat":dy(`repeat`,`count`),"text.indexOf":e=>`${e.self()}.indexOf(${my(e,`search`,`from`)})`,"text.lastIndexOf":e=>`${e.self()}.lastIndexOf(${my(e,`search`,`from`)})`,"text.match":e=>`(${e.self()}.match(new RegExp(${J(e,`pattern`)}, "g")) ?? [] as string[])`,"text.test":e=>`new RegExp(${J(e,`pattern`)}).test(${e.self()})`,"text.isEmpty":e=>`(${e.self()}.length === 0)`,"text.isNotEmpty":e=>`(${e.self()}.length > 0)`,"text.toNum":uy(`Number`),"text.toBool":e=>`(${e.self()}.length > 0)`,"list.length":fy(`length`),"list.at":e=>`${e.helper(`$listAt`)}(${e.self()}, ${J(e,`index`)})`,"list.push":py(dy(`push`,`value`)),"list.pop":dy(`pop`),"list.shift":dy(`shift`),"list.unshift":py(dy(`unshift`,`value`)),"list.insert":e=>`void ${e.self()}.splice(${J(e,`index`)}, 0, ${J(e,`value`)})`,"list.remove":e=>`${e.self()}.splice(${J(e,`index`)}, 1)[0]!`,"list.clear":e=>`void (${e.self()}.length = 0)`,"list.slice":e=>`${e.self()}.slice(${my(e,`start`,`end`)})`,"list.concat":dy(`concat`,`other`),"list.reverse":e=>`[...${e.self()}].reverse()`,"list.join":e=>`${e.self()}.map(String).join(${cy(e.arg(`separator`),`","`)})`,"list.indexOf":dy(`indexOf`,`value`),"list.contains":e=>`(${e.self()}.indexOf(${J(e,`value`)}) !== -1)`,"list.unique":e=>`[...new Set(${e.self()})]`,"list.duplicates":e=>`${e.helper(`$duplicates`)}(${e.self()})`,"list.map":hy(`map`),"list.filter":hy(`filter`),"list.find":hy(`find`),"list.reduce":hy(`reduce`,`initial`),"list.some":hy(`some`),"list.every":hy(`every`),"list.sort":e=>e.arg(`fn`)===void 0?`${e.helper(`$sortNatural`)}(${e.self()})`:hy(`sort`)(e),"list.isEmpty":e=>`(${e.self()}.length === 0)`,"list.isNotEmpty":e=>`(${e.self()}.length > 0)`,"list.first":e=>`${e.self()}[0]`,"list.last":e=>`${e.self()}.at(-1)`,"map.size":fy(`size`),"map.at":dy(`get`,`key`),"map.has":dy(`has`,`key`),"map.delete":dy(`delete`,`key`),"map.clear":py(dy(`clear`)),"map.keys":e=>`[...${e.self()}.keys()]`,"map.values":e=>`[...${e.self()}.values()]`,"map.isEmpty":e=>`(${e.self()}.size === 0)`,"map.isNotEmpty":e=>`(${e.self()}.size > 0)`,"object.keys":e=>(e.discard(),JSON.stringify(e.fields())),"object.values":e=>{let t=e.once();return`[${e.fields().map(e=>by(t,e)).join(`, `)}]`},"object.entries":e=>{let t=e.once();return`[${e.fields().map(e=>`[${JSON.stringify(e)}, ${by(t,e)}] as [string, unknown]`).join(`, `)}]`},"object.has":e=>(e.discard(),`(${JSON.stringify(e.fields())} as string[]).includes(${J(e,`key`)})`),"object.eq":e=>`${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.neq":e=>`!${e.helper(`$deepEq`)}(${e.self()}, ${J(e,`other`)})`,"object.toText":e=>`${e.helper(`$objText`)}(${e.self()} as any, ${JSON.stringify(e.fields())})`,"tuple.length":fy(`length`),"tuple.first":e=>`${e.self()}[0]`,"tuple.last":e=>{let t=e.once();return`${t}[${t}.length - 1]`},"tuple.toList":e=>`[...${e.self()}]`,"optional.value":e=>`${e.helper(`$optValue`)}(${e.self()})`,"optional.has":e=>`(${e.self()} !== undefined)`,"optional.or":e=>{let t=e.once();return`(${t} !== undefined ? ${t} : ${J(e,`fallback`)})`},"optional.map":gy(`undefined`),"nullable.value":e=>`${e.helper(`$nullValue`)}(${e.self()})`,"nullable.isNull":e=>`(${e.self()} === null)`,"nullable.or":e=>{let t=e.once();return`(${t} !== null ? ${t} : ${J(e,`fallback`)})`},"nullable.map":gy(`null`),"enum.name":e=>{let t=Sy(e.selfType),n={};for(let[e,r]of Object.entries(t?.options.values??{}))n[String(r)]=e;return`((${JSON.stringify(n)} as Record<string, string>)[String(${e.self()})] ?? "")`},"enum.value":e=>e.self(),"enum.eq":ly(`===`),"enum.neq":ly(`!==`),"enum.toText":e=>`String(${e.self()})`,"date.year":dy(`getUTCFullYear`),"date.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"date.day":dy(`getUTCDate`),"date.dayOfWeek":dy(`getUTCDay`),"date.dayOfYear":e=>`${e.helper(`$date`)}.dayOfYear(${e.self()})`,"date.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"date.neq":e=>`(${e.self()}.getTime() !== ${J(e,`other`)}.getTime())`,"date.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"date.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"date.addDays":e=>`${e.helper(`$date`)}.addDays(${e.self()}, ${J(e,`days`)})`,"date.addMonths":e=>`${e.helper(`$date`)}.addMonths(${e.self()}, ${J(e,`months`)})`,"date.addYears":e=>`${e.helper(`$date`)}.addYears(${e.self()}, ${J(e,`years`)})`,"date.diffDays":e=>`${e.helper(`$date`)}.diffDays(${e.self()}, ${J(e,`other`)})`,"date.diffMonths":e=>`${e.helper(`$date`)}.diffMonths(${e.self()}, ${J(e,`other`)})`,"date.diffYears":e=>`(${e.self()}.getUTCFullYear() - ${J(e,`other`)}.getUTCFullYear())`,"date.toText":e=>`${e.self()}.toISOString().slice(0, 10)`,"timestamp.year":dy(`getUTCFullYear`),"timestamp.month":e=>`(${e.self()}.getUTCMonth() + 1)`,"timestamp.day":dy(`getUTCDate`),"timestamp.hour":dy(`getUTCHours`),"timestamp.minute":dy(`getUTCMinutes`),"timestamp.second":dy(`getUTCSeconds`),"timestamp.millisecond":dy(`getUTCMilliseconds`),"timestamp.eq":e=>`(${e.self()}.getTime() === ${J(e,`other`)}.getTime())`,"timestamp.before":e=>`(${e.self()}.getTime() < ${J(e,`other`)}.getTime())`,"timestamp.after":e=>`(${e.self()}.getTime() > ${J(e,`other`)}.getTime())`,"timestamp.addDuration":e=>`new Date(${e.self()}.getTime() + ${J(e,`duration`)})`,"timestamp.subDuration":e=>`new Date(${e.self()}.getTime() - ${J(e,`duration`)})`,"timestamp.diff":e=>`(${e.self()}.getTime() - ${J(e,`other`)}.getTime())`,"timestamp.toDate":e=>`${e.helper(`$date`)}.toDate(${e.self()})`,"timestamp.toEpoch":dy(`getTime`),"timestamp.toText":dy(`toISOString`),"duration.init":e=>`${e.helper(`$duration`)}.init(${e.self()})`,"duration.totalSeconds":e=>`(${e.self()} / 1000)`,"duration.totalMinutes":e=>`(${e.self()} / 60000)`,"duration.totalHours":e=>`(${e.self()} / 3600000)`,"duration.totalDays":e=>`(${e.self()} / 86400000)`,"duration.days":e=>`Math.trunc(${e.self()} / 86400000)`,"duration.hours":e=>`(Math.trunc(${e.self()} / 3600000) % 24)`,"duration.minutes":e=>`(Math.trunc(${e.self()} / 60000) % 60)`,"duration.seconds":e=>`(Math.trunc(${e.self()} / 1000) % 60)`,"duration.ms":e=>`(${e.self()} % 1000)`,"duration.toText":e=>`${e.helper(`$duration`)}.toText(${e.self()})`,"color.init":e=>`${e.helper(`$color`)}.init(${e.self()})`,"color.hue":e=>`${e.helper(`$color`)}.hsl(${e.self()}).h`,"color.saturation":e=>`${e.helper(`$color`)}.hsl(${e.self()}).s`,"color.lightness":e=>`${e.helper(`$color`)}.hsl(${e.self()}).l`,"color.eq":ly(`===`),"color.neq":ly(`!==`),"color.lighten":e=>`${e.helper(`$color`)}.lighten(${e.self()}, ${J(e,`amount`)})`,"color.darken":e=>`${e.helper(`$color`)}.lighten(${e.self()}, -${J(e,`amount`)})`,"color.saturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, ${J(e,`amount`)})`,"color.desaturate":e=>`${e.helper(`$color`)}.saturate(${e.self()}, -${J(e,`amount`)})`,"color.opacity":e=>`${e.helper(`$color`)}.opacity(${e.self()}, ${J(e,`alpha`)})`,"color.invert":e=>`${e.helper(`$color`)}.invert(${e.self()})`,"color.mix":e=>`${e.helper(`$color`)}.mix(${e.self()}, ${my(e,`other`,`weight`)})`,"color.complement":e=>`${e.helper(`$color`)}.complement(${e.self()})`,"color.toHex":e=>`${e.helper(`$color`)}.toHex(${e.self()})`,"color.toRgb":e=>`${e.helper(`$color`)}.toRgb(${e.self()})`,"color.toHsl":e=>`${e.helper(`$color`)}.toHsl(${e.self()})`,"color.toText":e=>`${e.helper(`$color`)}.toHex(${e.self()})`};for(let e of[`color.r`,`color.g`,`color.b`,`color.a`]){let t=e.slice(-1);_y[e]=e=>`${e.helper(`$color`)}.${t}(${e.self()})`}var vy={"list.indexGet":e=>`${e.helper(`$listGet`)}(${e.self}, ${e.key})`,"text.charAt":e=>`${e.helper(`$charAt`)}(${e.self}, ${e.key})`,"map.indexGet":e=>`${e.helper(`$mapGet`)}(${e.self}, ${e.key})`,"object.indexGet":e=>`(${e.self} as any)[${e.key}]`,"tuple.at":e=>`${e.self}[${e.key}]`},yy={"list.indexSet":e=>`${e.helper(`$listSet`)}(${e.self}, ${e.key}, ${e.value})`,"map.indexSet":e=>`${e.self}.set(${e.key}, ${e.value})`,"object.indexSet":e=>`(${e.self} as any)[${e.key}] = ${e.value}`,"tuple.setAt":e=>`${e.self}[${e.key}] = ${e.value}`};function by(e,t){return xy(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function xy(e){return/^[A-Za-z_$][\w$]*$/.test(e)}function Sy(e){let t=e;for(let e=0;e<10&&t;e++){if(t instanceof Yg)return t;t=t.base}}var Cy=class extends Error{constructor(e){super(`gin \u2192 TypeScript: ${e.length} problem${e.length===1?``:`s`}
|
|
370
370
|
- ${e.join(`
|
|
371
|
-
- `)}`),this.problems=e,this.name=`TypeScriptExportError`}problems},
|
|
372
|
-
`));return t.length===1?`/** ${
|
|
371
|
+
- `)}`),this.problems=e,this.name=`TypeScriptExportError`}problems},wy=class{constructor(e){this.ctxAllowed=e}ctxAllowed;awaited=!1;loops=[]},Ty=new Set(`break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.export.extends.false.finally.for.function.if.import.in.instanceof.new.null.return.super.switch.this.throw.true.try.typeof.var.void.while.with.as.implements.interface.let.package.private.protected.public.static.yield.await.async.undefined.arguments.eval.ctx.args.self.Promise.Math.Number.String.Boolean.Date.Map.Set.Array.Object.JSON.Error.RegExp`.split(`.`)),Ey=/^(-?\d[\d.e+-]*|"(?:[^"\\]|\\.)*"|true|false|null|undefined)$/,Dy=class{constructor(e,t={}){this.engine=e,this.registry=e.registry,this.opt={types:t.types??`referenced`,includeComments:t.includeComments??!0,prelude:t.prelude??`separate`,async:t.async??`always`,export:t.export??!1,scope:t.scope??{}},this.names=new sy(this.registry,e=>this.splits(this.decl(e)))}engine;registry;types=new Map;helpers=new Map;problems=new Set;opt;names;defined=new Set;makers=new Map;guards=new Map;used=new Set;ctxVars=new Map;usesExit=!1;get always(){return this.opt.async===`always`}get exp(){return this.opt.export?`export `:``}problem(e){this.problems.add(e)}check(){if(this.problems.size>0)throw new Cy([...this.problems])}uniq(e){let t=e.replace(/[^\w$]/g,`_`);/^[A-Za-z_$]/.test(t)||(t=`_`+t),(/^make[A-Z]/.test(t)||/^is[A-Z]/.test(t)||t.startsWith(`$`))&&(t=`_`+t);let n=Ty.has(t)||this.used.has(t)?`${t}_1`:t;for(let e=2;this.used.has(n);e++)n=`${t}_${e}`;return this.used.add(n),n}tsName(e){return this.names.type(e)}helper(e){if(this.helpers.has(e))return e;let t=ry[e];if(!t)throw Error(`gin \u2192 TypeScript: no prelude helper '${e}'`);for(let e of t.deps??[])this.helper(e);return this.helpers.set(e,t.code),e}ref(e,t={generics:new Set}){if(e instanceof Wg){let n=e.options.name;if(t.generics.has(n))return n;let r=e.simplify();if(r!==e&&!(r instanceof Wg))return this.ref(r,t);let i=this.registry.lookup(n);return i&&!(i instanceof Wg)?this.ref(i,t):`any`}if(e instanceof Rg)return this.namedRef(e,t);if(e instanceof zg)return`any`;if(e instanceof __)return`void`;if(e instanceof s_)return`null`;if(e instanceof Gg)return`boolean`;if(e instanceof l_||e instanceof Jg||e instanceof Kg)return`number`;if(e instanceof f_)return`string`;if(e instanceof qg||e instanceof p_)return`Date`;if(e instanceof t_)return Gy(this.ref(e.item,t));if(e instanceof a_)return`Map<${this.ref(e.key,t)}, ${this.ref(e.value,t)}>`;if(e instanceof h_)return`[${e.elements.map(e=>this.ref(e,t)).join(`, `)}]`;if(e instanceof u_)return Wy([this.ref(e.inner,t),`undefined`]);if(e instanceof c_)return Wy([this.ref(e.inner,t),`null`]);if(e instanceof d_)return Wy(e.variants.map(e=>this.ref(e,t)));if(e instanceof Hg)return e.parts.map(e=>Uy(this.ref(e,t))).join(` & `)||`unknown`;if(e instanceof Yg){let t=Object.values(e.options.values).map(e=>JSON.stringify(e));return t.length?t.join(` | `):`never`}if(e instanceof e_)return JSON.stringify(e.literal);if(e instanceof Qg){let n=e.call();return n?this.fnSig(n,t,`unknown`,e.generic):`(...args: any[]) => any`}if(e instanceof Bg)return this.objLiteralType(Object.entries(e.fields),t);if(e instanceof $g){let n=this.members(Object.entries(e._props),t,void 0);return e._call&&n.push(`(${this.params(e._call.args,t)}): ${this.returns(e._call,t,`unknown`)}`),Hy(n)}return e instanceof o_||e instanceof g_?`unknown`:`any`}decl(e){let t=this.registry.lookup(e.name);return t instanceof Rg&&t.name===e.name?t:e}namedRef(e,t,n=!1){if(e.local.useSite)return e.original instanceof Rg?this.namedRef(e.original,t,n):this.ref(e.original,t);let r=this.decl(e);this.define(r);let i=n&&this.splits(r)?this.dataName(r):this.tsName(r.name),a=Object.keys(r.generic??{});if(a.length===0)return i;let o=a.map(n=>{let r=e.generic?.[n];return r&&!U.isGenericPlaceholder(n,r)?this.ref(r,t):t.generics.has(n)?n:`any`});return o.every(e=>e===`any`)?i:`${i}<${o.join(`, `)}>`}define(e){if(this.defined.has(e.name))return;this.defined.add(e.name);let t=this.maker(e);this.declaration(e,t)}surface(e){let t=e.definitionProps();return Object.entries(t).map(([e,t])=>[e,$h.from(t)])}definitionCall(e){return e.definitionCall()}splits(e){if(!Ay(e.base))return!1;if(this.definitionCall(e)||this.surface(e).some(([,e])=>ky(e)))return!0;let t=e.original;return t instanceof Rg&&!t.local.useSite&&this.splits(this.decl(t))}carriedMembers(e){let t=new Map,n=new Set;for(let r=e;r instanceof Rg&&!r.local.useSite;r=r.original)for(let[e,i]of this.surface(this.decl(r)))n.has(e)||(n.add(e),ky(i)&&(!i.get||i.get instanceof Jv)&&t.set(e,i));return[...t]}dataName(e){return this.names.dataName(e.name)}declaration(e,t){if(this.opt.types===`none`)return;let n=this.tsName(e.name),r=e.generic??{},i={generics:new Set(Object.keys(r))},a=this.genericParams(r,i);if(!this.splits(e)){this.types.set(n,this.singleDeclaration(e,t));return}let o=Object.keys(r).length?`<${Object.keys(r).join(`, `)}>`:``,s=e.original,c=s instanceof Rg&&!s.local.useSite,l=this.surface(e),u=this.members(l.filter(([,e])=>!ky(e)),i,t),d=this.members(l.filter(([,e])=>ky(e)),i,t),f=this.definitionCall(e);f&&d.push(`(${this.params(f.args,i)}): ${this.returns(f,i,`unknown`)}`);let p=this.dataName(e),m=[];c&&m.push(this.namedRef(s,i,!0)),(u.length||m.length===0)&&m.push(Hy(u));let h=[`The stored fields of ${n}${t?` \u2014 what \`${t.name}\` takes`:``}.`];this.types.set(p,`${this.docBlock(h)}${this.exp}type ${p}${a} = ${m.join(` & `)};`);let ee=[];c&&ee.push(this.namedRef(s,i)),ee.push(`${p}${o}`),d.length&&ee.push(Hy(d)),this.types.set(n,`${this.docBlock(this.typeDocs(e))}${this.exp}type ${n}${a} = ${ee.join(` & `)};`)}typeDocs(e){let t=[];return e.docs&&t.push(e.docs),e.local.options&&Object.keys(e.local.options).length>0&&t.push(`gin: ${e.base.toCode(void 0,{includeComments:!1})}`),e.local.constraint&&t.push(`constraint: ${e.local.constraint.toCode(this.registry,{expectsValue:!0,includeComments:!1})}`),t}singleDeclaration(e,t){let n=this.tsName(e.name),r=e.generic??{},i={generics:new Set(Object.keys(r))},a=this.genericParams(r,i),o=this.typeDocs(e),s=e.original,c=s instanceof Rg&&!s.local.useSite,l=Ay(e.base),u=this.definitionCall(e),d=l||c?this.members(this.surface(e),i,t):[];u&&d.push(`(${this.params(u.args,i)}): ${this.returns(u,i,`unknown`)}`);let f;if(c){let e=this.ref(s,i);f=d.length?`${e} & ${Hy(d)}`:e}else l?f=Hy(d):(f=this.ref(e.base,i),d.length&&(f=`${Uy(f)} & ${Hy(d)}`));return`${this.docBlock(o)}${this.exp}type ${n}${a} = ${f};`}genericParams(e,t){let n=Object.keys(e);return n.length===0?``:`<${n.map(n=>{let r=e[n];if(U.isGenericPlaceholder(n,r))return`${n} = any`;let i=this.ref(r,t);return`${n} extends ${i} = ${i}`}).join(`, `)}>`}members(e,t,n){let r=[];for(let[i,a]of e){let e=xy(i)?i:JSON.stringify(i),o=[];a.docs&&o.push(a.docs);let s=a.type.call(),c=n?.members.get(i);if(s&&(a.get||a.type instanceof Qg)){let n=c?c.async===!1?`sync`:`async`:this.hostMemberKind(a);r.push(`${this.docLine(o)}${e}: ${this.fnSig(s,t,n,a.type.generic)}`);continue}if(a.get){let n=this.ref(a.type,t);r.push(`${this.docLine(o)}readonly ${e}: ${c?.async===!0?`Promise<${n}>`:n}`);continue}let l=a.type.isOptional(),u=l?a.type.required():a.type,d=zy(u);d&&o.push(d),r.push(`${this.docLine(o)}${e}${l?`?`:``}: ${this.ref(u,t)}`)}return r}hostMemberKind(e){return this.always?`async`:e.get instanceof Jv&&!_y[e.get.id]?e.get.effects()&(B.EXTERNAL|B.SYSTEM)?`async`:`sync`:e.get instanceof Jv?`sync`:`unknown`}objLiteralType(e,t){return Hy(this.members(e,t,void 0))}fnSig(e,t,n,r){let i=Object.keys(r??{}),a=i.length?{generics:new Set([...t.generics,...i])}:t;return`${i.length?this.genericParams(r,a):``}(${this.params(e.args,a)}) => ${this.returns(e,a,n)}`}returns(e,t,n){let r=e.returns?this.ref(e.returns,t):`any`;return n===`sync`?r:n===`async`||this.always?`Promise<${r}>`:`${Uy(r)} | Promise<${r}>`}params(e,t){if(e instanceof Bg){let n=Object.entries(e.fields);return n.length===0?``:`args${n.every(([,e])=>e.type.isOptional()||e.default!==void 0)?`?`:``}: ${this.objLiteralType(n,t)}`}return e instanceof zg||e instanceof __?``:`args: ${this.ref(e,t)}`}defParams(e,t){let n=this.params(e,t);return n.startsWith(`args?:`)?`args:${n.slice(6)} = {}`:n}docBlock(e){if(!this.opt.includeComments||e.length===0)return``;let t=e.flatMap(e=>e.split(`
|
|
372
|
+
`));return t.length===1?`/** ${qy(t[0])} */
|
|
373
373
|
`:`/**
|
|
374
|
-
${t.map(e=>` * ${
|
|
374
|
+
${t.map(e=>` * ${qy(e)}`).join(`
|
|
375
375
|
`)}
|
|
376
376
|
*/
|
|
377
|
-
`}docLine(e){return!this.opt.includeComments||e.length===0?``:`/** ${
|
|
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
|
|
377
|
+
`}docLine(e){return!this.opt.includeComments||e.length===0?``:`/** ${qy(e.join(` · `).replace(/\n/g,` `))} */ `}maker(e){if(this.makers.has(e.name))return this.makers.get(e.name)??void 0;let t=e.definitionProps(),n=Object.entries(t).map(([e,t])=>[e,$h.from(t)]).filter(([,e])=>e.get&&!(e.get instanceof Jv)),r=e.original instanceof Rg&&!e.original.local.useSite?this.maker(this.decl(e.original)):void 0;if(n.length===0&&!r){this.makers.set(e.name,null);return}if(!Ay(e.base)){this.problem(`type '${e.name}': members written in gin on a non-object type are not supported`),this.makers.set(e.name,null);return}let i={name:`make${this.tsName(e.name)}`,members:new Map(r?.members??[])};for(let[e,t]of n)i.members.set(e,{kind:t.type.call()?`method`:`computed`,async:`pending`});this.makers.set(e.name,i);let a=e.generic??{},o={generics:new Set(Object.keys(a))},s=this.genericParams(a,o),c=Object.keys(a).length?`<${Object.keys(a).join(`, `)}>`:``,l=`${this.tsName(e.name)}${c}`;this.define(e);let u=new Set(this.used);this.used.clear();let d=`self`,f=[];f.push(r?`const ${d} = ${r.name}(data) as ${l};`:`const ${d} = data as ${l};`);for(let[t,r]of n){let n=new wy(!1),a=[],s=new Map([[`this`,{ts:d,type:e}]]),c=r.type.call();if(c){let e=this.uniq(t);s.set(`args`,{ts:`args`,type:c.args}),s.set(`recurse`,{ts:e,type:r.type}),this.stmt(r.get,s,n,a,{kind:`return`});let l=this.always||n.awaited;i.members.set(t,{kind:`method`,async:l});let u=this.defParams(c.args,o);f.push(`${by(d,t)} = ${l?`async `:``}function ${e}(${u}) {`),f.push(...By(a),`};`)}else this.stmt(r.get,s,n,a,{kind:`return`}),i.members.set(t,{kind:`computed`,async:n.awaited}),f.push(`Object.defineProperty(${d}, ${JSON.stringify(t)}, {`),f.push(` get: ${n.awaited?`async `:``}() => {`,...By(By(a)),` },`),f.push(` enumerable: false,`,` configurable: true,`,`});`)}f.push(`return ${d};`),this.used.clear();for(let e of u)this.used.add(e);let p=this.members(this.carriedMembers(e),o,i),m=`${this.dataName(e)}${c}${p.length?` & ${Hy(p)}`:``}`,h=[`/** Attach ${e.name}'s gin-written members to its data. */`,`${this.exp}function ${i.name}${s}(data: ${m}): ${l} {`,...By(f),`}`].join(`
|
|
378
|
+
`);return this.helpers.set(i.name,h),this.declaration(e,i),i}guard(e){let t=this.ref(e),n=t,r=this.guards.get(n);if(r)return r;let i=e instanceof Rg?`$is${this.tsName(this.decl(e).name)}`:`$is_${Xy(t)}`;this.guards.set(n,i);let a=this.checkExpr(e,`v`,0,!0);return this.helpers.set(i,`function ${i}(v: unknown): v is ${t} {
|
|
379
379
|
return ${a};
|
|
380
|
-
}`),i}checkExpr(e,t,n,r=!1){let i=`x${n}`;if(e instanceof
|
|
380
|
+
}`),i}checkExpr(e,t,n,r=!1){let i=`x${n}`;if(e instanceof Wg){let r=e.simplify();return r===e?`true`:this.checkExpr(r,t,n)}if(e instanceof Rg)return r?this.checkExpr(e.base,t,n):`${this.guard(e)}(${t})`;if(e instanceof l_||e instanceof Jg||e instanceof Kg)return`typeof ${t} === "number"`;if(e instanceof f_)return`typeof ${t} === "string"`;if(e instanceof Gg)return`typeof ${t} === "boolean"`;if(e instanceof s_)return`${t} === null`;if(e instanceof __)return`${t} === undefined`;if(e instanceof qg||e instanceof p_)return`${t} instanceof Date`;if(e instanceof Qg)return`typeof ${t} === "function"`;if(e instanceof a_)return`${t} instanceof Map`;if(e instanceof t_){let r=this.checkExpr(e.item,i,n+1);return r===`true`?`Array.isArray(${t})`:`(Array.isArray(${t}) && ${t}.every((${i}: unknown) => ${r}))`}if(e instanceof h_){let r=e.elements.map((e,r)=>this.checkExpr(e,`${t}[${r}]`,n+1));return`(Array.isArray(${t}) && ${t}.length === ${e.elements.length}${r.map(e=>` && ${e}`).join(``)})`}if(e instanceof u_)return`(${t} === undefined || ${this.checkExpr(e.inner,t,n)})`;if(e instanceof c_)return`(${t} === null || ${this.checkExpr(e.inner,t,n)})`;if(e instanceof d_)return`(${e.variants.map(e=>this.checkExpr(e,t,n)).join(` || `)})`;if(e instanceof Hg)return`(${e.parts.map(e=>this.checkExpr(e,t,n)).join(` && `)})`;if(e instanceof Yg)return`${JSON.stringify(Object.values(e.options.values))}.includes(${t} as any)`;if(e instanceof e_)return`${t} === ${JSON.stringify(e.literal)}`;if(e instanceof Bg||e instanceof $g){let r=e instanceof Bg?Object.entries(e.fields):Object.entries(e._props),i=[`typeof ${t} === "object"`,`${t} !== null`];for(let[e,a]of r){if(a.get||a.type.call())continue;let r=`(${t} as any)${xy(e)?`.`+e:`[${JSON.stringify(e)}]`}`;i.push(a.type.isOptional()?`(${r} === undefined || ${this.checkExpr(a.type.required(),r,n+1)})`:this.checkExpr(a.type,r,n+1))}return`(${i.join(` && `)})`}return`true`}exportFunction(e,t){this.ctxVars=new Map,this.usesExit=!1,(!xy(t)||Ty.has(t))&&this.problem(`'${t}' is not usable as a function name`);let n=t;this.used.add(t);let r=new wy(!0),i=[],a=[],o=``;if(e instanceof Hv){let t=e.fnType.call(),s={generics:new Set(Object.keys(e.fnType.generic??{}))},c=new Map([[`args`,{ts:`args`,type:t?.args??this.registry.obj({})}],[`recurse`,{ts:n,type:e.fnType}]]);e.constraint&&this.constraint(e.constraint,c,r,i),this.stmt(e.body,c,r,i,{kind:`return`}),a=[(t?this.defParams(t.args,s):``)||`args: {} = {}`],t?.returns&&(o=this.ref(t.returns,s))}else this.stmt(e,new Map,r,i,{kind:`return`});let s=this.always||r.awaited;if(this.ctxVars.size>0){let e=this.names.fresh(`${Yy(t)}Ctx`),n=[...this.ctxVars].map(([e,t])=>{let n=this.engine.getGlobal(e),r=n?.docs?[n.docs]:[];return`${this.docLine(r)}${xy(e)?e:JSON.stringify(e)}: ${this.ref(t)}`});this.types.set(e,`${this.docBlock([`Free variables ${t} reads (engine globals and run extras).`])}${this.exp}type ${e} = ${Hy(n)};`),a.push(`ctx: ${e}`)}let c=i;if(this.usesExit){let e=this.helper(`$Exit`);c=[`try {`,...By(i),`} catch ($exit) {`,` if ($exit instanceof ${e}) return $exit.value as any;`,` throw $exit;`,`}`]}let l=o?`: ${s?`Promise<${o}>`:o}`:``;return[`${e.comment?this.docBlock([e.comment]):``}${this.exp}${s?`async `:``}function ${n}(${a.join(`, `)})${l} {`,...By(c),`}`].join(`
|
|
381
381
|
`)}constraint(e,t,n,r){let i=this.val(e,t,n,r),a=JSON.stringify(`lambda constraint failed: ${e.toCode(this.registry,{expectsValue:!0,includeComments:!1})}`);r.push(`if (${i.code} !== true) throw new Error(${a});`)}stmt(e,t,n,r,i){if(e.comment&&this.opt.includeComments&&r.push(...e.comment.split(`
|
|
382
|
-
`).map(e=>`// ${e}`)),e instanceof
|
|
382
|
+
`).map(e=>`// ${e}`)),e instanceof Pv){if(e.lines.length===0)return this.finish(`undefined`,r,i,!0);e.lines.forEach((a,o)=>this.stmt(a,t,n,r,o===e.lines.length-1?i:{kind:`discard`}));return}if(e instanceof Mv){let a=this.defineVars(e,t,n,r);return this.stmt(e.body,a,n,r,i)}if(e instanceof Rv)return this.ifStmt(e,t,n,r,i);if(e instanceof zv)return this.switchStmt(e,t,n,r,i);if(e instanceof Bv){this.loop(e,t,n,r),i.kind===`assign`&&r.push(`${i.name} = undefined;`);return}if(e instanceof Fv)return this.flow(e,t,n,r);if(e instanceof jv)return this.set(e,t,n,r),this.finish(`true`,r,i,!0);let a=this.val(e,t,n,r);this.finish(a.code,r,i,a.pure)}finish(e,t,n,r){n.kind===`return`?e!==`undefined`&&t.push(`return ${Ky(e)};`):n.kind===`assign`?t.push(`${n.name} = ${Ky(e)};`):r||t.push(`${Ky(e)};`)}defineVars(e,t,n,r){let i=new Map(t);for(let t of e.vars){let e=this.val(t.value,i,n,r),a=this.uniq(t.name),o=t.type??e.type,s=t.type?`: ${this.ref(t.type)}`:``;r.push(`let ${a}${s} = ${Ky(e.code)};`),i.set(t.name,{ts:a,type:o,sync:e.sync})}return i}ifStmt(e,t,n,r,i){let a=(r,o)=>{if(r>=e.ifs.length){e.otherwise&&this.stmt(e.otherwise,t,n,o,i);return}let s=e.ifs[r],c=this.val(s.condition,t,n,o),l=[];this.stmt(s.body,t,n,l,i),o.push(`if (${Ky(c.code)}) {`,...By(l),`}`);let u=[];a(r+1,u),u.length!==0&&(u[0].startsWith(`if (`)&&Vy(u)?(o[o.length-1]=`} else ${u[0]}`,o.push(...u.slice(1))):(o[o.length-1]=`} else {`,o.push(...By(u),`}`)))};a(0,r)}switchStmt(e,t,n,r,i){let a=this.spill(this.val(e.value,t,n,r),r,`sw`),o=[];if(e.cases.forEach((e,r)=>{let s=[],c=e.equals.map(e=>this.val(e,t,n,s).code);s.length&&this.problem(`switch: a case value that needs statements is not supported`);let l=[];this.stmt(e.body,t,n,l,i);let u=c.length?c.map(e=>`${a} === ${e}`).join(` || `):`false`;o.push(`${r===0?`if`:`} else if`} (${u}) {`,...By(l))}),e.otherwise){let a=[];if(this.stmt(e.otherwise,t,n,a,i),o.length===0){r.push(...a);return}o.push(`} else {`,...By(a))}o.length&&r.push(...o,`}`)}flow(e,t,n,r){let i=n.loops[n.loops.length-1];switch(e.action){case`break`:i===`for`?r.push(`break;`):this.problem(i===`parallel`?`flow: break inside a parallel loop is not supported`:`flow: break outside a loop`);return;case`continue`:i===`for`?r.push(`continue;`):i===`parallel`?r.push(`return;`):this.problem(`flow: continue outside a loop`);return;case`return`:{i===`parallel`&&this.problem(`flow: return inside a parallel loop is not supported`);let a=e.value?this.val(e.value,t,n,r).code:void 0;r.push(a&&a!==`undefined`?`return ${Ky(a)};`:`return;`);return}case`exit`:{let i=e.value?this.val(e.value,t,n,r).code:`undefined`;this.usesExit=!0,r.push(`throw new ${this.helper(`$Exit`)}(${Ky(i)});`);return}case`throw`:{let i=e.error?this.val(e.error,t,n,r).code:`undefined`;r.push(`throw new ${this.helper(`$Throw`)}(${Ky(i)});`);return}}}loop(e,t,n,r){let i=this.registry.any(),a=this.typeOfExpr(e.over,t),o=a.get(),s=o?.loop instanceof Jv?o.loop.id:void 0,c=e.keyName??`key`,l=e.valueName??`value`,u=this.uniq(c),d=this.uniq(l),f=new Map(t);if(f.set(c,{ts:u,type:o?.key??i}),f.set(l,{ts:d,type:o?.value??i}),e.parallel)return this.parallelLoop(e,t,n,r,f,s,u,d,!!o?.loopDynamic);let p=[];if(n.loops.push(`for`),this.stmt(e.body,f,n,p,{kind:`discard`}),n.loops.pop(),o?.loopDynamic){let i=[],a=this.val(e.over,t,n,i);r.push(`for (let ${u} = 0; ; ${u}++) {`,...By(i),` const ${d} = ${Ky(a.code)};`,` if (!${d}) break;`,...By(p),`}`);return}let m=this.spill(this.val(e.over,t,n,r),r,`over`);switch(s){case`list.iterate`:case`tuple.iterate`:r.push(`for (let ${u} = 0; ${u} < ${m}.length; ${u}++) {`,` const ${d} = ${m}[${u}];`,...By(p),`}`);return;case`text.chars`:r.push(`for (let ${u} = 0; ${u} < ${m}.length; ${u}++) {`,` const ${d} = ${m}[${u}]!;`,...By(p),`}`);return;case`map.iterate`:r.push(`for (const [${u}, ${d}] of ${m}) {`,...By(p),`}`);return;case`num.loop`:{let e=this.uniq(`count`);r.push(`for (let ${u} = 0, ${e} = Math.abs(Math.trunc(${m})); ${u} < ${e}; ${u}++) {`,` const ${d} = ${m} < 0 ? -${u} : ${u};`,...By(p),`}`);return}case`object.iterate`:{let e=JSON.stringify(My(a));r.push(`for (const ${u} of ${e}) {`,` const ${d} = (${m} as any)[${u}];`,` if (${d} === undefined) continue;`,...By(p),`}`);return}default:this.problem(`loop: iterating '${a.toCode()}' is not supported (only built-in iterables)`)}}parallelLoop(e,t,n,r,i,a,o,s,c){if(c){this.problem(`loop: a parallel while-loop is not supported`);return}let l=e.parallel?.concurrent?this.val(e.parallel.concurrent,t,n,r).code:`undefined`,u=e.parallel?.rate?this.val(e.parallel.rate,t,n,r).code:`undefined`,d=this.typeOfExpr(e.over,t),f=this.spill(this.val(e.over,t,n,r),r,`over`),p;switch(a){case`list.iterate`:case`tuple.iterate`:p=`${f}.entries()`;break;case`text.chars`:p=`${f}.split("").entries()`;break;case`map.iterate`:p=f;break;case`num.loop`:p=`Array.from({ length: Math.abs(Math.trunc(${f})) }, (_, i) => [i, ${f} < 0 ? -i : i] as [number, number])`;break;case`object.iterate`:p=`${JSON.stringify(My(d))}.map((f) => [f, (${f} as any)[f]] as [string, any]).filter((e) => e[1] !== undefined)`;break;default:this.problem(`loop: iterating '${d.toCode()}' is not supported (only built-in iterables)`);return}let m=[],h=new wy(n.ctxAllowed);h.loops.push(`parallel`),this.stmt(e.body,i,h,m,{kind:`discard`}),n.awaited=!0,r.push(`await ${this.helper(`$parallel`)}(${p}, ${l}, ${u}, async (${o}, ${s}) => {`,...By(m),`});`)}val(e,t,n,r){if(e instanceof fv)return this.newValue(e,t,n,r);if(e instanceof Av)return this.path(e.path.steps,t,n,r);if(e instanceof jv)return this.set(e,t,n,r),{code:`true`,type:this.registry.bool(),pure:!0};if(e instanceof Hv)return this.lambda(e,t,n);if(e instanceof Kv)return this.template(e,t,n,r);if(e instanceof Pv){if(e.lines.length===0)return{code:`undefined`,type:this.registry.void(),pure:!0};for(let i of e.lines.slice(0,-1))this.stmt(i,t,n,r,{kind:`discard`});return this.val(e.lines[e.lines.length-1],t,n,r)}if(e instanceof Mv)return this.val(e.body,this.defineVars(e,t,n,r),n,r);if(e instanceof Rv)return this.ifValue(e,t,n,r);if(e instanceof zv||e instanceof Bv){let i=this.uniq(`v`);return r.push(`let ${i};`),this.stmt(e,t,n,r,{kind:`assign`,name:i}),{code:i,type:this.typeOfExpr(e,t),pure:!0}}return e instanceof Fv?(this.flow(e,t,n,r),{code:`undefined as never`,type:this.registry.void(),pure:!0}):e instanceof Jv?(this.problem(`native '${e.id}' used directly as an expression is not supported`),{code:`undefined as any`,type:this.registry.any(),pure:!0}):(this.problem(`expression kind '${e.kind}' is not supported`),{code:`undefined as any`,type:this.registry.any(),pure:!0})}ifValue(e,t,n,r){let i=[],a=e.ifs.map(e=>{let r=[],a=this.val(e.condition,t,n,r),o=[],s=this.val(e.body,t,n,o);return i.push(r,o),{cb:r,c:a,bb:o,v:s}}),o=[],s=e.otherwise?this.val(e.otherwise,t,n,o):void 0;i.push(o);let c=this.typeOfExpr(e,t);if(i.every(e=>e.length===0)){let e=s?s.code:`undefined`;for(let t=a.length-1;t>=0;t--)e=`${a[t].c.code} ? ${a[t].v.code} : ${e}`;return{code:`(${e})`,type:c,pure:a.every(e=>e.c.pure&&e.v.pure)&&(s?.pure??!0)}}let l=this.uniq(`v`);r.push(`let ${l};`);let u=(e,t)=>{if(e>=a.length){s&&t.push(...o,`${l} = ${Ky(s.code)};`);return}let n=a[e];t.push(...n.cb,`if (${Ky(n.c.code)}) {`,...By([...n.bb,`${l} = ${Ky(n.v.code)};`]),`}`);let r=[];u(e+1,r),r.length&&(t[t.length-1]=`} else {`,t.push(...By(r),`}`))};return u(0,r),{code:l,type:c,pure:!0}}template(e,t,n,r){let i=this.registry.text(),a=e.params?this.val(e.params,t,n,r):void 0,o=a?this.spill(a,r,`params`):void 0,s=e.template instanceof fv&&typeof e.template.value==`string`?e.template.value:void 0;if(s===void 0){let a=this.val(e.template,t,n,r);return{code:`${this.helper(`$template`)}(${a.code}, ${o??`undefined`} as any)`,type:i,pure:!1}}let c=a?Ny(a.type):void 0,l="`",u=0;for(let e of s.matchAll(/\{(\w+)\}/g)){l+=Jy(s.slice(u,e.index)),u=e.index+e[0].length;let r=e[1],i;if(o&&c?.has(r))i={code:by(o,r),type:c.get(r)};else if(o&&!c)i={code:`(${o} as any)[${JSON.stringify(r)}]`,type:this.registry.any()};else{let e=this.lookup(r,t,n);e&&(i={code:e.ts,type:e.type})}i&&(l+="${"+(Fy(i.type)?i.code:`${this.helper(`$str`)}(${i.code})`)+`}`)}return l+=Jy(s.slice(u))+"`",{code:l,type:i,pure:!0}}lambda(e,t,n){let r=e.fnType.call(),i={generics:new Set(Object.keys(e.fnType.generic??{}))},a=this.uniq(`recurse`),o=new wy(n.ctxAllowed),s=new Map(t);s.set(`args`,{ts:`args`,type:r?.args??this.registry.obj({})}),s.set(`recurse`,{ts:a,type:e.fnType});let c=[];e.constraint&&this.constraint(e.constraint,s,o,c),this.stmt(e.body,s,o,c,{kind:`return`});let l=this.always||o.awaited,u=r?this.defParams(r.args,i):``,d=r?.returns?`: ${l?`Promise<${this.ref(r.returns,i)}>`:this.ref(r.returns,i)}`:``,f=Object.keys(e.fnType.generic??{}).length?this.genericParams(e.fnType.generic,i):``,p=c.some(e=>RegExp(`\\b${a.replace(/\$/g,`\\$`)}\\b`).test(e)),m;if(p)m=[`${l?`async `:``}function ${a}${f}(${u})${d} {`,...By(c),`}`].join(`
|
|
383
383
|
`);else if(c.length===1&&c[0].startsWith(`return `)&&!c[0].includes(`
|
|
384
|
-
`)){let e=c[0].slice(7,-1);e.startsWith(`{`)&&(e=`(${e})`),m=`${l?`async `:``}${f}(${u})${d} => ${e}`}else m=[`${l?`async `:``}${f}(${u})${d} => {`,...
|
|
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
|
|
384
|
+
`)){let e=c[0].slice(7,-1);e.startsWith(`{`)&&(e=`(${e})`),m=`${l?`async `:``}${f}(${u})${d} => ${e}`}else m=[`${l?`async `:``}${f}(${u})${d} => {`,...By(c),`}`].join(`
|
|
385
|
+
`);return{code:`(${m})`,type:e.fnType,pure:!0,sync:!l}}newValue(e,t,n,r){let i=e.type,a=i.init();if(e.value!==void 0&&a){let t=a.run instanceof Jv?a.run.id:void 0;if(t!==`duration.init`&&t!==`color.init`)return this.problem(`new ${i.toCode()}: a constructor written in gin is not supported`),{code:`undefined as any`,type:i,pure:!0};let n=this.literal(a.args.parse(e.value).toLogical(),a.args);return{code:`${this.helper(t===`duration.init`?`$duration`:`$color`)}.init(${n})`,type:i,pure:!0}}if(e.value===void 0){let e=this.construct(i,this.literal(new W(i,i.create()).toLogical(),i));return{code:e,type:i,pure:!e.startsWith(`make`)}}let o=this.fill(e.value,i,t,n,r);return{code:o.code,type:i,pure:o.pure}}fill(e,t,n,r,i){let a=e instanceof xh?e:Qh(e,t.scope??this.registry);if(a){let e=this.val(a,n,r,i);return{code:e.code,pure:e.pure}}if(!Ly(e,this.registry))try{let n=this.construct(t,this.literal(t.parse(e).toLogical(),t));return{code:n,pure:!n.startsWith(`make`)}}catch(e){return this.problem(`new ${t.toCode()}: ${e instanceof Error?e.message:String(e)}`),{code:`undefined as any`,pure:!0}}if(t instanceof Wg)return this.fill(e,t.simplify(),n,r,i);if(t instanceof u_||t instanceof c_)return e===void 0?{code:`undefined`,pure:!0}:e===null?{code:`null`,pure:!0}:this.fill(e,t.inner,n,r,i);let o=e=>this.ordered(e.map(([e,t,i])=>a=>{let o=this.fill(t,i,n,r,a);return{code:o.code,pure:o.pure,key:e}}),i);if(t instanceof t_&&Array.isArray(e))return{code:`[${o(e.map(e=>[void 0,e,t.item])).map(e=>e.code).join(`, `)}]`,pure:!1};if(t instanceof h_&&Array.isArray(e))return{code:`[${o(e.map((e,n)=>[void 0,e,t.elements[n]??this.registry.any()])).map(e=>e.code).join(`, `)}] as ${this.ref(t)}`,pure:!1};if(t instanceof a_&&Array.isArray(e)){let n=[];for(let r of e){let[e,i]=Array.isArray(r)?r:[r?.key,r?.value];n.push([void 0,e,t.key],[void 0,i,t.value])}let r=o(n),i=[];for(let e=0;e<r.length;e+=2)i.push(`[${r[e].code}, ${r[e+1].code}]`);return{code:`new Map<${this.ref(t.key)}, ${this.ref(t.value)}>([${i.join(`, `)}])`,pure:!1}}let s=jy(t);if(s&&e&&typeof e==`object`&&!Array.isArray(e)){let a=e,c=[],l=[];for(let[e,t]of s)e in a?c.push([e,a[e],t.type]):t.default&&l.push([e,t.default]);let u=o(c);for(let[e,t]of l)u.push({key:e,code:this.val(t,n,r,i).code});let d=u.map(e=>`${xy(e.key)?e.key:JSON.stringify(e.key)}: ${e.code}`);return{code:this.construct(t,`{ ${d.join(`, `)} }`),pure:!1}}return this.problem(`new ${t.toCode()}: payload shape not supported`),{code:`undefined as any`,pure:!0}}construct(e,t){let n=e instanceof Rg&&!e.local.useSite?this.decl(e):void 0;if(n){this.define(n);let e=this.carriedMembers(n).map(([e])=>e);e.length&&this.problem(`new ${n.name}: its host member${e.length>1?`s`:``} ${e.join(`, `)} cannot be supplied in TypeScript \u2014 build the value on the host (\`make${this.tsName(n.name)}\` / \`${this.dataName(n)}\`) and pass it in`);let r=this.maker(n);if(r)return`${r.name}(${t})`}return t.startsWith(`[`)||t.startsWith(`{`)||n?`(${t} as ${this.ref(e)})`:t}literal(e,t){if(e===void 0)return`undefined`;if(e===null)return`null`;if(typeof e==`number`)return Object.is(e,-0)?`-0`:Number.isFinite(e)?String(e):e>0?`Infinity`:e<0?`-Infinity`:`NaN`;if(typeof e==`string`||typeof e==`boolean`)return JSON.stringify(e);if(e instanceof Date)return`new Date(${JSON.stringify(e.toISOString())})`;let n=t instanceof Rg?t.base:t instanceof u_||t instanceof c_?t.inner:t;if(e instanceof Map){let t=n instanceof a_?n.key:this.registry.any(),r=n instanceof a_?n.value:this.registry.any(),i=[...e].map(([e,n])=>`[${this.literal(e,t)}, ${this.literal(n,r)}]`);return`new Map<${this.ref(t)}, ${this.ref(r)}>([${i.join(`, `)}])`}if(Array.isArray(e)){if(n instanceof h_)return`[${e.map((e,t)=>this.literal(e,n.elements[t]??this.registry.any())).join(`, `)}]`;let t=n instanceof t_?n.item:this.registry.any();return`[${e.map(e=>this.literal(e,t)).join(`, `)}]`}if(typeof e==`object`){let n=new Map(jy(t)??[]);return`{ ${Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${xy(e)?e:JSON.stringify(e)}: ${this.literal(t,n.get(e)?.type??this.registry.any())}`).join(`, `)} }`}return`undefined`}set(e,t,n,r){let i=e.path.steps,a=this.val(e.value,t,n,r);if(i.length===1&&i[0]instanceof wv){let e=i[0].prop,o=this.lookup(e,t,n);if(!o){this.problem(`set: unknown variable '${e}'`);return}r.push(`${o.ts} = ${Ky(a.code)};`);return}let o=Ey.test(a.code)?a.code:this.spill(a,r,`value`),s=i[i.length-1];if(s instanceof Tv){this.problem(`set: assigning through a method call is not supported`);return}let c=this.path(i.slice(0,-1),t,n,r);if(s instanceof wv){let e=c.type.prop(s.prop);if(e?.set){this.problem(`set: prop '${s.prop}' has a gin setter, which is not supported`);return}if(e?.get&&!e.type.call()){this.problem(`set: prop '${s.prop}' is computed and cannot be assigned`);return}r.push(`${by(c.code,s.prop)} = ${o};`)}else if(s instanceof Ev){let e=this.val(s.key,t,n,r).code,i=c.type.get(),a=i?.set instanceof Jv?i.set.id:void 0,l=a?yy[a]:void 0;if(!l){this.problem(`set: indexed assignment on '${c.type.toCode()}' is not supported`);return}r.push(`${l({self:c.code,key:e,value:o,helper:e=>this.helper(e)})};`)}}lookup(e,t,n){let r=t.get(e);if(r)return r;let i=this.engine.getGlobal(e),a=this.opt.scope[e]??i?.type;if(a)return n.ctxAllowed?(this.ctxVars.set(e,a),{ts:by(`ctx`,e),type:a}):(this.problem(`'${e}' is read inside a gin-written member, where only this / args / recurse are in scope`),{ts:`undefined as any`,type:a})}path(e,t,n,r){let i;for(let a=0;a<e.length;a++){let o=e[a];if(o instanceof wv){if(!i){let e=this.lookup(o.prop,t,n);e?i={code:e.ts,type:e.type,pure:!0,sync:e.sync}:(this.problem(`unknown variable '${o.prop}'`),i={code:`undefined as any`,type:this.registry.any(),pure:!0});continue}this.touch(i.type);let s=i.type.prop(o.prop);if(!s){this.problem(`no prop '${o.prop}' on '${i.type.toCode()}' (the TypeScript export dispatches on the static type)`),i={code:by(i.code,o.prop),type:this.registry.any(),pure:!1};continue}let c=s.type instanceof Wg?s.type.simplify(i.type.scope):s.type,l=e[a+1];if(l instanceof Tv&&c.call()){i=this.invoke(i,o.prop,s,c,l,t,n,r),a++;continue}if(!(l instanceof Tv)&&Oy(c)){i=this.invoke(i,o.prop,s,c,new Tv({}),t,n,r);continue}i=this.readProp(i,o.prop,s,c,n,r)}else{if(!i)return this.problem(`path: must start with a variable`),{code:`undefined as any`,type:this.registry.any(),pure:!0};if(o instanceof Ev){this.touch(i.type);let e=i,a=[],s=this.val(o.key,t,n,a),c=a.length||!s.pure?this.spill(e,r,`recv`):e.code;r.push(...a);let l=e.type.get(),u=l?.get instanceof Jv?l.get.id:void 0,d=u?vy[u]:void 0;d||this.problem(`indexing '${e.type.toCode()}' is not supported`),i={code:d?d({self:c,key:s.code,helper:e=>this.helper(e)}):`undefined as any`,type:l?.value??this.registry.any(),pure:!1}}else if(o instanceof Tv){let e=i.type,a=e.scope;try{a=o.callSiteScope(e)}catch(e){this.problem(String(e instanceof Error?e.message:e))}let s=e.call(a);s?.get&&this.problem(`calling a '${e.toCode()}' value implemented in gin is not supported`);let{recv:c,args:l}=this.orderedArgs(i,o.args,t,n,r),u=`${c}(${Ry(l,s)})`;i.sync!==!0&&(u=this.aw(u,n));let d=s?.returns?.simplify(a)??s?.returns??this.registry.any();i=o.catch_?this.withCatch(u,o.catch_,d,t,n,r):{code:u,type:d,pure:!1}}}}return i??{code:`undefined as any`,type:this.registry.any(),pure:!0}}touch(e){e instanceof Rg&&!e.local.useSite&&this.define(this.decl(e))}readProp(e,t,n,r,i,a){let o=n.get instanceof Jv?n.get.id:void 0,s=o?_y[o]:void 0;if(s)return{code:s(this.nativeCtx(e,{},void 0,i,a)),type:r,pure:e.pure};let c=by(e.code,t);return n.get&&this.memberAsync(e.type,t,n,`computed`)&&(c=this.aw(c,i)),{code:c,type:r,pure:e.pure&&!n.get}}invoke(e,t,n,r,i,a,o,s){let c=r.scope;try{c=i.callSiteScope(r)}catch(e){this.problem(String(e instanceof Error?e.message:e))}let l=r.call(c),u=l?.returns?.simplify(c)??l?.returns??this.registry.any(),d=n.get instanceof Jv?n.get.id:void 0,f=d?_y[d]:void 0,{recv:p,args:m}=this.orderedArgs(e,i.args,a,o,s),h;if(f){let t=i.generic?.T?this.registry.parse(i.generic.T,c):void 0;h=f(this.nativeCtx({...e,code:p},m,t,o,s))}else h=`${by(p,t)}(${Ry(m,l)})`,this.memberAsync(e.type,t,n,`method`)&&(h=this.aw(h,o));return i.catch_?this.withCatch(h,i.catch_,u,a,o,s):{code:h,type:u,pure:!!f&&e.pure&&Object.values(m).every(e=>e.pure)&&!(d&&Iy(d))}}memberAsync(e,t,n,r){if(n.get&&!(n.get instanceof Jv)){let n=e instanceof Rg?this.decl(e):void 0,i=this.findMember(n,t);return i?i.async!==!1:r===`method`}return r!==`computed`&&this.hostMemberKind(n)!==`sync`}findMember(e,t){for(let n=e;n instanceof Rg;n=n.original){let e=this.makers.get(this.decl(n).name)?.members.get(t);if(e)return e}}orderedArgs(e,t,n,r,i){let a=Object.entries(t).map(([e,t])=>{let i=[];return{k:e,r:this.val(t,n,r,i),buf:i}}),o=a.some(e=>e.buf.length>0||!e.r.pure),s=o&&!Ey.test(e.code)?this.spill(e,i,`recv`):e.code,c={};for(let e of a)i.push(...e.buf),c[e.k]=o&&!e.r.pure&&e.r.sync===void 0?{...e.r,code:this.spill(e.r,i,e.k),pure:!0}:e.r;return{recv:s,args:c}}ordered(e,t){let n=e.map(e=>{let t=[];return{r:e(t),buf:t}}),r=n.reduce((e,t,n)=>t.buf.length?n:e,-1);return n.map((e,n)=>{if(t.push(...e.buf),n<r&&!e.r.pure&&!Ey.test(e.r.code)){let n=this.uniq(`slot`);return t.push(`const ${n} = ${Ky(e.r.code)};`),{...e.r,code:n,pure:!0}}return e.r})}nativeCtx(e,t,n,r,i){let a=e.code,o={};for(let[e,n]of Object.entries(t))o[e]=n.code;return{self:()=>a,once:()=>(xy(a)||(a=this.spill({...e,code:a},i,`recv`)),a),discard:()=>{e.pure||i.push(`${Ky(a)};`)},arg:e=>o[e],argOnce:e=>{let n=o[e];return n===void 0||xy(n)?n:(o[e]=this.spill({...t[e],code:n},i,e),o[e])},fn:e=>{let n=t[e];if(n)return{code:n.code,sync:!this.always&&n.sync===!0}},helper:e=>this.helper(e),aw:e=>this.aw(e,r),selfType:e.type,fields:()=>My(e.type),guard:()=>n?this.guard(n):void 0,staticTypeName:()=>Py(e.type)}}withCatch(e,t,n,r,i,a){let o=this.uniq(`result`),s=this.uniq(`e`),c=this.uniq(`error`),l=this.helper(`$Throw`);a.push(`let ${o};`,`try {`,` ${o} = ${Ky(e)};`,`} catch (${s}) {`,` if (!(${s} instanceof ${l})) throw ${s};`);let u=[`const ${c} = ${s}.error as any;`],d=new Map(r);d.set(`error`,{ts:c,type:this.registry.any()});let f=this.val(t,d,i,u);return u.push(`${o} = ${Ky(f.code)};`),a.push(...By(u),`}`),{code:o,type:n,pure:!0}}aw(e,t){return t.awaited=!0,`(await ${e})`}spill(e,t,n){if(xy(e.code)||Ey.test(e.code))return e.code;let r=this.uniq(n);return t.push(`const ${r} = ${Ky(e.code)};`),r}typeOfExpr(e,t){let n=new Map;for(let[e,t]of this.engine.getGlobals())n.set(e,t.type);for(let[e,t]of Object.entries(this.opt.scope))n.set(e,t);for(let[e,r]of t)n.set(e,r.type);try{return e.typeOf(this.engine,n)}catch{return this.registry.any()}}};function Oy(e){let t=e.call();return t?t.args instanceof Bg?Object.values(t.args.fields).every(e=>e.type.isOptional()):!0:!1}function ky(e){return!!e.get||e.type instanceof Qg}function Ay(e){return e instanceof Bg||e instanceof $g||e instanceof Rg&&Ay(e.base)}function jy(e){if(e instanceof Bg)return Object.entries(e.fields);if(e instanceof $g)return Object.entries(e._props);if(e instanceof Rg){let t=jy(e.base);if(!t)return;let n=new Map(t);for(let[t,r]of Object.entries(e.local.props??{}))n.set(t,$h.from(r));return[...n]}}function My(e){return(jy(e)??[]).filter(([,e])=>!e.get&&!e.type.call()).map(([e])=>e)}function Ny(e){let t=jy(e);if(t)return new Map(t.filter(([,e])=>!e.get).map(([e,t])=>[e,t.type]))}function Py(e){if(!(e instanceof zg||e instanceof d_||e instanceof Hg||e instanceof o_||e instanceof Wg||e instanceof u_||e instanceof c_))return e.name}function Fy(e){let t=e instanceof Rg?e.base:e;return t instanceof f_||t instanceof l_||t instanceof Gg||t instanceof Yg}function Iy(e){return/\.(push|pop|shift|unshift|insert|remove|clear|delete|indexSet|setAt)$/.test(e)}function Ly(e,t){return e instanceof xh?!0:!e||typeof e!=`object`?!1:!Array.isArray(e)&&typeof e.kind==`string`&&t.exprClass(e.kind)?!0:Object.values(e).some(e=>Ly(e,t))}function Ry(e,t){let n=Object.entries(e);return n.length===0?(t?.args instanceof Bg?Object.values(t.args.fields):[]).some(e=>!e.type.isOptional()&&e.default===void 0)?`{} as any`:``:`{ ${n.map(([e,t])=>e===t.code?e:`${xy(e)?e:JSON.stringify(e)}: ${Ky(t.code)}`).join(`, `)} }`}function zy(e){let t=e.options;if(t&&typeof t==`object`&&Object.keys(t).length!==0&&(e instanceof l_||e instanceof f_||e instanceof t_||e instanceof qg||e instanceof p_))return`gin: ${e.toCode(void 0,{includeComments:!1})}`}function By(e){return e.flatMap(e=>e.split(`
|
|
386
|
+
`)).map(e=>e&&` ${e}`)}function Vy(e){return e[e.length-1]===`}`}function Hy(e){if(e.length===0)return`{}`;let t=`{ ${e.join(`; `)} }`;return t.length<=80&&!t.includes(`
|
|
387
387
|
`)&&!t.includes(`/**`)?t:`{
|
|
388
|
-
${
|
|
388
|
+
${By(e.map(e=>`${e};`)).join(`
|
|
389
389
|
`)}
|
|
390
|
-
}`}function
|
|
390
|
+
}`}function Uy(e){return e.includes(`=>`)||e.includes(` | `)||e.includes(` & `)?`(${e})`:e}function Wy(e){let t=[];for(let n of e.map(e=>e.includes(`=>`)?`(${e})`:e))t.includes(n)||t.push(n);return t.join(` | `)}function Gy(e){return/^[\w$.]+(<.*>)?$/.test(e)&&!e.includes(` `)?`${e}[]`:`Array<${e}>`}function Ky(e){if(!e.startsWith(`(`)||!e.endsWith(`)`))return e;let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===`(`)t++;else if(r===`)`){if(t--,t===0&&n<e.length-1)return e}else if(r===`"`||r==="`"||r===`'`)return e}return e.slice(1,-1)}function qy(e){return e.replace(/\*\//g,`*\\/`)}function Jy(e){return e.replace(/\\/g,`\\\\`).replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}function Yy(e){let t=e.replace(/[^\w$]+(.)/g,(e,t)=>t.toUpperCase());return t.charAt(0).toUpperCase()+t.slice(1)}function Xy(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)>>>0;return t.toString(36)}function Zy(e,t,n={}){let r=e.registry.parseExpr(t),i=new Dy(e,n),a=n.name??`main`,o=i.exportFunction(r,a);i.helpers.has(a)&&i.problem(`function name '${a}' is also the name of a helper the code needs \u2014 pick another`),i.check();let s=new Map(i.helpers);return n.prelude===`inline`&&s.size>0&&(o=`${[...s.values()].join(`
|
|
391
391
|
|
|
392
392
|
`)}
|
|
393
393
|
|
|
394
|
-
${o}`,s.clear()),{code:o,types:new Map(i.types),helpers:s,functions:[a]}}var 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
|
|
394
|
+
${o}`,s.clear()),{code:o,types:new Map(i.types),helpers:s,functions:[a]}}var Qy=class{constructor(e){this.registry=e}registry;globals=new Map;registerGlobal(e,t){return this.globals.set(e,t),this}getGlobal(e){return this.globals.get(e)}getGlobals(){return this.globals}parse(e){if(!e||typeof e!=`object`||!(`kind`in e))throw Error(`engine.parse: expected ExprDef with kind, got ${typeof e}`);return e}createRootScope(e,t){let n=new wh(null,void 0,t);for(let[e,t]of this.globals)n.vars.set(e,G(t.type,t.value));if(e)for(let[t,r]of Object.entries(e))n.vars.set(t,r);return n}async run(e,t,n){let r=n?new Ag(n):void 0;r?.check();let i=this.createRootScope(t,r);try{return await this.evaluate(e,i)}catch(e){if(e instanceof Ph)return e.value??G(this.registry.void(),void 0);throw e}}typeOf(e,t){let n=t??this.globalTypeScope();return Th(this,e,n)}validate(e,t,n){let r=t??this.globalTypeScope();return Dh(this,e,r,n)}toCode(e,t){return this.registry.toCode(e,t)}toGinCode(e,t){return this.registry.toGinCode(e,t)}toJSONCode(e,t=2){return this.registry.toJSONCode(e,t)}toTypeScript(e,t){return Zy(this,e,t)}globalTypeScope(){let e=new Map;for(let[t,n]of this.globals)e.set(t,n.type);return e}async evaluate(e,t){return(e instanceof xh?e:this.registry.parseExpr(e)).evaluate(this,t)}async validateValue(e,t){let n=new eh,r=e.type.constraints();if(r.length===0)return n;let i=t??this.createRootScope();for(let t=0;t<r.length;t++){let a=r[t],o=i.child({this:e});try{(await a.evaluate(this,o)).raw!==!0&&n.at(`constraint[${t}]`,()=>n.error(`constraint.failed`,`value failed constraint: ${a.toCode(this.registry,{expectsValue:!0})}`))}catch(e){n.at(`constraint[${t}]`,()=>n.error(`constraint.threw`,`constraint threw: ${e.message}`))}}return n}};function $y(e){return new Qy(e)}var eb=`^[a-z]\\S*$`,tb=`A fn's name, as your tools spell it.`;function nb(e){if(e.name!==`text`)return!1;let t=e.options;return typeof t==`object`&&!!t&&`pattern`in t&&t.pattern===`^[a-z]\\S*$`}var rb=R.string().pattern(eb).describe(tb);function ib(e){return R.codec(rb,{decode:t=>e.fn(t)??Error(`${t} names no fn: write a fn's name as your tools spell it.`),encode:t=>e.name(t)})}var ab=new WeakMap,ob=0;function sb(e){if(e===void 0)return 0;let t=ab.get(e);return t===void 0&&ab.set(e,t=++ob),t}var cb=Qm.declare().dynamic((e,t,n)=>({...qm(e,n),FnName:t===void 0?rb:ib(t)}),{key:(e,t,n)=>`${Zm(e,n)}|${sb(t)}`,cacheSize:4}),lb={result:e=>cb.result(e)},ub=e=>nb(e)?R.ref(`FnName`):void 0;function db(e,t={}){return e.toA({...t.scope===void 0?{}:{scope:t.scope},...t.includeDocs===void 0?{}:{includeDocs:t.includeDocs},...t.unknownKeys===void 0?{}:{unknownKeys:t.unknownKeys},override:ub})}function fb(e,t={}){return lb.result(db(e,t))}var pb=new WeakMap,mb=new WeakMap;function hb(e,t){let n=t.unknownKeys??`strip`,r=pb;t.scope!==void 0&&(r=mb.get(t.scope)??new WeakMap,mb.set(t.scope,r));let i=r.get(e)??new Map;r.set(e,i);let a=i.get(n);if(a!==void 0)return a;let o=fb(e,{...t,includeDocs:`none`});return i.set(n,o),o}function gb(e,t={}){return hb(e,t).bind(e.registry)}function _b(e){return e.map(String).join(`.`)}function vb(e,t,n={}){let r=gb(e,n).render($l).parse(t,{inPlace:!1,...n.repair===void 0?{}:{repair:n.repair},...n.label===void 0?{}:{label:n.label}});return r.ok?{ok:!0,value:r.value}:{ok:!1,problems:r.issues.map(e=>({path:_b(e.codePath),message:e.message})),message:r.message}}var yb=v().regex(/^[a-z][A-Za-z0-9_-]{0,63}$/).brand(),bb=`[A-Za-z0-9](?:[A-Za-z0-9-]|_(?![_.]|$))*`,xb=RegExp(`^${bb}(?:\\.${bb})*$`);v().regex(xb,"a fn name is letters, digits, `_` and `-` in dot-separated parts, each starting with a letter or digit, with no `__` and no part ending in `_`");function Sb(e){if(!xb.test(e))return e.includes(`__`)?`${e} holds \`__\`, which separates the parts of the name the model calls it by: write one \`_\``:/(?:^|\.)_|_(?:\.|$)/.test(e)?`a part of ${e} starts or ends with \`_\`: start each part with a letter or digit and end it with no \`_\``:`${e} is not a fn name: letters, digits, \`_\` and \`-\` in dot-separated parts, each starting with a letter or digit`}function Cb(e){let{system:t,local:n}=Il(e);return`${t}__${n.replaceAll(`.`,`__`)}`}function wb(e){return e.length===64&&/_x[0-9a-f]{8}$/.test(e)}function Tb(e){return Cb(e).length>64}function Eb(e){if(wb(e))return;let t=e.indexOf(`__`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+2).split(`__`).join(`.`);if(!Nl.test(n)||!xb.test(r))return;let i=I.safeParse(`${n}/${r}`);return i.success&&!Tb(i.data)&&Cb(i.data)===e?i.data:void 0}function Db(e,t){let n=I.safeParse(e);if(n.success)return n.data;let r=t?.(e);return r===void 0?e.includes(`--`)?Ob(e)??Eb(e):Eb(e)??Ob(e):r}function Ob(e){if(e.length>=64)return;let t=I.safeParse(e.replace(`__`,`/`).replaceAll(`--`,`.`));if(t.success)return t.data.replaceAll(`/`,`__`).replaceAll(`.`,`--`).replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,64)===e?t.data:void 0}S({model:yb,fn:I,until:N}),S({model:yb,fn:I,system:F});var kb=I.describe(tb),Ab=v().min(1).regex(/^\S+$/,`a type's name, with no spaces`);Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);var jb=/^https?:\/\/[^\s\u0000-\u001f\u007f]+$/i;function Mb(e){try{let{protocol:t}=new URL(e);return t===`http:`||t===`https:`}catch{return!1}}var Nb=v().regex(jb,`expected an http or https URL`).refine(Mb,`expected an http or https URL`);function Pb(e){return Nb.safeParse(e).success}var Fb=`outsideImages`,Ib=E([`ask`,`always`]),Lb=S({value:Ib,setBy:M.optional(),updatedAt:N.optional()}),Rb=`https`,zb={der:`/harness-ca.crt`,pem:`/harness-ca.pem`},Bb=E([`own`,`files`]),Vb=S({on:b(),source:Bb,setBy:M.optional(),updatedAt:N.optional(),fingerprint:v().optional(),authorityName:v().optional(),host:v(),links:x(v())}),Hb=v().regex(/^(?:\*|[a-z*][a-z0-9*-]*\/[A-Za-z0-9_*][A-Za-z0-9_.*-]*)$/,`an agent's name (crm/reviewer) or a pattern (hub/chat*, crm/*, *)`).refine(e=>!e.includes(`**`),`write one *`),Ub=S({into:x(Hb).min(1),order:y().int().min(0).max(1e3).default(100),requires:x(I).default([]),mode:E([`tools`,`static`]).optional(),replaces:x(I).optional()}),Wb=C([D(`none`),S({detail:E([`full`,`summary`]).default(`full`),maxTokens:y().int().min(1).optional()})]),Gb=S({target:Hb,agents:x(I)}),Kb=E([`approved`,`pending`,`declined`]);S({context:I,system:F,title:v(),inject:Ub,fns:x(I),targets:x(Gb),agents:x(I),review:Kb,off:b(),dynamic:b()}),S({hook:I,system:F,explains:v(),review:Kb});var qb=S({section:E([`context`,`hooks`]),name:I,title:v(),change:E([`added`,`changed`,`removed`]),tokens:y().int().min(0).optional(),targets:x(Gb),agents:x(I),replaces:x(I).optional()});S({agent:I,context:I,on:b(),order:y().int().min(0).max(1e3).optional(),by:M,at:N});var Jb=E([`off`,`pending`,`declined`,`system-off`,`fns-unusable`,`mode`,`replaced`,`no-fit`]),Yb=S({agent:I,context:I,source:w(`type`,[S({type:D(`context`)}),S({type:D(`hook`),hook:I})]),system:F,via:Hb,title:v(),detail:E([`full`,`summary`]),text:v(),tokens:y().int().min(0),order:y().int(),on:b(),leftOut:S({why:Jb,reason:v()}).optional(),switched:S({by:M,at:N}).optional()}),Xb=S({injections:x(Yb),targets:x(Gb)}),Zb=S({agent:I,context:I,on:b().optional(),order:y().int().min(0).max(1e3).nullable().optional()}),Qb=[`listed`,`signature`,`full`],$b=E(Qb),ex=S({fn:I,detail:$b}),tx=S({type:D(`tools`)}),nx=E([`auto`,`native`,`text`]),rx=E([`system-end`,`tail`]),ix=w(`type`,[tx,S({type:D(`static`),protocol:nx.default(`auto`),placement:rx.default(`system-end`),loadDetail:$b.default(`full`)})]),ax=E(ix.options.map(e=>e.shape.type.value));E([`find`,`find_ctx`,`inspect`,`load`,`unload`,`run`]);var ox=S({fn:v().min(1).describe(`The fn to run, by its qualified name (fs/read).`),args:T(v(),Zc()).default({}).describe(`Its args, as its card shows them.`),on:L.optional().describe(`For a system with several machines connected, which one runs it (laptop).`)}),sx=S({type:D(`plain`)}),cx=S({type:D(`suggest`),topN:y().int().min(0).default(6),autoInject:S({tokens:y().int().min(0),items:y().int().min(0)}).optional()}),lx=E([`embedding`,`words`,`turnsAgo`,`age`,`selectedBefore`,`used`]),ux=S({weight:y().min(0),target:y().optional(),k:y().positive().optional()}),dx=E([`perMessage`,`perIteration`]),fx=[`history`,`context`,`fns`],px=E(fx),mx=T(px,y().min(0)),hx=w(`type`,[sx,cx,S({type:D(`graph`),metrics:bc(lx,ux).default({}),spread:S({damping:y().min(0).max(.95).default(.5),hops:y().int().min(0).max(4).default(2)}).prefault({}),floorExchanges:y().int().min(0).default(1),shares:mx.default({history:.45,context:.35,fns:.2}),threshold:y().min(0).default(.15),evaluate:dx.default(`perMessage`)})]),gx=E(hx.options.map(e=>e.shape.type.value)),_x=S({contextWindow:y().int().min(256).optional(),maxOutputTokens:y().int().min(16).optional(),reasoningTokens:y().int().min(0).optional(),charsPerToken:y().min(1).max(8).optional()}),vx=_x.keyof();vx.options;var yx=_x.required(),bx=E([`admin`,`probe`,`model-info`,`default`]),xx=S({model:v(),limits:yx,sources:T(vx,bx),ratio:y()});S({model:v(),limits:_x,setBy:M,updatedAt:N}),S({model:v(),ratio:y().min(.5).max(2),samples:y().int().min(0),updatedAt:N});var Sx=S({asked:y().int().min(0),got:y().int().min(0)}),Cx=S({window:y().int().min(0),output:y().int().min(0),reasoning:y().int().min(0),margin:y().int().min(0),fixed:y().int().min(0),pools:T(px,Sx),estimate:y().int().min(0),cut:x(S({what:v(),why:v()}))}),wx=S({name:I,detail:$b,activation:y().min(0)}),Tx=S({tokens:y().int().min(0),items:x(S({name:I,detail:E([`full`,`summary`,`listed`]),tokens:y().int().min(0)})),leftOut:x(S({name:I,why:Jb,reason:v()})),rebuilt:S({added:x(I),dropped:x(I)}).optional()}),Ex=S({contextor:gx,mode:ax,context:x(wx),fns:x(wx),linear:y().int().min(0),earlier:x(y().int().min(0)),budget:Cx,injected:Tx.optional()}),Dx=S({session:j,text:v().min(1),model:v().min(1).optional(),count:x(v()).max(200).optional()}),Ox=S({agent:I,model:v(),window:y().int().min(0),maxTokens:y().int().min(0),estimate:y().int().min(0),system:v(),tools:x(S({name:v(),description:v(),parameters:Zc(),tokens:y().int().min(0)})),messages:x(S({role:v(),content:v(),tokens:y().int().min(0)})),parts:S({instructions:v(),injected:v(),context:v(),guide:v(),tokens:S({instructions:y().int(),injected:y().int(),context:y().int(),guide:y().int(),system:y().int()})}),counts:x(y().int().min(0)),report:Ex}),kx=S({turn:cl,items:x(wx),at:N}),Ax=[`none`,`read`,`write`,`delete`,`auto`],jx=E(Ax),Mx=S({name:v().optional(),sheetName:v().optional(),sheetIndex:y().int().nonnegative().optional(),headers:x(v()),rows:x(x(v()))});E([`empty`,`boolean`,`integer`,`number`,`date`,`text`]);var Nx=E([`file`,`folder`,`link`,`other`]);S({entries:x(S({name:v(),location:v(),kind:Nx,type:v().optional(),size:y().nonnegative().optional(),modifiedAt:y().optional()})),truncated:b(),total:y().int().nonnegative()});var Px={converter:v(),from:v(),title:v().optional(),metadata:T(v(),sc()).optional()},Fx=w(`kind`,[S({kind:D(`markdown`),...Px,text:v()}),S({kind:D(`text`),...Px,text:v()}),S({kind:D(`code`),...Px,language:v(),text:v()}),S({kind:D(`pages`),...Px,pages:x(v())}),S({kind:D(`table`),...Px,tables:x(Mx)})]),Ix=Fx.options.map(e=>e.shape.kind.value),Lx=/^(?:true|false|yes|no)$/i,Rx=/^[-+]?\d{1,15}$/,zx=/^[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)?(?:\.\d+)?(?:e[-+]?\d+)?%?$/i,Bx=/^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[-+]\d{2}:?\d{2})?)?$|^\d{1,2}\/\d{1,2}\/\d{2,4}$/;function Vx(e){return Lx.test(e)?`boolean`:Rx.test(e)?`integer`:/\d/.test(e)&&zx.test(e)?`number`:Bx.test(e)&&!Number.isNaN(Date.parse(e))?`date`:`text`}function Hx(e,t){return e===`empty`||e===t?t:e===`integer`&&t===`number`||e===`number`&&t===`integer`?`number`:`text`}function Ux(e){let t=Math.max(e.headers.length,...e.rows.map(e=>e.length));return Array.from({length:t},(t,n)=>{let r=`empty`;for(let t of e.rows){let e=(t[n]??``).trim();e!==``&&(r=Hx(r,Vx(e)))}return r})}var Wx=Wc([v().regex(/^[a-z][a-z0-9+.-]*$/),`://`,v()]),Gx=v().min(1).brand(),Kx=`^[0-9a-f]{64}$`,qx=new RegExp(Kx),Jx=S({hash:v().regex(qx),size:y().int().min(0),mime:v()});S({content:Jx,mime:v(),finalUrl:v(),status:y().int(),rendered:b(),title:v().optional()});var Yx=S({uri:Wx,name:v(),description:v(),index:E([`all`,`on-read`,`none`]),ignore:x(v()),watch:b()}),Xx=S({uri:Wx,name:v(),type:E([`folder`,`file`,`page`,`record`,`other`]),mime:v().optional(),format:v().optional(),size:y().int().min(0).optional(),modifiedAt:N.optional(),version:v()}),Zx=S({uri:Wx.optional(),raw:v(),kind:E([`child`,`import`,`link`,`embed`,`external`]),title:v().optional()}),Qx=E([`links`,`text`,`bytes`]),$x=C([S({inline:v()}),S({ref:Jx})]),eS=S({stat:Xx,links:x(Zx).optional(),text:$x.optional(),bytes:Jx.optional()});E(Ix);var tS=[`description`,`ocr`,`transcript`,`thumbnail`];E(tS);var nS=E([...Ix,...tS]),rS=S({key:Gx,path:x(v()),title:v(),start:y().int().min(0),end:y().int().min(0),embedText:v().optional(),form:nS.optional()}),iS=S({uri:Wx,change:E([`added`,`changed`,`removed`]),version:v().optional()}),aS=S({format:v().optional(),mime:v().optional(),glob:v().optional(),form:nS.optional()}),oS=C([S({resource:Wx,section:Gx.optional(),title:v().optional()}),S({url:Nb,title:v()}),S({file:Jx,title:v()}),S({run:A,title:v()})]),sS=S({uri:Wx,section:Gx.optional(),title:v(),preview:v(),rank:y()}),cS=Gi();function lS(e,t){return cS.add(e,{why:t}),e}function uS(e){let t=e;for(;t!==void 0;){if(cS.has(t))return!0;t=t instanceof Tc||t instanceof jc||t instanceof Nc||t instanceof kc||t instanceof Vc?t.unwrap():void 0}return!1}function dS(e){let t=e.shape;return Object.entries(t).filter(([,e])=>uS(e)).map(([e])=>e)}var fS=new WeakMap;function pS(e,t){return fS.set(e,{schema:t}),e}var mS=w(`to`,[S({to:D(`session`),session:j}),S({to:D(`user`),user:M}),S({to:D(`everyone`)})]),hS=E([`live`,`snapshot`]),gS=w(`type`,[S({type:D(`system`)}),S({type:D(`memory`),scope:mS,author:M,run:A.optional()}),S({type:D(`resource`),uri:Wx,section:Gx.optional(),version:v(),copy:hS})]),_S=[`system`,`memory`,`resource`],vS=S({full:y().int().min(0),summary:y().int().min(0)}),yS=E([`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`mentions`,`about`,`learned`]),bS=[`imports`,`brings`,`suggests`,`parent`,`next`,`related`,`about`],xS=E(bS),SS=w(`kind`,[S({kind:D(`context`),name:I}),S({kind:D(`fn`),name:kb}),S({kind:D(`type`),name:I}),S({kind:D(`resource`),uri:Wx,section:Gx.optional()})]),CS=[`fn`,`context`,`resource`,`type`],wS=S({to:SS,relation:xS,weight:y().min(0).max(1).default(.5)}),TS=E([`declared`,`mentioned`,`resource`,`learned`,`authored`]),ES=S({from:I,to:SS,toKey:v(),relation:yS,weight:y().min(0).max(1),source:TS,uses:y().min(0).optional(),by:M.optional(),updatedAt:N}),DS=S({weight:y().min(0).max(2).optional(),summary:v().optional(),tags:x(v().min(1)).optional(),fns:x(kb).optional(),suggestFns:x(kb).optional(),inject:lS(Ub.optional(),`a model never writes text that lands in later prompts`),command:v().regex(/^[a-z][a-z0-9-]*$/).optional(),visible:zl.optional(),suggest:zl.optional(),parent:I.optional()}),OS=S({text:v().min(1),title:v().optional(),scope:E([`session`,`user`,`everyone`]).default(`session`),about:x(SS).optional(),question:v().min(1).max(500).optional(),when:v().min(1).max(500).optional()}).extend(DS.shape),kS=DS.keyof().exclude(DS.keyof().options.filter(e=>dS(DS).includes(e))),AS=OS.omit({scope:!0}).partial().extend({name:I,clear:pS(x(DS.keyof()).optional(),x(kS).optional())}),jS=S({uri:Wx,sections:x(Gx).optional(),copy:hS.default(`live`)}).extend(DS.omit({summary:!0,parent:!0}).shape),MS=S({created:x(I),updated:x(I),links:y().int().min(0)}),NS={maxDepth:3,maxDecisions:256,maxTokens:8e3},PS=[`active`,`hidden`,`not_applicable`,`pending_approval`,`pending_removal`,`pending_plan`],FS=E(PS),IS=E([`active`,`hidden`,`not_applicable`,`pending_approval`,`pending_removal`]);function LS(e){return e===`active`||e===`pending_removal`}var RS=[`person`,`system`,`research`],zS=E(RS),BS=S({status:FS,from:FS.optional(),by:M,reason:v().optional(),at:N}),VS=S({of:I,similarity:y().min(0).max(1).optional(),reason:v(),at:N}),HS=E([`question`,`when`,`askedBy`,`validUntil`]),US=S({model:v(),at:N,contentHash:v(),fields:x(HS)}),WS=S({from:I.optional(),into:x(I).optional()}),GS=`newContextStatus`,KS=E([`active`,`pending_approval`,`hidden`]),qS=S({value:KS,setBy:M.optional(),updatedAt:N.optional()}),JS=E([`question`,`content`]),YS=S({statuses:x(IS).min(1).optional(),returnNotApplicable:b().optional(),semanticOver:JS.optional()}),XS=[`approve`,`hide`,`restore`,`confirm_removal`],ZS=E(XS),QS=S({names:x(I).min(1).max(200),action:ZS,reason:v().min(1).max(500).optional()}),$S=S({changed:x(S({name:I,status:C([FS,D(`removed`)])})),skipped:x(S({name:I,reason:v()}))}),eC=[`duplicate`,`contradiction`,`pending_approval`,`pending_removal`],tC=E(eC),nC=S({kinds:x(tC).min(1).optional(),systems:x(v().min(1)).min(1).optional(),limit:y().int().min(1).max(200).optional(),cursor:v().optional()}),rC=S({name:I,system:v(),title:v(),question:v().optional(),status:FS,statusReason:v().optional(),lastModified:N,excerpt:v().optional()}),iC=S({items:x(S({kind:tC,item:rC,other:rC.optional(),flag:VS.optional()})),next:v().optional(),counts:S({duplicate:y().int().min(0),contradiction:y().int().min(0),pending_approval:y().int().min(0),pending_removal:y().int().min(0)})}),aC=S({keep:I,drop:I,reason:v().min(1).max(500).optional()}),oC=S({kept:I,hidden:I,links:y().int().min(0),mentions:y().int().min(0)}),sC=S({name:I,of:I}),cC=S({names:x(I).min(1).max(20)}),lC=S({done:x(S({name:I,fields:x(HS),split:x(I).optional()})),failed:x(S({name:I,reason:v()}))}),uC=S({name:I,question:v().optional(),when:v().optional(),askedBy:zS.optional(),validUntil:N.optional(),lastModified:N,status:FS,statusReason:v().optional(),statusHistory:x(BS),metadata:US.optional(),metadataStale:b(),duplicate:VS.optional(),contradiction:VS.optional(),notDuplicates:x(I),split:WS.optional()}),dC={openQuestions:60,depth:6,minutes:10,cost:2},fC=S({openQuestions:y().int().min(1).max(500).optional().describe(`The most open (unanswered) questions the plan may hold; planning stops when it is reached. Default 60.`),depth:y().int().min(1).max(12).optional().describe(`How many levels of questions deep the plan may go (1: only the first questions and their options). Default 6.`),minutes:y().min(.1).max(120).optional().describe(`The most minutes planning may take. Default 10.`),cost:y().min(0).max(100).optional().describe(`The most US dollars the model calls may cost. Default 2.`)}),pC=S({openQuestions:y().int().min(1),depth:y().int().min(1),minutes:y().min(0),cost:y().min(0)}),mC=E([`complete`,`open_questions`,`depth`,`time`,`cost`,`stopped`]),hC={complete:`Every question has its options`,open_questions:`Stopped at the open-question limit`,depth:`Stopped at the depth limit`,time:`Stopped at the time limit`,cost:`Stopped at the cost limit`,stopped:`Stopped before it finished`},gC=v().regex(/^o\d+$/),_C=S({id:gC,label:v().min(1).max(200),detail:v().max(1e3).optional(),raises:x(I),later:x(v().min(1).max(500)).optional()}),vC=S({question:I,option:gC}),yC=S({name:I,question:v().min(1),askedBy:zS.optional(),depth:y().int().min(1),parents:x(vC),options:x(_C),planned:b(),known:b().optional(),picked:x(gC),text:v().max(4e3).optional(),answeredBy:M.optional(),answeredAt:N.optional(),status:FS,statusReason:v().optional(),reasonEdited:b().optional()}),bC=S({questions:y().int().min(0),answered:y().int().min(0),open:y().int().min(0),ruledOut:y().int().min(0),decide:y().int().min(0)}),xC=S({description:v().min(1),limits:pC,stop:mC,cost:P,time:y().min(0),startedAt:N,updatedAt:N,roots:x(I),questions:x(yC),counts:bC,revision:y().int().min(0)}),SC=S({description:v().trim().min(1).max(4e3).describe(`What is to be planned, in the person's words with whatever they said about it: the more it says, the better the questions.`),limits:fC.optional()}),CC=S({run:A.describe(`The run of hub/ctx_plan that made the plan (its id, such as run_01HZX3).`)}),wC=CC.extend({format:E([`plan`,`markdown`]).optional().describe("`plan` (the default): the plan itself; `markdown`: the questions, answers and what was ruled out, as markdown to read or share.")}),TC=S({run:A,plan:xC,markdown:v().optional()}),EC=S({question:I.describe(`The question, by its context name as the plan gives it.`),picked:x(v().min(1)).max(20).describe(`The options chosen, by id (o1) or label; several when more than one applies. Empty with no text clears the answer.`),text:v().max(4e3).optional().describe(`The person's own words with the answer: a detail, a condition, or an answer none of the options gives.`)}),DC=S({question:I,reason:v().trim().min(1).max(500)}),OC=CC.extend({answers:x(EC).max(100).optional(),reasons:x(DC).max(100).optional()}),kC=S({run:A,plan:xC,changed:x(S({name:I,status:FS})),deeper:x(I),skipped:x(S({question:v(),reason:v()}))}),AC=CC.extend({under:I.optional().describe(`The question to plan deeper under, by its context name; leave out to go on with the whole plan.`),replan:b().optional().describe(`Write the options of the open questions under it again, taking the answers given since into account (after an answer changed).`),limits:fC.optional().describe("Limits of its own. Its `depth` is counted from the question it plans under (1: only the questions right under it), or, without `under`, from the deepest level that already has options.")}),jC=S({run:A,description:v(),counts:bC,stop:mC.optional(),running:b(),actor:M,session:v().optional(),createdAt:N,updatedAt:N}),MC=S({limit:y().int().min(1).max(100).optional()}),NC=S({items:x(jC)});function PC(e){return e.known===!0||e.picked.length>0||(e.text??``).trim()!==``}function FC(e){return e.options.filter(t=>e.picked.includes(t.id)).map(e=>e.label)}function IC(e){let t=FC(e).map(e=>`"${e}"`);return`${t.length>0?t.join(` and `):`none of the options`} for '${e.question}'`}function LC(e){return`You chose ${IC(e)}`}function RC(e,t){return`'${e.question}' no longer applies${t===void 0?``:`: you chose ${IC(t)}`}`}function zC(e,t){return e.picked.length===0||e.picked.includes(t)}function BC(e,t){let n=new Set(t),r=[...t];for(let t=r.shift();t!==void 0;t=r.shift()){let i=e.get(t);if(i!==void 0){for(let t of i.options)if(zC(i,t.id))for(let i of t.raises)!n.has(i)&&e.has(i)&&(n.add(i),r.push(i))}}return n}function VC(e,t){return e.picked.length>0&&!e.picked.includes(t)}function HC(e){let t=new Map(e.questions.map(e=>[e.name,e])),n=BC(t,e.roots.filter(e=>{let n=(t.get(e)?.parents??[]).filter(n=>n.question!==e&&t.has(n.question));return n.length===0?t.has(e):!n.every(e=>{let n=t.get(e.question);return n!==void 0&&VC(n,e.option)})})),r=e=>e.parents.flatMap(n=>{let r=t.get(n.question);return r===void 0||n.question===e.name?[]:[{edge:n,parent:r}]}),i=e=>{let t=r(e).filter(e=>VC(e.parent,e.edge.option)).map(e=>e.parent);return t.find(e=>n.has(e.name))??t[0]},a=(e,t)=>{if(t.has(e.name))return;t.add(e.name);let n=i(e);if(n!==void 0)return n;for(let{parent:n}of r(e)){let e=a(n,t);if(e!==void 0)return e}},o=new Map;for(let t of e.questions){if(n.has(t.name)){o.set(t.name,{live:!0});continue}let e=i(t);if(e!==void 0){o.set(t.name,{live:!1,reason:LC(e)});continue}let s=r(t)[0]?.parent;s===void 0?o.set(t.name,{live:!1,reason:`It no longer sits under any question of the plan`}):o.set(t.name,{live:!1,reason:RC(s,a(s,new Set([t.name])))})}return o}function UC(e){return`${e.answered} answered · ${e.open} open · ${e.decide} ${e.decide===1?`decision`:`decisions`} to make now`}y().int().min(1).max(65535).default({hub:4300,web:4310,mockHub:4320}.hub);function WC(e){return e.split(`/`).filter((e,t)=>t!==0||e!==``).map(e=>e.startsWith(`:`)?{t:`param`,k:e.slice(1)}:{t:`lit`,v:e})}function GC(e){return`/`+e.map(e=>e.t===`param`?`:${e.k}`:e.v).join(`/`)}function KC(e,t){return`/`+e.map(e=>{if(e.t===`lit`)return e.v;let n=t[e.k];if(n===void 0)throw Error(`path is missing a value for ":${e.k}"`);return encodeURIComponent(String(n))}).join(`/`)}function qC(e){return e.filter(e=>e.t===`param`).map(e=>e.k)}var JC=class extends Error{status;code;data;constructor(e,t,n,r){super(n??t),this.status=e,this.code=t,this.data=r,this.name=`ApiError`}},YC=()=>{let e=globalThis.navigator;return typeof e?.onLine==`boolean`?e.onLine:void 0};function XC(e={}){let t=new Set,n=e.initial??(YC()===!1?`offline`:`online`),r=e=>{if(e!==n){n=e;for(let n of[...t])n(e)}},i=e=>(t.add(e),()=>void t.delete(e)),a=()=>{},o=globalThis;if((e.browser??!0)&&typeof o.addEventListener==`function`&&typeof o.removeEventListener==`function`){let e=()=>r(`online`),t=()=>r(`offline`);o.addEventListener(`online`,e),o.addEventListener(`offline`,t),a=()=>{o.removeEventListener(`online`,e),o.removeEventListener(`offline`,t)}}return{get status(){return n},subscribe:i,whenOnline:(e,t)=>new Promise((r,a)=>{if(n===`online`){r();return}if(e?.aborted){a(e.reason);return}let o=null,s=t=>{l(),o&&clearTimeout(o),e?.removeEventListener(`abort`,c),t()};function c(){s(()=>a(e.reason))}let l=i(e=>{e===`online`&&s(r)});t?.timeout!==void 0&&(o=setTimeout(()=>s(r),t.timeout)),e?.addEventListener(`abort`,c,{once:!0})}),report:r,dispose:()=>{a(),a=()=>{}}}}var ZC=e=>{if(Array.isArray(e))return e.map(ZC);if(e&&typeof e==`object`){let t={};for(let n of Object.keys(e).sort())t[n]=ZC(e[n]);return t}return e},QC=e=>JSON.stringify(ZC(e))??`null`,$C=e=>{try{return JSON.stringify(e)!==void 0}catch{return!1}},ew=(e,t)=>({get:n=>e.getItem(t+n)??void 0,set:(n,r)=>e.setItem(t+n,r),delete:n=>{let r=t+n,i=e.getItem(r)!==null;return e.removeItem(r),i},keys:function*(){for(let n=0;n<e.length;n++){let r=e.key(n);r!==null&&r.startsWith(t)&&(yield r.slice(t.length))}}}),tw=(e,t)=>{if(typeof e==`object`)return e;if(e!==`memory`)try{let n=e===`local`?globalThis.localStorage:globalThis.sessionStorage;if(n)return ew(n,t)}catch{}let n=new Map;return{get:e=>n.get(e),set:(e,t)=>void n.set(e,t),delete:e=>n.delete(e),keys:()=>n.keys()}};function nw(e={}){let t=e.max??500,n=e.ttl??0,r=e.now??Date.now,i=tw(e.store??`memory`,e.prefix??`ayepi:cache:`),a=new Map;for(let e of i.keys())a.set(e,!0);let o=e=>{a.delete(e),a.set(e,!0)},s=e=>{let t=i.get(e);if(t!==void 0)try{return JSON.parse(t)}catch{i.delete(e);return}},c=e=>(a.delete(e),i.delete(e)),l=()=>{for(;a.size>t;)c(a.keys().next().value)};return{read:e=>{let t=s(e);if(!t)return;let n=r();if(t.exp&&n>=t.exp){if(!t.stale||n>=t.stale){c(e);return}return o(e),{value:t.v,stale:!0}}return o(e),{value:t.v,stale:!1}},write:(e,t,a)=>{if(!$C(t))return;let s=a?.ttl??n,c=s>0?r()+s:0,u={v:t,exp:c,stale:c&&a?.staleWhileRevalidate?c+a.staleWhileRevalidate:0,tags:a?.tags??[]};i.set(e,JSON.stringify(u)),o(e),l()},remove:e=>void c(e),removeWhere:e=>{let t=0;for(let n of[...i.keys()])e(n)&&c(n)&&(t+=1);return t},invalidateTags:e=>{if(e.length===0)return 0;let t=new Set(e),n=0;for(let e of[...i.keys()]){let r=s(e);r&&r.tags.some(e=>t.has(e))&&c(e)&&(n+=1)}return n},clear:()=>{for(let e of[...i.keys()])i.delete(e);a.clear()}}}function rw(e={},t=XC()){let n=new Map,r=t=>{let r=t??e.store??`memory`,i=n.get(r);return i||(i=nw({...e,store:r}),n.set(r,i)),i};return{cacheFor:r,invalidateTags:e=>{r(void 0);for(let t of n.values())t.invalidateTags(e)},connectivity:t}}var iw=class extends Error{constructor(e=`caller rate limit exceeded`){super(e),this.name=`CallerRateLimited`}},aw=`\0`,ow=e=>new DOMException(e,`AbortError`),sw=e=>{let t=e.filter(e=>e!==void 0);if(t.length===1)return t[0];let n=new AbortController,r=()=>{n.abort();for(let e of t)e.removeEventListener(`abort`,r)};for(let e of t){if(e.aborted)return n.abort(),n.signal;e.addEventListener(`abort`,r,{once:!0})}return n.signal},cw=(e,t)=>new Promise((n,r)=>{if(t.aborted){r(ow(`aborted`));return}let i=()=>{clearTimeout(a),r(ow(`aborted`))},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},e);t.addEventListener(`abort`,i,{once:!0})}),lw=(e,t)=>t.reduceRight((e,t)=>t(e),e),uw=(e,t,n)=>e===void 0?[]:typeof e==`function`?e(t,n):e,dw=(e,t)=>n=>async(r,i)=>{t.n+=1,e.onStart?.(r.data);try{let t=await n(r,i);return e.onSuccess?.(t,r.data),t}catch(t){throw e.onError?.(t,r.data),t}finally{--t.n,e.onSettled?.(r.data)}},fw=(e,t,n)=>r=>async(i,a)=>{t!==`success`&&n.invalidateTags(uw(e,i.data,void 0));let o=await r(i,a);return t!==`start`&&n.invalidateTags(uw(e,i.data,o)),o},pw=(e,t,n)=>r=>async(i,a)=>{let o=n(i.data),s=n=>t.write(o,n,{ttl:e.ttl,staleWhileRevalidate:e.staleWhileRevalidate,tags:uw(e.tags,i.data,n)}),c=t.read(o);if(c&&!c.stale)return c.value;if(c&&c.stale)return r(i,a).then(s).catch(()=>{}),c.value;let l=await r(i,a);return s(l),l},mw=e=>{let t=new Map;return n=>(r,i)=>{let a=e(r.data),o=t.get(a);if(o)return o;let s=n(r,i).finally(()=>t.delete(a));return t.set(a,s),s}},hw=()=>{let e=null;return t=>(n,r)=>{e?.abort(ow(`superseded`));let i=new AbortController;e=i;let a=sw([r,i.signal]);return new Promise((e,r)=>{a.addEventListener(`abort`,()=>r(ow(`superseded`)),{once:!0}),t(n,a).then(e,r)}).finally(()=>{e===i&&(e=null)})}},gw=e=>{let t=e.onLimit??`wait`,n=e.window/e.limit,r=e.limit,i=Date.now(),a=()=>{let t=Date.now(),n=(t-i)/e.window*e.limit;n>0&&(r=Math.min(e.limit,r+n),i=t)};return e=>async(i,o)=>{if(a(),r<1){if(t===`throw`||t===`drop`)throw new iw;await cw((1-r)*n,o),a()}return--r,e(i,o)}},_w=e=>{let t=e.attempts??3,n=e.base??200,r=e.factor??2,i=e.max??3e4,a=e.jitter??.5;return e=>async(o,s)=>{let c;for(let l=1;l<=t;l+=1)try{return await e(o,s)}catch(e){if(c=e,l>=t)break;await cw(Math.min(i,n*r**(l-1))*(1-a*Math.random()),s)}throw c}},vw=e=>e instanceof JC&&e.status===0&&e.code===`DISCONNECTED`,yw=(e,t)=>{let n=e.maxRetries??1/0,r=e.backoff??1e3;return i=>async(a,o)=>{let s=e.timeout===void 0?1/0:Date.now()+e.timeout,c=0;for(;;)try{return await i(a,o)}catch(e){if(!vw(e)||c>=n)throw e;let i=s-Date.now();if(i<=0)throw e;c+=1,await t.connectivity.whenOnline(o,{timeout:Math.min(r,i)})}}},bw=(e,t)=>{let n=null,r=[],i=0;return a=>{let o=t=>{n&&=(clearTimeout(n),null);let o=r;r=[],i=0;let s=o.map(e=>e.call.data);a(e.accumulate?{data:e.accumulate(s),opts:o[o.length-1].call.opts}:o[o.length-1].call,t).then(t=>{let n=e.spread?e.spread(t,s):null;o.forEach((e,r)=>e.resolve(n?n[r]:t))},e=>o.forEach(t=>t.reject(e)))};return t.push(()=>{n&&=(clearTimeout(n),null);let e=r;r=[],i=0;for(let t of e)t.reject(ow(`cancelled`))}),(t,a)=>new Promise((s,c)=>{let l=Date.now();r.length===0&&(i=l),r.push({call:t,resolve:s,reject:c});let u=e.leading&&n===null&&r.length===1;n&&clearTimeout(n);let d=e.maxWait!==void 0&&l-i>=e.maxWait;if(u||d){o(a);return}let f=e.maxWait===void 0?e.wait:Math.min(e.wait,i+e.maxWait-l);n=setTimeout(()=>o(a),f)})}};function xw(e,t,n,r,i){if(t.items||t.itemsIn||t.streamIn!==null||t.streamOut!==null)return{call:(...e)=>n(...e),cancel:()=>{},invalidate:()=>{},pending:0};let a=t.p.length>0||t.q.length>0||t.hasBody||t.f.length>0,o=i.cache===!0||i.cache===void 0||i.cache===!1?{}:i.cache,s=e=>o.key?o.key(e):QC(e),c=t=>`${e}${aw}${s(t)}`,l=i.cache?r.cacheFor(o.store):null,u={n:0},d=[],f=new AbortController,p=(e,t)=>{let r={...e.opts??{},signal:t};return Promise.resolve(a?n(e.data,r):n(r))},m=[];if((i.onStart||i.onSuccess||i.onError||i.onSettled)&&m.push(dw(i,u)),i.invalidates&&m.push(fw(i.invalidates,i.invalidateOn??`success`,r)),l&&m.push(pw(o,l,c)),i.dedupe&&m.push(mw(c)),i.lastOnly&&m.push(hw()),i.debounce!==void 0){let e=typeof i.debounce==`number`?{wait:i.debounce}:i.debounce;m.push(bw(e,d))}i.rateLimit&&m.push(gw(i.rateLimit)),i.retry&&m.push(_w(i.retry));let h=t.sideEffects===!1||t.sideEffects===void 0&&t.method===`GET`,ee=i.replay===!1?null:i.replay===void 0?h?{}:null:typeof i.replay==`object`?i.replay:{};ee&&(h||ee.force)&&m.push(yw(ee,r)),(i.onOnline||i.onOffline)&&r.connectivity.subscribe(e=>e===`online`?i.onOnline?.():i.onOffline?.());let te=lw(p,m);return{call:(...e)=>{let t=a?e[0]:void 0,n=a?e[1]:e[0],r=sw([n?.signal,f.signal]);return te({data:t,opts:n},r)},cancel:()=>{f.abort(ow(`cancelled`)),f=new AbortController;for(let e of d)e()},invalidate:()=>void l?.removeWhere(t=>t.startsWith(`${e}${aw}`)),get pending(){return u.n}}}function Sw(e){try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:null}catch{return null}}function Cw(e){let{id:t,...n}=e;return JSON.stringify({rid:typeof t==`string`?t:null,...n})}function ww(e){let{rid:t,...n}=e;return JSON.stringify(typeof t==`string`?{id:t,...n}:n)}function Tw(e,t){return JSON.stringify({id:e,$status:0,$code:`DISCONNECTED`,$error:t})}function Ew(e){return`$status`in e||e.end===!0}var Dw=class{#e=new Set;add(e){this.#e.add(e)}settle(e){typeof e.id==`string`&&Ew(e)&&this.#e.delete(e.id)}fail(e,t){let n=[...this.#e];this.#e.clear();for(let r of n)e(Tw(r,t))}},Ow={$status:501,$code:`NOT_SERVED`,$error:`this client serves no spec`};function kw(e,t){let n=e.rid;typeof n==`string`&&typeof e.type==`string`&&t(JSON.stringify({rid:n,...Ow}))}var Aw=class{app;send;request;#e=null;constructor(e,t,n){this.app=e,this.send=t,this.request=n}receive(e){let t=this.#e??this.#t();this.app.ws.message(t,ww(e))}drop(){let e=this.#e;e&&(this.#e=null,this.app.ws.close(e))}#t(){let e=this.app.ws.open(t=>{let n=Sw(t);n&&this.#e===e&&this.send(Cw(n))},this.request());return this.#e=e,e}},jw=new Set([101,204,205,304]);function Mw(e,t,n,r,i,a){return new Promise((o,s)=>{if(i?.aborted){s(new DOMException(`The operation was aborted.`,`AbortError`));return}let c=new XMLHttpRequest;c.open(e,t,!0),c.responseType=`arraybuffer`;for(let[e,t]of Object.entries(n))c.setRequestHeader(e,t);c.upload.onprogress=e=>{e.lengthComputable&&a({loaded:e.loaded,total:e.total})};let l=()=>c.abort(),u=()=>i?.removeEventListener(`abort`,l);c.onload=()=>{u();let e=jw.has(c.status)?null:c.response;o(new Response(e,{status:c.status,statusText:c.statusText}))},c.onerror=()=>{u(),s(TypeError(`Network request failed`))},c.onabort=()=>{u(),s(new DOMException(`The operation was aborted.`,`AbortError`))},i?.addEventListener(`abort`,l,{once:!0}),c.send(r)})}function Nw(e){return!!e&&typeof e.parse==`function`}function Pw(e){let t=Fw(e);return t?t():e}function Fw(e){let t=e[Symbol.for(`ayepi.manifest`)];return typeof t==`function`?t:void 0}function Iw(e){return typeof e==`number`&&e>=200&&e<300}var Lw={400:`Bad Request`,401:`Unauthorized`,403:`Forbidden`,404:`Not Found`,405:`Method Not Allowed`,409:`Conflict`,410:`Gone`,422:`Unprocessable Entity`,429:`Too Many Requests`,500:`Internal Server Error`,502:`Bad Gateway`,503:`Service Unavailable`};function Rw(e){let t=Number(e.$status);return new JC(t,typeof e.$code==`string`?e.$code:`ERROR`,typeof e.$error==`string`?e.$error:Lw[t]??`Request failed with status ${t}`,e.data)}function zw(e){let t=Pw(e.manifest),n=e.fetchImpl??(e=>fetch(e)),r=XC(),i=rw(e.cache,r);e.ws?.onState?.(e=>r.report(e===`open`?`online`:`offline`));let a=()=>typeof e.headers==`function`?e.headers():e.headers??{},o=t=>e.unauthorized!==void 0&&Object.keys(t).some(e=>e.toLowerCase()===`authorization`),s=null,c=()=>{let t=e.unauthorized;return t?(s??=t().catch(()=>!1).finally(()=>{s=null}),s):Promise.resolve(!1)},l=t=>e.validate?.endpoints[t]?.cfg,u=(e,t)=>{let n=l(e);return n?.response?n.response.parse(t):t},d=(e,t)=>{let n=l(e);return n&&Nw(n.streamOut)?n.streamOut.parse(t):t},f=(e,t,n)=>{let r=l(e)?.responses?.[t];return r?r.parse(n):n},p=0,m=new Map,h=new Map,ee=new Map,te=new Map,ne=new Map,re=(t,n,r)=>{r&&o(a())&&ne.set(t,n),e.ws?.send(n)},ie=e=>{let t=te.get(e);t&&(te.delete(e),t())},ae=(t,n,r)=>{if(!n)return;let i=()=>{te.delete(t),ne.delete(t),r(n.reason)&&e.ws?.send(JSON.stringify({id:t,abort:!0}))};n.aborted?i():(n.addEventListener(`abort`,i,{once:!0}),te.set(t,()=>n.removeEventListener(`abort`,i)))},oe=e=>JSON.stringify(e??{},Object.keys(e??{}).sort());if(e.ws){let t=e.ws,n=e=>t.send(e),r=e.serve?new Aw(e.serve,n,()=>new Request(new URL(e.baseUrl,`http://peer.invalid/`))):null;r&&t.onState?.(e=>{e!==`open`&&r.drop()}),t.onMessage(e=>{let i=Sw(e);if(!i)return;if(`rid`in i){r?r.receive(i):kw(i,n);return}if(typeof i.id!=`string`){if(typeof i.type==`string`){let e=`${i.type}|${oe(i.params)}`;for(let t of ee.get(e)??[])t(i.data)}return}let a=i.id,o=ne.get(a);ne.delete(a),o!==void 0&&i.$status===401?c().then(e=>{(m.has(a)||h.has(a))&&(e?t.send(o):se(a,i))}):se(a,i)})}function se(e,t){let n=`$status`in t&&!Iw(t.$status);if(h.has(e)){let r=h.get(e);`chunk`in t?r.push(t.chunk):t.end===!0?(h.delete(e),ie(e),r.end()):n&&(h.delete(e),ie(e),r.fail(Rw(t)))}else if(m.has(e)){let r=m.get(e);m.delete(e),ie(e),n?r.reject(Rw(t)):r.resolve(t.data)}}function ce(){let e=[],t=!1,n,r=null;return{push(t){e.push(t),r?.()},end(){t=!0,r?.()},fail(e){n=e,t=!0,r?.()},async*iterate(){for(;;)if(e.length>0)yield e.shift();else{if(n!==void 0)throw n;if(t)return;await new Promise(e=>r=e),r=null}}}}function le(t,n){let r=typeof n==`function`?n():n;(async()=>{try{for await(let n of r)e.ws.send(JSON.stringify({id:t,chunk:n}));e.ws.send(JSON.stringify({id:t,end:!0}))}catch{e.ws.send(JSON.stringify({id:t,end:!0}))}})()}function ue(e,t,n){return JSON.stringify(t.ws===null?{id:e,type:t.path,method:t.method,data:n}:{id:e,type:t.ws,data:n})}function de(t,n,r,i,a){if(!e.ws){let e=Error(`no websocket transport configured`);if(!n.items)return Promise.reject(e);throw e}let o=`c${++p}`;if(n.items){let e=ce();return h.set(o,e),ae(o,a,t=>h.delete(o)?(e.fail(t),!0):!1),re(o,ue(o,n,r),!n.itemsIn),n.itemsIn&&le(o,i),(async function*(){for await(let n of e.iterate())yield d(t,n)})()}let s=new Promise((e,t)=>{m.set(o,{resolve:e,reject:t}),ae(o,a,e=>{let t=m.get(o);return t?(m.delete(o),t.reject(e),!0):!1}),re(o,ue(o,n,r),!1)});return n.itemsIn&&le(o,i),s.then(e=>n.multi?e:u(t,e))}function fe(t,n){if(!e.ws)return Promise.reject(Error(`no websocket transport configured`));let r=`c${++p}`;return new Promise((e,i)=>{m.set(r,{resolve:e,reject:i}),ae(r,n,e=>{let t=m.get(r);return t?(m.delete(r),t.reject(e),!0):!1}),re(r,JSON.stringify({id:r,...t}),!0)})}function g(e,t){if(e.b===`raw`)return{p:{},q:{},b:t,f:{}};let n={},r={},i={},a={},o=new Set(e.p),s=new Set(e.q),c=new Set(e.b??[]),l=new Set(e.f);for(let[e,u]of Object.entries(t??{}))if(o.has(e))n[e]=u;else if(s.has(e))r[e]=u;else if(c.has(e))i[e]=u;else if(l.has(e))a[e]=u;else throw Error(`key "${e}" does not belong to endpoint data`);return{p:n,q:r,b:e.hasBody?i:void 0,f:a}}function pe(t,n,r){let i=KC(WC(t.path),n),a=new URL(i.slice(1),e.baseUrl.endsWith(`/`)?e.baseUrl:e.baseUrl+`/`);for(let[e,t]of Object.entries(r))if(t!==void 0){if(Array.isArray(t))for(let n of t)a.searchParams.append(e,String(n));else a.searchParams.set(e,String(t))}return a}function me(e){let t=(typeof e==`function`?e():e)[Symbol.asyncIterator](),n=new TextEncoder;return new ReadableStream({async pull(e){let{done:r,value:i}=await t.next();if(r)return e.close();e.enqueue(n.encode(JSON.stringify(i)+`
|
|
395
|
+
`))},async cancel(){await t.return?.(void 0)}})}async function he(e,t,i,s=!1){let{p:l,q:u,b:d,f}=g(e,t),p=i?.stream,m=pe(e,l,u),h={...a(),...i?.headers??{}},ee=null,te=!1;if(e.streamIn)h[`content-type`]=e.streamIn,e.itemsIn?(ee=me(p),te=!0):(ee=p,te=p instanceof ReadableStream);else if(e.f.length>0){let e=new FormData;d!==void 0&&e.set(`body`,JSON.stringify(d));for(let[t,n]of Object.entries(f))if(n!==void 0){if(Array.isArray(n))for(let r of n)e.append(t,r);else e.set(t,n)}ee=e}else if(e.hasBody){if(e.bodyEnc===`urlencoded`){h[`content-type`]=`application/x-www-form-urlencoded`;let e=new URLSearchParams;for(let[t,n]of Object.entries(d??{}))if(n!==void 0){if(Array.isArray(n))for(let r of n)e.append(t,String(r));else e.set(t,String(n))}ee=e.toString()}else h[`content-type`]=`application/json`,ee=JSON.stringify(d)}let ne={method:e.method,headers:h,body:ee,signal:i?.signal};te&&(ne.duplex=`half`);let re=i?.onUploadProgress,ie;try{ie=re&&!e.streamIn&&!e.streamOut&&typeof XMLHttpRequest<`u`?await Mw(e.method,m.toString(),h,ee,i?.signal,re):await n(new Request(m,ne))}catch(e){throw e instanceof TypeError?(r.report(`offline`),new JC(0,`DISCONNECTED`,`network request failed`)):e}if(r.report(`online`),ie.status===401&&!s&&e.streamIn===null&&o(h)&&await c())return await ie.body?.cancel().catch(()=>{}),he(e,t,i,!0);if(!ie.ok){let e=await ie.json().catch(()=>({})),t=e?.error;throw new JC(ie.status,t?.code??`ERROR`,t?.message,e)}return ie}async function ge(e,t,n,r){let i=await he(t,n,r);if(t.streamOut)return i.body??new ReadableStream({start:e=>e.close()});if(t.multi)return{status:i.status,data:f(e,i.status,await i.json())};if(i.status!==204)return u(e,await i.json())}async function*_e(e,t,n,r){let i=await he(t,n,r);if(!i.body)return;let a=t.streamOut===`text/event-stream`,o=a?`
|
|
396
396
|
|
|
397
397
|
`:`
|
|
398
398
|
`,s=t=>{let n=a?t.split(`
|
|
399
399
|
`).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(`
|
|
400
|
-
`):t;if(n.trim())return d(e,JSON.parse(n))},c=i.body.getReader(),l=new TextDecoder,u=``;try{for(;;){let{done:e,value:t}=await c.read();if(e)break;u+=l.decode(t,{stream:!0});let n;for(;(n=u.indexOf(o))>=0;){let e=u.slice(0,n);u=u.slice(n+o.length);let t=s(e);t!==void 0&&(yield t)}}u+=l.decode();let e=s(u);e!==void 0&&(yield e)}finally{await c.cancel().catch(()=>{})}}function ve(n,...r){let i=t.endpoints[n];if(!i)return Promise.reject(Error(`unknown endpoint "${n}"`));let a=i.p.length>0||i.q.length>0||i.hasBody||i.f.length>0||i.streamIn!==null,o=a?r[0]:void 0,s=a?r[1]:r[0],c=s?.transport??(e.prefer===`ws`&&!i.httpOnly&&e.ws?`ws`:`http`);if(c===`ws`&&i.httpOnly){let e=Error(`endpoint "${n}" is http-only`);if(i.items)throw e;return Promise.reject(e)}return i.items||i.itemsIn?c===`ws`?de(n,i,o,s?.stream,s?.signal):i.items?_e(n,i,o,s):ge(n,i,o,s):c===`ws`?fe(i.ws===null?{type:i.path,method:i.method,data:o}:{type:i.ws,data:o},s?.signal).then(e=>i.multi?e:u(n,e)):ge(n,i,o,s)}function ye(e,...n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);if(r.method!==`GET`)throw Error(`url() requires a GET endpoint; "${e}" is ${r.method}`);let{p:i,q:a}=g(r,n[0]);return pe(r,i,a).toString()}function be(n,...r){let i=t.events[n];if(!i)throw Error(`unknown event "${n}"`);if(!e.ws)throw Error(`no websocket transport configured`);let a=i.hasParams?r[0]:void 0,o=i.hasParams?r[1]:r[0],s=`${i.ws}|${oe(a)}`,c=ee.get(s);return c||ee.set(s,c=new Set),c.add(o),fe({sub:i.ws,params:a}),()=>{c.delete(o),c.size===0&&fe({unsub:i.ws,params:a})}}function xe(e,n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);return 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-
|
|
400
|
+
`):t;if(n.trim())return d(e,JSON.parse(n))},c=i.body.getReader(),l=new TextDecoder,u=``;try{for(;;){let{done:e,value:t}=await c.read();if(e)break;u+=l.decode(t,{stream:!0});let n;for(;(n=u.indexOf(o))>=0;){let e=u.slice(0,n);u=u.slice(n+o.length);let t=s(e);t!==void 0&&(yield t)}}u+=l.decode();let e=s(u);e!==void 0&&(yield e)}finally{await c.cancel().catch(()=>{})}}function ve(n,...r){let i=t.endpoints[n];if(!i)return Promise.reject(Error(`unknown endpoint "${n}"`));let a=i.p.length>0||i.q.length>0||i.hasBody||i.f.length>0||i.streamIn!==null,o=a?r[0]:void 0,s=a?r[1]:r[0],c=s?.transport??(e.prefer===`ws`&&!i.httpOnly&&e.ws?`ws`:`http`);if(c===`ws`&&i.httpOnly){let e=Error(`endpoint "${n}" is http-only`);if(i.items)throw e;return Promise.reject(e)}return i.items||i.itemsIn?c===`ws`?de(n,i,o,s?.stream,s?.signal):i.items?_e(n,i,o,s):ge(n,i,o,s):c===`ws`?fe(i.ws===null?{type:i.path,method:i.method,data:o}:{type:i.ws,data:o},s?.signal).then(e=>i.multi?e:u(n,e)):ge(n,i,o,s)}function ye(e,...n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);if(r.method!==`GET`)throw Error(`url() requires a GET endpoint; "${e}" is ${r.method}`);let{p:i,q:a}=g(r,n[0]);return pe(r,i,a).toString()}function be(n,...r){let i=t.events[n];if(!i)throw Error(`unknown event "${n}"`);if(!e.ws)throw Error(`no websocket transport configured`);let a=i.hasParams?r[0]:void 0,o=i.hasParams?r[1]:r[0],s=`${i.ws}|${oe(a)}`,c=ee.get(s);return c||ee.set(s,c=new Set),c.add(o),fe({sub:i.ws,params:a}),()=>{c.delete(o),c.size===0&&fe({unsub:i.ws,params:a})}}function xe(e,n){let r=t.endpoints[e];if(!r)throw Error(`unknown endpoint "${e}"`);return xw(e,r,(...t)=>ve(e,...t),i,n??{})}return{call:ve,on:be,url:ye,caller:xe,connection:{get status(){return r.status},subscribe:e=>r.subscribe(e)}}}var Bw={initial:500,max:3e4,factor:2,jitter:!0},Vw={interval:3e4,timeout:1e4};function Hw(e,t={}){let n=t.WebSocket??globalThis.WebSocket;if(!n)throw Error(`wsTransport: no WebSocket implementation available; pass opts.WebSocket`);let r=n,i=t.whileDisconnected??`fail`,a={...Bw,...t.backoff},o=t.heartbeat===!1?null:{...Vw,...t.heartbeat??{}},s=t.maxRetries??1/0,c=null,l=`closed`,u=null,d=0,f=!1,p=!1,m=null,h=null,ee=null,te=[],ne=new Map,re=new Dw,ie=new Set,ae=e=>{if(e!==l){l=e,t.onStateChange?.(e);for(let t of[...ie])t(e)}},oe=e=>u?.(e),se=e=>JSON.stringify(e??{},Object.keys(e??{}).sort());function ce(){re.fail(oe,`connection closed`)}function le(){h&&clearInterval(h),ee&&clearTimeout(ee),h=ee=null}function ue(){o&&(le(),h=setInterval(()=>{l===`open`&&c&&(c.send(JSON.stringify({ping:!0})),ee&&clearTimeout(ee),ee=setTimeout(()=>c?.close(),o.timeout))},o.interval))}function de(e){let t=null;try{t=JSON.parse(e)}catch{oe(e);return}t&&t.pong===!0?ee&&=(clearTimeout(ee),null):(t&&re.settle(t),oe(e))}function fe(){if(p)return;f=!0,d=0,ae(`open`);for(let e of ne.values())c?.send(e);let e=te.splice(0);for(let t of e)c?.send(t);ue()}function g(){le(),c=null,ce(),p?ae(`closed`):pe()}function pe(){if(p)return;if(d>=s){ae(`closed`);return}let e=Math.min(a.max,a.initial*a.factor**+d),t=a.jitter?e/2+e/2*Math.random():e;d++,ae(`connecting`),m=setTimeout(me,t)}function me(){if(p||c)return;m&&=(clearTimeout(m),null),ae(`connecting`);let n;try{n=new r(typeof e==`function`?e():e,typeof t.protocols==`function`?t.protocols():t.protocols)}catch(e){t.onError?.(e),pe();return}c=n;let i=!1,a=()=>{c===n&&g()};n.addEventListener(`open`,()=>{i=!0,fe()}),n.addEventListener(`message`,e=>de(String(e.data))),n.addEventListener(`close`,a),n.addEventListener(`error`,e=>{t.onError?.(e),i||a()})}function he(e){let t={};try{t=JSON.parse(e)}catch{}typeof t.sub==`string`?ne.set(`${t.sub}|${se(t.params)}`,e):typeof t.unsub==`string`&&ne.delete(`${t.unsub}|${se(t.params)}`),typeof t.id==`string`&&typeof t.type==`string`&&re.add(t.id);let n=typeof t.sub==`string`||typeof t.unsub==`string`;l===`open`&&c?c.send(e):`rid`in t||(me(),n||(!f||i===`queue`?te.push(e):typeof t.id==`string`&&oe(Tw(t.id,`not connected`))))}return{send:he,onMessage(e){u=e},connect:me,reconnect(){if(p)return;let e=c;c=null,le(),ce(),e?.close(),d=0,me()},close(){p=!0,m&&clearTimeout(m),m=null,le(),ce(),c?.close(),c=null,ae(`closed`)},get state(){return l},onState(e){return ie.add(e),()=>void ie.delete(e)}}}function Uw(e,t,n){return{kind:`endpoint`,cfg:e,mws:t,prefixes:n}}function Y(e){return Uw(e,[],[])}function X(e){for(let[t,n]of Object.entries(e.endpoints)){let e=n.cfg;if(e.streamIn&&(e.body||e.files))throw Error(`endpoint "${t}": streamIn excludes body/files`);if(e.files&&`body`in e.files)throw Error(`endpoint "${t}": "body" is reserved as the multipart JSON field name`);if(e.streamOut&&e.response)throw Error(`endpoint "${t}": streamOut excludes response`);if(e.responses&&e.response)throw Error(`endpoint "${t}": responses (multi-status) excludes response`);if(e.responses&&e.streamOut)throw Error(`endpoint "${t}": responses excludes streamOut`);if(e.streamEncoding&&!(e.streamOut instanceof ws))throw Error(`endpoint "${t}": streamEncoding requires a typed (schema) streamOut`);if(e.bodyEncoding===`urlencoded`&&!(e.body instanceof dc))throw Error(`endpoint "${t}": urlencoded bodies must be z.object(...)`);if(e.download&&typeof e.streamOut!=`string`)throw Error(`endpoint "${t}": download requires a raw (content-type) streamOut`);for(let n of[`params`,`query`,`headers`,`cookies`]){let r=e[n];if(r&&!(r instanceof dc))throw Error(`endpoint "${t}": ${n} must be a z.object(...)`)}qw(t,n)}let t;return Object.defineProperty(e,Ww,{value:()=>t??=Gw(e),enumerable:!1,configurable:!0}),e}var Ww=Symbol.for(`ayepi.manifest`);function Gw(e){let t=Object.entries(e.endpoints).map(([e,t])=>qw(e,t));return{endpoints:Object.fromEntries(t.map(e=>[e.name,{method:e.method,path:e.path,ws:e.ws,httpOnly:e.httpOnly,streamIn:e.streamInCt,itemsIn:e.itemsIn,streamOut:e.streamOutCt,items:e.items,p:e.p,q:e.q,b:e.bRaw?`raw`:e.b,f:e.f,hasBody:!!e.def.cfg.body,hasHeaders:!!e.def.cfg.headers,multi:e.multi,bodyEnc:e.bodyEnc,sideEffects:e.def.cfg.sideEffects}])),events:Object.fromEntries(Object.entries(e.events??{}).map(([e,t])=>[e,{ws:t.ws??e,hasParams:!!t.params}]))}}function Kw(e){return e&&e instanceof dc?Object.keys(e.shape):null}function qw(e,t){let n=t.cfg,r=tT(t.mws),i=t=>{throw Error(`endpoint "${e}": ${t}`)},a=new Map;for(let e of r)e.paramKey&&e.paramSchema&&a.set(e.paramKey,e.paramSchema);let o=new Map,s=(e,t)=>{for(let n of e.keys)(a.has(n)||o.has(n))&&i(`param ":${n}" is declared more than once (${t})`),o.set(n,e.schemas[n])};for(let e of t.prefixes)typeof e!=`string`&&s(e,`prefix path`);let c=typeof n.path==`object`&&n.path!==null?n.path:null;c&&s(c,`endpoint path`);let l=Kw(n.params)??[];for(let e of l)(a.has(e)||o.has(e))&&i(`param ":${e}" is declared more than once (params schema)`);let u=new Set([...a.keys(),...o.keys(),...l]),d=[];for(let e of t.prefixes)d.push(...typeof e==`string`?WC(e):e.parts);if(c)d.push(...c.parts);else if(typeof n.path==`string`)d.push(...WC(n.path));else{d.push({t:`lit`,v:e});let t=new Set(qC(d));for(let e of u)t.has(e)||d.push({t:`param`,k:e})}let f=qC(d),p=new Set(f);f.length!==p.size&&i(`path positions a param more than once: ${GC(d)}`);for(let e of f)u.has(e)||i(`path references undeclared param ":${e}"`);for(let e of u)p.has(e)||i(`declared param ":${e}" has no position in path ${GC(d)}`);let m=[...u],h=Kw(n.query)??[],ee=n.body?Kw(n.body):null,te=!!n.body&&ee===null,ne=Object.keys(n.files??{}),re=new Map;for(let[e,t]of[[`path`,m],[`query`,h],[`body`,ee??[]],[`files`,ne]])for(let n of t){let t=re.get(n);t&&i(`key "${n}" appears in both ${t} and ${e} — kinds must be disjoint`),re.set(n,e)}te&&(m.length>0||h.length>0||ne.length>0)&&i(`a non-object body is the entire data payload — params/query/files are not allowed alongside it`);let ie=n.streamIn instanceof ws,ae=typeof n.streamIn==`string`?n.streamIn:ie?`application/x-ndjson`:null,oe=n.streamOut instanceof ws,se=oe&&n.streamEncoding===`sse`,ce=typeof n.streamOut==`string`?n.streamOut:oe?se?`text/event-stream`:`application/x-ndjson`:null,le=!!(n.httpOnly||typeof n.streamIn==`string`||typeof n.streamOut==`string`||ne.length>0);return{name:e,def:t,method:n.method??`POST`,parts:d,path:GC(d),ws:n.ws??null,wsEligible:!le,httpOnly:le,streamInCt:ae,itemsIn:ie,streamOutCt:ce,items:oe,sse:se,multi:!!(n.responses&&Object.keys(n.responses).length>0),bodyEnc:n.body?n.bodyEncoding??`json`:null,p:m,q:h,b:ee,bRaw:te,f:ne,loaders:a,tplSchemas:o,chain:r}}function Jw(){return{}}function Yw(e){return()=>{throw Error(`middleware "${e}" has no implementation — bind it with implement(api).middleware(def, impl)`)}}function Xw(e,t,n,r,i,a){let o={kind:`middleware`,name:e,requires:t,optional:n,paramKey:r,paramSchema:i,doc:a,run:Yw(e),with(...e){return Zw([o,...e],[])},path(e){return Zw([o],[e])},endpoint(e){return Zw([o],[]).endpoint(e)},group(e){return Zw([o],[]).group(e)}};return o}function Zw(e,t){return{kind:`stack`,mws:e,prefixes:t,with(...n){return Zw([...e,...n],t)},path(n){return Zw(e,[...t,n])},endpoint(n){return Uw(n,e,t)},group(n){let r={};for(let[i,a]of Object.entries(n))r[i]=Uw(a,e,t);return r}}}function Z(...e){return Zw([...e],[])}function Qw(e,t){return Xw(e,t?.requires??[],t?.optional??[],void 0,void 0,t?.doc)}function $w(e,t,n){return Xw(e,n?.requires??[],n?.optional??[],e,t,n?.doc)}var eT=Object.assign(Qw,{loader:$w});function tT(e){let t=new Set,n=[],r=(e,i)=>{if(!t.has(e)){if(i.has(e))throw Error(`middleware cycle involving "${e.name}"`);i.add(e);for(let t of e.requires)r(t,i);i.delete(e),t.add(e),n.push(e)}};for(let t of e)r(t,new Set);let i=new Map(n.map((e,t)=>[e,t]));return[...n].sort((e,t)=>e.optional.includes(t)?1:t.optional.includes(e)?-1:i.get(e)-i.get(t))}function nT(...e){let t={},n={};for(let r of e){for(let[e,n]of Object.entries(r.endpoints)){if(Object.hasOwn(t,e))throw Error(`mergeSpecs: endpoint "${e}" is in more than one spec`);t[e]=n}for(let[e,t]of Object.entries(r.events??{})){if(Object.hasOwn(n,e))throw Error(`mergeSpecs: event "${e}" is in more than one spec`);n[e]=t}}return X({endpoints:t,events:n})}var rT=new WeakMap;function iT(e,t){return rT.set(e._zod.def,{source:t}),e}function aT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof Map)}var oT=class e extends U{static NAME=`record`;name=e.NAME;static optionKeys=[];static genericKeys=[`V`];static from(t,n){let r=t.generic?.V;return new e(n,r===void 0?n.registry.any():n.parse(r))}static toA(){return R.object({name:R.literal(e.NAME),generic:R.object({V:R.ref(`TypeDef`)}).optional()}).describe(`A record: an object with any text keys, each value a V.`)}constructor(e,t){super(e,{},{V:t})}get value(){let e=this.generic.V;if(e===void 0)throw Error(`record has no value type`);return e}valid(e,t){return aT(e)&&Object.values(e).every(e=>{try{return this.value.parse(e,t),!0}catch{return!1}})}parse(e,t){if(!aT(e))throw new th({path:[],code:`record.invalid`,message:`record.parse: expected an object of values by key`,severity:`error`});for(let[n,r]of Object.entries(e))try{this.value.parse(r,t)}catch(e){throw new th({path:[n],code:`record.value`,message:`record.parse: ${n}: ${e instanceof Error?e.message:String(e)}`,severity:`error`})}return new W(this,e)}encode(e){return e}create(){return{}}random(e){return{}}compatibleType(t){return t instanceof e&&this.value.compatibleType(t.value)}or(t){return t instanceof e&&this.value.compatibleType(t.value)?this:t}narrow(){return{}}toJSON(){return{name:e.NAME,generic:{V:this.value.toJSON()}}}clone(){return new e(this.scope,this.value)}toCode(e,t){return`${this.docsPrefix(t)}record<${this.value.toCode(void 0,t)}>`}valueA(e){return R.record(this.value.toA(e))}toNewA(){return R.record(R.ref(`Expr`))}};function sT(e){return e.typeClass(oT.NAME)===void 0&&e.define(oT),e}function cT(){return sT(ny())}var lT;function uT(){return lT??=cT(),lT}var dT=lb.result(`TypeDef`),fT=lb.result(`Expr`);function pT(e){return()=>{let{description:t,...n}=e(uT()).render($l).jsonSchema;return n}}function mT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function hT(e){return mT(e)&&`name`in e&&typeof e.name==`string`}var gT=iT(Jc(hT,{message:`Expected a gin type definition ({ name, ... }).`}),pT(e=>dT.bind(e,void 0,{namedRefs:!0})));function _T(e){return hT(e)}var vT=iT(Jc(_T,{message:`Expected a gin object type definition ({ name: "obj", props: { ... } }).`}),pT(e=>fb(e.typ(e.obj({}))).bind(e,void 0,{namedRefs:!0})));function yT(e){return mT(e)&&`kind`in e&&typeof e.kind==`string`}var bT=iT(Jc(yT,{message:`Expected a gin expression ({ kind, ... }).`}),pT(e=>fT.bind(e,void 0,{namedRefs:!0}))),xT=new Set(`id.uuid.guid.url.uri.api.json.csv.tsv.xml.html.css.yaml.sql.pdf.svg.png.jpg.ip.dns.http.https.ssh.tls.ssl.tcp.udp.vpn.os.cpu.gpu.ram.ui.ux.ai.llm.sku.sms.otp.jwt.utc.iso.gmt.ssn.vat.faq.crm.rgb.db.mime.ttl.oauth.sso.mfa`.split(`.`)),ST=new Map([[`ctx`,`context`]]);function CT(e,t){let n=e.toLowerCase();if(xT.has(n))return n.toUpperCase();let r=ST.get(n);return r===void 0?n.endsWith(`s`)&&xT.has(n.slice(0,-1))?`${n.slice(0,-1).toUpperCase()}s`:t?e:n:t?OT(r):r}function wT(e){return OT((/[\s._/:-]/.test(e)&&!/[a-z]/.test(e)?e.toLowerCase():e).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).split(/[\s._/:-]+/).filter(e=>e!==``).map((e,t)=>CT(e,t===0)).join(` `))||e}function TT(e){return e.label??wT(e.name)}function ET(e){return wT(Il(e).local)}function DT(e){return/^[A-Z][a-z]/.test(e)?`${e.charAt(0).toLowerCase()}${e.slice(1)}`:e}function OT(e){return e===``?e:`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function kT(e,t){let n=e.replace(/\s+/g,` `).trim();if(n.length<=t)return n;let r=n.slice(0,t-1),i=r.lastIndexOf(` `);return`${i>t*.6?r.slice(0,i):r}…`}var AT=[`path`,`file`,`uri`,`query`,`command`,`url`,`name`,`title`,`text`,`pattern`,`message`];function jT(e,t=60){if(e==null)return``;if(typeof e==`string`)return kT(e,t);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e))return e.length===0?``:`${e.length} item${e.length===1?``:`s`}`;let n=AT.map(t=>e[t]).find(e=>typeof e==`string`&&e!==``);if(typeof n==`string`)return kT(n,t);for(let[n,r]of Object.entries(e))if(typeof r==`string`||typeof r==`number`||typeof r==`boolean`)return kT(`${n}: ${String(r)}`,t);return``}var MT=[`active`,`retry`,`done`,`failed`],NT=E(MT),PT=S({one:v().min(1),many:v().min(1)}),FT=S({active:PT,retry:PT,done:PT,failed:PT}),IT=S({phase:NT,one:v(),many:v()}),LT={active:{one:`{fn}…`,many:`{fn} ×{n}…`},retry:{one:`Retrying {fn}…`,many:`Retrying {fn} ×{n}…`},done:{one:`{fn} done`,many:`{fn} ×{n} done`},failed:{one:`{fn} failed`,many:`{fn} ×{n} failed`}};function RT(e,t){switch(e){case`queued`:case`running`:case`waiting`:return t>1?`retry`:`active`;case`invalid-input`:return`retry`;case`done`:return`done`;case`failed`:return`failed`;case`awaiting-approval`:case`paused`:case`cancelled`:case`undone`:return}}var zT=60,BT=3,VT=/\{([^{}|]+)(?:\|([^{}]*))?\}/g;function HT(e,t,n){for(let r of e){if(r===void 0)continue;let e=WT(r[t].one,n,!1),i=WT(r[t].many,n,!0);if(e!==void 0&&i!==void 0)return{phase:t,one:e,many:i}}let r=LT[t];return{phase:t,one:WT(r.one,n,!1)??r.one,many:WT(r.many,n,!0)??r.many}}function UT(e,t){return t===1?e.one:e.many.replaceAll(`{n}`,String(t))}function WT(e,t,n){let r=[],i=e.replace(VT,(e,i,a)=>{let o=GT(i.trim(),t,n);return o===void 0?a===void 0?(r.push(i),e):a:o});return r.length>0?void 0:OT(i.replace(/…{2,}/g,`…`))}function GT(e,t,n){if(e===`fn`)return DT(ET(t.fn));if(e===`n`)return n?`{n}`:void 0;let[r,...i]=e.split(`.`),a=r===`args`?t.args:r===`output`?t.output:void 0;return a===void 0?void 0:qT(KT(a,i))}function KT(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=Array.isArray(n)?n[Number(e)]:n[e]}return n}function qT(e){if(e!=null){if(typeof e==`string`)return e===``?void 0:YT(e);if(typeof e==`number`||typeof e==`boolean`)return String(e);if(Array.isArray(e)){let t=e.map(qT).filter(e=>e!==void 0);if(t.length===0)return;let n=t.slice(0,BT),r=t.length-n.length;return JT(r>0?[...n,`${r} more`]:n)}for(let t of[`title`,`name`,`id`]){let n=e[t];if(typeof n==`string`&&n!==``)return YT(n)}}}function JT(e){return e.length<=2?e.join(` and `):`${e.slice(0,-1).join(`, `)} and ${e.at(-1)??``}`}function YT(e){let t=e.split(`
|
|
401
|
+
`)[0]??``;return t.length>zT?`${t.slice(0,59)}…`:t}var XT=E([`system-needs-config`,`system-disconnected`,`system-removed`,`kind-missing`,`kind-system-disconnected`,`dep-unavailable`,`disabled`,`held`,`paused`,`role-unset`]),ZT=C([D(!0),S({unavailable:XT,detail:v()})]),QT=S({code:E([...XT.options,`no-such-fn`,`not-a-name`,`other-system`,`not-for-model`,`connect-account`]),reason:v().min(1),system:F.optional()}),$T=QT.extend({fn:v()}),eE=QT.extend({name:v()}),tE=S({id:M,name:v(),email:v(),role:E([`admin`,`member`]),groups:x(S({id:M,name:v()})),timeZone:v(),locale:v()}),nE=S({now:N,timeZone:v(),local:v()}),rE=S({name:v(),instance:L,boot:v(),from:S({system:v(),fn:I,run:A}).optional()}),iE=S({id:A,fn:I,parent:A.optional(),turn:cl,session:j.optional(),user:tE,time:nE,system:rE,caller:M,attempt:y().int().min(1),priority:Rl,watched:b().optional(),inChat:b().optional()}),aE=S({timeZone:v(),locale:v(),now:N}),oE=E([`card`,`message`,`hidden`]),sE=S({cancel:b(),pause:b(),undo:b(),background:b()}),cE=sE.pick({cancel:!0,pause:!0,background:!0}),lE=S({timeout:Ml.optional(),retries:y().int().min(0).optional(),cost:P.optional()}),uE=w(`type`,[S({type:D(`none`)}),S({type:D(`linear`)}),S({type:D(`steps`),steps:T(v(),v())})]),dE=E([`pending`,`active`,`done`,`failed`,`skipped`]),fE=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({steps:T(v(),S({status:dE,detail:v().optional()}))})]),pE=C([S({fraction:y().min(0).max(1),message:v().optional()}),S({step:v(),status:dE,detail:v().optional()})]),mE=[`retry`,`caller`,`fatal`],hE=S({class:E(mE),message:v(),code:v().optional(),data:O.optional()}),gE=E([`json`,`schema`,`validation`,`unavailable`,`result`]),_E=S({path:v(),message:v()}),vE=S({path:v(),repair:E([`json-string`])});function yE(e){return e.path===``?e.message:`${e.path}: ${e.message}`}var bE=S({source:gE,problems:x(_E).min(1),raw:v().optional(),blocked:QT.optional()}),xE=[`awaiting-approval`,`queued`,`running`,`waiting`,`paused`,`done`,`invalid-input`,`failed`,`cancelled`,`undone`],SE=E(xE),CE={"awaiting-approval":!1,queued:!1,running:!1,waiting:!1,paused:!1,done:!0,"invalid-input":!0,failed:!0,cancelled:!0,undone:!0},wE={"awaiting-approval":`Needs approval`,queued:`Queued`,running:`Running`,waiting:`Waiting`,paused:`Paused`,done:`Done`,"invalid-input":`Thinking harder`,failed:`Failed`,cancelled:`Cancelled`,undone:`Undone`};function TE(e){return CE[e]}function EE(e){return!CE[e]}var DE=xE.filter(TE),OE=xE.filter(EE),kE=w(`type`,[S({type:D(`status`),status:SE,text:IT.optional()}),S({type:D(`progress`),progress:fE}),S({type:D(`allowed`),operations:cE}),S({type:D(`cost`),cost:P,total:P}),S({type:D(`background`)}),S({type:D(`result`),revision:y().int().min(1)})]),AE=w(`status`,[S({status:D(`done`),result:O,undo:O.optional(),cost:P.optional(),expose:x(ex).optional()}),S({status:D(`invalid-input`),invalid:bE,undo:O.optional(),cost:P.optional()}),S({status:D(`paused`),resume:O,cost:P.optional()}),S({status:D(`failed`),error:hE,undo:O.optional(),cost:P.optional()}),S({status:D(`cancelled`),partial:O.optional(),undo:O.optional(),cost:P.optional(),error:hE.optional()})]),jE=w(`status`,[S({status:D(`done`),result:O}),S({status:D(`failed`),error:hE}),S({status:D(`cancelled`),error:hE.optional()}),S({status:D(`background`),run:A})]),ME=w(`status`,[S({status:D(`undone`),summary:v()}),S({status:D(`failed`),error:hE}),S({status:D(`gone`)})]),NE=w(`ok`,[S({ok:D(!0),value:O}),S({ok:D(!1),error:hE})]),PE=S({cost:P,time:Ml,limitedBy:v()}),FE=Fx,IE=S({hash:v().regex(qx),kind:nS,converter:v().min(1),content:Jx,chars:y().int().min(0),tokens:y().int().min(0),call:Ol.optional(),createdAt:N}),LE=S({kind:nS,model:v().optional(),estimate:y().min(0).optional()}),RE=w(`from`,[S({from:D(`system`),system:F,served:E([`bytes`,`text`]).optional()}),S({from:D(`upload`),by:M}),S({from:D(`web`),url:Nb,finalUrl:Nb.optional(),fetchedAt:N,rendered:b()}),S({from:D(`run`),run:A,fn:I})]),zE=[`system`,`upload`,`web`,`run`],BE=E([`auto`,`always`,`never`]),VE=`hub://resources/`,HE=[`document`,`code`,`image`,`table`,`audio`,`video`,`web`,`data`,`archive`,`folder`,`other`],UE=E(HE),WE={markdown:`document`,text:`document`,pdf:`document`,docx:`document`,pptx:`document`,rtf:`document`,odt:`document`,notebook:`document`,html:`web`,json:`data`,jsonl:`data`,yaml:`data`,toml:`data`,xml:`data`,ini:`data`,csv:`table`,tsv:`table`,excel:`table`,ods:`table`,image:`image`,svg:`image`,mermaid:`image`,audio:`audio`,video:`video`,zip:`archive`,folder:`folder`,...Object.fromEntries(`typescript.javascript.jsx.tsx.vue.python.ruby.go.rust.java.c.cpp.csharp.php.swift.kotlin.scala.css.scss.less.shell.sql.dockerfile.graphql.lua.r.dart`.split(`.`).map(e=>[e,`code`]))};function GE(e,t){let n=e===void 0?void 0:WE[e];if(n!==void 0)return n;let r=t?.split(`/`)[0];return r===`image`||r===`audio`||r===`video`?r:`other`}var KE=E([`type`,`source`,`path`,`date`]),qE=S({value:v(),label:v(),count:y().int().min(0)}),JE=Hl.extend({search:v().optional(),system:F.optional(),family:UE.optional(),source:E(zE).optional(),under:v().optional(),form:nS.optional(),missing:nS.optional(),group:KE.optional(),in:v().optional()}),YE=S({uri:Wx}),XE=S({uri:Wx,section:Gx.optional()}),ZE=S({image:Wx,question:v().trim().min(1).max(2e3),page:y().int().min(1).optional()}),QE=S({answer:v(),model:v(),image:S({id:Wx,name:v()})}),$E=S({uri:Wx,form:C([nS,D(`raw`)]).optional(),section:Gx.optional(),offset:y().int().min(0).optional(),maxChars:y().int().min(1).max(2e5).optional(),rows:S({table:v(),from:y().int().min(0),to:y().int().min(0)}).optional()}),eD=S({uri:Wx,form:C([nS,D(`raw`)]),text:v(),offset:y().int().min(0),total:y().int().min(0),truncated:b(),partial:v().optional(),note:v().optional(),forms:x(nS),offers:x(LE)}),tD=C([S({url:Nb,render:BE.optional(),name:v().optional(),folder:v().min(1).optional()}),S({content:Jx,name:v().min(1),path:v().optional()})]),nD=C([S({model:v().min(1)}),S({category:v().min(1)}),S({auto:S({cost:y().min(0).optional(),speed:y().min(0).optional(),accuracy:y().min(0).optional()})})]),rD=S({id:v(),name:v(),arguments:v(),invalid:v().optional()}),iD=S({type:E([`text`,`image`,`file`,`audio`,`video`]),content:v(),format:v().optional(),name:v().optional()}),aD=S({role:E([`system`,`user`,`assistant`,`tool`]),content:C([v(),x(iD)]),name:v().optional(),toolCallId:v().optional(),toolCalls:x(rD).optional(),refusal:v().optional(),tokens:y().int().optional()}),oD=S({input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional()}),sD=E([`stop`,`length`,`tool_calls`,`content_filter`,`refusal`]),cD=S({content:v().optional(),reasoning:v().optional(),toolCallNamed:rD.optional(),toolCallArguments:rD.optional(),toolCallMore:rD.optional(),toolCall:rD.optional(),finishReason:sD.optional(),refusal:v().optional(),usage:oD.optional()}),lD=C([b(),y().positive()]),uD=E([`summary`,`list`,`markers`,`full`]),dD=C([uD,S({detail:uD.optional(),maxErrors:y().int().min(0).optional(),maxChars:y().int().min(0).optional(),suggestions:b().optional(),expected:b().optional(),context:y().int().min(0).optional(),depth:y().int().min(0).optional(),header:b().optional()})]),fD=S({name:v(),description:v().optional(),parameters:O,strict:lD.optional(),errorFormat:dD.optional()}),pD=C([D(`text`),D(`json`),S({schema:O,strict:lD,errorFormat:dD.optional(),schemaDelivery:E([`auto`,`structured`,`json`,`prompt`]).optional()})]),mD=S({messages:x(aD),temperature:y().optional(),maxTokens:y().int().optional(),stop:x(v()).optional(),tools:x(fD).optional(),toolChoice:C([E([`auto`,`none`,`required`]),S({tool:v()})]).optional(),responseFormat:pD.optional(),errorFormat:dD.optional()}),hD=S({run:A.optional(),request:mD,model:nD.optional(),stream:b()}),gD=w(`type`,[S({type:D(`chunk`),chunk:cD}),S({type:D(`done`),usage:oD,cost:P,interaction:fl,model:v()}),S({type:D(`error`),message:v(),kind:E([`model`,`tool`,`limit`,`provider`])})]),_D=S({id:v().min(1),text:v().min(1),score:y().min(0).max(1)}),vD=S({run:A,question:v().min(1),candidates:x(_D).min(1).max(50),max:y().int().min(1).max(20)}),yD=w(`by`,[S({by:D(`decision`),picked:x(S({id:v(),why:v().optional()})),note:v().optional(),call:Ol.optional()}),S({by:D(`off`)}),S({by:D(`failed`),message:v()})]),bD=w(`type`,[S({type:D(`predicate`),instructions:v().min(1)}),S({type:D(`choice`),instructions:v().min(1),choices:T(v(),v())}),S({type:D(`score`),instructions:v().min(1),levels:x(v()).min(1)})]),xD=C([v().min(1),x(aD).min(1)]),SD=T(v().min(1),bD),CD=y().min(0).max(1),wD=w(`type`,[S({type:D(`predicate`),probability:CD}),S({type:D(`choice`),choice:v(),probabilities:T(v(),CD),confidence:CD}),S({type:D(`score`),score:y(),probabilities:x(CD),confidence:CD}),S({type:D(`refusal`)})]),TD=T(v(),wD),ED=.5,DD=[`chat`,`embed`,`image`,`transcribe`,`speech`,`decide`];E(DD);var OD=E([`yes`,`no`,`unknown`]),kD=S({modality:D(`chat`),input:y().int().min(0),output:y().int().min(0),cached:y().int().min(0).optional(),reasoning:y().int().min(0).optional(),caching:OD.optional()}),AD=S({modality:D(`embed`),texts:y().int().min(0),characters:y().int().min(0),images:y().int().min(1).optional(),tokens:y().int().min(0).optional(),dimensions:y().int().min(1)}),jD=S({modality:D(`image`),images:y().int().min(0),size:v().optional()}),MD=S({modality:D(`transcribe`),seconds:y().min(0),bytes:y().int().min(0)}),ND=S({modality:D(`speech`),characters:y().int().min(0),seconds:y().min(0).optional()}),PD=S({modality:D(`decide`),questions:y().int().min(0),characters:y().int().min(0),images:y().int().min(0).optional(),tokens:y().int().min(0).optional()});w(`modality`,[kD,AD,jD,MD,ND,PD]);var FD=E([`mp3`,`wav`,`ogg`]),ID=E([`running`,`done`,`failed`,`aborted`]),LD=S({id:Ol,provider:v(),model:v(),run:A.optional(),turn:cl.optional(),session:j.optional(),system:F.optional(),fn:I.optional(),purpose:v().optional(),interaction:fl.optional(),cost:P,status:ID,error:v().optional(),priority:Rl.optional(),sent:y().int().min(0),received:y().int().min(0),queued:Ml,firstByte:Ml.optional(),total:Ml.optional(),startedAt:N,endedAt:N.optional()}),RD=e=>S({modality:e.shape.modality,units:e}),zD=w(`modality`,[RD(kD),RD(AD),RD(jD),RD(MD),RD(ND),RD(PD)]),BD=e=>LD.extend(e.shape),VD=w(`modality`,[BD(zD.options[0]),BD(zD.options[1]),BD(zD.options[2]),BD(zD.options[3]),BD(zD.options[4]),BD(zD.options[5])]),HD=w(`modality`,[S({modality:D(`embed`),texts:x(v()).min(1),model:nD.optional()}),S({modality:D(`image`),prompt:v().min(1),model:nD.optional(),size:v().optional(),count:y().int().min(1).max(10).optional()}),S({modality:D(`transcribe`),audio:Jx,model:nD.optional(),language:v().optional()}),S({modality:D(`speech`),text:v().min(1),model:nD.optional(),voice:v().optional(),format:FD.optional()}),S({modality:D(`decide`),input:xD,questions:SD,model:nD.optional()})]).and(S({run:A.optional()})),UD=w(`modality`,[S({modality:D(`embed`),vectors:x(x(y()))}),S({modality:D(`image`),images:x(Jx)}),S({modality:D(`transcribe`),text:v(),segments:x(S({start:y().min(0),end:y().min(0),text:v()})).optional()}),S({modality:D(`speech`),audio:Jx}),S({modality:D(`decide`),answers:TD})]).and(S({call:Ol,cost:P,model:v()})),WD=E([`chat`,`transcribe`,`dictate`,`speak`,`describe`,`ocr`,`decide`,`metadata`,`plan`]),GD={chat:`chat`,transcribe:`hearing`,dictate:`hearing`,speak:`audio`,describe:`vision`,ocr:`vision`,decide:`decision`,metadata:`chat`,plan:`chat`},KD=S({model:nD,provider:Tl.optional()}),qD=w(`engine`,[S({engine:D(`browser`)}),KD.extend({engine:D(`model`)})]),JD=[`browser`,`model`],YD=WD.exclude([`dictate`,`decide`]),XD=KD.extend({role:D(`decide`),threshold:y().min(0).max(1).default(ED)}),ZD=w(`role`,[S({role:D(`dictate`),engine:qD,language:v().optional()}),XD,KD.extend({role:YD,language:v().optional()})]);S({choice:ZD,setBy:M,updatedAt:N});var QD=C([S({model:v(),provider:v()}),S({problem:v()})]),$D=S({role:WD,choice:ZD.optional(),from:E([`setting`,`env`,`none`]),resolved:QD.optional(),fallback:S({role:WD,reason:v()}).optional()}),eO=[`done`,`invalid-input`,`failed`,`cancelled`],tO=T(E(eO),y().int().min(0));function nO(){return{done:0,"invalid-input":0,failed:0,cancelled:0}}function rO(e){return eO.reduce((t,n)=>t+e[n],0)}var iO=v().regex(/^\d{4}-\d{2}-\d{2}$/),aO=[50,100,250,500,1e3,2500,5e3,1e4,3e4,6e4,3e5],oO=S({count:y().int().min(0),sum:Ml,max:Ml,histogram:x(y().int().min(0)).length(aO.length+1)}),sO=S({fn:I,system:F,day:iO,outcomes:tO,queued:oO,approval:oO,ran:oO,cost:P,tokens:y().int().min(0),retries:y().int().min(0),modelCalls:y().int().min(0),updatedAt:N}),cO=S({fn:I,system:F,from:iO,to:iO,runs:y().int().min(0),outcomes:tO,p50:Ml.optional(),p95:Ml.optional(),averageQueued:Ml.optional(),averageCost:P,cost:P,tokens:y().int().min(0),retries:y().int().min(0),lastRunAt:N.optional()}),lO=S({fn:kb.optional(),system:F.optional(),days:y().int().min(1).max(365).optional()}),uO=E([`private`,`shared`,`public`]),dO={private:`Only me`,shared:`Me and chosen people`,public:`Everyone`},fO=S({owner:M,visibility:uO,with:x(M)});E([`system`,`fn`,`context`,`root`,`connection`]);var pO=w(`kind`,[S({kind:D(`system`),system:F}),S({kind:D(`fn`),fn:I}),S({kind:D(`context`),context:I}),S({kind:D(`root`),uri:v().min(1)}),S({kind:D(`connection`),connection:jl})]);function mO(e){switch(e.kind){case`system`:return`system:${e.system}`;case`fn`:return`fn:${e.fn}`;case`context`:return`context:${e.context}`;case`root`:return`root:${e.uri}`;case`connection`:return`connection:${e.connection}`}}S({key:v(),target:pO,sharing:fO,scoped:b().optional(),setBy:M,updatedAt:N});var hO=S({target:pO,sharing:fO,editable:b()}),gO=S({multiUser:b()}),_O=fO.omit({owner:!0}),vO=S({run:A,fn:k,share:_O}),yO=S({run:A,fns:x(k).max(1e3)}),bO=S({source:E([`fn`,`context`,`system`,`person`,`group`,`model`,`resource`,`type`,`kind`]),text:v().optional(),values:x(v()).max(200).optional(),limit:y().int().min(1).max(50).optional()}),xO=S({value:v(),label:v(),hint:v().optional(),icon:v().optional(),missing:b().optional()}),SO=S({on:b(),ask:b()}),CO=w(`flow`,[S({flow:D(`oauth`)}),S({flow:D(`form`),form:gT})]),wO=S({flow:CO.optional(),share:b().default(!1),title:v().min(1)}),TO=v().regex(Nl).brand(),EO=C([TO,S({arg:k})]),DO=S({title:v(),description:v(),icon:v().optional(),how:CO,settings:gT,fns:T(k,SO),scope:E([`system`,`instance`,`key`]).optional(),keys:S({type:I}).optional(),defaults:SO.optional()}),OO=E([`pending`,`connected`,`expired`,`failed`]),kO=S({label:v(),detail:v().optional(),choices:T(v(),x(xO)).optional()}),AO=S({id:jl,system:F,instance:L.optional(),key:TO.optional(),owner:M,status:OO,account:kO.optional(),credentials:Cl.optional(),expiresAt:N.optional(),settings:O,fns:T(k,SO),share:_O,problem:v().optional(),createdAt:N,updatedAt:N}).omit({credentials:!0}),jO=S({system:F,decl:DO,ready:b(),connections:x(AO),instances:x(S({instance:L,label:v(),connect:wO})).optional(),keys:x(S({key:TO,label:v(),connect:wO,host:v().optional()})).optional()}),MO=S({id:jl,owner:M,credentials:O,settings:O}),NO=S({connection:jl,owner:M,redirect:Ls(),state:v(),instance:L.optional(),key:TO.optional()}),PO=S({connection:jl,owner:M,instance:L.optional(),key:TO.optional(),redirect:Ls(),answer:C([S({params:T(v(),v())}),S({form:O})])}),FO=C([S({account:kO,credentials:O,expiresAt:N.optional()}),S({problem:v()})]),IO=S({connection:jl,update:C([S({credentials:O,expiresAt:N.optional()}),S({expired:v()})])}),LO=S({connection:jl,settings:O.optional(),fns:T(k,SO).optional(),share:_O.optional()}),RO=[`embedding`,`imageEmbedding`],zO=S({input:P,output:P,cached:P.optional(),cacheWrite:P.optional()}),BO=S({id:v().min(1),name:v().optional(),capabilities:x(v()),contextWindow:y().int().min(1),maxOutput:y().int().min(1).optional(),pricing:zO,caching:b(),dimensions:y().int().min(1).optional(),maxInput:y().int().min(1).optional(),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}).refine(e=>!RO.some(t=>e.capabilities.includes(t))||e.dimensions!==void 0,{message:`An embedding model says how many dimensions its vectors have.`,path:[`dimensions`]}),VO=S({name:k,description:v(),models:x(BO),runtime:D(!0).optional(),instance:L.optional()}),HO=S({provider:k,model:v(),request:mD,stream:b(),run:A.optional()}),UO=w(`type`,[S({type:D(`chunk`),chunk:cD}),S({type:D(`done`),usage:oD}),S({type:D(`error`),message:v(),kind:E([`model`,`limit`,`provider`,`auth`])})]),WO=S({id:v().min(1),contextWindow:y().int().min(1).optional(),maxOutput:y().int().min(1).optional(),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}),GO=S({provider:k}),KO=w(`listed`,[S({listed:D(!0),models:x(WO)}),S({listed:D(!1)})]),qO=S({provider:k,model:v(),input:xD,questions:SD}),JO=S({answers:TD,tokens:y().int().min(0).optional()}),YO=S({image:v().regex(/^(https?:|data:)/,`an http(s) or data URL`),mimeType:v().optional()}),XO=C([v(),YO]),ZO=S({provider:k,model:v(),inputs:x(XO).min(1)}),QO=S({vectors:x(x(y())),tokens:y().int().min(0).optional()});function $O(e){return S({provider:D(`aws`),region:v().min(1),auth:w(`kind`,[S({kind:D(`keys`),accessKeyId:v().min(1),secretAccessKey:e,sessionToken:e.optional()}),S({kind:D(`apiKey`),apiKey:e})]),profilePrefix:v().optional()})}var ek=S({input:b(),output:b()}),tk=C([S({ok:D(!0)}),S({ok:D(!1),reason:v().min(1)})]),nk=C([S({ok:D(!0)}),S({ok:D(!1),action:E([`retry`,`stop`]),reason:v().min(1)})]),rk=w(`phase`,[S({phase:D(`input`),run:iE,fn:v(),args:O}),S({phase:D(`output`),run:iE,fn:v(),args:O,result:O,attempt:y().int().min(1)})]),ik=C([nk,tk]),ak=S({kind:E([`builtin`,`dynamic-import`,`dynamic-require`,`eval`,`new-function`]),line:y().int().min(1),detail:v(),code:v()}),ok=S({size:y().int().min(0),builtins:x(v()),concerns:x(ak),urls:x(v()),hosts:x(v())}),sk=E([`passed`,`failed`,`skipped`]),ck=S({file:v().min(1),name:v().min(1),status:sk,duration:Ml,real:b().optional(),error:v().max(4e3).optional()}),lk=[`phone`,`desktop`],uk=E(lk);E([`empty`,`loading`,`error`,`typical`,`long`]);var dk=S({component:v().min(1),state:v().min(1),viewport:uk,theme:E([`light`,`dark`]),image:Jx}),fk=S({scan:ok,tests:S({system:F,version:v().min(1),ranAt:N,duration:Ml,passed:y().int().min(0),failed:y().int().min(0),skipped:y().int().min(0),cases:x(ck).max(500),more:y().int().min(0).optional(),previews:x(dk).max(200).optional()}).optional()}),pk=E([`ai`,`embed`,`resources`,`fns`,`search`,`decide`,`approvals`,`connections`,`settings`,`state`,`data`,`runs`]),mk=S({roles:x(WD).optional(),models:x(v().min(1)).optional(),perRun:P.optional(),perDay:P.optional()}),hk=S({read:x(v().min(1)),write:x(v().min(1))}),gk=S({hub:x(pk),models:mk.optional(),secrets:x(v().min(1)).optional(),calls:x(C([I,F])).optional(),network:x(v().min(1)).optional(),files:hk.optional()}),_k=S({component:v().min(1),mode:E([`replace`,`beside`])}),vk=[`installed`,`live`],yk=E(vk),bk=[`text`,`integer`,`number`,`boolean`,`date`,`datetime`,`time`,`uuid`,`json`,`binary`],xk=E(bk),Sk=E([`group`,`measure`,`attribute`]),Ck=S({name:k,label:v().min(1),accepts:x(xk).min(1),required:b(),many:b(),min:y().int().min(1).optional(),role:E([`group`,`measure`]).optional()}),wk=w(`rule`,[S({rule:D(`distinct`),channel:k,max:y().int().min(1),min:y().int().min(1).optional()}),S({rule:D(`non-negative`),channel:k}),S({rule:D(`bounded`),channel:k}),S({rule:D(`distinct-columns`),channels:x(k).min(2)}),S({rule:D(`links`),from:k,to:k})]),Tk=E([`window`,`top-n`,`partition`,`aggregate`]),Ek=S({name:k,label:v().min(1),whole:D(!0).optional(),needs:x(k).optional(),columns:T(k,S({min:y().int().min(0).optional(),max:y().int().min(0).optional()})).optional(),rules:x(wk).optional()}),Dk=S({claim:D(`range`),channel:k}),Ok=E([`floor`,`structural`,`encoded`,`time-encoded`]),kk=E([`temporal-key`,`low-cardinality`,`enum-key`,`high-null`,`many-categories`]),Ak=S({channels:x(Ck).min(1),rows:S({min:y().int().min(0),max:y().int().min(1).optional()}),whole:b(),rules:x(wk).default([]),size:Tk.optional(),styles:x(Ek).min(1).default([{name:`default`,label:`Default`}]),claims:x(Dk).default([]),priority:S({band:Ok,terms:x(kk)}).default({band:`structural`,terms:[]}),pageSize:y().int().min(1).max(500).optional()}),jk=S({name:k,description:v(),data:gT}),Mk=S({registry:I,name:k,label:v().min(1),description:v().optional(),icon:v().optional(),shape:Ak.optional()}),Nk=Mk.extend({system:F}),Pk=S({name:v().min(1),label:v().optional(),kind:xk,nullable:b(),type:gT.optional(),ref:I.optional(),role:Sk.optional(),key:b().optional(),editable:b().optional()}),Fk=S({column:v().min(1),dir:E([`asc`,`desc`])}),Ik=S({fn:I,args:T(v(),O),keys:x(v().min(1))}),Lk=S({columns:x(Pk),rows:x(x(O)),offset:y().int().min(0),limit:y().int().min(1).optional(),total:y().int().min(0).optional(),truncated:b(),sort:x(Fk),write:S({affected:y().int().min(0)}).optional(),records:S({type:I,id:v().min(1)}).optional(),drill:Ik.optional()}),Rk=S({flag:E([`delete-fns`,`write-fns`,`runs`,`injects`,`effects`,`capabilities`,`secrets`,`hosts`,`files`,`calls`,`models`]),line:v().min(1),items:x(v().min(1)),lead:v().min(1).optional(),tail:v().min(1).optional()}),zk=S({section:v().min(1),added:y().int().min(0),changed:y().int().min(0),removed:y().int().min(0)}),Bk=E([`widened`,`narrowed`,`changed`,`added`]),Vk=S({line:v(),counts:x(zk),flags:x(Rk),grants:Bk.optional(),config:E([`added`,`changed`,`removed`]).optional()}),Hk=E([`gitignored`,`env`,`key`,`credential`,`token`,`secret-content`,`runs-code`,`unknown-path`]),Uk=E([`allow`,`ask`,`refuse`]),Wk=E([`ask`,`refuse`]),Gk=w(`type`,[S({type:D(`glob`),glob:v().min(1)}),S({type:D(`content`),pattern:v().min(1)}),S({type:D(`gitignored`)})]);S({name:v().min(1),kind:Hk,match:Gk,except:x(v().min(1)).optional(),read:Uk,write:Wk,why:v().min(1)});var Kk=S({path:v().min(1),kind:Hk,rule:v().min(1),access:E([`read`,`write`]),action:E([`allow`,`ask`,`refuse`]),why:v().min(1),certain:b()}),qk=S({flags:x(Kk)}),Jk=w(`type`,[S({type:D(`text`),text:v()}),S({type:D(`code`),language:v(),code:v(),title:v().optional()}),S({type:D(`table`),title:v(),table:Lk}),S({type:D(`type-diff`),name:v(),before:gT.optional(),after:gT.optional(),changes:x(v()),breaks:x(S({fn:v(),why:v()}))}),S({type:D(`flags`),flags:x(Kk).min(1)})]),Yk=S({kind:D(`system-install`),system:F,instance:L,version:v().min(1),manifestHash:v().min(1),bundleHash:v().min(1),sourceHash:v().min(1),host:ql,source:v().min(1).optional(),grants:gk.optional(),replaces:S({version:v().min(1),manifestHash:v().min(1)}).optional()}),Xk=w(`kind`,[Yk]),Zk=S({title:v().min(1),parts:x(Jk),irreversible:b(),subject:Xk.optional(),checks:fk.optional(),summary:Vk.optional()}),Qk=E([`person`,`admins`]),$k=S({preview:b(),remember:b(),approver:Qk.optional()}),eA=S({run:A,fn:k,args:O,user:tE,kind:Pl.optional(),payload:O.optional()}),tA=S({run:A,fn:k,args:O,user:tE,deadline:N}),nA=S({problems:x(_E)}),rA=S({type:gT,into:k,label:v().min(1).max(80).optional()}),iA=S({fn:k,args:O,key:v().min(1),parent:A.optional(),approver:Qk,for:M.optional(),chat:j.optional(),ask:rA.optional(),preview:Zk}).refine(e=>e.parent!==void 0||e.approver===`admins`||e.for!==void 0,{message:"A run proposed outside a run waits for an admin, or for the person named in `for`.",path:[`approver`]}),aA=S({by:M,preview:Zk}),oA=S({run:A,subject:Yk}),sA=S({token:v().min(1),expiresAt:N}),cA=S({run:A,approval:gl}),lA=v().regex(/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/),uA=x(lA),dA=`•••• kept`,fA=S({$secret:Cl,json:D(!0).optional()}),pA=v().regex(/^[a-z][a-z0-9-]{0,39}$/,`a page segment is lowercase letters, digits and dashes, starting with a letter (at most 40)`),mA=E([`main`,`hidden`]),hA=E([`app`,`admin`]),gA=E([`everyone`,`admin`]),_A=S({segment:pA,title:v().trim().min(1).max(40),description:v().optional(),icon:v().min(1).optional(),nav:mA.default(`main`),access:gA.default(`everyone`),area:hA.optional(),component:v().min(1)});function vA(e){let t=new Set;return e.flatMap(e=>t.has(e.segment)?[`page ${e.segment} is declared twice`]:(t.add(e.segment),[]))}var yA=x(_A).superRefine((e,t)=>{for(let n of vA(e))t.addIssue({code:`custom`,message:n})}),bA=_A.extend({system:F,client:S({url:v().min(1),hash:v().min(1)})}),xA=S({instance:L,description:v(),online:b(),version:v()}),SA=`http://127.0.0.1:11434`;function CA(e){return w(`provider`,[S({provider:D(`openai`),apiKey:e,baseURL:Ls().optional()}),S({provider:D(`anthropic`),apiKey:e}),S({provider:D(`google`),apiKey:e}),S({provider:D(`openrouter`),apiKey:e}),S({provider:D(`ollama`),baseURL:Ls().default(SA),contextWindow:y().int().min(256).optional(),decisionModels:x(v().min(1)).optional()}),$O(e)])}var wA=CA(Cl),TA=E(wA.options.map(e=>e.shape.provider.value));S({id:Tl,config:wA,createdAt:N}),S({id:Cl,name:v(),owner:M,ciphertext:v(),createdAt:N});var EA=S({id:wl,name:v(),description:v(),models:x(v())}),DA=w(`scope`,[S({scope:D(`hub`)}),S({scope:D(`group`),group:M}),S({scope:D(`user`),user:M}),S({scope:D(`session`),session:j}),S({scope:D(`turn`),turn:cl}),S({scope:D(`system`),system:F}),S({scope:D(`fn`),fn:I}),S({scope:D(`model`),model:v()})]),OA=E([`hub`,`group`,`user`,`session`,`turn`]),kA=w(`scope`,[S({scope:D(`hub`)}),S({scope:D(`group`),group:M}),S({scope:D(`user`),user:M}),S({scope:D(`session`),session:j}),S({scope:D(`turn`),turn:cl})]),AA=S({id:_l,target:DA,period:C([S({window:Ml}),D(`all-time`),D(`per-turn`)]),maxCost:P,maxTokens:y().int().optional(),maxCalls:y().int().optional(),maxTime:Ml.optional(),share:E([`pooled`,`each`]).optional(),onLimit:E([`wait`,`refuse`,`ask`]),setBy:M}),jA=S({id:vl,target:kA,default:Rl.optional(),max:Rl.optional(),setBy:M}),MA=S({priority:Rl,priorityFrom:S({default:OA,cappedBy:OA.optional()}),turn:S({cost:P,time:Ml}),budgets:x(S({rule:_l,scope:DA,remaining:P})),limitedBy:_l.optional()});S({id:yl,budgets:x(_l),estimate:P,createdAt:N,settled:S({cost:P,at:N}).optional()}),S({id:bl,at:N,cost:P,tokens:y().int().min(0),actor:M,system:F.optional(),session:j.optional(),fn:I,model:v().optional(),llmCall:fl.optional(),modelCall:Ol.optional(),run:A});var NA=E([`chat`,`admin`,`disconnected`,`needs-config`,`held`,`removed`]),PA=S({prompt:x(S({name:F,label:v(),description:v(),summary:v().optional()})),on:x(F),off:x(S({name:F,why:NA}))}),FA=S({name:F,reason:v(),label:v().optional(),description:v().optional()}),IA=RegExp(`(\\d+)`,`g`);function LA(e,t=[]){let n=new Map(t.map(e=>[e.index,e.number]));return e.replace(IA,(e,t)=>{let r=n.get(Number(t));return r===void 0?``:`[${r}]`})}function RA(e){let t=e.trim().replace(/^\$\.?/,``);if(t===``)return[];let n=[],r=/\[\s*(?:"([^"]*)"|'([^']*)'|(\d+))\s*\]|([^.[\]]+)/y,i=0;for(;i<t.length;){if(t[i]===`.`){i+=1;continue}r.lastIndex=i;let e=r.exec(t);if(e===null)return;n.push(e[1]??e[2]??e[3]??e[4]??``),i=r.lastIndex}return n}function zA(e){try{return O.parse(JSON.parse(e))}catch{return}}function BA(e,t){let n=RA(t);if(n===void 0)return;let r=e;for(let e of n){let t=typeof r==`string`?zA(r):r;if(Array.isArray(t)){if(!/^\d+$/.test(e))return;let n=t[Number(e)];if(n===void 0)return;r=n}else if(typeof t==`object`&&t){if(!Object.hasOwn(t,e))return;let n=t[e];if(n===void 0)return;r=n}else return}return{value:r}}var VA=S({index:y().int().min(1),number:y().int().min(1),tool:v(),path:v(),note:v()}),HA=E([`result`,`reply`]),UA=VA.extend({run:A.optional(),fn:I.optional(),found:HA.optional(),value:O.optional(),large:D(!0).optional(),problem:v().optional()}),WA=S({prompt:b(),on:b()}),GA=y().int().min(0).max(3),KA=S({agent:I,model:nD.optional(),mode:ix.optional(),contextor:hx.optional(),fnMode:jx.optional(),systems:C([x(F),D(`all`)]),instructions:v().optional(),citations:b().optional()}),qA=KA.partial(),JA=x(S({label:v().trim().min(1).max(40).optional(),settings:qA})).min(2).max(4),YA=S({turn:cl,variant:GA,label:v()}),XA=S({variant:GA,label:v(),settings:qA,session:j,turn:cl}),ZA=S({run:A,fn:I}),QA=S({variant:GA,effects:x(ZA)}),$A=S({variant:GA,label:v(),effects:x(ZA).min(1)}),ej=S({variants:x(XA).min(2).max(4),reserved:P,chosen:GA.optional(),chosenBy:M.optional(),chosenAt:N.optional(),discarded:x(QA)}),tj=S({field:v(),type:v(),before:O.optional(),after:O.optional()}),nj=S({id:A,fn:I,fnVersion:v(),kind:Pl,system:F,instance:L.optional(),parent:A.optional(),root:A,turn:cl,session:j.optional(),key:v(),actor:M,caller:M,connection:jl.optional(),llmCall:fl.optional(),toolCallId:v().optional(),args:O,repairs:x(vE).optional(),test:b().optional(),status:SE,awaitingSystem:b().optional(),text:IT.optional(),outcome:AE.optional(),progress:fE.optional(),allowed:cE,cost:P,totalCost:P,priority:Rl,background:b(),attempt:y().int().min(1),errors:x(S({attempt:y().int(),error:hE,cost:P,at:N})),undo:O.optional(),resume:O.optional(),stateChanges:x(tj),tokens:y().int().min(0).optional(),createdAt:N,approvedAt:N.optional(),startedAt:N.optional(),endedAt:N.optional(),resultRevision:y().int().min(1).optional(),resultUpdatedAt:N.optional(),resultUpdatedBy:M.optional()}),rj=nj.pick({id:!0,fn:!0,status:!0,cost:!0,totalCost:!0,startedAt:!0,endedAt:!0}),ij=S({session:j,system:F,name:v(),type:v(),def:gT,value:O,version:y().int().min(1),updatedBy:C([S({run:A}),S({delivery:ul})]),updatedAt:N}).pick({name:!0,type:!0}).extend({value:O.optional()}),aj=E([`queued`,`delivered`,`done`,`failed`,`expired`]),oj=S({id:ul,system:F,kind:C([S({action:v(),input:O}),S({form:A,value:O})]),session:j,actor:M,run:A.optional(),status:aj,result:O.optional(),error:hE.optional(),attempts:y().int().min(0),createdAt:N,deliveredAt:N.optional(),doneAt:N.optional(),expiresAt:N.optional()}).pick({id:!0,status:!0,result:!0,error:!0}),sj=S({id:dl,run:A,handler:v(),args:O,decl:S({description:v(),args:gT,returns:gT}),answerer:C([S({user:M}),S({system:F,run:A})]),status:E([`pending`,`answered`,`failed`]),result:O.optional(),createdAt:N}),cj=E([`running`,`done`,`failed`,`cancelled`,`paused`,`undone`]),lj=S({transcript:y().int().min(0),tools:x(I),context:x(I),selection:kx.optional(),suggested:x(I).optional(),announcedSystems:PA.optional(),citationsTold:WA.optional()});S({id:cl,session:j.optional(),message:ll.optional(),actor:M,user:tE,time:nE,client:aE.optional(),root:A.optional(),status:cj,limits:MA,cost:P,errors:C([S({max:y().int().min(1)}),D(`feed-back`)]),start:lj.optional(),compare:ej.optional(),createdAt:N,continuedAt:N.optional(),endedAt:N.optional()});var uj=E([`queued`,`streaming`,`done`,`failed`,`aborted`]),dj=S({content:v(),reasoning:v().optional(),toolCalls:x(cD.shape.toolCall.unwrap()).optional(),finishReason:cD.shape.finishReason.unwrap(),refusal:v().optional()}),fj=S({id:fl,turn:cl,run:A,session:j.optional(),system:F.optional(),iteration:y().int().min(0),provider:v(),model:v(),request:mD,response:dj.optional(),usage:oD.optional(),cost:P,status:uj,error:v().optional(),priority:Rl,selection:Ex.optional(),modelCall:Ol.optional(),queuedAt:N,startedAt:N.optional(),firstTokenAt:N.optional(),endedAt:N.optional()}),pj=Kc(()=>S({run:rj,llmCalls:x(fj.pick({id:!0,model:!0,cost:!0,status:!0})),children:x(pj)})),mj=S({turn:cl,undone:x(S({run:A,fn:I,summary:v()})),failed:x(S({run:A,fn:I,error:hE})),notUndoable:x(S({run:A,fn:I})),kept:x($A).optional(),session:S({messages:y().int().min(0),unloaded:x(I),reloaded:x(I)}).optional()});S({run:A,turn:cl,session:j.optional(),iteration:y().int().min(0),priority:Rl}),S({run:A,priority:Rl});var hj=[`system`,`instance`,`fn`,`context`,`type`,`kind`,`resource`,`root`,`component`,`registry`,`command`,`provider`],gj=E(hj),_j=[`brings`,`names`,`loads`,`next`,`reads`,`writes`,`calls`,`uses`,`kind`,`creates`,`updates`,`removes`,`refers`,`renders`,`contributes`,`belongs`],vj=E(_j),yj=[...vk,`pending`];E(yj);var bj=E([`text`,`enum`,`number`,`date`,`boolean`]);E([`is`,`isNot`,`in`,`notIn`,`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`,`contains`]);var xj={text:[`contains`,`is`,`isNot`,`in`,`notIn`,`empty`,`notEmpty`],enum:[`is`,`isNot`,`in`,`notIn`,`empty`,`notEmpty`],number:[`gt`,`gte`,`lt`,`lte`,`between`,`is`,`isNot`,`empty`,`notEmpty`],date:[`gt`,`gte`,`lt`,`lte`,`between`,`empty`,`notEmpty`],boolean:[`is`]},Sj={is:`is`,isNot:`is not`,in:`in`,notIn:`not in`,gt:`>`,gte:`≥`,lt:`<`,lte:`≤`,between:`between`,empty:`is empty`,notEmpty:`is not empty`,contains:`contains`},Cj=C([v(),y(),b()]),wj=E([`usd`,`ms`,`tokens`,`bytes`,`count`]);S({label:v(),type:bj,sortable:b(),filterable:b(),values:x(v()).readonly().optional(),dynamic:b().optional(),unit:wj.optional()});var Tj=v().min(1),Ej=w(`op`,[S({field:Tj,op:E([`is`,`isNot`,`gt`,`gte`,`lt`,`lte`,`contains`]),value:Cj}),S({field:Tj,op:E([`in`,`notIn`]),values:x(Cj).min(1)}),S({field:Tj,op:D(`between`),from:Cj,to:Cj}),S({field:Tj,op:E([`empty`,`notEmpty`])})]),Dj=S({field:Tj,dir:E([`asc`,`desc`])}),Oj=Hl.extend({text:v().optional(),filters:x(Ej).max(20).optional(),sort:x(Dj).max(3).optional()}),kj=(e,t={})=>({label:e,type:`text`,sortable:!0,filterable:!0,...t}),Aj=(e,t)=>({label:e,type:`enum`,sortable:!0,filterable:!0,values:t}),jj=e=>({label:e,type:`enum`,sortable:!0,filterable:!0,dynamic:!0}),Mj=(e,t)=>({label:e,type:`number`,sortable:!0,filterable:!0,unit:t}),Nj=e=>({label:e,type:`date`,sortable:!0,filterable:!0}),Pj=e=>({label:e,type:`boolean`,sortable:!1,filterable:!0}),Fj=e=>({...e,sortable:!1}),Ij=[`resources`,`fns`,`runs`,`modelCalls`,`llmCalls`,`sessions`,`contexts`,`notifications`,`systems`,`types`,`graph`,`users`,`groups`],Lj=E(Ij),Rj={resources:{fields:{name:kj(`Name`),system:jj(`System`),family:Aj(`Type`,HE),source:Aj(`Source`,zE),forms:{...Aj(`Forms`,nS.options),sortable:!1},size:Mj(`Size`,`bytes`),seenAt:Nj(`Seen`),modifiedAt:Nj(`Modified`)},defaultSort:[{field:`seenAt`,dir:`desc`}]},fns:{fields:{name:kj(`Name`),system:jj(`System`),kind:jj(`Kind`),available:Pj(`Available`),paused:Pj(`Paused`),disabled:Pj(`Disabled`),runs:Mj(`Runs`,`count`),failures:Mj(`Failures`,`count`),averageCost:Mj(`Avg cost`,`usd`),averageTime:Mj(`Avg time`,`ms`),lastRunAt:Nj(`Last run`),updatedAt:Nj(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},runs:{fields:{fn:jj(`Fn`),system:jj(`System`),status:Aj(`Status`,xE),session:jj(`Session`),actor:jj(`By`),cost:Mj(`Cost`,`usd`),duration:Mj(`Duration`,`ms`),createdAt:Nj(`Started`),endedAt:Nj(`Ended`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},modelCalls:{fields:{modality:Aj(`Modality`,DD),model:jj(`Model`),provider:jj(`Provider`),system:jj(`System`),status:Aj(`Status`,ID.options),session:jj(`Session`),cost:Mj(`Cost`,`usd`),tokens:Mj(`Tokens`,`tokens`),duration:Mj(`Duration`,`ms`),createdAt:Nj(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},llmCalls:{fields:{model:jj(`Model`),system:jj(`System`),status:Aj(`Status`,uj.options),session:jj(`Session`),cost:Mj(`Cost`,`usd`),tokens:Mj(`Tokens`,`tokens`),duration:Mj(`Duration`,`ms`),createdAt:Nj(`Started`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},sessions:{fields:{title:kj(`Title`),agent:jj(`Agent`),status:Aj(`Status`,[`idle`,`running`,`paused`]),archived:Pj(`Archived`),createdAt:Nj(`Created`),updatedAt:Nj(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},contexts:{fields:{name:kj(`Name`),system:jj(`System`),origin:Aj(`Origin`,_S),tags:jj(`Tag`),status:Aj(`Status`,PS),askedBy:Aj(`Asked by`,RS),stale:Pj(`Stale`),tokens:Mj(`Tokens`,`tokens`),lastModified:Nj(`Last modified`),updatedAt:Nj(`Updated`)},defaultSort:[{field:`updatedAt`,dir:`desc`}]},notifications:{fields:{kind:jj(`Kind`),read:Pj(`Read`),createdAt:Nj(`Received`)},defaultSort:[{field:`createdAt`,dir:`desc`}]},systems:{fields:{name:kj(`Name`),status:jj(`Status`),version:kj(`Version`),instances:Mj(`Instances`,`count`),fns:Mj(`Fns`,`count`),context:Mj(`Context`,`count`),types:Mj(`Types`,`count`),parts:Mj(`Other parts`,`count`),pending:Mj(`Pending changes`,`count`),refusals:Mj(`Refusals`,`count`),lastSeenAt:Nj(`Last seen`)},defaultSort:[{field:`name`,dir:`asc`}]},types:{fields:{name:kj(`Name`),system:jj(`System`),instance:jj(`Instance`),references:Mj(`Refers to`,`count`),updatedAt:Nj(`Updated`)},defaultSort:[{field:`name`,dir:`asc`}]},graph:{fields:{name:Fj(kj(`Name`)),system:Fj(jj(`System`)),nodeKind:Fj(Aj(`Item`,hj)),edgeKind:Fj(Aj(`Link`,_j)),fnKind:Fj(jj(`Fn kind`)),mode:Fj(jj(`Mode`)),effect:Fj(jj(`Effect on`)),visibility:Fj(Aj(`Visible to`,zl.options)),stage:Fj(Aj(`Stage`,yj)),on:Pj(`On`)},defaultSort:[]},users:{fields:{name:kj(`Name`),email:kj(`Email`),role:Aj(`Role`,[`admin`,`member`]),disabled:Pj(`Disabled`),createdAt:Nj(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]},groups:{fields:{name:kj(`Name`),createdAt:Nj(`Added`)},defaultSort:[{field:`name`,dir:`asc`}]}};function zj(e,t){return t.sort!==void 0&&t.sort.length>0?t.sort:Rj[e].defaultSort}var Bj=S({value:Cj,label:v().optional(),count:y().int().min(0)}),Vj=S({list:Lj,field:Tj,prefix:v().optional(),limit:y().int().min(1).max(50).optional()}),Hj=S({list:Lj,query:Oj.default({})}),Uj=Vl(Zc()).extend({sort:x(Dj),total:y().int().min(0).optional(),partial:D(!0).optional().describe(`More rows than the hub reads at once: more may match; narrow the filters for a full answer.`)}),Wj=sl.record,Gj=S({shape:E([`table`,`value`]),owner:E([`shared`,`person`]),writers:D(`admins`).optional(),search:S({text:x(v().min(1)),embed:b()})}),Kj=S({id:Wj,type:I,value:O,owner:M.optional(),title:v(),version:y().int().min(1),createdAt:N,updatedAt:N,updatedBy:M.optional(),updatedBySystem:F.optional(),run:A.optional()}),qj=S({id:v().min(1),record:Wj,type:I,number:y().int().min(1),change:E([`created`,`updated`,`removed`]),value:O,by:M.optional(),bySystem:F.optional(),run:A.optional(),at:N}),Jj=S({type:I,query:Oj.optional(),search:v().min(1).optional(),run:A.optional()}),Yj=Vl(Kj),Xj=Jj.extend({query:Oj.omit({cursor:!0,limit:!0}).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(500).optional()}),Zj=S({type:I,id:Wj,run:A.optional()}),Qj=S({type:I,id:Wj.optional(),value:O,expect:y().int().min(1).optional(),run:A.optional(),owner:M.optional()}),$j=S({type:I,id:Wj,set:T(v().min(1),O).refine(e=>Object.keys(e).length>0,`set at least one field`),expect:y().int().min(1).optional(),run:A.optional()}),eM=S({type:I,id:Wj,run:A.optional()}),tM=Hl.extend({type:I,id:Wj}),nM=Vl(qj),rM=S({type:I,system:F,description:v(),storage:Gj,records:y().int().min(0),updatedAt:N.optional()}),iM=Hl.extend({text:v().optional(),system:F.optional()}),aM=Vl(rM),oM=`general`,sM=S({name:k,title:v().min(1),description:v().min(1)}),cM=E([`sqlite`,`postgres`,`sqlserver`]),lM=cM.options,uM=S({description:v().min(1).max(500),vectors:b().default(!1),engines:x(cM).min(1).default([...lM])}),dM=v().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/,`A migration id is letters, digits, dots, dashes and underscores, starting with a letter or digit.`),fM=v().regex(/^[A-Za-z_][A-Za-z0-9_]{0,62}$/,`A schema name is letters, digits and underscores, starting with a letter or underscore.`),pM=E([`postgres`,`sqlserver`]);E([`system`,`hub`,`external`]);var mM=`system`,hM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:pM,connection:fA,schema:fM})]),gM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:pM,connection:v().min(1).max(4e3),schema:fM})]),_M=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:pM,connection:v().min(1),schema:fM})]),vM=[`sqlite`,`postgres`,`sqlserver`],yM={postgres:`Postgres with the pgvector extension installed (CREATE EXTENSION vector)`,sqlserver:`SQL Server 2025 or newer, which has the VECTOR type`};function bM(e){return e.placement===`external`&&e.engine!==void 0?e.engine:`sqlite`}function xM(e,t){let n=bM(t),r=t.placement===`external`?`an external ${n} database`:`the ${t.placement===`hub`?`hub`:`system`} (SQLite)`;return e.engines.includes(n)?e.vectors&&!vM.includes(n)?[`This store keeps vectors, which ${r} can't hold.`]:[]:[`This store runs only on ${e.engines.join(`, `)}, so it can't be kept in ${r}.`]}var SM=E([`preparing`,`migrating`,`ready`,`moving`,`failed`]),CM=S({applied:x(S({id:dM,checksum:v().min(1),at:N})),pending:x(dM)}),wM=S({name:v().min(1).max(200),rows:y().int().min(0)}),TM=S({bytes:y().int().min(0).optional(),tables:x(wM).max(200),at:N,more:b().optional()}),EM=S({state:SM,engine:cM,migrations:CM,error:v().max(4e3).optional(),measure:TM.optional()}),DM=EM.extend({at:N}),OM=w(`placement`,[S({placement:D(`system`)}),S({placement:D(`hub`)}),S({placement:D(`external`),engine:pM,schema:fM})]),kM=v().regex(/^[0-9a-z][0-9a-z_.-]{0,120}$/),AM=S({id:kM,system:v(),instance:v(),where:OM,bytes:y().int().min(0).optional(),at:N,reason:E([`move`,`removed`]),orphaned:b().default(!1)}),jM=v().regex(/^move_[0-9a-z]{8,40}$/),MM=E([`draining`,`waiting`,`copying`,`switching`,`done`,`failed`]),NM=E([`ask`,`cancel`,`wait`]),PM=E([`cancel`,`wait`]),FM=S({step:E([`exporting`,`transferring`,`migrating`,`copying`,`checking`]).optional(),tables:S({done:y().int().min(0),total:y().int().min(0)}),table:v().max(200).optional(),rows:y().int().min(0),bytes:S({done:y().int().min(0),total:y().int().min(0)})}),IM=S({move:jM,system:v(),instance:v(),from:OM,to:OM,phase:MM,runs:NM,running:x(v()),asking:N.optional(),progress:FM,startedAt:N,endedAt:N.optional(),by:v(),backups:x(AM),error:v().max(4e3).optional()}),LM=S({placement:hM,status:DM.optional(),backups:x(AM).optional()}),RM=S({system:v(),instance:v(),decl:uM,placement:OM,status:DM.optional(),holding:b(),measure:TM.optional(),file:S({bytes:y().int().min(0),snapshots:x(S({name:v(),bytes:y().int().min(0),at:N}))}).optional(),backups:x(AM).default([]),move:IM.optional()}),zM=v().regex(/^lease_[0-9a-z]{8,40}$/),BM=S({$bytes:v()}),VM=C([v(),y(),ic(),BM]),HM=S({sql:v().min(1).max(1e6),params:x(VM).max(32766),lease:zM.optional()}),UM=S({rows:x(T(v(),VM)),changes:y().int().min(0).optional(),insertId:y().int().optional()}),WM=S({lease:zM,expiresAt:N}),GM=v().regex(/^[0-9a-z][0-9a-z_.-]{0,120}\.db$/);function KM(e){for(let t of e.matchAll(VT)){let n=(t[1]??``).trim();if(!n.startsWith(`args.`))return`the claim "${e}" uses {${n}}: a claim reads only its call's args ({args.path})`}}var qM=v().min(1).max(500).superRefine((e,t)=>{let n=KM(e);n!==void 0&&t.addIssue({code:`custom`,message:n})}),JM=S({fn:k,args:O,user:tE,caller:A,session:j.optional()}),YM=S({claims:x(v().min(1))});function XM(e){return e==null||e===``?[]:typeof e==`string`?[e]:typeof e==`number`||typeof e==`boolean`?[String(e)]:Array.isArray(e)?e.flatMap(e=>Array.isArray(e)?[JSON.stringify(e)]:XM(e)):[JSON.stringify(e)]}function ZM(e,t){let n=[],r=[],i=0;for(let a of e.matchAll(VT)){n.push(e.slice(i,a.index)),i=a.index+a[0].length;let[o,...s]=(a[1]??``).trim().split(`.`),c=o===`args`?XM(KT(t,s)):[],l=a[2],u=c.length>0?c:l===void 0?[]:[l];if(u.length===0)return[];r.push(u)}n.push(e.slice(i));let a=[n[0]??``];return r.forEach((e,t)=>{let r=n[t+1]??``;a=a.flatMap(t=>e.map(e=>`${t}${e}${r}`))}),a}function QM(e,t){return[...new Set(e.flatMap(e=>ZM(e,t)))]}var $M=S({label:v(),plural:v().optional(),icon:v().optional(),color:v().optional(),title:v().optional(),subtitle:v().optional()}),eN=S({name:k,description:v(),def:gT,display:$M,methods:x(k),instance:L.optional(),audience:_O.optional(),meta:T(v(),O).optional(),records:Gj.optional()}),tN=E([`user-wins`,`union`,`intersect`,`most-restrictive`]),nN=E([`self`,`fns`]),rN=S({name:k,description:v(),type:gT,appliesTo:x(Bl),merge:tN,editableBy:x(nN)}),iN=S({name:k,description:v(),data:gT}),aN=S({name:k,description:v(),applicability:v(),payload:gT,approveChanges:b(),status:FT.optional(),estimates:b().optional(),approval:$k.optional()}),oN=S({description:v(),args:gT,returns:gT,required:b()}),sN=w(`to`,[S({to:D(`instance`),instance:L}),S({to:D(`any`)})]),cN=S({args:O,result:O.optional(),note:v().optional()}),lN=E([`read`,`write`,`delete`]),uN=E([`fns`,`types`,`context`,`resources`,`kinds`,`components`,`examples`,`approvals`,`secrets`,`connections`,`records`]),dN=[`create`,`update`,`remove`],fN=E(dN),pN=S({thing:uN,action:fN,kind:Pl.optional()}).refine(e=>e.kind===void 0||e.thing===`fns`,{message:`only fns have a kind`,path:[`kind`]}),mN=E([`resources`]),hN=S({mode:lN.optional(),reads:x(I).optional(),writes:x(I).optional(),free:b().optional(),registry:x(pN).optional(),keeps:x(mN).min(1).optional()}),gN=S({language:v().min(1),code:v()}),_N=S({every:Ml.min(1e3)}),vN=E([`developer`,`admin`,`reference`]),yN=S({deps:x(I)}),bN=S({name:k,description:v(),instructions:v().optional(),kind:Pl,payload:O.optional(),readable:gN.optional(),args:gT,returns:gT,deps:x(I),handlers:T(v(),oN),progress:uE,status:FT.optional(),operations:sE,undo:gT.optional(),resume:gT.optional(),state:gT.optional(),form:gT.optional(),display:oE,limits:lE,visibility:zl,tags:x(v()),niche:vN.optional(),examples:x(cN).optional(),validate:ek.optional(),approval:$k.optional(),routing:sN.optional(),connectKey:EO.optional(),effects:hN.optional(),promptExamples:y().int().min(0).max(20).optional(),group:k.optional(),flags:b().optional(),roles:x(WD).optional(),live:_N.optional(),parallelClaims:x(qM).optional(),dynamicClaims:b().optional(),check:yN.optional()}),xN=S({name:v(),hint:v(),required:b()}),SN=S({to:I,when:v().min(1).max(200)}),CN=S({name:k,title:v().min(1).optional(),description:v(),content:v().optional(),command:S({name:v(),args:x(xN)}).optional(),imports:x(I),fns:x(I),suggestFns:x(I),suggest:zl,visible:zl,inject:Ub.optional(),tags:x(v()),niche:vN.optional(),weight:y().min(0).max(2).optional(),summary:v().optional(),parent:I.optional(),next:I.optional(),choices:x(SN).optional(),links:x(wS).optional(),question:v().min(1).max(500).optional(),when:v().min(1).max(500).optional(),lastModified:N.optional(),askedBy:zS.optional()}),wN=S({name:k,description:v(),explains:v().min(1).max(2e3).optional(),order:y(),timeout:Ml}),TN=S({name:k,title:v(),description:v(),target:gT,of:I.optional()}),EN=S({name:k,description:v(),match:aS}),DN=S({name:k,description:v(),input:gT,returns:gT,state:gT.optional(),expires:Ml.optional()}),ON=[`message`,`run`,`resources`,`system`,`fns`],kN=E(ON),AN=S({entry:v(),hash:v(),files:x(S({path:v(),size:y().int().min(0),hash:v()}))}),jN=E([`types`,`settings`,`attachments`,`kinds`,`fns`,`context`,`hooks`,`mentions`,`sectioners`,`actions`]),MN={types:x(eN),settings:x(rN),attachments:x(iN),kinds:x(aN),fns:x(bN),context:x(CN),hooks:x(wN),mentions:x(TN),sectioners:x(EN),actions:x(DN)},NN=S({name:F,version:v(),description:v(),about:v().optional(),hash:v(),...MN,events:x(kN),resources:b(),client:AN.optional(),config:gT,requires:x(F),providers:x(VO).optional(),connect:DO.optional(),registries:x(jk).optional(),contributes:x(Mk).optional(),configSecrets:uA.optional(),runtime:bc(jN,x(k)).optional(),grants:gk.optional(),configComponent:_k.optional(),pages:yA.optional(),groups:x(sM).optional(),store:uM.optional()}),PN=S({hash:v(),upsert:S(MN).partial(),remove:bc(jN,x(k)),lists:NN.pick({providers:!0,registries:!0,contributes:!0}).optional(),roots:D(!0).optional()}),FN=S({added:x(I),updated:x(I),removed:x(I),refused:x(S({name:v(),problems:x(v())}))}),IN=S({args:gT,returns:gT,description:v(),mode:lN}),LN=S({args:gT,returns:gT,deps:x(I),types:x(I).optional(),refs:x(v()).optional(),operations:sE,handlers:T(v(),oN).optional(),progress:uE.optional(),status:FT.optional(),limits:lE.optional(),display:oE.optional(),approval:$k.optional(),effects:hN.optional(),readable:gN.optional(),connectKey:TO.optional(),parallelClaims:x(qM).optional(),examples:x(cN).min(1)});function RN(e){return e===`native`||e.startsWith(`hub/`)}function zN(e){return RN(e.kind)&&(e.examples??[]).length===0}var BN=S({session:j,turn:cl,text:v(),user:tE,time:nE}),VN=y(),HN=S({label:v(),mode:lN,blocked:v().optional(),args:v().optional(),returns:v().optional(),instructions:v().optional(),examples:x(cN).optional(),moreExamples:y().int().positive().optional()}),UN={toolset:ax.optional()},WN=w(`type`,[S({type:D(`text`),tag:v(),text:v()}),S({type:D(`suggest-context`),...UN,items:x(S({context:I,title:v().optional(),why:v().optional(),score:VN.optional()}))}),S({type:D(`suggest-fns`),...UN,items:x(S({fn:I,why:v().optional(),score:VN.optional(),card:HN.optional()}))}),S({type:D(`load`),context:x(I).optional(),fns:x(I).optional()})]),GN=S({label:v(),hint:v().optional(),icon:v().optional(),target:O}),KN=S({title:v(),subtitle:v().optional(),fields:x(S({label:v(),value:v()})).optional(),body:v().optional(),open:oS.optional(),value:O.optional()});CN.omit({name:!0,content:!0}).extend({key:k,summary:v().min(1).max(300),imports:x(I).default([]),fns:x(I).default([]),suggestFns:x(I).default([]),suggest:zl.default(`both`),visible:zl.default(`both`),tags:x(v()).default([]),lastModified:C([N,$c().transform(e=>Date.parse(e)),Qc({offset:!0}).transform(e=>Date.parse(e))]).optional()}).strict();var qN=E([`header`,`duplicate-key`,`broken-link`,`cycle`,`missing-summary`]);S({file:v().min(1),line:y().int().min(1),column:y().int().min(1),code:qN,message:v().min(1)});var JN=S({loaded:x(I),fns:x(I),fnsRefused:x($T),refused:x(S({context:v(),reason:v().min(1),closest:x(I)})),cards:v()}),YN=S({context:x(v().min(1)).min(1),guidance:v().min(1).max(4e3),maxDepth:y().int().min(0).max(10).default(NS.maxDepth),maxDecisions:y().int().min(1).max(4096).default(NS.maxDecisions),maxTokens:y().int().min(1).max(1e6).default(NS.maxTokens),metadataOnly:b().default(!1)}),XN=E([`start`,`import`,`choice`]),ZN=S({name:I,title:v().optional(),description:v(),depth:y().int().min(0),via:XN,from:I.optional(),probability:y().min(0).max(1).optional(),tokens:y().int().min(0),content:v().optional()}),QN=E([`declined`,`max-tokens`,`max-decisions`,`max-depth`,`unavailable`,`failed`]),$N=S({context:v(),from:I.optional(),depth:y().int().min(0),reason:QN,probability:y().min(0).max(1).optional()}),eP=E([`complete`,`max-depth`,`max-decisions`,`max-tokens`,`failed`]),tP=JN.extend({crawled:x(ZN),skipped:x($N),stop:S({reason:eP,detail:v().optional()}),depth:y().int().min(0),decisions:y().int().min(0),tokens:y().int().min(0),calls:x(Ol),metadataOnly:b()}),nP=S({loaded:x(I),refused:x($T),cards:v()});C([nP.strict(),JN.strict(),tP.strict()]);var rP=S({expiresIn:Ml.nullable().optional()}),iP=S({id:Al,secret:v().min(32),expiresAt:N.optional()}),aP=iP.pick({id:!0,secret:!0}),oP=S({id:Al,system:F,instance:L,secretHash:v(),previousHash:v().optional(),createdBy:M,createdAt:N,expiresAt:N.optional(),lastUsedAt:N.optional(),uses:y().int().min(0),revokedAt:N.optional()}).omit({secretHash:!0,previousHash:!0}),sP=E([`pairing`,`needs-config`,`connected`,`disconnected`,`removed`]),cP=C([S({path:v()}),S({package:v(),version:v()}),S({git:v(),ref:v()}),S({zip:v().regex(qx),file:v()})]),lP=S({policy:E([`always`,`on-failure`,`never`]),backoff:Ml,maxPerHour:y().int().min(1)}),uP=E([`installing`,`stopped`,`starting`,`running`,`crashed`,`disabled`]),dP=S({name:F,instance:L,source:cP,dir:v(),command:S({run:v(),args:x(v()),env:T(v(),v()),cwd:v().optional()}),version:v(),goodVersion:v().optional(),autoStart:b(),restart:lP,status:uP,pid:y().int().optional(),lastExit:S({code:y().int(),at:N,output:v()}).optional(),installedBy:M,installedAt:N}),fP=S({functions:b(),renderers:b(),context:b().optional()}),pP=S({value:O,version:y().int().min(1),setBy:M,setAt:N}),mP=S({keyFingerprint:v().optional(),publicKey:v().optional(),config:pP.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional()}),hP=E([`one`,`many`]),gP=S({name:F,description:v(),about:v().optional(),status:sP,enabled:fP,version:v(),manifestHash:v(),defaultInstance:L.optional(),actor:M,stage:yk.optional(),instances:hP.optional()}).extend(mP.shape),_P=S({id:pl,name:F,keyFingerprint:v(),publicKey:v(),version:v(),address:v(),method:E([`code`,`token`]),code:v().optional(),replaces:F.optional(),description:v().optional(),instance:L.optional(),configType:gT.optional(),configSecrets:uA.optional(),store:uM.optional(),status:E([`pending`,`approved`,`rejected`,`expired`]),createdAt:N,expiresAt:N});S({id:ml,name:F.optional(),tokenHash:v(),createdBy:M,expiresAt:N,usedAt:N.optional(),autoPair:rP.optional(),boundTo:S({instance:L,manifestHash:v().min(1),host:ql,run:A}).optional()}),S({system:F,manifest:NN,importedAt:N});var vP=cO.pick({averageCost:!0,averageQueued:!0,p95:!0,lastRunAt:!0}).extend({outcomes:tO.default(nO),averageTime:Ml,tokens:cO.shape.tokens.default(0)}),yP=E([`contract`,`runtime`]),bP=S({name:I,system:F,decl:bN,version:v(),origin:yP,addedBy:M.optional(),available:ZT,paused:b(),disabled:b(),stats:vP,updatedAt:N});S({name:I,system:F,decl:aN});var xP=eN.omit({name:!0,methods:!0}).extend({name:I,system:F,references:x(I),declaredBy:yP.optional(),version:v().optional(),updatedAt:N}),SP=S({types:x(xP),missing:x(I)}),CP=CN.extend({alwaysFor:x(I).optional()}),wP=S({name:I,system:F,origin:gS.optional(),declaredBy:yP.optional(),version:v().optional(),decl:CP,tokens:vS.optional(),status:FS.default(`active`),statusReason:v().optional(),statusHistory:x(BS).optional(),disabled:b().optional(),systemOff:b().optional(),lastModified:N.optional(),duplicate:VS.optional(),contradiction:VS.optional(),notDuplicates:x(I).optional(),checked:S({contentHash:v(),at:N}).optional(),metadata:US.optional(),split:WS.optional(),validUntil:N.optional(),askedBy:zS.optional(),mentions:S({context:x(I),fns:x(I)}),stale:b(),updatedAt:N,wantsMetadata:b().optional(),wantsCheck:b().optional(),inReview:b().optional()});function TP(e){return e.systemOff===!0||!LS(e.status)}function EP(e){return e.lastModified??e.updatedAt}var DP=[`kinds`,`commands`,`mentions`,`hooks`,`actions`,`settings`,`attachments`,`embedders`,`sectioners`,`providers`,`registries`,`components`,`examples`],OP=E(DP),kP=S({section:OP,name:v().min(1),about:v(),origin:yP,version:v(),visibility:zl.optional(),owner:I.optional(),decl:O,on:b().optional()}),AP=S({system:F}),jP=S({parts:x(kP),more:bc(OP,y().int().min(0))});function MP(e){return eT(e?.name??`otel`,{requires:e?.requires??[]})}var NP=v().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/),PP=/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i,FP=e=>e!==``&&e!==`.`&&e!==`..`&&!PP.test(e),IP=v().min(1).refine(e=>!e.includes(`\\`)&&!e.includes(`:`)&&e.split(`/`).every(FP),`A package path is relative, uses forward slashes and stays inside the package.`),LP=S({childProcess:b(),workers:b()});S({format:D(1),name:F,version:NP,description:v(),protocol:y().int().min(1),server:S({entry:IP,external:T(v(),v()).default({}),node:v().optional()}),client:S({entry:IP}).optional(),instances:hP.default(`one`),files:T(IP,v().regex(qx)).optional(),permissions:LP.partial().optional()});var RP=S({state:v(),data:v(),cache:v()}),zP=S({host:ql,path:v().min(1),bundleHash:v().min(1),approval:gl}),BP=S({system:F,instance:L,description:v(),status:sP,keyFingerprint:v(),publicKey:v(),version:v(),manifestHash:v(),config:pP.optional(),installed:dP.optional(),host:zP.optional(),dirs:RP.optional(),pairedAt:N.optional(),pairedBy:M.optional(),lastSeenAt:N.optional(),address:v().optional(),connect:wO.optional(),store:LM.optional()}),VP=S({instance:L,description:v(),online:b(),config:O,types:x(S({name:I,description:v()}))}),HP=S({pairing:pl,description:v(),instance:L,configType:gT.optional(),configSecrets:uA.optional(),store:uM.optional()});S({format:D(1),system:F,instance:L,version:v(),exportedAt:N,exportedBy:M,withSecrets:b()});var UP=S({system:F,instance:L,description:v().optional(),config:O,store:gM.optional()}),WP=S({at:N,stream:E([`stdout`,`stderr`,`hub`]),text:v()}),GP=S({meaning:b(),items:y().int().min(0),pending:y().int().min(0),embedding:b(),retrying:b(),lastError:S({at:N,message:v()}).optional()}),KP=C([TA,I]),qP=S({id:v(),provider:KP,name:v(),contextWindow:y().int().min(0).optional(),pricing:S({input:P,output:P}).optional(),capabilities:x(v()),maxQuestions:y().int().min(1).optional(),maxRequestBytes:y().int().min(1).optional()}),JP=qP.extend({tier:E([`flagship`,`efficient`,`legacy`,`experimental`]),maxOutputTokens:y().int().min(1).optional(),roles:x(WD)}),YP=AA.extend({spent:P}),XP=S({setting:I,system:F,decl:rN}),ZP=fj.omit({request:!0,response:!0}),QP=w(`kind`,[S({kind:D(`budget`),id:_l}),S({kind:D(`priority`),id:vl}),S({kind:D(`policy`),id:hl}),S({kind:D(`category`),id:wl}),S({kind:D(`provider`),id:Tl})]),$P=S({uri:Wx,system:F,stat:Xx,links:x(Zx),indexedVersion:v().optional(),sectioner:I.optional(),source:RE.optional(),raw:Jx.optional(),forms:x(nS).optional(),primary:nS.optional(),seenAt:N});S({id:El,match:aS,sectioner:I,setBy:M}),S({uri:Wx,from:v(),to:v(),added:x(Gx),changed:x(Gx),removed:x(Gx)});var eF=E([`fn`,`context`,`section`,`message`,`type`,`example`,`record`,`contextSection`,`image`,`contextContent`]);S({kind:eF,key:v(),system:F.optional(),text:v(),embedText:v().optional(),hash:v(),vectorHash:v().optional(),embedder:I,updatedAt:N,parent:v().optional(),image:v().optional()});var tF=E([`words`,`meaning`,`both`]);S({kind:eF,key:v(),rank:y().min(0).max(1),similarity:y().min(-1).max(1).optional(),matched:tF.optional(),parent:v().optional(),text:v()});var nF=E([`approval-needed`,`input-needed`,`config-needed`,`message`,`replied`,`turn-finished`,`turn-failed`,`pairing-requested`,`system-disconnected`,`spend-limit`,`system-paused`,`system-notice`,`system-message`]),rF=S({system:F,segment:v().min(1),path:x(v().min(1)).optional(),query:T(v(),v()).optional()}).strict(),iF=C([S({session:j}),S({approval:gl}),S({pairing:pl}),S({run:A}),S({system:F}),S({page:rF})]),aF=E([`ok`,`failed`,`info`]),oF=S({label:v().min(1).max(24),link:iF}),sF=S({id:xl,user:M,reason:nF,title:v(),body:v(),link:iF,read:b(),pushed:b(),resolved:v().optional(),tone:aF.optional(),also:oF.optional(),key:v().min(1).max(200).optional(),createdAt:N}),cF=S({id:Sl,user:M,endpoint:Ls(),keys:S({p256dh:v(),auth:v()}),device:v(),createdAt:N}),lF=sl.fnExample;cN.extend({id:lF,fn:I,system:F,source:E([`decl`,`added`,`runtime`]),key:v().min(1).max(200).optional(),order:y().int().min(0),text:v(),addedBy:M.optional(),createdAt:N});var uF=S({fn:k,upsert:x(cN.extend({key:v().min(1).max(200)})),remove:x(v().min(1).max(200))}),dF=S({fn:kb,query:v().optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(50).optional()}),fF=S({fn:I,items:x(cN.extend({id:lF,rank:y().optional()})),total:y().int().min(0),next:y().int().min(0).optional()}),pF=E([`text`,`semantic`,`hybrid`]),mF=[`session`,`user`,`everyone`],hF=E([`fn`,`context`]),gF=S({text:v().optional(),match:pF.optional(),items:x(hF).min(1).optional(),kinds:x(C([D(`native`),I])).min(1).optional(),systems:x(F).min(1).optional(),instance:L.optional(),visibility:E([`mine`,`shared`,`public`]).optional(),types:S({reads:x(Ab).optional(),writes:x(Ab).optional()}).optional(),modes:x(lN).min(1).optional(),effects:x(S({thing:uN,action:fN.optional(),kind:v().min(1).optional()})).min(1).optional(),names:x(I).min(1).max(100).optional(),filters:x(Ej).max(20).optional(),off:b().optional(),statuses:YS.shape.statuses,returnNotApplicable:YS.shape.returnNotApplicable,semanticOver:YS.shape.semanticOver,scopes:x(E(mF)).min(1).optional(),available:b().optional(),niches:x(vN).min(1).optional(),order:E([`rank`,`name`]).optional(),offset:y().int().min(0).optional(),limit:y().int().min(1).max(100).optional()}),_F=gF.omit({items:!0,match:!0,filters:!0,off:!0,scopes:!0,statuses:!0,returnNotApplicable:!0,semanticOver:!0}).extend({kinds:gF.shape.kinds.describe("Leave `kinds` out unless the person asks for a kind of fn by name: you can't know how a fn was made, and a search by what it does finds every kind."),names:x(kb).min(1).max(100).optional().describe(`Only these fns, by name, spelled as your tools and search hits spell them: to look up fns whose names you know. Leave it out to search by what a fn does.`),types:S({reads:x(Ab).optional(),writes:x(Ab).optional()}).optional().describe("Only fns that read (`reads`) or write (`writes`) any of these types: a table's name (`tasks`), or a type's name exactly as a result gave it. Leave it out unless you know the type.")}),vF=S({text:gF.shape.text,systems:gF.shape.systems,origins:x(E(_S)).min(1).optional(),scopes:gF.shape.scopes,tags:x(v().min(1)).min(1).max(20).optional(),names:gF.shape.names,niches:gF.shape.niches,returnNotApplicable:b().optional().describe(`Also find questions a plan ruled out (status not_applicable), each with why it was ruled out; only ones that have an answer come back. Leave it out unless you need to know what was decided against.`),semanticOver:gF.shape.semanticOver.describe("What the meaning of `text` is compared with: `question` (the default: each item is worded as the question it answers, so ask in plain words) or `content` (the item's text itself, for a phrase you expect inside it)."),order:gF.shape.order,offset:gF.shape.offset,limit:gF.shape.limit}),yF=S({key:Gx,path:x(v()),title:v()}),bF=S({item:hF,name:I,system:F,description:v(),kind:v().optional(),mode:lN.optional(),signature:v().optional(),effects:v().optional(),instance:L.optional(),rank:y().optional(),similarity:y().optional(),matched:tF.optional(),section:yF.optional(),question:v().optional(),answer:v().optional(),status:FS.optional(),statusReason:v().optional(),niche:vN.optional(),available:b(),blocked:QT.optional(),inPrompt:E([`injected`,`loaded`]).optional(),exact:D(!0).optional()}),xF=bF.pick({rank:!0,similarity:!0,matched:!0,section:!0}),SF=wP.extend({found:xF.optional(),metadataStale:b().optional()}),CF=S({item:hF,by:E([`decision`,`llm`]),dropped:x(S({name:I,note:v().optional()})),calls:x(Ol).min(1).optional(),failed:v().optional(),action:D(`load`).optional()}),wF=S({fns:x(I),context:x(I),note:v()}),TF=S({items:x(bF),next:y().int().min(0).optional(),filtered:x(CF).optional(),loaded:wF.optional(),missing:S({names:x(I).min(1),note:v()}).optional()}),EF=S({min:P,typical:P,max:P,basis:E([`free`,`history`,`payload`,`unknown`]),runs:y().int().min(0)}),DF=S({runs:y().int().min(0),typical:Ml,slow:Ml,longest:Ml}),OF=S({fn:I,kind:v(),mode:lN,reads:x(I),writes:x(I),uses:x(I),free:b(),registry:x(pN),cost:EF,times:DF.optional(),longRunning:b(),notice:v().optional()}),kF=S({kind:v().min(1),payload:O,args:O.optional(),history:EF.optional()}),AF=S({estimate:EF.optional()}),jF=S({model:KD.optional(),messages:y().int().min(0).max(20).default(4)}),MF=S({value:jF,setBy:M.optional(),updatedAt:N.optional()}),NF=S({entries:x(w(`type`,[S({type:D(`log`),at:N,level:E([`debug`,`info`,`warn`,`error`]),message:v().max(4e3),fields:T(v(),O).optional()}),S({type:D(`traffic`),at:N,method:v().max(16),endpoint:v().max(300),status:y().int(),duration:Ml})])).min(1).max(500),page:v().max(300).optional()}),PF=S({uri:Wx,written:y().int().min(0)});OF.pick({fn:!0,kind:!0,mode:!0,reads:!0,writes:!0,uses:!0,free:!0}).extend({registry:x(pN).optional(),system:F,instance:L.optional(),updatedAt:N}),S({fn:I,type:I,use:E([`read`,`write`])}),S({fn:I,type:I,kind:Pl,system:F}),S({fn:I,to:I,link:E([`dep`,`kind`,`role`]),system:F}),S({fn:I,uses:I}),S({id:v(),fn:I,number:y().int().min(1),decl:bN,savedBy:M.optional(),savedAt:N}),S({id:v(),type:I,number:y().int().min(1),decl:eN,instance:L.optional(),savedAt:N});var FF={fns:`fns`,types:`types`,context:`context`,resources:`resources`,kinds:`kinds`,components:`components`,examples:`examples`,approvals:`runs awaiting approval`,secrets:`secrets`,connections:`connections`,records:`records`},IF={create:`Creates`,update:`Updates`,remove:`Removes`};function LF(e){let t=[];for(let n of dN){let r=new Map;for(let t of e){if(t.action!==n)continue;let e=r.has(t.thing)?r.get(t.thing):new Set;e===void 0||t.kind===void 0?r.set(t.thing,void 0):(e.add(t.kind),r.set(t.thing,e))}if(r.size===0)continue;let i=[...r.entries()].map(([e,t])=>t===void 0||t.size===0?FF[e]:`${FF[e]} (${[...t].sort().join(`, `)})`);t.push(`${IF[n]} ${i.join(`, `)}.`)}return t.length===0?void 0:t.join(` `)}var RF=sl.refusal,zF=[`fns`,`context`,`types`,`roots`,...DP],BF=E(zF),VF=S({section:BF,name:v().min(1)});VF.extend({system:F,by:M,at:N});var HF=S({version:v(),hash:v().min(1),grants:gk,runtime:x(VF),by:M,at:N}),UF=S({section:C([BF,E([`grants`,`config`])]),name:v().min(1),change:E([`added`,`changed`,`removed`]),origin:yP,before:O.optional(),after:O.optional()}),WF=UF.pick({section:!0,name:!0}),GF=WF.extend({change:UF.shape.change,origin:yP,version:v(),by:M,at:N}),KF=S({version:v(),hash:v().min(1),by:yP,changes:x(UF),since:N});S({system:F,live:HF.optional(),pending:KF.optional(),checks:fk.optional(),declined:x(GF).optional(),updatedAt:N});var qF=S({mode:lN,effects:v().optional(),reads:x(I),writes:x(I),deps:x(I),cost:P.optional(),free:b().optional()}),JF=S({name:v().min(1),before:qF.optional(),after:qF.optional()}),YF=KF.extend({summary:Vk,fns:x(JF),injections:x(qb).default([])}),XF=[`stage`,`effects`,`mode`,`types`,`capability`,`models`,`budget`,`secrets`,`calls`,`network`,`files`,`visibility`],ZF=E(XF),QF=S({id:RF,system:F,instance:L,rule:ZF,attempt:v().min(1),detail:v().min(1),run:A.optional(),fn:I.optional(),at:N}),$F=S({instance:ql,rule:ZF.extract([`network`,`files`]),attempt:v().min(1).max(1e3),detail:v().min(1).max(2e3)}),eI=S({system:F.optional(),rule:ZF.optional(),cursor:v().optional(),limit:y().int().min(1).max(200).optional()}),tI=S({items:x(QF),next:v().optional()}),nI=S({system:F,stage:yk,manifest:NN,facts:x(OF),checks:fk.optional(),live:HF.optional(),pending:YF.optional(),declined:x(GF).default([]),off:x(VF),refusals:S({total:y().int().min(0),last:x(QF).max(10)}),previewUrls:T(v(),v()).optional(),clientApproved:b().optional()}),rI=S({system:F,hash:v().min(1),off:x(VF).default([])}),iI=S({system:F,hash:v().min(1),approve:x(WF).default([]),decline:x(WF).default([]),off:x(VF).default([])}).refine(e=>e.approve.length+e.decline.length>0,{message:`approve or decline at least one change`,path:[`approve`]}),aI=S({hash:v(),waiting:y().int().min(0)}),oI=C([S({preview:Zk,contract:NN.optional(),ask:rA.optional()}),S({refused:v().min(1)})]),sI=S({fn:I,args:O,instance:L.optional()}),cI=sl.mentionRequest,lI=S({request:cI,query:v(),roots:x(Wx).max(20).optional(),limit:y().int().min(1).max(50)}),uI=S({hits:x(sS)}),dI=2e3,fI=S({kind:I,changedSince:N.optional(),cursor:v().optional(),limit:y().int().min(1).max(100).optional()}),pI=S({items:x(S({fn:I,kind:I,owner:M,title:v(),version:y().int().min(1),payload:O,removed:b(),updatedAt:N})),cursor:v().optional()}),mI=S({fn:I,args:O,key:v().min(1).max(200),priority:Rl.extract([`background`,`interactive`]).optional(),maxSpend:P.positive().optional()}),hI=S({run:A,turn:cl,status:SE}),gI=S({title:v().min(1).max(120),body:v().max(dI),tone:aF.optional(),link:iF.optional(),also:oF.optional(),key:v().min(1).max(136).optional()}),_I=`fnloom`,vI=`hub.name`,yI=v().trim().min(1).max(40).refine(e=>!/[\r\n]/.test(e),{message:`One line only.`}),bI=S({name:yI,source:E([`setting`,`env`,`default`]),version:v()}),xI=S({name:yI.nullable()}),SI=[`off`,`text`,`model`];E(SI);var CI=w(`use`,[S({use:D(`off`)}),S({use:D(`text`)}),S({use:D(`model`),embedder:I})]),wI={use:`text`},TI=S({text:b(),images:b(),crossModal:b()}).extend({embedder:I,name:v(),dimensions:y().int().min(1)}),EI=w(`space`,[S({space:D(`none`),reason:v()}),S({space:D(`shared`),embedder:I}),S({space:D(`own`),embedder:I,crossModal:b()})]),DI=S({value:CI,setBy:M.optional(),updatedAt:N.optional(),text:I,options:x(TI),state:EI}),OI={id:M,name:v(),about:v(),createdAt:N,disabled:b()},kI=E([`admin`,`member`]),AI=S({...OI,kind:D(`user`),email:v(),role:kI,timeZone:v().optional()}),jI=w(`kind`,[AI,S({...OI,kind:D(`group`)}),S({...OI,kind:D(`agent`),fn:I}),S({...OI,kind:D(`system`),system:F}),S({...OI,kind:D(`mcp`),mcp:kl})]),MI=AI.pick({id:!0,kind:!0,name:!0,email:!0,role:!0,timeZone:!0});S({group:M,user:M,addedBy:M,addedAt:N,provider:v().optional()}),S({user:M,kind:E([`password`,`passkey`]),secretHash:v(),createdAt:N}),S({id:Dl,user:M,version:y().int().min(1),refreshHash:v(),rotatedHashes:x(v()).optional(),device:v(),createdAt:N,lastSeenAt:N,actingAs:M.optional()}),S({actor:M,session:Dl,version:y().int().min(1)});var NI=S({setting:I,actor:M,value:O,setBy:M,run:A.optional(),updatedAt:N}),PI=C([S({actor:M}),S({group:M}),S({kind:Bl}),S({everyone:D(!0)})]),FI=S({fn:v().optional(),system:F.optional(),kind:Pl.optional(),tags:x(v()).optional(),when:bT.optional(),via:I.optional()}),II=w(`by`,[S({by:D(`turn-user`)}),S({by:D(`actor`),actor:M}),S({by:D(`group`),group:M,quorum:y().int().min(1).optional()}),S({by:D(`admins`)}),S({by:D(`judge`),fn:I}),S({by:D(`hub`)})]);S({fn:I,args:O,actor:M}),S({approve:b(),reason:v()});var LI=w(`effect`,[S({effect:D(`allow`)}),S({effect:D(`deny`),reason:v()}),S({effect:D(`ask`),approver:II})]),RI=S({id:hl,description:v(),subject:PI,target:FI,decision:LI,priority:y().int(),expiresAt:N.optional(),createdBy:M,createdAt:N,yields:b().optional()}),zI=E([`once`,`session`,`always`]),BI=S({id:gl,run:A,fn:I,policy:hl.optional(),approver:II,status:E([`pending`,`approved`,`denied`,`expired`]),decisions:x(S({by:M,approve:b(),remember:zI,reason:v().optional(),at:N})),createdAt:N,preview:Zk.optional(),proposed:b().optional(),ask:rA.optional(),variant:YA.optional()}),VI=v().regex(/^[a-z0-9][a-z0-9-]{0,31}$/,`lower case letters, digits and dashes, starting with a letter or digit`),HI=S({role:v().min(1).default(`groups`).describe(`The claim whose values pick the role (default "groups").`),admin:x(v().min(1)).default([]).describe(`Values of the role claim that make an admin.`),member:x(v().min(1)).optional().describe(`When given, values of the role claim one of which (or an admin value) is needed to sign in.`),groups:v().min(1).optional().describe(`The claim whose values are hub group names to sync the person into.`)}),UI=S({id:VI,label:v().min(1).max(60),issuer:Ls(),clientId:v().min(1),clientSecret:v().min(1).optional(),scope:v().min(1).default(`openid email profile`),userinfo:b().default(!0),claims:HI.prefault({})});x(UI).refine(e=>new Set(e.map(e=>e.id)).size===e.length,`each provider needs its own id`);var WI=v().trim().toLowerCase().regex(/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/,`a domain such as example.com`),GI=w(`mode`,[S({mode:D(`invite`)}),S({mode:D(`domains`),domains:x(WI).min(1).max(50)}),S({mode:D(`anyone`)})]),KI=`signInPolicy`,qI=S({limit:y().int().min(1).max(1e5),window:y().int().min(1e3).max(864e5)}),JI=S({account:qI,address:qI}),YI=`signInLimits`,XI=S({proxies:y().int().min(0).max(5)}),ZI=`proxyTrust`;S({issuer:v(),sub:v(),provider:VI,user:M,email:v().optional(),linkedAt:N,lastSignInAt:N});var QI=UI.pick({id:!0,label:!0}),$I=S({providers:x(UI.omit({clientSecret:!0}).extend({confidential:b()})),policy:GI,breakGlass:MI.optional(),callbackUrl:v(),limits:JI,proxy:XI}),eL=S({ok:b(),detail:v()}),tL=S({provider:VI,ok:b(),discovery:eL,keys:eL,checkedAt:N}),nL=E([`linked`,`email`,`new`,`none`]),rL=S({allowed:b(),reason:v(),link:nL,user:MI.optional(),role:kI.optional(),groups:x(v()),unknownGroups:x(v())}),iL=S({id:v(),provider:VI,at:N,problem:v().optional(),subject:v().optional(),email:v().optional(),emailVerified:b(),claims:T(v(),O),outcome:rL.optional()}),aL=S({provider:VI,label:v(),email:v().optional(),lastSignInAt:N}),oL=MI.extend({disabled:b(),createdAt:N,breakGlass:b(),password:b(),identities:x(aL),groups:x(S({id:M,name:v(),synced:b()}))}),sL=S({id:M,name:v(),about:v(),createdAt:N,members:y().int().min(0)}),cL=S({user:M,name:v().trim().min(1).max(120).optional(),role:kI.optional(),disabled:b().optional()}),lL=S({group:M,user:M,member:b()});function uL(e){return`/auth/sso/${encodeURIComponent(e)}/start`}var dL=`harness_sso_handoff`,fL=E([`score`,`decision`,`graph`]),pL=E([`below-threshold`,`top-n`,`declined`,`budget`,`rule`,`failed`]),mL={"below-threshold":`Score under the threshold`,"top-n":`Others scored higher`,declined:`The decision model declined it`,budget:`No room in the token budget`,rule:`Hidden by a rule`,failed:`Decision model failed; the score decided`},hL=[`suggest`,`load`],gL=E(hL);function _L(e){return e.by===`none`?`suggest`:e.action??`suggest`}var vL=E([`loaded`,`budget`,`blocked`]),yL={loaded:`Loaded for the turn`,budget:`No room to load it, so suggested`,blocked:`Can't be loaded now, so suggested`},bL=w(`used`,[S({used:D(!0),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),note:v().optional(),load:vL.optional()}),S({used:D(!1),kind:E([`fn`,`context`]),name:I,score:y().optional(),broughtBy:I.optional(),reason:pL,note:v().optional()})]),xL=S({by:fL,threshold:y().optional(),calls:x(Ol).min(1).optional(),action:D(`load`).optional(),items:x(bL)}),SL=S({messages:y().int().min(1).max(20).default(3),candidates:y().int().min(1).max(50).default(20),cap:y().int().min(0).max(20).default(6),floor:y().min(0).max(1).default(.2)}),CL=[`decision`,`llm`,`none`];E(CL);var wL=w(`by`,[S({by:D(`none`)}),SL.extend({by:D(`decision`),model:KD.optional(),action:gL.optional()}),SL.extend({by:D(`llm`),model:KD,action:gL.optional()})]),TL={by:`none`},EL=SL.extend({enabled:b(),model:KD.optional()});function DL(e){let{enabled:t,model:n,...r}=e;return t&&n!==void 0?{by:`llm`,model:n,...r}:TL}var OL=C([wL,EL.transform(DL)]),kL=S({value:wL,setBy:M.optional(),updatedAt:N.optional()}),AL=[`none`,`decision`,`llm`];E(AL);var jL=w(`by`,[S({by:D(`none`)}),S({by:D(`decision`),model:KD.optional(),action:gL.optional()}),S({by:D(`llm`),model:KD,action:gL.optional()})]),ML={by:`none`},NL={fn:`fnsSearchDecision`,context:`contextSearchDecision`},PL=S({value:jL,setBy:M.optional(),updatedAt:N.optional()}),FL=S({fn:PL,context:PL}),IL=S({item:hF,value:jL});w(`key`,[S({key:D(`suggestDecision`),value:OL,setBy:M,updatedAt:N}),S({key:D(`autoClassifier`),value:jF,setBy:M,updatedAt:N}),S({key:D(NL.fn),value:jL,setBy:M,updatedAt:N}),S({key:D(NL.context),value:jL,setBy:M,updatedAt:N}),S({key:D(vI),value:yI,setBy:M,updatedAt:N}),S({key:D(`imageEmbedding`),value:CI,setBy:M,updatedAt:N}),S({key:D(KI),value:GI,setBy:M,updatedAt:N}),S({key:D(Fb),value:Ib,setBy:M,updatedAt:N}),S({key:D(YI),value:JI,setBy:M,updatedAt:N}),S({key:D(ZI),value:XI,setBy:M,updatedAt:N}),S({key:D(Rb),value:b(),setBy:M,updatedAt:N}),S({key:D(GS),value:KS,setBy:M,updatedAt:N})]);var LL=E([`all`,`replies`,`none`]),RL=S({actor:M,role:E([`owner`,`member`,`agent`]),notify:LL,joinedAt:N}),zL=E([`idle`,`running`,`paused`]),BL=S({hash:v(),injected:x(I),at:cl}),VL=S({id:j,title:v(),owner:M,...KA.shape,selection:kx.optional(),participants:x(RL),forkOf:j.optional(),fork:YA.optional(),tools:x(I),context:x(I),suggested:x(I).optional(),announcedSystems:PA.optional(),citationsTold:WA.optional(),fixed:BL.optional(),status:zL,transcript:x(aD),createdAt:N,updatedAt:N,archived:b()}),HL=VL.pick({id:!0,title:!0,owner:!0,agent:!0,status:!0,createdAt:!0,updatedAt:!0,archived:!0}),UL=E([`local-time`,`suggested-context`,`suggested-fns`]),WL=S({type:D(`text`),text:v()}),GL=S({type:D(`mention`),provider:I,label:v(),target:O,text:v()}),KL=S({type:D(`command`),context:I,args:T(v(),v())}),qL=S({type:D(`file`),ref:Jx,name:v(),uri:Wx.optional(),text:v().optional(),truncated:b().optional()}),JL=S({type:D(`input-answer`),run:A,title:v(),value:O,text:v()}),YL=`input-answer`,XL=S({type:D(`loaded-for-you`),by:E([`decision`,`llm`,`recall`]),toolset:ax.optional(),fns:x(S({fn:I,label:v(),why:v().optional(),broughtBy:I.optional()})),context:x(S({context:I,title:v().optional(),why:v().optional(),text:v(),fns:x(I).optional()}))}),ZL=w(`type`,[WL,S({type:D(`reasoning`),text:v()}),GL,KL,S({type:D(`invocation`),run:A,fn:I}),S({type:D(`call`),run:A,fn:I}),qL,JL,S({type:D(`extra`),extra:UL,blocks:x(WN)}),S({type:D(`hook`),hook:I,blocks:x(WN)}),S({type:D(`attachment`),attachment:I,data:O,title:v()}),S({type:D(`link`),link:oS}),S({type:D(`systems-changed`),on:x(FA),off:x(FA)}),S({type:D(`kept-effects`),variants:x($A)}),XL]),QL=new Set([`extra`,`hook`,`input-answer`,`systems-changed`,`loaded-for-you`]);function $L(e){return QL.has(e.type)}var eR=w(`type`,[WL,GL.omit({text:!0}),KL,qL,JL]),tR=S({id:ll,session:j,turn:cl,author:M,role:E([`user`,`assistant`,`note`]),parts:x(ZL),runs:x(A),status:E([`streaming`,`done`,`failed`]),replyTo:ll.optional(),replyAll:b(),answerers:x(M),suggestions:xL.optional(),compared:D(!0).optional(),cacheMiss:S({call:Ol,at:N}).optional(),citations:x(UA).optional(),createdAt:N}),nR=E([`pause`,`resume`,`cancel`]),rR=S({run:A,fn:I,status:SE,pause:b(),resume:b(),cancel:b()}),iR=S({pause:b(),cancel:b(),uncancellable:x(A),undoLastTurn:b(),continueLastTurn:b().optional(),runs:x(rR).optional()}),aR=S({session:j,user:M,focused:b(),typing:b(),lastActiveAt:N}),oR=S({voiceInput:b(),voiceOutput:b(),dictation:S({engine:E(JD),language:v().optional()}).optional(),uploads:b(),meaning:b(),mentions:x(S({provider:I,title:v(),of:I.optional()})),commands:x(S({name:v(),context:I,args:x(xN),description:v(),unavailable:v().optional()})),agents:x(S({fn:I,description:v()})),display:T(v(),oE),invocations:x(S({fn:I,description:v(),args:gT})),methods:x(S({type:I,method:v(),fn:I,description:v(),args:gT})),clients:x(S({system:F,url:v(),hash:v()})),systems:x(S({name:F,status:sP,enabled:b()})),models:x(qP)}),sR=tR.pick({id:!0,session:!0,author:!0,role:!0,replyTo:!0,replyAll:!0,createdAt:!0}).extend({text:v()}),cR=sP.extract([`connected`,`disconnected`,`removed`]),lR=w(`type`,[S({type:D(`message`),message:sR}),S({type:D(`run`),run:A,fn:I,update:kE,notified:b().optional()}),S({type:D(`resources`),changes:x(iS)}),S({type:D(`system`),system:F,status:cR}),S({type:D(`fns`),added:x(I),removed:x(I),changed:x(I).default([])})]),uR=S({protocol:D(1),name:F,version:v(),instance:L.default(Kl),instances:hP.optional(),boot:v(),publicKey:v(),manifestHash:v(),contractHash:v().optional(),pairingToken:v().optional(),autoPair:aP.optional()}),dR=w(`kind`,[S({kind:D(`challenge`),nonce:v()}),S({kind:D(`pairing`),pairing:pl,code:v().optional(),url:v(),expiresAt:N})]),fR=S({signature:v()}),pR=S({maxFrame:y().int().min(1024),maxChunk:y().int().min(1024),heartbeat:Ml}),mR=S({value:O,version:y().int().min(1)}),hR=S({instance:L,config:mR.optional(),start:S({first:b(),upgradedFrom:v().optional()}),token:v(),sendManifest:b(),limits:pR,autoPair:iP.optional(),store:_M.optional()});S({system:F,instance:L,boot:v()});var gR=eT(`linkSession`,{provides:Jw()}),_R=MP({name:`linkTel`}),vR=S({state:O,calls:T(v(),jE),reason:E([`resumed`,`restart`])}),yR=S({run:iE,fn:v(),kind:Pl,payload:O.optional(),args:O,budget:PE,handlers:x(v()),resume:vR.optional(),deadline:N,configVersion:y().int().min(0),connection:MO.optional(),approved:aA.optional()}),bR=C([S({run:A}),S({delivery:ul})]),xR=S({session:j,actor:M,user:tE,time:nE}),SR=S({level:E([`debug`,`info`,`warn`,`error`]),key:v(),fields:el}),CR=S({run:A,action:E([`cancel`,`pause`])}),wR=S({accepted:b(),reason:v().optional()}),TR=E([`restart`,`upgrade`,`shutdown`,`removed`]),ER=S({title:v().min(1).max(120),body:v().max(2e3)}),DR=Z(_R,gR).group({manifest:{body:NN,response:FN,ws:`mf`},patch:{body:PN,response:FN,ws:`mp`},call:{body:S({parent:A,fn:I,args:O,key:v(),budget:S({cost:P.optional(),time:Ml.optional()}).optional(),handlers:x(v()),background:b(),on:L.optional()}),response:jE,ws:`call`},handle:{body:S({run:A,handler:v(),args:O}),response:NE,ws:`ha`},control:{body:CR,response:wR,ws:`cl`},progress:{body:S({run:A,progress:pE}),ws:`pg`},allow:{body:S({run:A,operations:cE.partial()}),ws:`al`},undoWith:{body:S({run:A,undo:O}),ws:`uw`},updateResult:{body:S({run:A,result:O}),response:S({revision:y().int().min(1)}),ws:`ur`},attach:{body:S({run:A,item:C([S({attachment:I,data:O,title:v()}),S({link:oS})])}),ws:`at`},types:{body:S({names:x(I).min(1),run:A.optional()}),response:SP,ws:`ty`},fnShape:{body:S({name:I}),response:S({fn:IN.optional()}),ws:`fsh`},resourcesChanged:{body:S({changes:x(iS)}),ws:`rc`},llm:{body:hD,streamOut:gD,ws:`llm`},model:{body:HD,response:UD,ws:`mdl`},resource:{body:S({uri:Wx,want:x(Qx),run:A.optional(),sections:x(Gx).min(1).optional()}),response:eS,ws:`rs`},resourceSections:{body:S({uri:Wx,run:A.optional()}),response:x(rS),ws:`rsc`},content:{body:S({ref:Jx,offset:y().int().min(0),length:y().int().min(1),run:A.optional()}),response:S({chunk:v()}),ws:`ct`},upload:{body:S({upload:v(),chunk:v(),last:b(),mime:v()}),response:S({ref:Jx.optional()}),ws:`up`},setting:{body:S({run:A,setting:I}),response:S({value:O.optional()}),ws:`st`},stateGet:{body:S({owner:bR}),response:S({values:el,version:y().int()}),ws:`sg`},stateSet:{body:S({owner:bR,patch:el,clear:x(v()),version:y().int().optional()}),response:C([S({version:y().int()}),S({conflict:D(!0)})]),ws:`ss`},log:{body:SR,ws:`lg`},connectionUpdate:{body:IO,ws:`cu`},instanceConnect:{body:wO,ws:`ic`},shareFn:{body:vO,ws:`sh`},usableFns:{body:yO,response:S({fns:x(k)}),ws:`uf`},propose:{body:iA,response:cA,ws:`po`},decide:{body:vD,response:yD,ws:`de`},fleet:{body:S({}),response:x(VP),ws:`fl`},searchFns:{body:gF.extend({run:A.optional()}),response:TF,ws:`sf`},fnExamples:{body:dF,response:fF,ws:`fx`},examples:{body:uF,response:S({added:y().int().min(0),removed:y().int().min(0)}),ws:`xp`},models:{body:S({}),response:x(JP),ws:`mo`},grantPairing:{body:oA,response:sA,ws:`gp`},notifyAdmins:{body:ER,ws:`na`},notify:{body:S({run:A,notice:gI}),ws:`nf`},kindFns:{body:fI,response:pI,ws:`kf`},startRun:{body:mI,response:hI,ws:`sru`},notifyOwner:{body:S({fn:I,notice:gI}),ws:`nfo`},reportRefusal:{body:$F,ws:`rx`},mentionResources:{body:lI,response:uI,ws:`mr`},records:{body:Jj,response:Yj,ws:`rq`},record:{body:Zj,response:S({record:Kj.optional()}),ws:`rg`},recordTable:{body:Xj,response:Lk,ws:`rtb`},saveRecord:{body:Qj,response:Kj,ws:`rsv`},removeRecord:{body:eM,response:S({removed:b()}),ws:`rrm`},storeOpen:{body:S({}),response:S({bytes:y().int().min(0)}),ws:`sto`},storeRun:{body:HM,response:UM,ws:`stq`},storeBegin:{body:S({}),response:WM,ws:`stb`},storeCommit:{body:S({lease:zM}),ws:`stc`},storeRollback:{body:S({lease:zM}),ws:`str`},storeSnapshot:{body:S({}),response:S({snapshot:GM}),ws:`stn`},storeRestore:{body:S({snapshot:GM}),ws:`stx`},storeStatus:{body:EM,ws:`sts`},storeExport:{body:S({move:jM}),response:S({bytes:y().int().min(0),hash:v().regex(/^[0-9a-f]{64}$/)}),ws:`ste`},storeDownload:{body:S({move:jM,offset:y().int().min(0),length:y().int().min(1).max(4e6)}),response:S({chunk:v()}),ws:`std`},storeUpload:{body:S({move:jM,offset:y().int().min(0),chunk:v().max(6e6)}),ws:`stu`},storeUploadDone:{body:S({move:jM,bytes:y().int().min(0),hash:v().regex(/^[0-9a-f]{64}$/)}),ws:`stud`},storeMoveProgress:{body:S({move:jM,progress:FM}),ws:`stmp`}});X({endpoints:{...Z(_R).group({hello:{body:uR,response:dR,ws:`hi`},prove:{body:fR,response:hR,ws:`pr`},pairingInfo:{body:HP,ws:`pi`}}),...DR}}),X({endpoints:{paired:Y({body:S({pairing:pl}),ws:`pd`}),run:Y({body:yR,response:AE,ws:`run`}),control:Y({body:CR,response:wR,ws:`ctl`}),undo:Y({body:S({run:iE,fn:v(),kind:Pl,fnPayload:O.optional(),payload:O}),response:ME,ws:`un`}),handler:Y({body:S({call:dl,run:A,key:v(),handler:v(),args:O}),response:NE,ws:`hd`}),child:Y({body:S({parent:A,key:v(),run:A,update:kE.optional()}),ws:`ch`}),check:Y({body:S({kind:v(),payload:O}),response:S({problems:x(v()),description:LN.optional()}),ws:`ck`}),context:Y({body:xR.partial({session:!0}).extend({name:v(),args:T(v(),v())}),response:S({text:v()}),ws:`cx`}),roots:Y({response:x(Yx),ws:`ro`}),list:Y({body:S({uri:Wx,cursor:v().optional()}),response:Vl(Xx),ws:`ls`}),stat:Y({body:S({uri:Wx}),response:S({stat:Xx.optional()}),ws:`sa`}),read:Y({body:S({uri:Wx,want:x(Qx)}),response:eS,ws:`rd`}),sections:Y({body:S({sectioner:v(),uri:Wx,version:v()}),response:x(rS),ws:`sc`}),watch:Y({body:S({uris:x(Wx),on:b()}),ws:`wa`}),content:Y({body:S({ref:Jx,offset:y().int().min(0),length:y().int().min(1)}),response:S({chunk:v()}),ws:`ct`}),hook:Y({body:S({hook:v(),message:BN}),response:x(WN),ws:`hk`}),mentions:Y({body:xR.extend({provider:v(),query:v(),request:cI}),response:x(GN),ws:`mn`}),mentionHover:Y({body:xR.extend({provider:v(),target:O}),response:S({hover:KN.optional()}),ws:`mh`}),mentionText:Y({body:xR.extend({provider:v(),target:O}),response:S({text:v()}),ws:`mt`}),event:Y({body:lR,ws:`ev`}),action:Y({body:xR.extend({delivery:ul,action:v(),input:O,run:A.optional()}),response:S({result:O}),ws:`ac`}),form:Y({body:S({delivery:ul,run:A,value:O}),ws:`fm`}),restart:Y({body:S({reason:v()}),ws:`rt`}),stop:Y({body:S({reason:TR,timeout:Ml}),ws:`sp`}),configure:Y({body:mR.extend({previous:O.optional()}),ws:`cf`}),export:Y({body:S({timeout:Ml}),response:S({data:v()}),ws:`ex`}),validate:Y({body:rk,response:ik,ws:`vl`}),preview:Y({body:eA,response:oI,ws:`pv`}),estimate:Y({body:kF,response:AF,ws:`es`}),providerChat:Y({body:HO,streamOut:UO,ws:`pc`}),providerEmbed:Y({body:ZO,response:QO,ws:`pe`}),providerDecide:Y({body:qO,response:JO,ws:`pdc`}),providerModels:Y({body:GO,response:KO,ws:`pml`}),connectStart:Y({body:NO,response:S({url:Nb}),ws:`cs`}),connectFinish:Y({body:PO,response:FO,ws:`cn`}),disconnect:Y({body:MO.pick({id:!0,owner:!0,credentials:!0}),ws:`dc`}),flags:Y({body:eA,response:qk,ws:`fg`}),claims:Y({body:JM,response:YM,ws:`pcl`}),checkArgs:Y({body:tA,response:nA,ws:`cka`}),storeProbe:Y({body:S({to:_M}),response:S({problems:x(v())}),ws:`spb`}),storeMove:Y({body:S({move:jM,from:_M,to:_M}),response:S({tables:y().int().min(0),rows:y().int().min(0),bytes:y().int().min(0)}),ws:`smv`}),storeMoveEnd:Y({body:S({move:jM,outcome:E([`switched`,`aborted`]),from:_M,to:_M}),response:S({backups:x(S({id:kM,bytes:y().int().min(0)}))}),ws:`sme`}),storeDiscard:Y({body:w(`what`,[S({what:D(`store`)}),S({what:D(`backup`),backup:kM})]),ws:`sdc`})}});var OR=S({session:j,parts:x(eR).min(1),variants:JA,client:aE}),kR=XA.extend({status:cj,spent:P,tokens:y().int().min(0),startedAt:N,endedAt:N.optional(),time:Ml,messages:x(tR),approvals:x(BI)}),AR=ej.omit({variants:!0}).extend({turn:cl,session:j,message:ll,status:cj,variants:x(kR)}),jR=S({turn:cl,variant:GA,adopt:b().optional()}),MR=v().regex(Nl).max(64).brand(),NR=S({uri:v(),system:F.optional(),instance:L.optional()}),PR=S({systems:x(F).optional(),fns:x(FI).optional(),types:x(Jl).optional(),context:x(Jl).optional(),resources:x(NR).optional()}),FR=S({include:PR,exclude:PR}),IR=E([`each`,`static`]),LR=S({id:kl,slug:MR,name:v().min(1),instructions:v(),rules:FR,toolMode:IR,user:M,actor:M,secretDigest:v(),grantees:x(F),origins:x(v()),enabled:b(),createdBy:M,createdAt:N,updatedAt:N}),RR=LR.pick({slug:!0,name:!0,instructions:!0,rules:!0,toolMode:!0,user:!0,grantees:!0,origins:!0,enabled:!0});S({mcp:kl,label:v().min(1),exp:y().int()});var zR=S({mcp:kl,label:v().min(1),ttl:y().int().min(1e3).optional()}),BR=S({fns:x(I),types:x(I),closure:x(I),context:x(I),resources:x(NR),reach:x(I),warnings:x(v())}),VR=S({mcp:kl,session:v(),label:v(),client:S({name:v(),version:v()}).optional(),since:N,lastCallAt:N.optional(),calls:y().int().min(0)}),HR=LR.omit({secretDigest:!0}).extend({url:v(),sessions:y().int().min(0),callsToday:y().int().min(0)}),UR=E([`added`,`changed`,`removed`]),WR=S({id:v().min(1),system:F,section:BF,name:v().min(1),number:y().int().min(1),change:UR,decl:O,hash:v().min(1),declaredBy:yP.optional(),instance:L.optional(),savedBy:M.optional(),savedAt:N}),GR=Hl.extend({system:F,section:BF,name:v().min(1)}),KR=Vl(WR);rS.extend({uri:Wx,version:v(),hash:v()});var qR=(...e)=>e.join(`\0`),JR=`bearerAuth`,YR={security:{[JR]:{type:`http`,scheme:`bearer`,bearerFormat:`JWT`}}};function XR(e){let t=e?.name??JR,n=e?.doc??YR;return eT(t,{provides:Jw(),requires:e?.requires??[],doc:n})}var ZR=v().regex(/^[a-z]+:.+$/),QR=S({fnKind:Pl.optional(),mode:lN.optional(),effects:x(pN).optional(),reads:x(I).optional(),writes:x(I).optional(),visibility:zl.optional(),on:b(),stage:yk.optional(),pending:b().optional(),examples:y().int().min(0).optional()}),$R=S({id:ZR,kind:gj,name:v().min(1),about:v(),system:F.optional(),external:b(),collapsed:y().int().min(0).optional(),facts:QR}),ez=S({from:ZR,to:ZR,kind:vj,label:v().min(1),weight:y().min(0).max(1).optional()}),tz=S({node:ZR,kind:gj,count:y().int().min(1)}),nz=Oj.pick({text:!0,filters:!0}).extend({systems:x(F).min(1).optional(),external:b().optional(),focus:S({node:ZR,hops:y().int().min(1).max(4).optional()}).optional(),collapse:x(F).min(1).optional(),limit:y().int().min(1).max(1e3).optional()}),rz=S({nodes:x($R),edges:x(ez),more:x(tz),total:S({nodes:y().int().min(0),edges:y().int().min(0)})}),iz=`hub/visuals`,az=S({columns:x(S({name:v().min(1),kind:xk,role:Sk,numeric:b(),temporal:b(),day:b(),categorical:b(),key:b(),opaque:b(),distinct:y().int().min(0),nulls:y().min(0).max(1),nonNegative:b(),min:C([y(),v()]).optional(),max:C([y(),v()]).optional(),bound:S({min:y(),max:y()}).optional(),members:x(v()).optional()})),rows:y().int().min(0),whole:b()}),oz=new Set([`integer`,`number`]),sz=new Set([`date`,`datetime`]),cz=new Set([`text`,`boolean`]),lz=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function uz(e){return oz.has(e)?`measure`:sz.has(e)||cz.has(e)?`group`:`attribute`}function dz(e,t,n){return e===void 0||typeof e==typeof t&&(n===`min`?t<e:t>e)?t:e}function fz(e,t){return{columns:e.columns.map((n,r)=>{let i=new Set,a=0,o=0,s=0,c=!0,l,u;for(let t of e.rows){let e=t[r];e==null?a+=1:(s+=1,i.add(typeof e==`object`?JSON.stringify(e):String(e)),typeof e==`string`&&lz.test(e)&&(o+=1),(typeof e==`number`||typeof e==`string`)&&(l=dz(l,e,`min`),u=dz(u,e,`max`)),(typeof e!=`number`||e<0)&&(c=!1))}let d=n.kind,f=n.key===!0,p=d===`uuid`||s>0&&o===s||n.ref!==void 0||d===`binary`;return{name:n.name,kind:d,role:n.role??uz(d),numeric:oz.has(d),temporal:sz.has(d),day:d===`date`,categorical:cz.has(d),key:f,opaque:p,distinct:i.size,nulls:e.rows.length===0?0:a/e.rows.length,nonNegative:c&&s>0,...l===void 0?{}:{min:l},...u===void 0?{}:{max:u},...t?.(n)??{}}}),rows:e.rows.length,whole:e.offset===0&&!e.truncated}}var pz=T(k,x(v().min(1)).min(1));S({visual:k,coverage:y().int().min(0),priority:y(),bind:pz,styles:x(k).min(1),because:x(v())});var mz={floor:0,structural:10,encoded:20,"time-encoded":30},hz={"temporal-key":15,"low-cardinality":10,"enum-key":8,"high-null":-10,"many-categories":-10},gz=.5;function _z(e){return e.columns.filter(e=>!e.opaque)}function vz(e,t){return e.accepts.includes(t.kind)&&(e.role===void 0||e.role===t.role)}function yz(e,t,n){return!e.required&&e.role===`group`&&n>1&&t.distinct>=n}function bz(e,t,n){let r={},i=new Set;for(let a of e.channels){let e=t.filter(e=>!i.has(e.name)&&vz(a,e)&&!yz(a,e,n)).map(e=>e.name),o=a.many?e:e.slice(0,1);if(o.length<(a.many?a.min??1:1)){if(a.required)return`No column fits ${a.label} (${a.accepts.join(`, `)}).`;continue}let[s,...c]=o;if(s!==void 0){r[a.name]=[s,...c];for(let e of o)i.add(e)}}return r}function xz(e,t,n){return(e[t]??[]).flatMap(e=>n.columns.filter(t=>t.name===e))}function Sz(e,t,n,r,i){switch(e.rule){case`distinct`:{let r=xz(t,e.channel,n);return r.some(t=>t.distinct>e.max)?`${e.channel} has more than ${String(e.max)} values.`:e.min!==void 0&&r.some(t=>t.distinct<(e.min??0))?`${e.channel} has fewer than ${String(e.min)} values.`:void 0}case`non-negative`:return xz(t,e.channel,n).every(e=>e.nonNegative)?void 0:`${e.channel} has values below 0.`;case`bounded`:return xz(t,e.channel,n).every(e=>e.bound!==void 0)||t.max!==void 0?void 0:`${e.channel} has no known range.`;case`distinct-columns`:{let n=e.channels.flatMap(e=>t[e]??[]);return new Set(n).size===n.length?void 0:`${e.channels.join(` and `)} need different columns.`}case`links`:{if(r===void 0||i===void 0)return;let n=e=>i.findIndex(n=>n.name===t[e]?.[0]),a=n(e.from),o=n(e.to);if(a<0||o<0)return`${e.to} must name values of ${e.from}.`;let s=new Set(r.map(e=>JSON.stringify(e[a]??null)));return r.every(e=>e[o]===null||s.has(JSON.stringify(e[o]??null)))?void 0:`${e.to} names values that are not ${e.from} values.`}}}function Cz(e,t,n){let r=Object.values(t).flat().flatMap(e=>n.columns.filter(t=>t.name===e)),i=r.filter(e=>e.role===`group`),a={"temporal-key":i.some(e=>e.temporal),"low-cardinality":i.length>0&&i.every(e=>e.distinct<=8),"enum-key":i.some(e=>e.members!==void 0),"high-null":r.some(e=>e.nulls>gz),"many-categories":i.some(e=>e.distinct>5)},o=e.priority.terms.filter(e=>a[e]);return{priority:mz[e.priority.band]+o.reduce((e,t)=>e+hz[t],0),because:o.map(e=>`${e} (${String(hz[e])})`)}}function wz(e,t,n,r){let i=[];e.whole===!0&&!n.whole&&i.push(`style ${e.name} only draws a whole result.`);for(let n of e.needs??[])t[n]===void 0&&i.push(`style ${e.name} needs ${n} bound.`);for(let[n,r]of Object.entries(e.columns??{})){let a=t[n]?.length??0;r.min!==void 0&&a<r.min&&i.push(`style ${e.name} needs at least ${String(r.min)} ${n} columns.`),r.max!==void 0&&a>r.max&&i.push(r.max===0?`style ${e.name} draws no ${n}.`:`style ${e.name} draws at most ${String(r.max)} ${n} columns.`)}for(let a of e.rules??[]){let o=Sz(a,t,n,r?.rows,r?.columns);o!==void 0&&i.push(`style ${e.name}: ${o}`)}return i}function Tz(e,t,n,r){return e.styles.filter(e=>wz(e,t,n,r).length===0).map(e=>e.name)}function Ez(e,t,n,r){let i=[];for(let r of e.channels){let e=t[r.name]??[];if(e.length===0)r.required&&i.push(`${r.label} is not bound.`);else{!r.many&&e.length>1&&i.push(`${r.label} takes one column.`),r.many&&e.length<(r.min??1)&&i.push(`${r.label} needs at least ${String(r.min??1)} columns.`);for(let t of e){let e=n.columns.find(e=>e.name===t);e===void 0?i.push(`${r.label}: there is no column ${t}.`):(e.opaque&&i.push(`${r.label}: ${t} holds nothing a person reads.`),r.accepts.includes(e.kind)||i.push(`${r.label}: ${t} is ${e.kind}, not ${r.accepts.join(` or `)}.`))}}}n.rows<e.rows.min&&i.push(`Needs at least ${String(e.rows.min)} rows.`),e.rows.max!==void 0&&n.rows>e.rows.max&&e.size===void 0&&i.push(`Draws at most ${String(e.rows.max)} rows.`),e.whole&&!n.whole&&i.push(`Only draws a whole result, and this is one page of it.`);for(let a of e.rules){let e=Sz(a,t,n,r?.rows,r?.columns);e!==void 0&&i.push(e)}return i}function Dz(e,t,n){let r=_z(t);return e.flatMap((e,i)=>{let a=bz(e.shape,r.length>0?r:t.columns,t.rows);if(typeof a==`string`||Ez(e.shape,a,t,n).length>0)return[];let[o,...s]=Tz(e.shape,a,t,n);if(o===void 0)return[];let{priority:c,because:l}=Cz(e.shape,a,t),u=new Set(Object.values(a).flat().filter(e=>r.some(t=>t.name===e))).size;return[{rank:{visual:e.name,coverage:u,priority:c,bind:a,styles:[o,...s],because:[`covers ${String(u)}`,...l]},index:i}]}).sort((e,t)=>t.rank.coverage-e.rank.coverage||t.rank.priority-e.rank.priority||e.index-t.index).map(e=>e.rank)}var Oz=[`integer`,`number`];function kz(e,t,n,r={}){return{name:e,label:t,accepts:[...n],required:r.required??!0,many:r.many??!1,...r.min===void 0?{}:{min:r.min},...r.role===void 0?{}:{role:r.role}}}var Az=[`table`,`value`];E(Az);var jz={table:{label:`Table`,icon:`table`,description:`Every readable column and row, sortable and paged; cards on a phone.`,shape:Ak.parse({channels:[kz(`columns`,`Columns`,bk,{required:!1,many:!0})],rows:{min:0},whole:!1,size:`window`,pageSize:10,styles:[{name:`table`,label:`Table`},{name:`compact`,label:`Compact`},{name:`cards`,label:`Cards`}],priority:{band:`floor`,terms:[]}})},value:{label:`Value`,icon:`hash`,description:`One to four rows of numbers as cards, each titled by a text column or named by its column.`,shape:Ak.parse({channels:[kz(`value`,`Values`,Oz,{many:!0,role:`measure`}),kz(`title`,`Title`,[`text`],{required:!1})],rows:{min:1,max:4},whole:!0,styles:[{name:`cards`,label:`Cards`},{name:`single`,label:`Single`}],priority:{band:`encoded`,terms:[]}})}};Az.map(e=>({name:e,shape:jz[e].shape}));var Mz=S({from:k,to:k}),Nz=S({offset:k,limit:k}),Pz=S({visual:k,style:k,label:v().min(1).optional(),bind:pz}),Fz=E([`open`,`refresh`,`status`]),Iz=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:Fz.optional()}),Lz=S({fn:I,label:v().min(1),bind:T(k,v().min(1))}),Rz=S({offset:k,limit:k,window:y().int().min(1),more:b()}),zz=S({fn:I,label:v().min(1),mode:lN,confirm:b(),bind:T(k,v().min(1)),form:gT.optional(),then:Fz}),Bz=S({title:v().min(1),table:Lk,facts:az,source:S({fn:I,run:A,args:T(v(),O)}),visuals:x(Pz).min(1),problems:x(v()),range:Mz.optional(),paging:Rz.optional(),actions:x(zz),drill:Lz.optional(),readOnly:b(),live:S({every:y().int().min(1)}).optional(),summary:v().min(1)}),Vz=S({name:k,description:v().min(1),preview:Bz,replaces:v().min(1).optional()}),Hz=S({types:x(I).max(20),narrow:x(Iz).optional()}).refine(e=>e.types.length>0||(e.narrow?.length??0)>0,{message:`name a row type or an action to offer`}),Uz=S({fn:I,args:T(v(),O)}),Wz=Uz.extend({on:L.optional()}),Gz=S({fn:I,args:v(),offset:k,limit:k,format:D(`csv`)});S({summary:v(),columns:x(v()),rows:x(x(O)),more:y().int().min(0),partial:v().optional()});function Kz(e,t){return e!==`read`||t===!0}function qz(e,t){return t?`open`:e===`read`?`status`:`refresh`}function Jz(e){return wT(e.split(/[/.]/).pop()??e)||e}var Q=MP(),$=XR(),Yz=eT(`adminOnly`,{requires:[$]}),Xz=S({access:v(),refresh:v(),expiresIn:Ml,user:MI}),Zz=bI.pick({name:!0,version:!0}).extend({needsAdmin:b(),sso:x(QI)}),Qz=S({kind:E([`fn`,`context`]),name:I,description:v(),score:VN,why:v().optional()}),$z=CA(v().min(1)),eB=S({approvals:x(BI),handlers:x(sj)}),tB=BP.omit({publicKey:!0}),nB=S({fns:y().int().min(0),context:y().int().min(0),types:y().int().min(0),parts:y().int().min(0),instances:y().int().min(0),pending:y().int().min(0),refusals:y().int().min(0)}),rB=gP.omit({keyFingerprint:!0,publicKey:!0,config:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0,instances:!0}).extend(BP.pick({keyFingerprint:!0,config:!0,installed:!0,host:!0,pairedAt:!0,pairedBy:!0,lastSeenAt:!0,address:!0}).shape).extend({counts:nB,instanceMode:hP,needsConfig:b(),configType:O.optional(),configSecrets:uA.optional(),store:uM.optional(),instances:x(tB)}),iB=w(`type`,[S({type:D(`message`),message:tR}),S({type:D(`token`),message:ll,text:v()}),S({type:D(`reasoning`),message:ll,text:v()}),S({type:D(`cite`),message:ll,cite:VA}),S({type:D(`controls`),controls:iR}),S({type:D(`run`),run:A,fn:I,update:kE}),S({type:D(`state`),system:F,fields:x(ij)}),S({type:D(`delivery`),delivery:oj}),S({type:D(`handler`),call:sj}),S({type:D(`approval`),approval:BI}),S({type:D(`budget`),run:A,budget:AA,reason:v()}),S({type:D(`presence`),presence:aR}),S({type:D(`session`),session:HL}),S({type:D(`compare`),turn:cl})]),aB=w(`type`,[S({type:D(`notification`),notification:sF}),S({type:D(`approval`),approval:BI}),S({type:D(`system`),system:F,status:sP}),S({type:D(`pairing`),pairing:_P}),S({type:D(`capabilities`)}),S({type:D(`session`),session:HL}),S({type:D(`session-deleted`),session:j}),S({type:D(`fn`),fn:I,system:F,stats:vP}),S({type:D(`resource`),uri:Wx,forms:x(nS)}),S({type:D(`context`),name:I}),S({type:D(`identity`),identity:bI})]),oB=nT(X({endpoints:Z(Q).group({setup:{method:`GET`,response:Zz,ws:`setup`},createAdmin:{body:S({email:Ns(),name:v().min(1),password:v().min(8),setup:v().trim().min(1)}),response:Xz,ws:`createAdmin`},signIn:{body:S({email:Ns(),password:v()}),response:Xz,errors:{401:S({reason:v()})},ws:`signIn`},refresh:{body:S({refresh:v()}),response:Xz,ws:`refresh`},redeemSso:{body:S({code:v().min(1)}),cookies:S({[dL]:v().optional()}),response:Xz,ws:`redeemSso`,httpOnly:!0}})}),X({endpoints:Z(Q,$).group({signOut:{ws:`signOut`},me:{method:`GET`,response:MI,ws:`me`},account:{method:`GET`,response:oL,ws:`account`}})})),sB=Hl.extend({query:Oj.optional()}),cB=Hl.extend({session:j}),lB=Hl.extend({unread:b().optional(),query:Oj.optional()}),uB=VL.pick({title:!0,systems:!0,agent:!0,archived:!0}).partial().extend({priority:Rl.optional(),notify:LL.optional(),model:VL.shape.model.unwrap().nullable().optional(),mode:VL.shape.mode.unwrap().nullable().optional(),contextor:VL.shape.contextor.unwrap().nullable().optional(),fnMode:VL.shape.fnMode.unwrap().nullable().optional(),instructions:VL.shape.instructions.unwrap().nullable().optional(),citations:VL.shape.citations}),dB=X({endpoints:Z(Q,$).group({capabilities:{body:S({session:j.optional()}),response:oR,ws:`capabilities`},types:{body:S({names:x(I).min(1)}),response:SP,ws:`types`},sessions:{body:sB,response:Vl(HL),ws:`sessions`},session:{body:S({session:j}),response:VL,ws:`session`},createSession:{body:VL.pick({agent:!0,systems:!0,title:!0}).partial(),response:VL,ws:`createSession`},updateSession:{body:uB.extend({session:j}),response:VL,ws:`updateSession`},deleteSession:{body:S({session:j}),response:S({deleted:b()}),ws:`deleteSession`},limits:{body:S({session:j}),response:MA,ws:`limits`},messages:{body:cB,response:Vl(tR),ws:`messages`},send:{body:S({session:j,parts:x(eR).min(1),replyTo:ll.optional(),replyAll:b().optional(),client:aE}),response:S({turn:cl,message:tR}),ws:`send`},compare:{body:OR,response:S({turn:cl,message:tR}),ws:`compare`},compareView:{body:S({turn:cl}),response:AR,ws:`compareView`},chooseVariant:{body:jR,response:AR,ws:`chooseVariant`},invoke:{body:S({session:j,fn:I,args:O,on:L.optional(),client:aE}),response:S({turn:cl,run:A}),ws:`invoke`},control:{body:S({session:j,action:nR,runs:x(A).min(1).optional()}),response:iR,ws:`control`},controls:{body:S({session:j}),response:iR,ws:`controls`},presence:{body:aR.omit({user:!0,lastActiveAt:!0}),ws:`presence`}})}),fB=X({endpoints:Z(Q,$).group({background:{body:S({run:A}),response:S({accepted:b()}),ws:`background`},undoTurn:{body:S({turn:cl}),response:mj,ws:`undoTurn`},continueTurn:{body:S({turn:cl}),response:S({turn:cl,run:A}),ws:`continueTurn`},tree:{body:S({turn:cl}),response:pj,ws:`tree`},run:{body:S({run:A}),response:nj,ws:`run`},llmCall:{body:S({id:fl}),response:fj,ws:`llmCall`},waiting:{body:S({session:j}),response:eB,ws:`waiting`},approve:{body:S({approval:gl,approve:b(),remember:zI,reason:v().optional(),answer:O.optional()}),response:BI,ws:`approve`},answer:{body:S({call:dl,value:O}),ws:`answer`},act:{body:S({session:j,system:F,action:v(),input:O,run:A.optional(),client:aE}),response:S({delivery:ul}),ws:`act`},submit:{body:S({run:A,value:O}),response:S({delivery:ul}),ws:`submit`},state:{body:S({run:A}),response:S({system:F,fields:x(ij)}),ws:`state`}})}),pB=X({endpoints:Z(Q,$).group({suggest:{body:S({session:j,text:v(),limit:y().int().min(1).max(20).optional()}),response:x(Qz),ws:`suggest`},mentions:{body:S({session:j,provider:I,query:v()}),response:x(GN),ws:`mentions`},mentionHover:{body:S({session:j,provider:I,target:O}),response:S({hover:KN.optional()}),ws:`mentionHover`},resource:{body:S({uri:Wx,want:x(Qx)}),response:eS,ws:`resource`}})}),mB=X({endpoints:Z(Q,$).group({notifications:{body:lB,response:Vl(sF),ws:`notifications`},readNotifications:{body:S({ids:x(sF.shape.id)}),ws:`readNotifications`},pushKey:{method:`GET`,response:S({publicKey:v()}),ws:`pushKey`},subscribePush:{body:cF.pick({endpoint:!0,keys:!0,device:!0}),response:cF.pick({id:!0}),ws:`subscribePush`}})}),hB=X({endpoints:Z(Q,$).group({upload:{body:S({name:v(),mime:v(),size:y().int().min(0)}),response:S({url:v(),upload:v()}),ws:`upload`},uploaded:{body:S({upload:v()}),response:Jx,ws:`uploaded`},transcribe:{body:S({audio:Jx}),response:S({text:v()}),ws:`transcribe`}})}),gB=S({section:E([`fns`,`context`]),name:I,on:b()}),_B=S({system:F,section:BF.exclude([`fns`,`context`]),name:v().min(1),on:b()}),vB=X({endpoints:Z(Q,$,Yz).group({systems:{body:S({query:Oj.optional()}),response:x(rB),ws:`systems`},system:{body:S({system:F}),response:rB,ws:`system`},pairings:{body:S({status:_P.shape.status.optional()}),response:x(_P),ws:`pairings`},approvePairing:{body:S({pairing:pl,approve:b(),instance:L.optional(),config:O.optional(),autoPair:rP.optional(),store:gM.optional()}),response:S({system:F.optional()}),ws:`approvePairing`},createPairingToken:{body:S({name:F.optional(),expiresIn:Ml,autoPair:rP.optional()}),response:S({token:v(),expiresAt:N}),ws:`createPairingToken`},configureSystem:{body:S({system:F,config:O,instance:L.optional()}),response:C([S({version:y().int()}),S({problems:x(v())})]),ws:`configureSystem`},enableSystem:{body:S({system:F,functions:b().optional(),renderers:b().optional(),context:b().optional()}),response:S({enabled:fP}),ws:`enableSystem`},switchItem:{body:gB,response:S({on:b()}),ws:`switchItem`},switchPart:{body:_B,response:S({on:b()}),ws:`switchPart`},removeSystem:{body:S({system:F,keepStore:b().optional()}),response:S({fnsUnavailable:y().int()}),ws:`removeSystem`},installSystem:{body:S({source:cP,config:O.optional(),autoStart:b().optional(),store:gM.optional()}),response:S({name:F}),ws:`installSystem`},systemStore:{body:S({system:F,instance:L.optional()}),response:RM,ws:`systemStore`},systemStoreMove:{body:S({system:F,instance:L.optional(),to:gM,runs:NM.optional()}),response:IM,ws:`systemStoreMove`},systemStoreMoveState:{body:S({system:F,instance:L.optional()}),response:S({move:IM.optional()}),ws:`systemStoreMoveState`},systemStoreMoveAnswer:{body:S({system:F,instance:L.optional(),answer:PM}),response:IM,ws:`systemStoreMoveAnswer`},systemStoreBackups:{body:S({system:F,instance:L.optional()}),response:x(AM),ws:`systemStoreBackups`},systemStoreBackupDelete:{body:S({system:F,instance:L.optional(),backup:kM}),response:S({deleted:D(!0),note:v().optional()}),ws:`systemStoreBackupDelete`},startSystem:{body:S({system:F,instance:L.optional()}),response:S({ok:b()}),ws:`startSystem`},stopSystem:{body:S({system:F,instance:L.optional()}),response:S({ok:b()}),ws:`stopSystem`},restartSystem:{body:S({system:F,instance:L.optional(),reason:v().min(1).max(200)}),response:S({ok:b()}),ws:`restartSystem`},upgradeSystem:{body:S({system:F,version:v().optional()}),response:S({from:v(),to:v()}),ws:`upgradeSystem`},reimport:{body:S({system:F}),response:FN,ws:`reimport`}})}),yB=X({endpoints:Z(Q,$,Yz).group({configureProvider:{body:$z,response:S({models:y().int()}),ws:`configureProvider`},providers:{body:S({}),response:x(S({id:Tl,provider:TA,models:y().int()})),ws:`providers`},setModelCategory:{body:EA.partial({id:!0}),response:EA.pick({id:!0}),ws:`setModelCategory`},setBudget:{body:AA.omit({setBy:!0}).partial({id:!0}),response:AA.pick({id:!0}),ws:`setBudget`},setPriority:{body:jA.omit({setBy:!0}).partial({id:!0}),response:jA.pick({id:!0}),ws:`setPriority`},setPolicy:{body:RI.omit({createdBy:!0,createdAt:!0}).partial({id:!0}),response:RI.pick({id:!0}),ws:`setPolicy`},setActorSetting:{body:S({setting:I,actor:M,value:O}),response:S({ok:b()}),ws:`setActorSetting`},addUser:{body:S({email:Ns(),name:v(),role:kI,groups:x(M).optional()}),response:S({id:M}),ws:`addUser`},addGroup:{body:S({name:v(),about:v(),members:x(M).optional()}),response:S({id:M}),ws:`addGroup`},updateUser:{body:cL,response:S({id:M}),ws:`updateUser`},setMembership:{body:lL,response:S({ok:b()}),ws:`setMembership`},setSignInPolicy:{body:GI,response:GI,ws:`setSignInPolicy`},setSignInLimits:{body:JI,response:JI,ws:`setSignInLimits`},setProxyTrust:{body:XI,response:XI,ws:`setProxyTrust`}})}),bB=X({endpoints:Z(Q,$,Yz).group({systemFns:{body:S({system:F}),response:x(bP),ws:`systemFns`},systemParts:{body:AP,response:jP,ws:`systemParts`},systemLogs:{body:S({system:F,limit:y().int().min(1).max(2e3).optional()}),response:x(WP),ws:`systemLogs`},models:{body:S({provider:Tl.optional()}),response:x(qP),ws:`models`},modelCategories:{body:S({}),response:x(EA),ws:`modelCategories`},budgets:{body:S({}),response:x(YP),ws:`budgets`},priorityRules:{body:S({}),response:x(jA),ws:`priorityRules`},resolveLimits:{body:S({user:M,session:j.optional()}),response:MA,ws:`resolveLimits`},policies:{body:S({}),response:x(RI),ws:`policies`},actors:{body:S({kind:Bl.optional()}),response:x(jI),ws:`actors`},actorSettings:{body:S({}),response:S({declared:x(XP),values:x(NI)}),ws:`actorSettings`},runs:{body:Hl.extend({query:Oj.optional()}),response:Vl(nj),ws:`runs`},llmCalls:{body:Hl.extend({query:Oj.optional()}),response:Vl(ZP),ws:`llmCalls`},resources:{body:Hl.extend({query:Oj.optional()}),response:Vl($P),ws:`resources`},removeRule:{body:QP,response:S({ok:b()}),ws:`removeRule`},indexStatus:{body:S({}),response:GP,ws:`indexStatus`}}),events:{systemLog:{params:S({system:F}),data:WP,guard:[$,Yz],ws:`on.systemLog`}}}),xB=eT(`ownEvents`,{requires:[$]}),SB=eT(`sessionWatch`,{requires:[$]}),CB=S({user:M}),wB=X({endpoints:{},events:{session:{params:S({session:j}),data:iB,guard:[$,SB],ws:`on.session`},user:{params:CB,data:aB,guard:[$,xB],ws:`on.user`}}}),TB=Vl($P).extend({facets:x(qE)}),EB=S({record:$P,forms:x(IE),offers:x(LE)}),DB=X({endpoints:Z(Q,$).group({browseResources:{body:JE.extend({query:Oj.optional()}),response:TB,ws:`browseResources`},resourceForms:{body:S({uri:Wx}),response:EB,ws:`resourceForms`},readResource:{body:$E,response:eD,ws:`readResource`},convertResource:{body:S({uri:Wx,kind:nS}),response:IE,ws:`convertResource`},downloadResource:{body:S({uri:Wx,form:nS.optional()}),response:S({url:v(),mime:v(),size:y().int().min(0)}),ws:`downloadResource`},importResource:{body:tD,response:$P,ws:`importResource`},renameResource:{body:S({uri:Wx,name:v().min(1)}),response:$P,ws:`renameResource`},deleteResource:{body:S({uri:Wx}),response:S({deleted:b(),referencedBy:y().int().min(0)}),ws:`deleteResource`},contextFromResource:{body:jS,response:MS,ws:`contextFromResource`}})}),OB=Hl.extend({query:Oj.optional()}),kB=S({record:wP,links:x(ES),backlinks:x(ES),text:v().optional()}),AB=X({endpoints:Z(Q,$).group({contexts:{body:OB,response:Vl(SF),ws:`contexts`},contextItem:{body:S({name:I}),response:kB,ws:`contextItem`},remember:{body:OS,response:S({name:I}),ws:`remember`},updateMemory:{body:AS,response:S({name:I}),ws:`updateMemory`},forget:{body:S({name:I}),response:S({ok:b()}),ws:`forget`},linkContext:{body:S({from:I,to:SS,relation:xS,weight:y().min(0).max(1)}),response:ES,ws:`linkContext`},unlinkContext:{body:ES.pick({from:!0,toKey:!0,relation:!0}),response:S({ok:b()}),ws:`unlinkContext`}})}),jB=nT(X({endpoints:Z(Q,$).group({contextMetadata:{body:S({name:I}),response:uC,ws:`contextMetadata`},setContextStatus:{body:QS,response:$S,ws:`setContextStatus`}})}),X({endpoints:Z(Q,$,Yz).group({contextReview:{body:nC,response:iC,ws:`contextReview`},mergeContext:{body:aC,response:oC,ws:`mergeContext`},notDuplicate:{body:sC,response:S({ok:b()}),ws:`notDuplicate`},reextractContext:{body:cC,response:lC,ws:`reextractContext`},newContextStatus:{body:S({}),response:qS,ws:`newContextStatus`},setNewContextStatus:{body:S({value:KS}),response:qS,ws:`setNewContextStatus`}})})),MB=X({endpoints:Z(Q,$).group({contextPlans:{body:MC,response:NC,ws:`contextPlans`},contextPlan:{body:wC,response:TC,ws:`contextPlan`},answerPlan:{body:OC,response:kC,ws:`answerPlan`}})}),NB=nT(X({endpoints:Z(Q,$).group({modelLimits:{body:S({model:v().optional()}),response:x(xx),ws:`modelLimits`},previewSelection:{body:S({session:j,text:v()}),response:Ex,ws:`previewSelection`}})}),X({endpoints:Z(Q,$,Yz).group({setModelLimits:{body:S({model:v().min(1),limits:_x}),response:xx,ws:`setModelLimits`},previewPrompt:{body:Dx,response:Ox,ws:`previewPrompt`}})})),PB=X({endpoints:Z(Q,$,Yz).group({modelRoles:{body:S({}),response:x($D),ws:`modelRoles`},setModelRole:{body:ZD,response:$D,ws:`setModelRole`},clearModelRole:{body:S({role:WD}),response:$D,ws:`clearModelRole`}})}),FB=Hl.extend({run:A.optional(),query:Oj.optional()}),IB=X({endpoints:Z(Q,$,Yz).group({modelCalls:{body:FB,response:Vl(VD),ws:`modelCalls`},modelCall:{body:S({id:Ol}),response:VD,ws:`modelCall`},fnMetrics:{body:lO,response:x(cO),ws:`fnMetrics`},fnMetricsDays:{body:S({fn:I,days:y().int().min(1).max(365).optional()}),response:x(sO),ws:`fnMetricsDays`}})}),LB=X({endpoints:Z(Q,$,Yz).group({mcps:{body:S({}),response:x(HR),ws:`mcps`},mcp:{body:S({mcp:kl}),response:HR,ws:`mcp`},createMcp:{body:RR,response:S({mcp:HR,secret:v()}),ws:`createMcp`},updateMcp:{body:RR.partial().extend({mcp:kl}),response:HR,ws:`updateMcp`},rotateMcpSecret:{body:S({mcp:kl}),response:S({secret:v()}),ws:`rotateMcpSecret`},deleteMcp:{body:S({mcp:kl}),response:S({ok:b()}),ws:`deleteMcp`},previewMcp:{body:S({rules:FR}),response:BR,ws:`previewMcp`},mcpSessions:{body:S({mcp:kl}),response:x(VR),ws:`mcpSessions`}})}),RB=X({endpoints:Z(Q,$,Yz).group({pairing:{body:S({pairing:pl}),response:_P,ws:`pairing`},instances:{body:S({system:F}),response:x(tB),ws:`instances`},installPackage:{body:S({zip:Jx,instance:L.optional(),config:O.optional(),data:Jx.optional(),autoStart:b().optional(),store:gM.optional()}),response:ql,ws:`installPackage`},removeInstance:{body:ql.extend({keepStore:b().optional()}),response:S({ok:b()}),ws:`removeInstance`},addInstance:{body:UP,response:ql,ws:`addInstance`},exportSystemData:{body:ql.extend({withSecrets:b().optional()}),response:Jx.extend({url:v()}),ws:`exportSystemData`}})}),zB=nT(X({endpoints:Z(Q,$).group({query:{body:Hj,response:Uj,ws:`query`},listValues:{body:Vj,response:x(Bj),ws:`listValues`}})}),X({endpoints:Z(Q,$,Yz).group({fns:{body:Oj,response:Vl(bP),ws:`fns`}})})),BB=X({endpoints:Z(Q,$,Yz).group({suggestDecision:{body:S({}),response:kL,ws:`suggestDecision`},setSuggestDecision:{body:wL,response:kL,ws:`setSuggestDecision`},searchDecisions:{body:S({}),response:FL,ws:`searchDecisions`},setSearchDecision:{body:IL,response:FL,ws:`setSearchDecision`},previewSuggestions:{body:S({session:j,text:v().min(1)}),response:xL,ws:`previewSuggestions`}})}),VB=X({endpoints:Z(Q,$,Yz).group({imageEmbedding:{body:S({}),response:DI,ws:`imageEmbedding`},setImageEmbedding:{body:CI,response:DI,ws:`setImageEmbedding`}})}),HB=nT(X({endpoints:Z(Q,$).group({outsideImages:{body:S({}),response:Lb,ws:`outsideImages`}})}),X({endpoints:Z(Q,$,Yz).group({setOutsideImages:{body:S({value:Ib}),response:Lb,ws:`setOutsideImages`}})})),UB=nT(X({endpoints:Z(Q,$).group({https:{body:S({}),response:Vb,ws:`https`}})}),X({endpoints:Z(Q,$,Yz).group({setHttps:{body:S({on:b()}),response:Vb,ws:`setHttps`}})})),WB=X({endpoints:Z(Q,$,Yz).group({autoPairs:{body:S({system:F.optional()}),response:x(oP),ws:`autoPairs`},revokeAutoPair:{body:S({id:Al}),response:S({ok:b()}),ws:`revokeAutoPair`}})}),GB=X({endpoints:Z(Q,$).group({accessInfo:{body:S({}),response:gO,ws:`accessInfo`},access:{body:S({targets:x(pO).min(1).max(200)}),response:x(hO),ws:`access`},setAccess:{body:S({target:pO,sharing:fO.omit({owner:!0})}),response:hO,ws:`setAccess`}})}),KB=X({endpoints:Z(Q,$).group({connectPages:{body:S({}),response:x(jO),ws:`connectPages`},connect:{body:S({system:F,instance:L.optional(),key:TO.optional(),form:O.optional()}),response:C([S({url:Nb}),S({connection:AO})]),ws:`connect`,httpOnly:!0},updateConnection:{body:LO,response:AO,ws:`updateConnection`},disconnect:{body:S({connection:jl}),response:S({ok:b()}),ws:`disconnect`}})}),qB=X({endpoints:Z(Q,$).group({pick:{body:bO,response:x(xO),ws:`pick`}})}),JB=X({endpoints:Z(Q,$).group({approvals:{body:S({runs:x(A).min(1).max(200)}),response:x(BI),ws:`approvals`}})}),YB=X({endpoints:Z(Q,$).group({contributions:{body:S({registry:I}),response:x(Nk),ws:`contributions`},systemPages:{body:S({}),response:x(bA),ws:`systemPages`},systemInstances:{body:S({system:F}),response:x(xA),ws:`systemInstances`}})}),XB=nT(X({endpoints:Z(Q,$).group({searchFns:{body:gF,response:TF,ws:`searchFns`},fnExamples:{body:dF,response:fF,ws:`fnExamples`},fnFacts:{body:S({fn:I,args:O.optional()}),response:OF,ws:`fnFacts`},fnsOfModelNames:{body:S({names:x(v().min(1).max(64)).min(1).max(200)}),response:T(v(),I),ws:`fnsOfModelNames`},clientLogs:{body:NF,response:PF,ws:`clientLogs`}})}),X({endpoints:Z(Q,$,Yz).group({autoClassifier:{body:S({}),response:MF,ws:`autoClassifier`},setAutoClassifier:{body:jF,response:MF,ws:`setAutoClassifier`}})})),ZB=X({endpoints:Z(Q,$).group({exploreRoots:{body:S({system:F,instance:L.optional()}),response:x(Yx),ws:`exploreRoots`},exploreList:{body:S({uri:Wx,cursor:v().optional()}),response:Vl(Xx),ws:`exploreList`},exploreRead:{body:S({uri:Wx,want:x(Qx).min(1)}),response:eS,ws:`exploreRead`}})}),QB=X({endpoints:Z(Q,$,Yz).group({systemReview:{body:S({system:F}),response:nI,ws:`systemReview`},goLive:{body:rI,response:S({stage:yk,hash:v()}),ws:`goLive`},approveReview:{body:rI,response:S({hash:v()}),ws:`approveReview`},rejectReview:{body:S({system:F,hash:v().min(1)}),response:S({ok:b()}),ws:`rejectReview`},decideReview:{body:iI,response:aI,ws:`decideReview`},testCall:{body:sI,response:S({run:A}),ws:`testCall`},refusals:{body:eI,response:tI,ws:`refusals`}})}),$B=X({endpoints:Z(Q,$).group({graph:{body:nz,response:rz,ws:`graph`}})}),eV=S({agent:I.optional(),context:I.optional(),mode:ax.optional(),fnMode:jx.optional()}),tV=X({endpoints:Z(Q,$,Yz).group({injections:{body:eV,response:Xb,ws:`injections`},setInjection:{body:Zb,response:Yb,ws:`setInjection`}})}),nV=nT(X({endpoints:Z(Q).group({identity:{method:`GET`,response:bI,ws:`identity`}})}),X({endpoints:Z(Q,$,Yz).group({setHubName:{body:xI,response:bI,ws:`setHubName`}})})),rV=X({endpoints:Z(Q,$,Yz).group({people:{body:Oj,response:Vl(oL),ws:`people`},groups:{body:Oj,response:Vl(sL),ws:`groups`},groupMembers:{body:Hl.extend({group:M}),response:Vl(MI).extend({group:sL}),ws:`groupMembers`},signInSettings:{body:S({}),response:$I,ws:`signInSettings`},checkSsoProvider:{body:S({provider:VI}),response:tL,ws:`checkSsoProvider`},testSsoSignIn:{body:S({provider:VI}),response:S({url:Nb,test:v()}),ws:`testSsoSignIn`,httpOnly:!0},ssoTestResult:{body:S({test:v()}),response:iL,ws:`ssoTestResult`}})}),iV=X({endpoints:Z(Q,$).group({itemVersions:{body:GR,response:KR,ws:`itemVersions`}})}),aV=X({endpoints:Z(Q,$).group({dataSets:{body:iM,response:aM,ws:`dataSets`},records:{body:Jj,response:Yj,ws:`records`},record:{body:Zj,response:S({record:Kj.optional()}),ws:`record`},recordTable:{body:Xj,response:Lk,ws:`recordTable`},saveRecord:{body:Qj,response:Kj,ws:`saveRecord`},updateRecord:{body:$j,response:Kj,ws:`updateRecord`},removeRecord:{body:eM,response:S({removed:b()}),ws:`removeRecord`},recordVersions:{body:tM,response:nM,ws:`recordVersions`}})}),oV=nT(oB,dB,fB,pB,mB,hB,vB,yB,bB,wB,DB,AB,jB,MB,NB,PB,IB,LB,RB,zB,BB,WB,VB,HB,UB,GB,KB,qB,JB,YB,XB,ZB,QB,$B,tV,nV,iV,aV,X({endpoints:Z(Q,$).group({rowActions:{body:Hz,response:x(zz),ws:`rowActions`},readFn:{body:Wz,response:O,ws:`readFn`}})}),X({endpoints:Z(Q,$).group({export:{method:`GET`,query:Gz,streamOut:`text/csv`,download:`export.csv`}})}),rV),sV={load_fns:`fns_load`,drop_fns:`fns_drop`,fn_examples:`fns_examples`,fn_get:`fns_get`,save_fn:`fns_save`,fn_metrics:`fns_metrics`,load_context:`ctx_load`,context_get:`ctx_get`,context_crawl:`ctx_crawl`,context_from_resource:`ctx_from_resource`,context_link:`ctx_link`,context_unlink:`ctx_unlink`};new Map(Object.entries(sV).map(([e,t])=>[`hub/${e}`,`hub/${t}`])),new Map(Object.entries(sV));var cV=E([`added`,`modified`,`deleted`,`renamed`]),lV=E([`binary`,`large`,`sensitive`,`not-in-git`]),uV=S({path:v().min(1),root:v().min(1),status:cV,from:v().min(1).optional(),size:y().int().min(0).optional(),diff:v().optional(),added:y().int().min(0).optional(),removed:y().int().min(0).optional(),noDiff:lV.optional(),sensitive:Hk.optional(),certain:b()}),dV=S({source:E([`git`,`watcher`]),cwd:v().min(1),files:x(uV),ignored:y().int().min(0),truncated:b()}),fV=S({arg:k,label:v().min(1).optional(),choices:x(O).min(1).optional(),custom:b().optional(),pinned:O.optional(),hidden:b().optional()}),pV=S({offset:k.optional(),limit:k.optional(),size:y().int().min(1).max(500)}),mV=S({visual:k,label:v().min(1).optional(),bind:T(k,x(v().min(1)).min(1))}),hV=E([`refresh`,`show`,`none`]),gV=S({fn:I,label:v().min(1).optional(),confirm:D(!0).optional(),bind:T(k,v().min(1)),then:hV});S({title:v().min(1),source:I,visuals:x(mV).min(1),controls:x(fV),paging:pV.optional(),actions:x(gV).optional()});var _V=sF.pick({id:!0,title:!0,body:!0,link:!0,reason:!0,also:!0,key:!0,tone:!0}),vV=`open`,yV=E([`link`,`also`]),bV=`also`;function xV(e,t=`link`){return`/inbox?${vV}=${encodeURIComponent(e.id)}${t===`also`?`&via=also`:``}`}function SV(e){return e.key??e.id}function CV(e){return e.also===void 0?{link:xV(e)}:{link:xV(e),also:xV(e,`also`)}}function wV(e,t){let n=e=>typeof e==`string`&&e.startsWith(`/`)&&!e.startsWith(`//`);if(n(e))return e;if(typeof e==`object`&&e){let r=Reflect.get(e,`also`),i=Reflect.get(e,`link`);if(t===`also`&&n(r))return r;if(n(i))return i}return`/inbox`}export{RR as $,cl as $a,fv as $i,VE as $n,DS as $r,NN as $t,fB as A,xf as Aa,vb as Ai,dA as An,ic as Ao,vT as Ar,jF as At,Hz as B,Kl as Ba,Jg as Bi,DO as Bn,T as Bo,xC as Br,DP as Bt,tV as C,Mf as Ca,zb as Ci,qA as Cn,yc as Co,kT as Cr,wI as Ct,RB as D,yf as Da,wb as Di,_A as Dn,pc as Do,DT as Dr,yI as Dt,PB as E,jf as Ea,Db as Ei,TA as En,ws as Eo,TT as Er,_I as Et,Gz as F,kl as Fa,Gg as Fi,Lk as Fn,D as Fo,JC as Fr,bF as Ft,jz as G,Ll as Ga,Rv as Gi,aO as Gn,Ls as Go,dC as Gr,EP as Gt,Jz as H,Ol as Ha,Rg as Hi,_O as Hn,vc as Ho,AC as Hr,cP as Ht,Nz as I,L as Ia,Tv as Ii,_k as In,fc as Io,zw as Ir,TF as It,fz as J,Wl as Ja,t_ as Ji,GD as Jn,PC as Jr,JN as Jt,Az as K,pl as Ka,Ev as Ki,rO as Kn,hC as Kr,YN as Kt,Vz as L,O as La,Kg as Li,gk as Ln,y as Lo,Hw as Lr,hF as Lt,BB as M,M as Ma,Wg as Mi,Nk as Mn,b as Mo,hT as Mr,fF as Mt,vB as N,Bl as Na,zg as Ni,Pk as Nn,w as No,oT as Nr,dF as Nt,zB as O,Nf as Oa,tb as Oi,vA as On,oc as Oo,OT as Or,zF as Ot,iV as P,zl as Pa,Pv as Pi,Fk as Pn,Zc as Po,cT as Pr,_F as Pt,qR as Q,N as Qa,Jv as Qi,FE as Qn,jS as Qr,sN as Qt,Uz as R,fl as Ra,qg as Ri,lk as Rn,S as Ro,OC as Rr,LF as Rt,oV as S,df as Sa,Ub as Si,aj as Sn,Vc as So,jT as Sr,FI as St,IB as T,vf as Ta,Sb as Ti,BA as Tn,Uc as To,wT as Tr,CI as Tt,Kz as U,Jl as Ua,Fv as Ui,dO as Un,C as Uo,wC as Ur,xP as Ut,Bz as V,ll as Va,Yg as Vi,TO as Vn,v as Vo,SC as Vr,wP as Vt,qz as W,xl as Wa,Av as Wi,mO as Wn,sc as Wo,TC as Wr,TP as Wt,ZR as X,j as Xa,Bv as Xi,ED as Xn,eC as Xr,cN as Xt,Dz as Y,A as Ya,e_ as Yi,ZD as Yn,HC as Yr,nP as Yt,nz as Z,F as Za,a_ as Zi,iD as Zn,XS as Zr,_N as Zt,AB as _,Lh as _a,hx as _i,Ij as _n,$s as _o,LT as _r,_L as _t,wV as a,d_ as aa,AS as ai,uM as an,ac as ao,GE as ar,eR as at,ZB as b,ff as ba,ox as bi,zj as bn,zc as bo,RT as br,JI as bt,dV as c,zv as ca,Kx as ci,yM as cn,Lc as co,xE as cr,hL as ct,GB as d,p_ as da,rS as di,oM as dn,xc as do,TE as dr,AL as dt,s_ as ea,bS as ei,ON as en,nl as eo,ZE as er,PR as et,bB as f,h_ as fa,Gx as fi,Kj as fn,Gc as fo,EE as fr,mL as ft,jB as g,Dm as ga,ix as gi,Rj as gn,kc as go,eE as gr,SL as gt,KB as h,$y as ha,Ax as hi,Ej as hn,rc as ho,$T as hr,wL as ht,_V as i,u_ as ia,OS as ii,mM as in,Il as io,XE as ir,YL as it,yB as j,Gl as ja,fb as ji,Mk as jn,x as jo,gT as jr,vF as jt,DB as k,sf as ka,eb as ki,lA as kn,E as ko,bT as kr,XF as kt,$z as l,Kv as la,nS as li,xM as ln,qc as lo,wE as lr,yL as lt,dB as m,__ as ma,fx as mi,Gj as mn,Fc as mo,QT as mr,TL as mt,yV as n,l_ as na,CS as ni,zN as nn,Ul as no,KE as nr,zR as nt,SV as o,wv as oa,fS as oi,gM as on,uc as oo,OE as or,HL as ot,WB as p,U as pa,Ux as pi,Wj as pn,Sc as po,yE as pr,CL as pt,iz as q,I as qa,Hv as qi,WD as qn,UC as qr,tP as qt,vV as r,Bg as ra,SS as ri,QM as rn,Fl as ro,YE as rr,NR as rt,CV as s,jv as sa,uS as si,fM as sn,nc as so,mE as sr,$L as st,bV as t,c_ as ta,wS as ti,RN as tn,tl as to,QE as tr,MR as tt,Xz as u,f_ as ua,Wx as ui,sM as un,jc as uo,DE as ur,ML as ut,NB as v,gf as va,Qb as vi,xj as vn,dc as vo,MT as vr,WI as vt,LB as w,cf as wa,Pb as wi,LA as wn,Es as wo,ET as wr,SI as wt,$B as x,Sf as xa,Wb as xi,hj as xn,Nc as xo,HT as xr,uL as xt,aV as y,Af as ya,_x as yi,Sj as yn,Tc as yo,UT as yr,XI as yt,zz as z,k as za,Mv as zi,BO as zn,Ec as zo,kC as zr,oF as zt};
|
|
402
|
+
//# sourceMappingURL=push-payload-B3EcrsVz.js.map
|